ha_berkeley.cc 77.7 KB
Newer Older
unknown's avatar
unknown committed
1
/* Copyright (C) 2000 MySQL AB & MySQL Finland AB & TCX DataKonsult AB
unknown's avatar
unknown committed
2

unknown's avatar
unknown committed
3 4 5 6
   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; either version 2 of the License, or
   (at your option) any later version.
unknown's avatar
unknown committed
7

unknown's avatar
unknown committed
8 9 10 11
   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.
unknown's avatar
unknown committed
12

unknown's avatar
unknown committed
13 14 15 16 17 18 19 20 21 22 23
   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA */


/*
  TODO:
  - Not compressed keys should use cmp_fix_length_key
  - Don't automaticly pack all string keys (To do this we need to modify
    CREATE TABLE so that one can use the pack_keys argument per key).
  - An argument to pack_key that we don't want compression.
unknown's avatar
unknown committed
24
  - DB_DBT_USERMEM should be used for fixed length tables
unknown's avatar
unknown committed
25 26 27
    We will need an updated Berkeley DB version for this.
  - Killing threads that has got a 'deadlock'
  - SHOW TABLE STATUS should give more information about the table.
unknown's avatar
unknown committed
28
  - Get a more accurate count of the number of rows (estimate_rows_upper_bound()).
29 30
    We could store the found number of rows when the table is scanned and
    then increment the counter for each attempted write.
31 32
  - We will need to extend the manager thread to makes checkpoints at
     given intervals.
unknown's avatar
unknown committed
33 34 35 36 37 38 39
  - When not using UPDATE IGNORE, don't make a sub transaction but abort
    the main transaction on errors.
  - Handling of drop table during autocommit=0 ?
    (Should we just give an error in this case if there is a pending
    transaction ?)
  - When using ALTER TABLE IGNORE, we should not start an transaction, but do
    everything wthout transactions.
40 41
  - When we do rollback, we need to subtract the number of changed rows
    from the updated tables.
unknown's avatar
unknown committed
42 43

  Testing of:
44 45
  - Mark tables that participate in a transaction so that they are not
    closed during the transaction.  We need to test what happens if
unknown's avatar
unknown committed
46
    MySQL closes a table that is updated by a not commited transaction.
unknown's avatar
unknown committed
47 48 49
*/


50
#ifdef USE_PRAGMA_IMPLEMENTATION
unknown's avatar
unknown committed
51 52 53 54
#pragma implementation				// gcc: Class implementation
#endif

#include "mysql_priv.h"
55

unknown's avatar
unknown committed
56 57 58 59
#include <m_ctype.h>
#include <myisampack.h>
#include <hash.h>
#include "ha_berkeley.h"
60
#include "sql_manager.h"
61
#include <stdarg.h>
unknown's avatar
unknown committed
62 63

#define HA_BERKELEY_ROWS_IN_TABLE 10000 /* to get optimization right */
unknown's avatar
unknown committed
64
#define HA_BERKELEY_RANGE_COUNT   100
65
#define HA_BERKELEY_MAX_ROWS	  10000000 /* Max rows in table */
unknown's avatar
unknown committed
66
/* extra rows for estimate_rows_upper_bound() */
67 68 69 70 71 72
#define HA_BERKELEY_EXTRA_ROWS	  100

/* Bits for share->status */
#define STATUS_PRIMARY_KEY_INIT 1
#define STATUS_ROW_COUNT_INIT	2
#define STATUS_BDB_ANALYZE	4
unknown's avatar
unknown committed
73

74 75 76
const u_int32_t bdb_DB_TXN_NOSYNC= DB_TXN_NOSYNC;
const u_int32_t bdb_DB_RECOVER= DB_RECOVER;
const u_int32_t bdb_DB_PRIVATE= DB_PRIVATE;
unknown's avatar
unknown committed
77
const char *ha_berkeley_ext=".db";
78
bool berkeley_shared_data=0;
unknown's avatar
unknown committed
79 80
u_int32_t berkeley_init_flags= DB_PRIVATE | DB_RECOVER, berkeley_env_flags=0,
          berkeley_lock_type=DB_LOCK_DEFAULT;
unknown's avatar
unknown committed
81
ulong berkeley_cache_size, berkeley_log_buffer_size, berkeley_log_file_size=0;
unknown's avatar
unknown committed
82 83
char *berkeley_home, *berkeley_tmpdir, *berkeley_logdir;
long berkeley_lock_scan_time=0;
84
ulong berkeley_trans_retry=1;
85
ulong berkeley_max_lock;
unknown's avatar
unknown committed
86 87 88 89 90 91
pthread_mutex_t bdb_mutex;

static DB_ENV *db_env;
static HASH bdb_open_tables;

const char *berkeley_lock_names[] =
92 93
{ "DEFAULT", "OLDEST", "RANDOM", "YOUNGEST", "EXPIRE", "MAXLOCKS",
  "MAXWRITE", "MINLOCKS", "MINWRITE", 0 };
unknown's avatar
unknown committed
94
u_int32_t berkeley_lock_types[]=
95 96 97
{ DB_LOCK_DEFAULT, DB_LOCK_OLDEST, DB_LOCK_RANDOM, DB_LOCK_YOUNGEST,
  DB_LOCK_EXPIRE, DB_LOCK_MAXLOCKS, DB_LOCK_MAXWRITE, DB_LOCK_MINLOCKS,
  DB_LOCK_MINWRITE };
98
TYPELIB berkeley_lock_typelib= {array_elements(berkeley_lock_names)-1,"",
99
				berkeley_lock_names, NULL};
unknown's avatar
unknown committed
100

101 102
static void berkeley_print_error(const DB_ENV *db_env, const char *db_errpfx,
                                 const char *buffer);
unknown's avatar
unknown committed
103 104
static byte* bdb_get_key(BDB_SHARE *share,uint *length,
			 my_bool not_used __attribute__((unused)));
105
static BDB_SHARE *get_share(const char *table_name, TABLE *table);
unknown's avatar
unknown committed
106 107
static int free_share(BDB_SHARE *share, TABLE *table, uint hidden_primary_key,
		      bool mutex_is_locked);
unknown's avatar
unknown committed
108
static int write_status(DB *status_block, char *buff, uint length);
109
static void update_status(BDB_SHARE *share, TABLE *table);
110
static void berkeley_noticecall(DB_ENV *db_env, db_notices notice);
unknown's avatar
unknown committed
111

112 113 114
static int berkeley_close_connection(THD *thd);
static int berkeley_commit(THD *thd, bool all);
static int berkeley_rollback(THD *thd, bool all);
115
static handler *berkeley_create_handler(TABLE *table);
116

117
handlerton berkeley_hton = {
unknown's avatar
unknown committed
118
  "BerkeleyDB",
119 120 121 122
  SHOW_OPTION_YES,
  "Supports transactions and page-level locking", 
  DB_TYPE_BERKELEY_DB,
  berkeley_init,
123 124 125 126 127 128 129 130 131 132
  0, /* slot */
  0, /* savepoint size */
  berkeley_close_connection,
  NULL, /* savepoint_set */
  NULL, /* savepoint_rollback */
  NULL, /* savepoint_release */
  berkeley_commit,
  berkeley_rollback,
  NULL, /* prepare */
  NULL, /* recover */
unknown's avatar
unknown committed
133
  NULL, /* commit_by_xid */
134
  NULL, /* rollback_by_xid */
135 136 137
  NULL, /* create_cursor_read_view */
  NULL, /* set_cursor_read_view */
  NULL, /* close_cursor_read_view */
138 139 140 141 142 143 144 145 146 147
  berkeley_create_handler, /* Create a new handler */
  NULL, /* Drop a database */
  berkeley_end, /* Panic call */
  NULL, /* Release temporary latches */
  NULL, /* Update Statistics */
  NULL, /* Start Consistent Snapshot */
  berkeley_flush_logs, /* Flush logs */
  berkeley_show_status, /* Show status */
  NULL, /* Replication Report Sent Binlog */
  HTON_CLOSE_CURSORS_AT_COMMIT | HTON_FLUSH_AFTER_RENAME
148 149
};

150 151 152 153 154
handler *berkeley_create_handler(TABLE *table)
{
  return new ha_berkeley(table);
}

155 156 157 158 159
typedef struct st_berkeley_trx_data {
  DB_TXN *all;
  DB_TXN *stmt;
  uint bdb_lock_count;
} berkeley_trx_data;
160

unknown's avatar
unknown committed
161 162
/* General functions */

163
bool berkeley_init(void)
unknown's avatar
unknown committed
164 165 166
{
  DBUG_ENTER("berkeley_init");

167 168 169
  if (have_berkeley_db != SHOW_OPTION_YES)
    goto error;

unknown's avatar
unknown committed
170 171 172 173
  if (!berkeley_tmpdir)
    berkeley_tmpdir=mysql_tmpdir;
  if (!berkeley_home)
    berkeley_home=mysql_real_data_home;
174 175
  DBUG_PRINT("bdb",("berkeley_home: %s",mysql_real_data_home));

unknown's avatar
unknown committed
176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192
  /*
    If we don't set set_lg_bsize() we will get into trouble when
    trying to use many open BDB tables.
    If log buffer is not set, assume that the we will need 512 byte per
    open table.  This is a number that we have reached by testing.
  */
  if (!berkeley_log_buffer_size)
  {
    berkeley_log_buffer_size= max(table_cache_size*512,32*1024);
  }
  /*
    Berkeley DB require that
    berkeley_log_file_size >= berkeley_log_buffer_size*4
  */
  berkeley_log_file_size= berkeley_log_buffer_size*4;
  berkeley_log_file_size= MY_ALIGN(berkeley_log_file_size,1024*1024L);
  berkeley_log_file_size= max(berkeley_log_file_size, 10*1024*1024L);
unknown's avatar
unknown committed
193 194

  if (db_env_create(&db_env,0))
195
    goto error;
unknown's avatar
unknown committed
196 197
  db_env->set_errcall(db_env,berkeley_print_error);
  db_env->set_errpfx(db_env,"bdb");
198
  db_env->set_noticecall(db_env, berkeley_noticecall);
unknown's avatar
unknown committed
199 200
  db_env->set_tmp_dir(db_env, berkeley_tmpdir);
  db_env->set_data_dir(db_env, mysql_data_home);
unknown's avatar
unknown committed
201
  db_env->set_flags(db_env, berkeley_env_flags, 1);
unknown's avatar
unknown committed
202
  if (berkeley_logdir)
unknown's avatar
unknown committed
203
    db_env->set_lg_dir(db_env, berkeley_logdir); /* purecov: tested */
unknown's avatar
unknown committed
204 205 206

  if (opt_endinfo)
    db_env->set_verbose(db_env,
207
			DB_VERB_DEADLOCK | DB_VERB_RECOVERY,
unknown's avatar
unknown committed
208
			1);
unknown's avatar
unknown committed
209

unknown's avatar
unknown committed
210
  db_env->set_cachesize(db_env, 0, berkeley_cache_size, 0);
unknown's avatar
unknown committed
211 212
  db_env->set_lg_max(db_env, berkeley_log_file_size);
  db_env->set_lg_bsize(db_env, berkeley_log_buffer_size);
unknown's avatar
unknown committed
213
  db_env->set_lk_detect(db_env, berkeley_lock_type);
214 215
  if (berkeley_max_lock)
    db_env->set_lk_max(db_env, berkeley_max_lock);
216

unknown's avatar
unknown committed
217 218
  if (db_env->open(db_env,
		   berkeley_home,
unknown's avatar
unknown committed
219
		   berkeley_init_flags |  DB_INIT_LOCK |
unknown's avatar
unknown committed
220
		   DB_INIT_LOG | DB_INIT_MPOOL | DB_INIT_TXN |
221
		   DB_CREATE | DB_THREAD, 0666))
unknown's avatar
unknown committed
222
  {
223 224
    db_env->close(db_env,0);
    db_env=0;
225
    goto error;
unknown's avatar
unknown committed
226
  }
227

unknown's avatar
unknown committed
228
  (void) hash_init(&bdb_open_tables,system_charset_info,32,0,0,
unknown's avatar
unknown committed
229
		   (hash_get_key) bdb_get_key,0,0);
230
  pthread_mutex_init(&bdb_mutex,MY_MUTEX_INIT_FAST);
231 232 233 234
  DBUG_RETURN(FALSE);
error:
  have_berkeley_db= SHOW_OPTION_DISABLED;	// If we couldn't use handler
  DBUG_RETURN(TRUE);
unknown's avatar
unknown committed
235 236 237
}


238
int berkeley_end(ha_panic_function type)
unknown's avatar
unknown committed
239
{
240
  int error= 0;
unknown's avatar
unknown committed
241
  DBUG_ENTER("berkeley_end");
242 243 244 245 246 247 248 249 250
  if (db_env)
  {
    berkeley_cleanup_log_files();
    error= db_env->close(db_env,0);		// Error is logged
    db_env= 0;
    hash_free(&bdb_open_tables);
    pthread_mutex_destroy(&bdb_mutex);
  }
  DBUG_RETURN(error);
unknown's avatar
unknown committed
251 252
}

253 254 255
static int berkeley_close_connection(THD *thd)
{
  my_free((gptr)thd->ha_data[berkeley_hton.slot], MYF(0));
unknown's avatar
unknown committed
256
  return 0;
257 258
}

unknown's avatar
unknown committed
259 260 261 262 263
bool berkeley_flush_logs()
{
  int error;
  bool result=0;
  DBUG_ENTER("berkeley_flush_logs");
unknown's avatar
unknown committed
264
  if ((error=db_env->log_flush(db_env,0)))
unknown's avatar
unknown committed
265
  {
266 267
    my_error(ER_ERROR_DURING_FLUSH_LOGS,MYF(0),error); /* purecov: inspected */
    result=1; /* purecov: inspected */
unknown's avatar
unknown committed
268
  }
unknown's avatar
unknown committed
269
  if ((error=db_env->txn_checkpoint(db_env,0,0,0)))
unknown's avatar
unknown committed
270
  {
271 272
    my_error(ER_ERROR_DURING_CHECKPOINT,MYF(0),error); /* purecov: inspected */
    result=1; /* purecov: inspected */
unknown's avatar
unknown committed
273 274 275 276
  }
  DBUG_RETURN(result);
}

277
static int berkeley_commit(THD *thd, bool all)
unknown's avatar
unknown committed
278 279
{
  DBUG_ENTER("berkeley_commit");
280 281
  DBUG_PRINT("trans",("ending transaction %s", all ? "all" : "stmt"));
  berkeley_trx_data *trx=(berkeley_trx_data *)thd->ha_data[berkeley_hton.slot];
unknown's avatar
unknown committed
282
  DB_TXN **txn= all ? &trx->all : &trx->stmt;
283
  int error= (*txn)->commit(*txn,0);
unknown's avatar
unknown committed
284
  *txn=0;
unknown's avatar
unknown committed
285 286
#ifndef DBUG_OFF
  if (error)
287
    DBUG_PRINT("error",("error: %d",error));
unknown's avatar
unknown committed
288 289 290 291
#endif
  DBUG_RETURN(error);
}

292
static int berkeley_rollback(THD *thd, bool all)
unknown's avatar
unknown committed
293 294
{
  DBUG_ENTER("berkeley_rollback");
295 296
  DBUG_PRINT("trans",("aborting transaction %s", all ? "all" : "stmt"));
  berkeley_trx_data *trx=(berkeley_trx_data *)thd->ha_data[berkeley_hton.slot];
unknown's avatar
unknown committed
297
  DB_TXN **txn= all ? &trx->all : &trx->stmt;
298
  int error= (*txn)->abort(*txn);
unknown's avatar
unknown committed
299
  *txn=0;
unknown's avatar
unknown committed
300 301 302
  DBUG_RETURN(error);
}

unknown's avatar
unknown committed
303

304
static bool berkeley_show_logs(THD *thd, stat_print_fn *stat_print)
unknown's avatar
unknown committed
305
{
306 307
  char **all_logs, **free_logs, **a, **f;
  int error=1;
unknown's avatar
unknown committed
308 309
  MEM_ROOT **root_ptr= my_pthread_getspecific_ptr(MEM_ROOT**,THR_MALLOC);
  MEM_ROOT show_logs_root, *old_mem_root= *root_ptr;
unknown's avatar
unknown committed
310 311
  DBUG_ENTER("berkeley_show_logs");

unknown's avatar
unknown committed
312 313
  init_sql_alloc(&show_logs_root, BDB_LOG_ALLOC_BLOCK_SIZE,
		 BDB_LOG_ALLOC_BLOCK_SIZE);
unknown's avatar
unknown committed
314
  *root_ptr= &show_logs_root;
315

316 317 318
  if ((error= db_env->log_archive(db_env, &all_logs,
				  DB_ARCH_ABS | DB_ARCH_LOG)) ||
      (error= db_env->log_archive(db_env, &free_logs, DB_ARCH_ABS)))
unknown's avatar
unknown committed
319 320 321
  {
    DBUG_PRINT("error", ("log_archive failed (error %d)", error));
    db_env->err(db_env, error, "log_archive: DB_ARCH_ABS");
unknown's avatar
unknown committed
322 323
    if (error== DB_NOTFOUND)
      error=0;					// No log files
324
    goto err;
unknown's avatar
unknown committed
325
  }
unknown's avatar
unknown committed
326 327
  /* Error is 0 here */
  if (all_logs)
unknown's avatar
unknown committed
328
  {
unknown's avatar
unknown committed
329
    for (a = all_logs, f = free_logs; *a; ++a)
unknown's avatar
unknown committed
330
    {
331
      const char *status;
unknown's avatar
unknown committed
332 333
      if (f && *f && strcmp(*a, *f) == 0)
      {
334 335
        f++;
        status= SHOW_LOG_STATUS_FREE;
unknown's avatar
unknown committed
336 337
      }
      else
338 339 340
        status= SHOW_LOG_STATUS_INUSE;
  
      if (stat_print(thd, berkeley_hton.name, *a, status))
unknown's avatar
unknown committed
341
      {
342 343
        error=1;
        goto err;
unknown's avatar
unknown committed
344 345
      }
    }
unknown's avatar
unknown committed
346
  }
347
err:
unknown's avatar
unknown committed
348
  free_root(&show_logs_root,MYF(0));
unknown's avatar
unknown committed
349
  *root_ptr= old_mem_root;
350
  DBUG_RETURN(error);
unknown's avatar
unknown committed
351
}
unknown's avatar
unknown committed
352

353 354 355 356 357 358 359 360 361 362
bool berkeley_show_status(THD *thd, stat_print_fn *stat_print,
                          enum ha_stat_type stat_type)
{
  switch (stat_type) {
  case HA_ENGINE_LOGS:
    return berkeley_show_logs(thd, stat_print);
  default:
    return FALSE;
  }
}
unknown's avatar
unknown committed
363

364 365
static void berkeley_print_error(const DB_ENV *db_env, const char *db_errpfx,
                                 const char *buffer)
unknown's avatar
unknown committed
366
{
367
  sql_print_error("%s:  %s",db_errpfx,buffer); /* purecov: tested */
unknown's avatar
unknown committed
368 369
}

unknown's avatar
unknown committed
370

371 372 373 374
static void berkeley_noticecall(DB_ENV *db_env, db_notices notice)
{
  switch (notice)
  {
375
  case DB_NOTICE_LOGFILE_CHANGED: /* purecov: tested */
376
    mysql_manager_submit(berkeley_cleanup_log_files);
377 378 379 380 381 382 383 384 385 386 387
    pthread_cond_signal(&COND_manager);
    break;
  }
}

void berkeley_cleanup_log_files(void)
{
  DBUG_ENTER("berkeley_cleanup_log_files");
  char **names;
  int error;

unknown's avatar
unknown committed
388 389
// by HF. Sometimes it crashes. TODO - find out why
#ifndef EMBEDDED_LIBRARY
390 391
  /* XXX: Probably this should be done somewhere else, and
   * should be tunable by the user. */
unknown's avatar
unknown committed
392
  if ((error = db_env->txn_checkpoint(db_env, 0, 0, 0)))
393
    my_error(ER_ERROR_DURING_CHECKPOINT, MYF(0), error); /* purecov: inspected */
unknown's avatar
unknown committed
394
#endif
unknown's avatar
unknown committed
395
  if ((error = db_env->log_archive(db_env, &names, DB_ARCH_ABS)) != 0)
396
  {
397 398 399
    DBUG_PRINT("error", ("log_archive failed (error %d)", error)); /* purecov: inspected */
    db_env->err(db_env, error, "log_archive: DB_ARCH_ABS"); /* purecov: inspected */
    DBUG_VOID_RETURN; /* purecov: inspected */
400 401 402
  }

  if (names)
unknown's avatar
unknown committed
403 404 405 406
  {						/* purecov: tested */
    char **np;					/* purecov: tested */
    for (np = names; *np; ++np)			/* purecov: tested */
      my_delete(*np, MYF(MY_WME));		/* purecov: tested */
407

unknown's avatar
unknown committed
408
    free(names);				/* purecov: tested */
409 410 411 412
  }

  DBUG_VOID_RETURN;
}
unknown's avatar
unknown committed
413 414 415 416 417


/*****************************************************************************
** Berkeley DB tables
*****************************************************************************/
418 419 420 421 422 423

ha_berkeley::ha_berkeley(TABLE *table_arg)
  :handler(&berkeley_hton, table_arg), alloc_ptr(0), rec_buff(0), file(0),
  int_table_flags(HA_REC_NOT_IN_SEQ | HA_FAST_KEY_READ |
                  HA_NULL_IN_KEY | HA_CAN_INDEX_BLOBS | HA_NOT_EXACT_COUNT |
                  HA_PRIMARY_KEY_IN_READ_INDEX | HA_FILE_BASED |
424
                  HA_CAN_GEOMETRY |
425 426 427 428 429
                  HA_AUTO_PART_KEY | HA_TABLE_SCAN_ON_INDEX),
  changed_rows(0), last_dup_key((uint) -1), version(0), using_ignore(0)
{}


unknown's avatar
unknown committed
430 431 432 433
static const char *ha_berkeley_exts[] = {
  ha_berkeley_ext,
  NullS
};
unknown's avatar
unknown committed
434 435

const char **ha_berkeley::bas_ext() const
unknown's avatar
unknown committed
436 437 438
{
  return ha_berkeley_exts;
}
unknown's avatar
unknown committed
439

440 441 442 443
ulong ha_berkeley::index_flags(uint idx, uint part, bool all_parts) const
{
  ulong flags= (HA_READ_NEXT | HA_READ_PREV | HA_READ_ORDER | HA_KEYREAD_ONLY
                | HA_READ_RANGE);
unknown's avatar
unknown committed
444
  for (uint i= all_parts ? 0 : part ; i <= part ; i++)
445
  {
unknown's avatar
unknown committed
446
    if (table->key_info[idx].key_part[i].field->type() == FIELD_TYPE_BLOB)
447 448
    {
      /* We can't use BLOBS to shortcut sorts */
unknown's avatar
unknown committed
449 450 451 452 453
      flags&= ~(HA_READ_ORDER | HA_KEYREAD_ONLY | HA_READ_RANGE);
      break;
    }
    switch (table->key_info[idx].key_part[i].field->key_type()) {
    case HA_KEYTYPE_TEXT:
454 455
    case HA_KEYTYPE_VARTEXT1:
    case HA_KEYTYPE_VARTEXT2:
unknown's avatar
unknown committed
456 457
      /*
        As BDB stores only one copy of equal strings, we can't use key read
458
        on these. Binary collations do support key read though.
unknown's avatar
unknown committed
459
      */
460 461 462
      if (!(table->key_info[idx].key_part[i].field->charset()->state
           & MY_CS_BINSORT))
        flags&= ~HA_KEYREAD_ONLY;
unknown's avatar
unknown committed
463 464
      break;
    default:                                    // Keep compiler happy
465 466 467 468 469 470 471
      break;
    }
  }
  return flags;
}


472
static int
473
berkeley_cmp_hidden_key(DB* file, const DBT *new_key, const DBT *saved_key)
474 475 476
{
  ulonglong a=uint5korr((char*) new_key->data);
  ulonglong b=uint5korr((char*) saved_key->data);
unknown's avatar
unknown committed
477
  return  a < b ? -1 : (a > b ? 1 : 0);
478 479
}

unknown's avatar
unknown committed
480
static int
481
berkeley_cmp_packed_key(DB *file, const DBT *new_key, const DBT *saved_key)
unknown's avatar
unknown committed
482
{
483 484
  KEY *key=	      (new_key->app_private ? (KEY*) new_key->app_private :
		       (KEY*) (file->app_private));
unknown's avatar
unknown committed
485 486 487 488 489
  char *new_key_ptr=  (char*) new_key->data;
  char *saved_key_ptr=(char*) saved_key->data;
  KEY_PART_INFO *key_part= key->key_part, *end=key_part+key->key_parts;
  uint key_length=new_key->size;

490
  DBUG_DUMP("key_in_index", saved_key_ptr, saved_key->size);
491
  for (; key_part != end && (int) key_length > 0; key_part++)
unknown's avatar
unknown committed
492 493
  {
    int cmp;
494
    uint length;
unknown's avatar
unknown committed
495 496
    if (key_part->null_bit)
    {
497 498
      if (*new_key_ptr != *saved_key_ptr++)
	return ((int) *new_key_ptr - (int) saved_key_ptr[-1]);
499
      key_length--;
500 501
      if (!*new_key_ptr++)
	continue;
unknown's avatar
unknown committed
502
    }
503 504 505
    if ((cmp= key_part->field->pack_cmp(new_key_ptr,saved_key_ptr,
                                        key_part->length,
                                        key->table->insert_or_update)))
unknown's avatar
unknown committed
506
      return cmp;
507 508
    length= key_part->field->packed_col_length(new_key_ptr,
                                               key_part->length);
unknown's avatar
unknown committed
509 510
    new_key_ptr+=length;
    key_length-=length;
511 512
    saved_key_ptr+=key_part->field->packed_col_length(saved_key_ptr,
						      key_part->length);
unknown's avatar
unknown committed
513
  }
514
  return key->handler.bdb_return_if_eq;
unknown's avatar
unknown committed
515 516 517
}


518 519
/* The following is not yet used; Should be used for fixed length keys */

520
#ifdef NOT_YET
unknown's avatar
unknown committed
521
static int
522
berkeley_cmp_fix_length_key(DB *file, const DBT *new_key, const DBT *saved_key)
unknown's avatar
unknown committed
523
{
524 525
  KEY *key=	      (new_key->app_private ? (KEY*) new_key->app_private :
		       (KEY*) (file->app_private));
unknown's avatar
unknown committed
526 527 528 529 530
  char *new_key_ptr=  (char*) new_key->data;
  char *saved_key_ptr=(char*) saved_key->data;
  KEY_PART_INFO *key_part= key->key_part, *end=key_part+key->key_parts;
  uint key_length=new_key->size;

531
  for (; key_part != end && (int) key_length > 0 ; key_part++)
unknown's avatar
unknown committed
532 533
  {
    int cmp;
534
    if ((cmp=key_part->field->pack_cmp(new_key_ptr,saved_key_ptr,0,0)))
unknown's avatar
unknown committed
535 536 537 538 539
      return cmp;
    new_key_ptr+=key_part->length;
    key_length-= key_part->length;
    saved_key_ptr+=key_part->length;
  }
540
  return key->handler.bdb_return_if_eq;
unknown's avatar
unknown committed
541
}
542
#endif
unknown's avatar
unknown committed
543

544

545 546 547 548 549 550
/* Compare key against row */

static bool
berkeley_key_cmp(TABLE *table, KEY *key_info, const char *key, uint key_length)
{
  KEY_PART_INFO *key_part= key_info->key_part,
unknown's avatar
unknown committed
551
		*end=key_part+key_info->key_parts;
552

553
  for (; key_part != end && (int) key_length > 0; key_part++)
554 555
  {
    int cmp;
556
    uint length;
557 558 559
    if (key_part->null_bit)
    {
      key_length--;
560 561 562 563
      /*
	With the current usage, the following case will always be FALSE,
	because NULL keys are sorted before any other key
      */
564 565 566
      if (*key != (table->record[0][key_part->null_offset] &
		   key_part->null_bit) ? 0 : 1)
	return 1;
567
      if (!*key++)				// Null value
568 569
	continue;
    }
570 571 572 573 574
    /*
      Last argument has to be 0 as we are also using this to function to see
      if a key like 'a  ' matched a row with 'a'
    */
    if ((cmp= key_part->field->pack_cmp(key, key_part->length, 0)))
575
      return cmp;
576 577 578
    length= key_part->field->packed_col_length(key,key_part->length);
    key+= length;
    key_length-= length;
579
  }
580
  return 0;					// Identical keys
581 582
}

583

584
int ha_berkeley::open(const char *name, int mode, uint test_if_locked)
unknown's avatar
unknown committed
585 586 587
{
  char name_buff[FN_REFLEN];
  uint open_mode=(mode == O_RDONLY ? DB_RDONLY : 0) | DB_THREAD;
588
  uint max_key_length;
unknown's avatar
unknown committed
589
  int error;
590
  TABLE_SHARE *table_share= table->s;
unknown's avatar
unknown committed
591 592
  DBUG_ENTER("ha_berkeley::open");

593 594
  /* Open primary key */
  hidden_primary_key=0;
595
  if ((primary_key= table_share->primary_key) >= MAX_KEY)
596
  {						// No primary key
597
    primary_key= table_share->keys;
598
    key_used_on_scan=MAX_KEY;
599 600
    ref_length=hidden_primary_key=BDB_HIDDEN_PRIMARY_KEY_LENGTH;
  }
601 602
  else
    key_used_on_scan=primary_key;
603

unknown's avatar
unknown committed
604
  /* Need some extra memory in case of packed keys */
605
  max_key_length= table_share->max_key_length + MAX_REF_PARTS*3;
unknown's avatar
unknown committed
606 607 608 609 610
  if (!(alloc_ptr=
	my_multi_malloc(MYF(MY_WME),
			&key_buff,  max_key_length,
			&key_buff2, max_key_length,
			&primary_key_buff,
611
			(hidden_primary_key ? 0 :
612
			 table->key_info[table_share->primary_key].key_length),
unknown's avatar
unknown committed
613
			NullS)))
614
    DBUG_RETURN(1); /* purecov: inspected */
615
  if (!(rec_buff= (byte*) my_malloc((alloced_rec_buff_length=
616
				     table_share->rec_buff_length),
617
				    MYF(MY_WME))))
unknown's avatar
unknown committed
618
  {
619 620
    my_free(alloc_ptr,MYF(0)); /* purecov: inspected */
    DBUG_RETURN(1); /* purecov: inspected */
unknown's avatar
unknown committed
621 622
  }

623
  /* Init shared structure */
624
  if (!(share= get_share(name,table)))
unknown's avatar
unknown committed
625
  {
626
    my_free((char*) rec_buff,MYF(0)); /* purecov: inspected */
627 628
    my_free(alloc_ptr,MYF(0)); /* purecov: inspected */
    DBUG_RETURN(1); /* purecov: inspected */
unknown's avatar
unknown committed
629 630
  }
  thr_lock_data_init(&share->lock,&lock,(void*) 0);
631 632
  key_file = share->key_file;
  key_type = share->key_type;
633
  bzero((char*) &current_row,sizeof(current_row));
unknown's avatar
unknown committed
634

635 636
  /* Fill in shared structure, if needed */
  pthread_mutex_lock(&share->mutex);
637
  file= share->file;
638
  if (!share->use_count++)
unknown's avatar
unknown committed
639
  {
640 641
    if ((error=db_create(&file, db_env, 0)))
    {
642
      free_share(share,table, hidden_primary_key,1); /* purecov: inspected */
643
      my_free((char*) rec_buff,MYF(0)); /* purecov: inspected */
644 645 646
      my_free(alloc_ptr,MYF(0)); /* purecov: inspected */
      my_errno=error; /* purecov: inspected */
      DBUG_RETURN(1); /* purecov: inspected */
647
    }
648
    share->file= file;
649 650 651 652 653

    file->set_bt_compare(file,
			 (hidden_primary_key ? berkeley_cmp_hidden_key :
			  berkeley_cmp_packed_key));
    if (!hidden_primary_key)
654
      file->app_private= (void*) (table->key_info + table_share->primary_key);
655
    if ((error= db_env->txn_begin(db_env, NULL, (DB_TXN**) &transaction, 0)) ||
unknown's avatar
unknown committed
656
	(error= (file->open(file, transaction,
657 658
			    fn_format(name_buff, name, "", ha_berkeley_ext,
				      2 | 4),
unknown's avatar
unknown committed
659 660
			    "main", DB_BTREE, open_mode, 0))) ||
	(error= transaction->commit(transaction, 0)))
661
    {
662
      free_share(share, table, hidden_primary_key,1); /* purecov: inspected */
663
      my_free((char*) rec_buff,MYF(0)); /* purecov: inspected */
664 665 666
      my_free(alloc_ptr,MYF(0)); /* purecov: inspected */
      my_errno=error; /* purecov: inspected */
      DBUG_RETURN(1); /* purecov: inspected */
667
    }
unknown's avatar
unknown committed
668

669
    /* Open other keys;  These are part of the share structure */
670 671 672 673
    key_file[primary_key]=file;
    key_type[primary_key]=DB_NOOVERWRITE;

    DB **ptr=key_file;
674
    for (uint i=0, used_keys=0; i < table_share->keys ; i++, ptr++)
675 676 677 678 679 680
    {
      char part[7];
      if (i != primary_key)
      {
	if ((error=db_create(ptr, db_env, 0)))
	{
unknown's avatar
unknown committed
681 682 683
	  close();				/* purecov: inspected */
	  my_errno=error;			/* purecov: inspected */
	  DBUG_RETURN(1);			/* purecov: inspected */
684 685 686 687 688 689
	}
	sprintf(part,"key%02d",++used_keys);
	key_type[i]=table->key_info[i].flags & HA_NOSAME ? DB_NOOVERWRITE : 0;
	(*ptr)->set_bt_compare(*ptr, berkeley_cmp_packed_key);
	(*ptr)->app_private= (void*) (table->key_info+i);
	if (!(table->key_info[i].flags & HA_NOSAME))
unknown's avatar
unknown committed
690 691
	{
	  DBUG_PRINT("bdb",("Setting DB_DUP for key %u", i));
692
	  (*ptr)->set_flags(*ptr, DB_DUP);
unknown's avatar
unknown committed
693
	}
694 695
	if ((error= db_env->txn_begin(db_env, NULL, (DB_TXN**) &transaction,
                                      0)) ||
unknown's avatar
unknown committed
696 697 698
	    (error=((*ptr)->open(*ptr, transaction, name_buff, part, DB_BTREE,
				 open_mode, 0))) ||
	    (error= transaction->commit(transaction, 0)))
699
	{
unknown's avatar
unknown committed
700 701 702
	  close();				/* purecov: inspected */
	  my_errno=error;			/* purecov: inspected */
	  DBUG_RETURN(1);			/* purecov: inspected */
703 704 705 706
	}
      }
    }
    /* Calculate pack_length of primary key */
707
    share->fixed_length_primary_key= 1;
708 709 710 711 712
    if (!hidden_primary_key)
    {
      ref_length=0;
      KEY_PART_INFO *key_part= table->key_info[primary_key].key_part;
      KEY_PART_INFO *end=key_part+table->key_info[primary_key].key_parts;
713
      for (; key_part != end ; key_part++)
714
	ref_length+= key_part->field->max_packed_col_length(key_part->length);
715
      share->fixed_length_primary_key=
716
	(ref_length == table->key_info[primary_key].key_length);
717
      share->status|= STATUS_PRIMARY_KEY_INIT;
718
    }    
719
    share->ref_length= ref_length;
unknown's avatar
unknown committed
720
  }
721
  ref_length= share->ref_length;                // If second open
722
  pthread_mutex_unlock(&share->mutex);
unknown's avatar
unknown committed
723 724 725

  transaction=0;
  cursor=0;
726
  key_read=0;
727
  block_size=8192;				// Berkeley DB block size
728 729
  share->fixed_length_row= !(table_share->db_create_options &
                             HA_OPTION_PACK_RECORD);
unknown's avatar
unknown committed
730

731
  get_status();
unknown's avatar
unknown committed
732
  info(HA_STATUS_NO_LOCK | HA_STATUS_VARIABLE | HA_STATUS_CONST);
unknown's avatar
unknown committed
733 734 735 736 737 738 739 740
  DBUG_RETURN(0);
}


int ha_berkeley::close(void)
{
  DBUG_ENTER("ha_berkeley::close");

741
  my_free((char*) rec_buff,MYF(MY_ALLOW_ZERO_PTR));
unknown's avatar
unknown committed
742
  my_free(alloc_ptr,MYF(MY_ALLOW_ZERO_PTR));
unknown's avatar
unknown committed
743
  ha_berkeley::extra(HA_EXTRA_RESET);		// current_row buffer
unknown's avatar
unknown committed
744
  DBUG_RETURN(free_share(share,table, hidden_primary_key,0));
unknown's avatar
unknown committed
745 746 747 748 749 750 751 752 753 754 755 756
}


/* Reallocate buffer if needed */

bool ha_berkeley::fix_rec_buff_for_blob(ulong length)
{
  if (! rec_buff || length > alloced_rec_buff_length)
  {
    byte *newptr;
    if (!(newptr=(byte*) my_realloc((gptr) rec_buff, length,
				    MYF(MY_ALLOW_ZERO_PTR))))
757
      return 1; /* purecov: inspected */
unknown's avatar
unknown committed
758 759 760 761 762 763 764 765 766 767 768
    rec_buff=newptr;
    alloced_rec_buff_length=length;
  }
  return 0;
}


/* Calculate max length needed for row */

ulong ha_berkeley::max_row_length(const byte *buf)
{
769 770 771 772 773 774 775 776 777
  ulong length= table->s->reclength + table->s->fields*2;
  uint *ptr, *end;
  for (ptr= table->s->blob_field, end=ptr + table->s->blob_fields ;
       ptr != end ;
       ptr++)
  {
    Field_blob *blob= ((Field_blob*) table->field[*ptr]);
    length+= blob->get_length((char*) buf + blob->offset())+2;
  }
unknown's avatar
unknown committed
778 779 780 781 782 783 784 785 786 787 788 789 790
  return length;
}


/*
  Pack a row for storage.  If the row is of fixed length, just store the
  row 'as is'.
  If not, we will generate a packed row suitable for storage.
  This will only fail if we don't have enough memory to pack the row, which;
  may only happen in rows with blobs,  as the default row length is
  pre-allocated.
*/

791
int ha_berkeley::pack_row(DBT *row, const byte *record, bool new_row)
unknown's avatar
unknown committed
792
{
793
  byte *ptr;
unknown's avatar
unknown committed
794
  bzero((char*) row,sizeof(*row));
795
  if (share->fixed_length_row)
unknown's avatar
unknown committed
796 797
  {
    row->data=(void*) record;
798
    row->size= table->s->reclength+hidden_primary_key;
799 800 801 802
    if (hidden_primary_key)
    {
      if (new_row)
	get_auto_primary_key(current_ident);
803
      memcpy_fixed((char*) record+table->s->reclength, (char*) current_ident,
804 805
		   BDB_HIDDEN_PRIMARY_KEY_LENGTH);
    }
unknown's avatar
unknown committed
806 807
    return 0;
  }
808
  if (table->s->blob_fields)
unknown's avatar
unknown committed
809 810
  {
    if (fix_rec_buff_for_blob(max_row_length(record)))
811
      return HA_ERR_OUT_OF_MEM; /* purecov: inspected */
unknown's avatar
unknown committed
812 813 814
  }

  /* Copy null bits */
815 816
  memcpy(rec_buff, record, table->s->null_bytes);
  ptr= rec_buff + table->s->null_bytes;
unknown's avatar
unknown committed
817 818

  for (Field **field=table->field ; *field ; field++)
819 820
    ptr=(byte*) (*field)->pack((char*) ptr,
			       (char*) record + (*field)->offset());
821 822 823 824 825 826 827 828 829

  if (hidden_primary_key)
  {
    if (new_row)
      get_auto_primary_key(current_ident);
    memcpy_fixed((char*) ptr, (char*) current_ident,
		 BDB_HIDDEN_PRIMARY_KEY_LENGTH);
    ptr+=BDB_HIDDEN_PRIMARY_KEY_LENGTH;
  }
unknown's avatar
unknown committed
830 831 832 833 834 835 836 837
  row->data=rec_buff;
  row->size= (size_t) (ptr - rec_buff);
  return 0;
}


void ha_berkeley::unpack_row(char *record, DBT *row)
{
838
  if (share->fixed_length_row)
839
    memcpy(record,(char*) row->data,table->s->reclength+hidden_primary_key);
unknown's avatar
unknown committed
840 841 842 843
  else
  {
    /* Copy null bits */
    const char *ptr= (const char*) row->data;
844 845
    memcpy(record, ptr, table->s->null_bytes);
    ptr+= table->s->null_bytes;
unknown's avatar
unknown committed
846 847 848 849 850 851
    for (Field **field=table->field ; *field ; field++)
      ptr= (*field)->unpack(record + (*field)->offset(), ptr);
  }
}


852 853 854 855
/* Store the key and the primary key into the row */

void ha_berkeley::unpack_key(char *record, DBT *key, uint index)
{
856
  KEY *key_info= table->key_info+index;
857
  KEY_PART_INFO *key_part= key_info->key_part,
858 859
		*end= key_part+key_info->key_parts;
  char *pos= (char*) key->data;
860

861
  for (; key_part != end; key_part++)
862 863 864 865 866 867 868 869 870 871 872 873 874 875 876
  {
    if (key_part->null_bit)
    {
      if (!*pos++)				// Null value
      {
	/*
	  We don't need to reset the record data as we will not access it
	  if the null data is set
	*/

	record[key_part->null_offset]|=key_part->null_bit;
	continue;
      }
      record[key_part->null_offset]&= ~key_part->null_bit;
    }
877 878
    pos= (char*) key_part->field->unpack_key(record + key_part->field->offset(),
                                             pos, key_part->length);
879 880 881 882
  }
}


unknown's avatar
unknown committed
883
/*
884 885 886 887
  Create a packed key from a row. This key will be written as such
  to the index tree.

  This will never fail as the key buffer is pre-allocated.
unknown's avatar
unknown committed
888 889
*/

890 891
DBT *ha_berkeley::create_key(DBT *key, uint keynr, char *buff,
			     const byte *record, int key_length)
unknown's avatar
unknown committed
892
{
893 894 895
  bzero((char*) key,sizeof(*key));
  if (hidden_primary_key && keynr == primary_key)
  {
896
    /* We don't need to set app_private here */
897 898 899 900 901
    key->data=current_ident;
    key->size=BDB_HIDDEN_PRIMARY_KEY_LENGTH;
    return key;
  }

unknown's avatar
unknown committed
902 903 904
  KEY *key_info=table->key_info+keynr;
  KEY_PART_INFO *key_part=key_info->key_part;
  KEY_PART_INFO *end=key_part+key_info->key_parts;
905
  DBUG_ENTER("create_key");
unknown's avatar
unknown committed
906 907

  key->data=buff;
908
  key->app_private= key_info;
909
  for (; key_part != end && key_length > 0; key_part++)
unknown's avatar
unknown committed
910 911 912 913 914 915 916 917 918 919 920 921
  {
    if (key_part->null_bit)
    {
      /* Store 0 if the key part is a NULL part */
      if (record[key_part->null_offset] & key_part->null_bit)
      {
	*buff++ =0;
	key->flags|=DB_DBT_DUPOK;
	continue;
      }
      *buff++ = 1;				// Store NOT NULL marker
    }
922
    buff=key_part->field->pack_key(buff,(char*) (record + key_part->offset),
923
				   key_part->length);
924
    key_length-=key_part->length;
unknown's avatar
unknown committed
925 926 927 928 929 930 931 932
  }
  key->size= (buff  - (char*) key->data);
  DBUG_DUMP("key",(char*) key->data, key->size);
  DBUG_RETURN(key);
}


/*
933 934 935 936
  Create a packed key from from a MySQL unpacked key (like the one that is
  sent from the index_read()

  This key is to be used to read a row
unknown's avatar
unknown committed
937 938 939 940 941 942 943 944
*/

DBT *ha_berkeley::pack_key(DBT *key, uint keynr, char *buff,
			   const byte *key_ptr, uint key_length)
{
  KEY *key_info=table->key_info+keynr;
  KEY_PART_INFO *key_part=key_info->key_part;
  KEY_PART_INFO *end=key_part+key_info->key_parts;
945
  DBUG_ENTER("bdb:pack_key");
unknown's avatar
unknown committed
946 947 948

  bzero((char*) key,sizeof(*key));
  key->data=buff;
949
  key->app_private= (void*) key_info;
unknown's avatar
unknown committed
950 951 952

  for (; key_part != end && (int) key_length > 0 ; key_part++)
  {
953
    uint offset=0;
unknown's avatar
unknown committed
954 955 956 957 958 959 960 961 962
    if (key_part->null_bit)
    {
      if (!(*buff++ = (*key_ptr == 0)))		// Store 0 if NULL
      {
	key_length-= key_part->store_length;
	key_ptr+=   key_part->store_length;
	key->flags|=DB_DBT_DUPOK;
	continue;
      }
963
      offset=1;					// Data is at key_ptr+1
unknown's avatar
unknown committed
964
    }
965
    buff=key_part->field->pack_key_from_key_image(buff,(char*) key_ptr+offset,
966
						  key_part->length);
unknown's avatar
unknown committed
967 968 969 970 971 972 973 974 975 976 977 978 979 980 981
    key_ptr+=key_part->store_length;
    key_length-=key_part->store_length;
  }
  key->size= (buff  - (char*) key->data);
  DBUG_DUMP("key",(char*) key->data, key->size);
  DBUG_RETURN(key);
}


int ha_berkeley::write_row(byte * record)
{
  DBT row,prim_key,key;
  int error;
  DBUG_ENTER("write_row");

982
  statistic_increment(table->in_use->status_var.ha_write_count, &LOCK_status);
983 984
  if (table->timestamp_field_type & TIMESTAMP_AUTO_SET_ON_INSERT)
    table->timestamp_field->set_time();
unknown's avatar
unknown committed
985 986
  if (table->next_number_field && record == table->record[0])
    update_auto_increment();
987
  if ((error=pack_row(&row, record,1)))
988
    DBUG_RETURN(error); /* purecov: inspected */
unknown's avatar
unknown committed
989

990
  table->insert_or_update= 1;                   // For handling of VARCHAR
991
  if (table->s->keys + test(hidden_primary_key) == 1)
unknown's avatar
unknown committed
992
  {
993 994
    error=file->put(file, transaction, create_key(&prim_key, primary_key,
						  key_buff, record),
unknown's avatar
unknown committed
995
		    &row, key_type[primary_key]);
unknown's avatar
unknown committed
996
    last_dup_key=primary_key;
unknown's avatar
unknown committed
997 998 999
  }
  else
  {
1000
    DB_TXN *sub_trans = transaction;
1001
    /* Don't use sub transactions in temporary tables */
unknown's avatar
unknown committed
1002 1003
    for (uint retry=0 ; retry < berkeley_trans_retry ; retry++)
    {
unknown's avatar
unknown committed
1004
      key_map changed_keys(0);
1005 1006
      if (!(error=file->put(file, sub_trans, create_key(&prim_key, primary_key,
							key_buff, record),
unknown's avatar
unknown committed
1007 1008
			    &row, key_type[primary_key])))
      {
1009
	changed_keys.set_bit(primary_key);
1010
	for (uint keynr=0 ; keynr < table->s->keys ; keynr++)
unknown's avatar
unknown committed
1011 1012 1013 1014
	{
	  if (keynr == primary_key)
	    continue;
	  if ((error=key_file[keynr]->put(key_file[keynr], sub_trans,
1015 1016
					  create_key(&key, keynr, key_buff2,
						     record),
unknown's avatar
unknown committed
1017 1018 1019 1020 1021
					  &prim_key, key_type[keynr])))
	  {
	    last_dup_key=keynr;
	    break;
	  }
1022
	  changed_keys.set_bit(keynr);
unknown's avatar
unknown committed
1023 1024
	}
      }
unknown's avatar
unknown committed
1025 1026
      else
	last_dup_key=primary_key;
1027
      if (error)
unknown's avatar
unknown committed
1028 1029 1030
      {
	/* Remove inserted row */
	DBUG_PRINT("error",("Got error %d",error));
1031
	if (using_ignore)
unknown's avatar
unknown committed
1032
	{
1033
	  int new_error = 0;
unknown's avatar
unknown committed
1034
	  if (!changed_keys.is_clear_all())
1035 1036
	  {
	    new_error = 0;
1037 1038
	    for (uint keynr=0;
                 keynr < table->s->keys+test(hidden_primary_key);
unknown's avatar
unknown committed
1039
                 keynr++)
1040
	    {
unknown's avatar
unknown committed
1041
	      if (changed_keys.is_set(keynr))
1042 1043
	      {
		if ((new_error = remove_key(sub_trans, keynr, record,
1044
					    &prim_key)))
1045
		  break; /* purecov: inspected */
1046 1047 1048 1049 1050
	      }
	    }
	  }
	  if (new_error)
	  {
1051 1052
	    error=new_error;			// This shouldn't happen /* purecov: inspected */
	    break; /* purecov: inspected */
1053
	  }
unknown's avatar
unknown committed
1054 1055 1056 1057 1058 1059
	}
      }
      if (error != DB_LOCK_DEADLOCK)
	break;
    }
  }
1060
  table->insert_or_update= 0;
unknown's avatar
unknown committed
1061 1062
  if (error == DB_KEYEXIST)
    error=HA_ERR_FOUND_DUPP_KEY;
1063 1064
  else if (!error)
    changed_rows++;
unknown's avatar
unknown committed
1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076
  DBUG_RETURN(error);
}


/* Compare if a key in a row has changed */

int ha_berkeley::key_cmp(uint keynr, const byte * old_row,
			 const byte * new_row)
{
  KEY_PART_INFO *key_part=table->key_info[keynr].key_part;
  KEY_PART_INFO *end=key_part+table->key_info[keynr].key_parts;

1077
  for (; key_part != end ; key_part++)
unknown's avatar
unknown committed
1078 1079 1080 1081 1082 1083 1084
  {
    if (key_part->null_bit)
    {
      if ((old_row[key_part->null_offset] & key_part->null_bit) !=
	  (new_row[key_part->null_offset] & key_part->null_bit))
	return 1;
    }
1085
    if (key_part->key_part_flag & (HA_BLOB_PART | HA_VAR_LENGTH_PART))
unknown's avatar
unknown committed
1086
    {
unknown's avatar
unknown committed
1087

1088 1089
      if (key_part->field->cmp_binary((char*) (old_row + key_part->offset),
				      (char*) (new_row + key_part->offset),
unknown's avatar
unknown committed
1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105
				      (ulong) key_part->length))
	return 1;
    }
    else
    {
      if (memcmp(old_row+key_part->offset, new_row+key_part->offset,
		 key_part->length))
	return 1;
    }
  }
  return 0;
}


/*
  Update a row from one value to another.
1106
  Clobbers key_buff2
unknown's avatar
unknown committed
1107 1108 1109
*/

int ha_berkeley::update_primary_key(DB_TXN *trans, bool primary_key_changed,
1110 1111
				    const byte * old_row, DBT *old_key,
				    const byte * new_row, DBT *new_key,
1112
                                    bool local_using_ignore)
unknown's avatar
unknown committed
1113
{
1114
  DBT row;
1115
  int error;
unknown's avatar
unknown committed
1116 1117 1118 1119 1120 1121
  DBUG_ENTER("update_primary_key");

  if (primary_key_changed)
  {
    // Primary key changed or we are updating a key that can have duplicates.
    // Delete the old row and add a new one
1122
    if (!(error=remove_key(trans, primary_key, old_row, old_key)))
unknown's avatar
unknown committed
1123
    {
1124 1125 1126 1127 1128 1129 1130
      if (!(error=pack_row(&row, new_row, 0)))
      {
	if ((error=file->put(file, trans, new_key, &row,
			     key_type[primary_key])))
	{
	  // Probably a duplicated key; restore old key and row if needed
	  last_dup_key=primary_key;
unknown's avatar
unknown committed
1131
	  if (local_using_ignore)
1132 1133 1134 1135 1136
	  {
	    int new_error;
	    if ((new_error=pack_row(&row, old_row, 0)) ||
		(new_error=file->put(file, trans, old_key, &row,
				     key_type[primary_key])))
1137
	      error=new_error;                  // fatal error /* purecov: inspected */
1138 1139 1140
	  }
	}
      }
unknown's avatar
unknown committed
1141 1142 1143 1144 1145
    }
  }
  else
  {
    // Primary key didn't change;  just update the row data
1146 1147
    if (!(error=pack_row(&row, new_row, 0)))
      error=file->put(file, trans, new_key, &row, 0);
unknown's avatar
unknown committed
1148
  }
1149
  DBUG_RETURN(error);
unknown's avatar
unknown committed
1150 1151
}

1152 1153 1154 1155 1156 1157
/*
  Restore changed keys, when a non-fatal error aborts the insert/update
  of one row.
  Clobbers keybuff2
*/

unknown's avatar
unknown committed
1158
int ha_berkeley::restore_keys(DB_TXN *trans, key_map *changed_keys,
1159 1160
			      uint primary_key,
			      const byte *old_row, DBT *old_key,
1161
			      const byte *new_row, DBT *new_key)
1162 1163 1164
{
  int error;
  DBT tmp_key;
1165
  uint keynr;
1166 1167 1168 1169 1170
  DBUG_ENTER("restore_keys");

  /* Restore the old primary key, and the old row, but don't ignore
     duplicate key failure */
  if ((error=update_primary_key(trans, TRUE, new_row, new_key,
1171
				old_row, old_key, FALSE)))
1172
    goto err; /* purecov: inspected */
1173 1174 1175 1176 1177 1178

  /* Remove the new key, and put back the old key
     changed_keys is a map of all non-primary keys that need to be
     rolled back.  The last key set in changed_keys is the one that
     triggered the duplicate key error (it wasn't inserted), so for
     that one just put back the old value. */
unknown's avatar
unknown committed
1179
  if (!changed_keys->is_clear_all())
1180
  {
1181
    for (keynr=0 ; keynr < table->s->keys+test(hidden_primary_key) ; keynr++)
1182
    {
unknown's avatar
unknown committed
1183
      if (changed_keys->is_set(keynr))
unknown's avatar
unknown committed
1184
      {
unknown's avatar
unknown committed
1185
        if (changed_keys->is_prefix(1) &&
unknown's avatar
unknown committed
1186 1187 1188 1189 1190 1191 1192 1193
            (error = remove_key(trans, keynr, new_row, new_key)))
          break; /* purecov: inspected */
        if ((error = key_file[keynr]->put(key_file[keynr], trans,
                                          create_key(&tmp_key, keynr, key_buff2,
                                                     old_row),
                                          old_key, key_type[keynr])))
          break; /* purecov: inspected */
      }
1194 1195
    }
  }
unknown's avatar
unknown committed
1196

1197
err:
unknown's avatar
unknown committed
1198
  DBUG_ASSERT(error != DB_KEYEXIST);
1199 1200
  DBUG_RETURN(error);
}
unknown's avatar
unknown committed
1201 1202 1203 1204


int ha_berkeley::update_row(const byte * old_row, byte * new_row)
{
1205
  DBT prim_key, key, old_prim_key;
unknown's avatar
unknown committed
1206 1207 1208 1209
  int error;
  DB_TXN *sub_trans;
  bool primary_key_changed;
  DBUG_ENTER("update_row");
unknown's avatar
unknown committed
1210
  LINT_INIT(error);
unknown's avatar
unknown committed
1211

1212
  statistic_increment(table->in_use->status_var.ha_update_count,&LOCK_status);
1213 1214
  if (table->timestamp_field_type & TIMESTAMP_AUTO_SET_ON_UPDATE)
    table->timestamp_field->set_time();
1215

1216
  table->insert_or_update= 1;                   // For handling of VARCHAR
1217 1218 1219 1220 1221 1222
  if (hidden_primary_key)
  {
    primary_key_changed=0;
    bzero((char*) &prim_key,sizeof(prim_key));
    prim_key.data= (void*) current_ident;
    prim_key.size=BDB_HIDDEN_PRIMARY_KEY_LENGTH;
unknown's avatar
unknown committed
1223
    old_prim_key=prim_key;
1224 1225 1226
  }
  else
  {
1227
    create_key(&prim_key, primary_key, key_buff, new_row);
unknown's avatar
unknown committed
1228

1229
    if ((primary_key_changed=key_cmp(primary_key, old_row, new_row)))
1230
      create_key(&old_prim_key, primary_key, primary_key_buff, old_row);
1231 1232 1233
    else
      old_prim_key=prim_key;
  }
unknown's avatar
unknown committed
1234

1235
  sub_trans = transaction;
unknown's avatar
unknown committed
1236 1237
  for (uint retry=0 ; retry < berkeley_trans_retry ; retry++)
  {
unknown's avatar
unknown committed
1238
    key_map changed_keys(0);
unknown's avatar
unknown committed
1239 1240
    /* Start by updating the primary key */
    if (!(error=update_primary_key(sub_trans, primary_key_changed,
1241 1242
				   old_row, &old_prim_key,
				   new_row, &prim_key,
1243
				   using_ignore)))
unknown's avatar
unknown committed
1244 1245
    {
      // Update all other keys
1246
      for (uint keynr=0 ; keynr < table->s->keys ; keynr++)
unknown's avatar
unknown committed
1247 1248 1249 1250 1251
      {
	if (keynr == primary_key)
	  continue;
	if (key_cmp(keynr, old_row, new_row) || primary_key_changed)
	{
1252
	  if ((error=remove_key(sub_trans, keynr, old_row, &old_prim_key)))
1253
	  {
1254
            table->insert_or_update= 0;
1255
	    DBUG_RETURN(error);			// Fatal error /* purecov: inspected */
1256
	  }
1257
	  changed_keys.set_bit(keynr);
1258
	  if ((error=key_file[keynr]->put(key_file[keynr], sub_trans,
1259
					  create_key(&key, keynr, key_buff2,
1260
						     new_row),
unknown's avatar
unknown committed
1261 1262 1263 1264 1265 1266 1267 1268
					  &prim_key, key_type[keynr])))
	  {
	    last_dup_key=keynr;
	    break;
	  }
	}
      }
    }
1269
    if (error)
unknown's avatar
unknown committed
1270 1271
    {
      /* Remove inserted row */
1272 1273 1274 1275
      DBUG_PRINT("error",("Got error %d",error));
      if (using_ignore)
      {
	int new_error = 0;
unknown's avatar
unknown committed
1276
        if (!changed_keys.is_clear_all())
unknown's avatar
unknown committed
1277
	  new_error=restore_keys(transaction, &changed_keys, primary_key,
1278
				 old_row, &old_prim_key, new_row, &prim_key);
1279 1280
	if (new_error)
	{
1281 1282 1283
          /* This shouldn't happen */
	  error=new_error;			/* purecov: inspected */
	  break;                                /* purecov: inspected */
1284 1285 1286
	}
      }
    }
unknown's avatar
unknown committed
1287 1288 1289
    if (error != DB_LOCK_DEADLOCK)
      break;
  }
1290
  table->insert_or_update= 0;
unknown's avatar
unknown committed
1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302
  if (error == DB_KEYEXIST)
    error=HA_ERR_FOUND_DUPP_KEY;
  DBUG_RETURN(error);
}


/*
  Delete one key
  This uses key_buff2, when keynr != primary key, so it's important that
  a function that calls this doesn't use this buffer for anything else.
*/

1303
int ha_berkeley::remove_key(DB_TXN *trans, uint keynr, const byte *record,
unknown's avatar
unknown committed
1304 1305 1306 1307 1308 1309 1310
			    DBT *prim_key)
{
  int error;
  DBT key;
  DBUG_ENTER("remove_key");
  DBUG_PRINT("enter",("index: %d",keynr));

unknown's avatar
unknown committed
1311 1312 1313 1314 1315
  if (keynr == active_index && cursor)
    error=cursor->c_del(cursor,0);
  else if (keynr == primary_key ||
	   ((table->key_info[keynr].flags & (HA_NOSAME | HA_NULL_PART_KEY)) ==
	    HA_NOSAME))
unknown's avatar
unknown committed
1316
  {						// Unique key
unknown's avatar
unknown committed
1317
    DBUG_ASSERT(keynr == primary_key || prim_key->data != key_buff2);
1318
    error=key_file[keynr]->del(key_file[keynr], trans,
unknown's avatar
unknown committed
1319 1320
			       keynr == primary_key ?
			       prim_key :
1321
			       create_key(&key, keynr, key_buff2, record),
unknown's avatar
unknown committed
1322 1323 1324 1325 1326 1327 1328 1329 1330
			       0);
  }
  else
  {
    /*
      To delete the not duplicated key, we need to open an cursor on the
      row to find the key to be delete and delete it.
      We will never come here with keynr = primary_key
    */
unknown's avatar
unknown committed
1331
    DBUG_ASSERT(keynr != primary_key && prim_key->data != key_buff2);
unknown's avatar
unknown committed
1332
    DBC *tmp_cursor;
1333 1334
    if (!(error=key_file[keynr]->cursor(key_file[keynr], trans,
					&tmp_cursor, 0)))
unknown's avatar
unknown committed
1335
    {
1336
      if (!(error=tmp_cursor->c_get(tmp_cursor,
1337 1338
                                    create_key(&key, keynr, key_buff2, record),
                                    prim_key, DB_GET_BOTH | DB_RMW)))
unknown's avatar
unknown committed
1339
      {					// This shouldn't happen
unknown's avatar
unknown committed
1340
	error=tmp_cursor->c_del(tmp_cursor,0);
unknown's avatar
unknown committed
1341
      }
unknown's avatar
unknown committed
1342
      int result=tmp_cursor->c_close(tmp_cursor);
unknown's avatar
unknown committed
1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353
      if (!error)
	error=result;
    }
  }
  DBUG_RETURN(error);
}


/* Delete all keys for new_record */

int ha_berkeley::remove_keys(DB_TXN *trans, const byte *record,
unknown's avatar
unknown committed
1354
			     DBT *new_record, DBT *prim_key, key_map *keys)
unknown's avatar
unknown committed
1355
{
1356
  int result = 0;
1357 1358 1359
  for (uint keynr=0;
       keynr < table->s->keys+test(hidden_primary_key);
       keynr++)
unknown's avatar
unknown committed
1360
  {
unknown's avatar
unknown committed
1361
    if (keys->is_set(keynr))
unknown's avatar
unknown committed
1362
    {
1363
      int new_error=remove_key(trans, keynr, record, prim_key);
unknown's avatar
unknown committed
1364 1365
      if (new_error)
      {
1366 1367
	result=new_error;			// Return last error /* purecov: inspected */
	break;					// Let rollback correct things /* purecov: inspected */
unknown's avatar
unknown committed
1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378
      }
    }
  }
  return result;
}


int ha_berkeley::delete_row(const byte * record)
{
  int error;
  DBT row, prim_key;
1379
  key_map keys= table->s->keys_in_use;
unknown's avatar
unknown committed
1380
  DBUG_ENTER("delete_row");
1381
  statistic_increment(table->in_use->status_var.ha_delete_count,&LOCK_status);
unknown's avatar
unknown committed
1382

1383
  if ((error=pack_row(&row, record, 0)))
1384
    DBUG_RETURN((error)); /* purecov: inspected */
1385
  create_key(&prim_key, primary_key, key_buff, record);
1386
  if (hidden_primary_key)
1387
    keys.set_bit(primary_key);
1388

1389 1390 1391
  /* Subtransactions may be used in order to retry the delete in
     case we get a DB_LOCK_DEADLOCK error. */
  DB_TXN *sub_trans = transaction;
unknown's avatar
unknown committed
1392 1393
  for (uint retry=0 ; retry < berkeley_trans_retry ; retry++)
  {
unknown's avatar
unknown committed
1394
    error=remove_keys(sub_trans, record, &row, &prim_key, &keys);
unknown's avatar
unknown committed
1395
    if (error)
1396
    { /* purecov: inspected */
unknown's avatar
unknown committed
1397
      DBUG_PRINT("error",("Got error %d",error));
unknown's avatar
unknown committed
1398
      break;                                    // No retry - return error
unknown's avatar
unknown committed
1399 1400 1401 1402
    }
    if (error != DB_LOCK_DEADLOCK)
      break;
  }
unknown's avatar
unknown committed
1403
#ifdef CANT_COUNT_DELETED_ROWS
1404 1405
  if (!error)
    changed_rows--;
unknown's avatar
unknown committed
1406
#endif
1407
  DBUG_RETURN(error);
unknown's avatar
unknown committed
1408 1409 1410
}


1411
int ha_berkeley::index_init(uint keynr, bool sorted)
unknown's avatar
unknown committed
1412 1413
{
  int error;
1414
  DBUG_ENTER("ha_berkeley::index_init");
1415
  DBUG_PRINT("enter",("table: '%s'  key: %d", table->s->table_name, keynr));
unknown's avatar
unknown committed
1416 1417 1418 1419 1420 1421

  /*
    Under some very rare conditions (like full joins) we may already have
    an active cursor at this point
  */
  if (cursor)
unknown's avatar
unknown committed
1422 1423
  {
    DBUG_PRINT("note",("Closing active cursor"));
unknown's avatar
unknown committed
1424
    cursor->c_close(cursor);
unknown's avatar
unknown committed
1425
  }
unknown's avatar
unknown committed
1426
  active_index=keynr;
1427 1428 1429 1430
  if ((error=key_file[keynr]->cursor(key_file[keynr], transaction, &cursor,
				     table->reginfo.lock_type >
				     TL_WRITE_ALLOW_READ ?
				     0 : 0)))
unknown's avatar
unknown committed
1431
    cursor=0;				// Safety /* purecov: inspected */
unknown's avatar
unknown committed
1432 1433 1434 1435 1436 1437 1438
  bzero((char*) &last_key,sizeof(last_key));
  DBUG_RETURN(error);
}

int ha_berkeley::index_end()
{
  int error=0;
1439
  DBUG_ENTER("ha_berkely::index_end");
unknown's avatar
unknown committed
1440 1441
  if (cursor)
  {
1442
    DBUG_PRINT("enter",("table: '%s'", table->s->table_name));
unknown's avatar
unknown committed
1443 1444 1445
    error=cursor->c_close(cursor);
    cursor=0;
  }
unknown's avatar
unknown committed
1446
  active_index=MAX_KEY;
unknown's avatar
unknown committed
1447 1448 1449 1450 1451 1452 1453
  DBUG_RETURN(error);
}


/* What to do after we have read a row based on an index */

int ha_berkeley::read_row(int error, char *buf, uint keynr, DBT *row,
1454
			  DBT *found_key, bool read_next)
unknown's avatar
unknown committed
1455
{
1456
  DBUG_ENTER("ha_berkeley::read_row");
unknown's avatar
unknown committed
1457 1458 1459 1460 1461 1462 1463
  if (error)
  {
    if (error == DB_NOTFOUND || error == DB_KEYEMPTY)
      error=read_next ? HA_ERR_END_OF_FILE : HA_ERR_KEY_NOT_FOUND;
    table->status=STATUS_NOT_FOUND;
    DBUG_RETURN(error);
  }
1464 1465 1466 1467 1468
  if (hidden_primary_key)
    memcpy_fixed(current_ident,
		 (char*) row->data+row->size-BDB_HIDDEN_PRIMARY_KEY_LENGTH,
		 BDB_HIDDEN_PRIMARY_KEY_LENGTH);
  table->status=0;
unknown's avatar
unknown committed
1469 1470
  if (keynr != primary_key)
  {
1471 1472 1473 1474 1475 1476 1477 1478 1479
    /* We only found the primary key.  Now we have to use this to find
       the row data */
    if (key_read && found_key)
    {
      unpack_key(buf,found_key,keynr);
      if (!hidden_primary_key)
	unpack_key(buf,row,primary_key);
      DBUG_RETURN(0);
    }
unknown's avatar
unknown committed
1480 1481
    DBT key;
    bzero((char*) &key,sizeof(key));
1482
    key.data=key_buff;
unknown's avatar
unknown committed
1483
    key.size=row->size;
1484
    key.app_private= (void*) (table->key_info+primary_key);
1485
    memcpy(key_buff,row->data,row->size);
unknown's avatar
unknown committed
1486 1487 1488 1489
    /* Read the data into current_row */
    current_row.flags=DB_DBT_REALLOC;
    if ((error=file->get(file, transaction, &key, &current_row, 0)))
    {
1490 1491
      table->status=STATUS_NOT_FOUND; /* purecov: inspected */
      DBUG_RETURN(error == DB_NOTFOUND ? HA_ERR_CRASHED : error); /* purecov: inspected */
unknown's avatar
unknown committed
1492 1493 1494 1495 1496 1497 1498 1499
    }
    row= &current_row;
  }
  unpack_row(buf,row);
  DBUG_RETURN(0);
}


1500 1501
/* This is only used to read whole keys */

unknown's avatar
unknown committed
1502 1503 1504
int ha_berkeley::index_read_idx(byte * buf, uint keynr, const byte * key,
				uint key_len, enum ha_rkey_function find_flag)
{
1505
  table->in_use->status_var.ha_read_key_count++;
unknown's avatar
unknown committed
1506 1507
  DBUG_ENTER("index_read_idx");
  current_row.flags=DB_DBT_REALLOC;
unknown's avatar
unknown committed
1508
  active_index=MAX_KEY;
1509
  DBUG_RETURN(read_row(key_file[keynr]->get(key_file[keynr], transaction,
unknown's avatar
unknown committed
1510 1511 1512
				 pack_key(&last_key, keynr, key_buff, key,
					  key_len),
				 &current_row,0),
1513
		       (char*) buf, keynr, &current_row, &last_key, 0));
unknown's avatar
unknown committed
1514 1515 1516 1517 1518 1519 1520
}


int ha_berkeley::index_read(byte * buf, const byte * key,
			    uint key_len, enum ha_rkey_function find_flag)
{
  DBT row;
1521
  int error;
1522
  KEY *key_info= &table->key_info[active_index];
1523
  int do_prev= 0;
1524
  DBUG_ENTER("ha_berkeley::index_read");
1525

1526
  table->in_use->status_var.ha_read_key_count++;
unknown's avatar
unknown committed
1527
  bzero((char*) &row,sizeof(row));
1528 1529 1530 1531 1532 1533 1534 1535 1536 1537
  if (find_flag == HA_READ_BEFORE_KEY)
  {
    find_flag= HA_READ_KEY_OR_NEXT;
    do_prev= 1;
  }
  else if (find_flag == HA_READ_PREFIX_LAST_OR_PREV)
  {
    find_flag= HA_READ_AFTER_KEY;
    do_prev= 1;
  }
1538
  if (key_len == key_info->key_length &&
1539
      !(table->key_info[active_index].flags & HA_END_SPACE_KEY))
1540
  {
1541 1542
    if (find_flag == HA_READ_AFTER_KEY)
      key_info->handler.bdb_return_if_eq= 1;
1543 1544 1545 1546
    error=read_row(cursor->c_get(cursor, pack_key(&last_key,
						  active_index,
						  key_buff,
						  key, key_len),
1547 1548 1549
				 &row,
				 (find_flag == HA_READ_KEY_EXACT ?
				  DB_SET : DB_SET_RANGE)),
1550
		   (char*) buf, active_index, &row, (DBT*) 0, 0);
1551
    key_info->handler.bdb_return_if_eq= 0;
1552 1553 1554 1555 1556 1557
  }
  else
  {
    /* read of partial key */
    pack_key(&last_key, active_index, key_buff, key, key_len);
    /* Store for compare */
1558
    memcpy(key_buff2, key_buff, (key_len=last_key.size));
1559 1560 1561 1562 1563 1564
    /*
      If HA_READ_AFTER_KEY is set, return next key, else return first
      matching key.
    */
    key_info->handler.bdb_return_if_eq= (find_flag == HA_READ_AFTER_KEY ?
					 1 : -1);
1565
    error=read_row(cursor->c_get(cursor, &last_key, &row, DB_SET_RANGE),
1566
		   (char*) buf, active_index, &row, (DBT*) 0, 0);
1567
    key_info->handler.bdb_return_if_eq= 0;
1568 1569
    if (!error && find_flag == HA_READ_KEY_EXACT)
    {
1570 1571
      /* Ensure that we found a key that is equal to the current one */
      if (!error && berkeley_key_cmp(table, key_info, key_buff2, key_len))
1572 1573 1574
	error=HA_ERR_KEY_NOT_FOUND;
    }
  }
1575 1576 1577 1578 1579
  if (do_prev)
  {
    bzero((char*) &row, sizeof(row));
    error= read_row(cursor->c_get(cursor, &last_key, &row, DB_PREV),
                         (char*) buf, active_index, &row, &last_key, 1);
unknown's avatar
unknown committed
1580
  }
1581
  DBUG_RETURN(error);
unknown's avatar
unknown committed
1582 1583
}

1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595
/*
  Read last key is solved by reading the next key and then reading
  the previous key
*/

int ha_berkeley::index_read_last(byte * buf, const byte * key, uint key_len)
{
  DBT row;
  int error;
  KEY *key_info= &table->key_info[active_index];
  DBUG_ENTER("ha_berkeley::index_read");

1596 1597
  statistic_increment(table->in_use->status_var.ha_read_key_count,
		      &LOCK_status);
1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615
  bzero((char*) &row,sizeof(row));

  /* read of partial key */
  pack_key(&last_key, active_index, key_buff, key, key_len);
  /* Store for compare */
  memcpy(key_buff2, key_buff, (key_len=last_key.size));
  key_info->handler.bdb_return_if_eq= 1;
  error=read_row(cursor->c_get(cursor, &last_key, &row, DB_SET_RANGE),
		 (char*) buf, active_index, &row, (DBT*) 0, 0);
  key_info->handler.bdb_return_if_eq= 0;
  bzero((char*) &row,sizeof(row));
  if (read_row(cursor->c_get(cursor, &last_key, &row, DB_PREV),
	       (char*) buf, active_index, &row, &last_key, 1) ||
      berkeley_key_cmp(table, key_info, key_buff2, key_len))
    error=HA_ERR_KEY_NOT_FOUND;
  DBUG_RETURN(error);
}

unknown's avatar
unknown committed
1616 1617 1618 1619 1620

int ha_berkeley::index_next(byte * buf)
{
  DBT row;
  DBUG_ENTER("index_next");
1621 1622
  statistic_increment(table->in_use->status_var.ha_read_next_count,
		      &LOCK_status);
unknown's avatar
unknown committed
1623 1624
  bzero((char*) &row,sizeof(row));
  DBUG_RETURN(read_row(cursor->c_get(cursor, &last_key, &row, DB_NEXT),
1625
		       (char*) buf, active_index, &row, &last_key, 1));
unknown's avatar
unknown committed
1626 1627 1628 1629 1630 1631 1632
}

int ha_berkeley::index_next_same(byte * buf, const byte *key, uint keylen)
{
  DBT row;
  int error;
  DBUG_ENTER("index_next_same");
1633 1634
  statistic_increment(table->in_use->status_var.ha_read_next_count,
		      &LOCK_status);
unknown's avatar
unknown committed
1635
  bzero((char*) &row,sizeof(row));
1636
  if (keylen == table->key_info[active_index].key_length &&
1637
      !(table->key_info[active_index].flags & HA_END_SPACE_KEY))
unknown's avatar
unknown committed
1638
    error=read_row(cursor->c_get(cursor, &last_key, &row, DB_NEXT_DUP),
1639
		   (char*) buf, active_index, &row, &last_key, 1);
unknown's avatar
unknown committed
1640 1641 1642
  else
  {
    error=read_row(cursor->c_get(cursor, &last_key, &row, DB_NEXT),
1643
		   (char*) buf, active_index, &row, &last_key, 1);
unknown's avatar
unknown committed
1644
    if (!error && ::key_cmp_if_same(table, key, active_index, keylen))
unknown's avatar
unknown committed
1645 1646 1647 1648 1649 1650 1651 1652 1653 1654
      error=HA_ERR_END_OF_FILE;
  }
  DBUG_RETURN(error);
}


int ha_berkeley::index_prev(byte * buf)
{
  DBT row;
  DBUG_ENTER("index_prev");
1655 1656
  statistic_increment(table->in_use->status_var.ha_read_prev_count,
		      &LOCK_status);
unknown's avatar
unknown committed
1657 1658
  bzero((char*) &row,sizeof(row));
  DBUG_RETURN(read_row(cursor->c_get(cursor, &last_key, &row, DB_PREV),
1659
		       (char*) buf, active_index, &row, &last_key, 1));
unknown's avatar
unknown committed
1660
}
unknown's avatar
unknown committed
1661

unknown's avatar
unknown committed
1662 1663 1664 1665 1666

int ha_berkeley::index_first(byte * buf)
{
  DBT row;
  DBUG_ENTER("index_first");
1667 1668
  statistic_increment(table->in_use->status_var.ha_read_first_count,
		      &LOCK_status);
unknown's avatar
unknown committed
1669 1670
  bzero((char*) &row,sizeof(row));
  DBUG_RETURN(read_row(cursor->c_get(cursor, &last_key, &row, DB_FIRST),
1671
		       (char*) buf, active_index, &row, &last_key, 1));
unknown's avatar
unknown committed
1672 1673 1674 1675 1676 1677
}

int ha_berkeley::index_last(byte * buf)
{
  DBT row;
  DBUG_ENTER("index_last");
1678 1679
  statistic_increment(table->in_use->status_var.ha_read_last_count,
		      &LOCK_status);
unknown's avatar
unknown committed
1680 1681
  bzero((char*) &row,sizeof(row));
  DBUG_RETURN(read_row(cursor->c_get(cursor, &last_key, &row, DB_LAST),
1682
		       (char*) buf, active_index, &row, &last_key, 0));
unknown's avatar
unknown committed
1683 1684 1685 1686
}

int ha_berkeley::rnd_init(bool scan)
{
1687
  DBUG_ENTER("rnd_init");
unknown's avatar
unknown committed
1688
  current_row.flags=DB_DBT_REALLOC;
1689
  DBUG_RETURN(index_init(primary_key, 0));
unknown's avatar
unknown committed
1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700
}

int ha_berkeley::rnd_end()
{
  return index_end();
}

int ha_berkeley::rnd_next(byte *buf)
{
  DBT row;
  DBUG_ENTER("rnd_next");
1701 1702
  statistic_increment(table->in_use->status_var.ha_read_rnd_next_count,
		      &LOCK_status);
unknown's avatar
unknown committed
1703 1704
  bzero((char*) &row,sizeof(row));
  DBUG_RETURN(read_row(cursor->c_get(cursor, &last_key, &row, DB_NEXT),
1705
		       (char*) buf, primary_key, &row, &last_key, 1));
unknown's avatar
unknown committed
1706 1707 1708 1709 1710
}


DBT *ha_berkeley::get_pos(DBT *to, byte *pos)
{
1711
  /* We don't need to set app_private here */
unknown's avatar
unknown committed
1712 1713 1714
  bzero((char*) to,sizeof(*to));

  to->data=pos;
1715
  if (share->fixed_length_primary_key)
unknown's avatar
unknown committed
1716 1717 1718 1719 1720 1721
    to->size=ref_length;
  else
  {
    KEY_PART_INFO *key_part=table->key_info[primary_key].key_part;
    KEY_PART_INFO *end=key_part+table->key_info[primary_key].key_parts;

1722
    for (; key_part != end ; key_part++)
1723
      pos+=key_part->field->packed_col_length((char*) pos,key_part->length);
unknown's avatar
unknown committed
1724 1725
    to->size= (uint) (pos- (byte*) to->data);
  }
1726
  DBUG_DUMP("key", (char*) to->data, to->size);
unknown's avatar
unknown committed
1727 1728 1729 1730 1731 1732 1733
  return to;
}


int ha_berkeley::rnd_pos(byte * buf, byte *pos)
{
  DBT db_pos;
1734
  
1735
  DBUG_ENTER("ha_berkeley::rnd_pos");
1736 1737
  statistic_increment(table->in_use->status_var.ha_read_rnd_count,
		      &LOCK_status);
unknown's avatar
unknown committed
1738
  active_index= MAX_KEY;
1739 1740 1741 1742
  DBUG_RETURN(read_row(file->get(file, transaction,
				 get_pos(&db_pos, pos),
				 &current_row, 0),
		       (char*) buf, primary_key, &current_row, (DBT*) 0, 0));
unknown's avatar
unknown committed
1743 1744
}

1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766
/*
  Set a reference to the current record in (ref,ref_length).

  SYNOPSIS
    ha_berkeley::position()
    record                      The current record buffer

  DESCRIPTION
    The BDB handler stores the primary key in (ref,ref_length).
    There is either an explicit primary key, or an implicit (hidden)
    primary key.
    During open(), 'ref_length' is calculated as the maximum primary
    key length. When an actual key is shorter than that, the rest of
    the buffer must be cleared out. The row cannot be identified, if
    garbage follows behind the end of the key. There is no length
    field for the current key, so that the whole ref_length is used
    for comparison.

  RETURN
    nothing
*/

unknown's avatar
unknown committed
1767 1768 1769
void ha_berkeley::position(const byte *record)
{
  DBT key;
1770
  DBUG_ENTER("ha_berkeley::position");
1771
  if (hidden_primary_key)
1772 1773
  {
    DBUG_ASSERT(ref_length == BDB_HIDDEN_PRIMARY_KEY_LENGTH);
1774
    memcpy_fixed(ref, (char*) current_ident, BDB_HIDDEN_PRIMARY_KEY_LENGTH);
1775
  }
1776
  else
1777
  {
1778
    create_key(&key, primary_key, (char*) ref, record);
1779 1780 1781 1782
    if (key.size < ref_length)
      bzero(ref + key.size, ref_length - key.size);
  }
  DBUG_VOID_RETURN;
unknown's avatar
unknown committed
1783 1784 1785 1786 1787
}


void ha_berkeley::info(uint flag)
{
1788
  DBUG_ENTER("ha_berkeley::info");
unknown's avatar
unknown committed
1789 1790
  if (flag & HA_STATUS_VARIABLE)
  {
1791
    records = share->rows + changed_rows; // Just to get optimisations right
unknown's avatar
unknown committed
1792 1793
    deleted = 0;
  }
1794 1795 1796
  if ((flag & HA_STATUS_CONST) || version != share->version)
  {
    version=share->version;
1797
    for (uint i=0 ; i < table->s->keys ; i++)
1798 1799 1800 1801 1802
    {
      table->key_info[i].rec_per_key[table->key_info[i].key_parts-1]=
	share->rec_per_key[i];
    }
  }
unknown's avatar
unknown committed
1803
  /* Don't return key if we got an error for the internal primary key */
1804
  if (flag & HA_STATUS_ERRKEY && last_dup_key < table->s->keys)
unknown's avatar
unknown committed
1805
    errkey= last_dup_key;
unknown's avatar
unknown committed
1806 1807 1808 1809 1810 1811
  DBUG_VOID_RETURN;
}


int ha_berkeley::extra(enum ha_extra_function operation)
{
1812 1813 1814 1815
  switch (operation) {
  case HA_EXTRA_RESET:
  case HA_EXTRA_RESET_STATE:
    key_read=0;
1816
    using_ignore=0;
unknown's avatar
unknown committed
1817 1818 1819 1820 1821 1822 1823 1824 1825
    if (current_row.flags & (DB_DBT_MALLOC | DB_DBT_REALLOC))
    {
      current_row.flags=0;
      if (current_row.data)
      {
	free(current_row.data);
	current_row.data=0;
      }
    }
1826 1827 1828 1829 1830 1831 1832
    break;
  case HA_EXTRA_KEYREAD:
    key_read=1;					// Query satisfied with key
    break;
  case HA_EXTRA_NO_KEYREAD:
    key_read=0;
    break;
1833 1834 1835 1836 1837 1838
  case HA_EXTRA_IGNORE_DUP_KEY:
    using_ignore=1;
    break;
  case HA_EXTRA_NO_IGNORE_DUP_KEY:
    using_ignore=0;
    break;
1839 1840 1841
  default:
    break;
  }
unknown's avatar
unknown committed
1842 1843 1844
  return 0;
}

1845

unknown's avatar
unknown committed
1846 1847
int ha_berkeley::reset(void)
{
1848
  ha_berkeley::extra(HA_EXTRA_RESET);
1849
  key_read=0;					// Reset to state after open
unknown's avatar
unknown committed
1850 1851 1852 1853 1854 1855 1856
  return 0;
}


/*
  As MySQL will execute an external lock for every new table it uses
  we can use this to start the transactions.
1857 1858 1859 1860
  If we are in auto_commit mode we just need to start a transaction
  for the statement to be able to rollback the statement.
  If not, we have to start a master transaction if there doesn't exist
  one from before.
unknown's avatar
unknown committed
1861 1862 1863 1864 1865
*/

int ha_berkeley::external_lock(THD *thd, int lock_type)
{
  int error=0;
1866
  berkeley_trx_data *trx=(berkeley_trx_data *)thd->ha_data[berkeley_hton.slot];
unknown's avatar
unknown committed
1867
  DBUG_ENTER("ha_berkeley::external_lock");
1868 1869 1870 1871 1872 1873 1874
  if (!trx)
  {
    thd->ha_data[berkeley_hton.slot]= trx= (berkeley_trx_data *)
      my_malloc(sizeof(*trx), MYF(MY_ZEROFILL));
    if (!trx)
      DBUG_RETURN(1);
  }
unknown's avatar
unknown committed
1875 1876
  if (lock_type != F_UNLCK)
  {
1877
    if (!trx->bdb_lock_count++)
unknown's avatar
unknown committed
1878
    {
1879
      DBUG_ASSERT(trx->stmt == 0);
unknown's avatar
unknown committed
1880
      transaction=0;				// Safety
1881
      /* First table lock, start transaction */
unknown's avatar
unknown committed
1882
      if ((thd->options & (OPTION_NOT_AUTOCOMMIT | OPTION_BEGIN |
1883
                           OPTION_TABLE_LOCK)) && !trx->all)
1884 1885
      {
	/* We have to start a master transaction */
1886 1887
	DBUG_PRINT("trans",("starting transaction all:  options: 0x%lx",
                            (ulong) thd->options));
1888
        if ((error= db_env->txn_begin(db_env, NULL, &trx->all, 0)))
1889
	{
1890 1891
          trx->bdb_lock_count--;        // We didn't get the lock
          DBUG_RETURN(error);
1892
	}
1893
        trans_register_ha(thd, TRUE, &berkeley_hton);
unknown's avatar
unknown committed
1894 1895
	if (thd->in_lock_tables)
	  DBUG_RETURN(0);			// Don't create stmt trans
1896
      }
unknown's avatar
unknown committed
1897
      DBUG_PRINT("trans",("starting transaction stmt"));
1898
      if ((error= db_env->txn_begin(db_env, trx->all, &trx->stmt, 0)))
1899 1900
      {
	/* We leave the possible master transaction open */
1901 1902
        trx->bdb_lock_count--;                  // We didn't get the lock
        DBUG_RETURN(error);
1903
      }
1904
      trans_register_ha(thd, FALSE, &berkeley_hton);
unknown's avatar
unknown committed
1905
    }
1906
    transaction= trx->stmt;
unknown's avatar
unknown committed
1907 1908 1909 1910
  }
  else
  {
    lock.type=TL_UNLOCK;			// Unlocked
1911
    thread_safe_add(share->rows, changed_rows, &share->mutex);
1912
    changed_rows=0;
1913
    if (!--trx->bdb_lock_count)
unknown's avatar
unknown committed
1914
    {
1915
      if (trx->stmt)
unknown's avatar
unknown committed
1916
      {
unknown's avatar
unknown committed
1917
	/*
unknown's avatar
unknown committed
1918
	   F_UNLCK is done without a transaction commit / rollback.
1919 1920
	   This happens if the thread didn't update any rows
	   We must in this case commit the work to keep the row locks
unknown's avatar
unknown committed
1921
	*/
1922
	DBUG_PRINT("trans",("commiting non-updating transaction"));
1923
        error= trx->stmt->commit(trx->stmt,0);
1924
        trx->stmt= transaction= 0;
unknown's avatar
unknown committed
1925 1926 1927 1928
      }
    }
  }
  DBUG_RETURN(error);
unknown's avatar
unknown committed
1929
}
unknown's avatar
unknown committed
1930

unknown's avatar
unknown committed
1931 1932 1933 1934 1935 1936 1937

/*
  When using LOCK TABLE's external_lock is only called when the actual
  TABLE LOCK is done.
  Under LOCK TABLES, each used tables will force a call to start_stmt.
*/

unknown's avatar
unknown committed
1938
int ha_berkeley::start_stmt(THD *thd, thr_lock_type lock_type)
unknown's avatar
unknown committed
1939 1940 1941
{
  int error=0;
  DBUG_ENTER("ha_berkeley::start_stmt");
1942
  berkeley_trx_data *trx=(berkeley_trx_data *)thd->ha_data[berkeley_hton.slot];
unknown's avatar
unknown committed
1943
  DBUG_ASSERT(trx);
1944 1945 1946 1947 1948 1949
  /*
    note that trx->stmt may have been already initialized as start_stmt()
    is called for *each table* not for each storage engine,
    and there could be many bdb tables referenced in the query
  */
  if (!trx->stmt)
unknown's avatar
unknown committed
1950
  {
unknown's avatar
unknown committed
1951
    DBUG_PRINT("trans",("starting transaction stmt"));
1952
    error= db_env->txn_begin(db_env, trx->all, &trx->stmt, 0);
1953
    trans_register_ha(thd, FALSE, &berkeley_hton);
unknown's avatar
unknown committed
1954
  }
1955
  transaction= trx->stmt;
unknown's avatar
unknown committed
1956 1957 1958 1959
  DBUG_RETURN(error);
}


1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987
/*
  The idea with handler::store_lock() is the following:

  The statement decided which locks we should need for the table
  for updates/deletes/inserts we get WRITE locks, for SELECT... we get
  read locks.

  Before adding the lock into the table lock handler (see thr_lock.c)
  mysqld calls store lock with the requested locks.  Store lock can now
  modify a write lock to a read lock (or some other lock), ignore the
  lock (if we don't want to use MySQL table locks at all) or add locks
  for many tables (like we do when we are using a MERGE handler).

  Berkeley DB changes all WRITE locks to TL_WRITE_ALLOW_WRITE (which
  signals that we are doing WRITES, but we are still allowing other
  reader's and writer's.

  When releasing locks, store_lock() are also called. In this case one
  usually doesn't have to do anything.

  In some exceptional cases MySQL may send a request for a TL_IGNORE;
  This means that we are requesting the same lock as last time and this
  should also be ignored. (This may happen when someone does a flush
  table when we have opened a part of the tables, in which case mysqld
  closes and reopens the tables and tries to get the same locks at last
  time).  In the future we will probably try to remove this.
*/

unknown's avatar
unknown committed
1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998

THR_LOCK_DATA **ha_berkeley::store_lock(THD *thd, THR_LOCK_DATA **to,
					enum thr_lock_type lock_type)
{
  if (lock_type != TL_IGNORE && lock.type == TL_UNLOCK)
  {
    /* If we are not doing a LOCK TABLE, then allow multiple writers */
    if ((lock_type >= TL_WRITE_CONCURRENT_INSERT &&
	 lock_type <= TL_WRITE) &&
	!thd->in_lock_tables)
      lock_type = TL_WRITE_ALLOW_WRITE;
unknown's avatar
unknown committed
1999
    lock.type= lock_type;
unknown's avatar
unknown committed
2000 2001 2002 2003 2004 2005 2006 2007 2008
  }
  *to++= &lock;
  return to;
}


static int create_sub_table(const char *table_name, const char *sub_name,
			    DBTYPE type, int flags)
{
2009
  int error;
unknown's avatar
unknown committed
2010 2011
  DB *file;
  DBUG_ENTER("create_sub_table");
unknown's avatar
unknown committed
2012
  DBUG_PRINT("enter",("sub_name: %s  flags: %d",sub_name, flags));
unknown's avatar
unknown committed
2013 2014 2015 2016

  if (!(error=db_create(&file, db_env, 0)))
  {
    file->set_flags(file, flags);
unknown's avatar
unknown committed
2017
    error=(file->open(file, NULL, table_name, sub_name, type,
unknown's avatar
unknown committed
2018 2019 2020
		      DB_THREAD | DB_CREATE, my_umask));
    if (error)
    {
2021 2022 2023
      DBUG_PRINT("error",("Got error: %d when opening table '%s'",error, /* purecov: inspected */
			  table_name)); /* purecov: inspected */
      (void) file->remove(file,table_name,NULL,0); /* purecov: inspected */
unknown's avatar
unknown committed
2024 2025 2026 2027 2028 2029
    }
    else
      (void) file->close(file,0);
  }
  else
  {
2030
    DBUG_PRINT("error",("Got error: %d when creting table",error)); /* purecov: inspected */
unknown's avatar
unknown committed
2031 2032
  }
  if (error)
2033
    my_errno=error; /* purecov: inspected */
unknown's avatar
unknown committed
2034 2035 2036 2037 2038 2039 2040 2041 2042
  DBUG_RETURN(error);
}


int ha_berkeley::create(const char *name, register TABLE *form,
			HA_CREATE_INFO *create_info)
{
  char name_buff[FN_REFLEN];
  char part[7];
2043
  uint index=1;
unknown's avatar
unknown committed
2044
  int error;
unknown's avatar
unknown committed
2045 2046 2047 2048 2049
  DBUG_ENTER("ha_berkeley::create");

  fn_format(name_buff,name,"", ha_berkeley_ext,2 | 4);

  /* Create the main table that will hold the real rows */
unknown's avatar
unknown committed
2050 2051
  if ((error= create_sub_table(name_buff,"main",DB_BTREE,0)))
    DBUG_RETURN(error); /* purecov: inspected */
unknown's avatar
unknown committed
2052

2053
  primary_key= table->s->primary_key;
unknown's avatar
unknown committed
2054
  /* Create the keys */
2055
  for (uint i=0; i < form->s->keys; i++)
unknown's avatar
unknown committed
2056
  {
2057 2058 2059
    if (i != primary_key)
    {
      sprintf(part,"key%02d",index++);
unknown's avatar
unknown committed
2060 2061 2062 2063
      if ((error= create_sub_table(name_buff, part, DB_BTREE,
				   (table->key_info[i].flags & HA_NOSAME) ? 0 :
				   DB_DUP)))
	DBUG_RETURN(error); /* purecov: inspected */
2064
    }
unknown's avatar
unknown committed
2065 2066 2067 2068
  }

  /* Create the status block to save information from last status command */
  /* Is DB_BTREE the best option here ? (QUEUE can't be used in sub tables) */
unknown's avatar
unknown committed
2069 2070

  DB *status_block;
unknown's avatar
unknown committed
2071
  if (!(error=(db_create(&status_block, db_env, 0))))
unknown's avatar
unknown committed
2072
  {
unknown's avatar
unknown committed
2073
    if (!(error=(status_block->open(status_block, NULL, name_buff,
unknown's avatar
unknown committed
2074
				    "status", DB_BTREE, DB_CREATE, 0))))
unknown's avatar
unknown committed
2075 2076
    {
      char rec_buff[4+MAX_KEY*4];
2077
      uint length= 4+ table->s->keys*4;
unknown's avatar
unknown committed
2078
      bzero(rec_buff, length);
unknown's avatar
unknown committed
2079
      error= write_status(status_block, rec_buff, length);
unknown's avatar
unknown committed
2080 2081 2082 2083
      status_block->close(status_block,0);
    }
  }
  DBUG_RETURN(error);
unknown's avatar
unknown committed
2084 2085 2086
}


unknown's avatar
unknown committed
2087

unknown's avatar
unknown committed
2088 2089 2090 2091
int ha_berkeley::delete_table(const char *name)
{
  int error;
  char name_buff[FN_REFLEN];
unknown's avatar
unknown committed
2092
  DBUG_ENTER("delete_table");
unknown's avatar
unknown committed
2093
  if ((error=db_create(&file, db_env, 0)))
2094
    my_errno=error; /* purecov: inspected */
unknown's avatar
unknown committed
2095 2096 2097
  else
    error=file->remove(file,fn_format(name_buff,name,"",ha_berkeley_ext,2 | 4),
		       NULL,0);
unknown's avatar
unknown committed
2098
  file=0;					// Safety
unknown's avatar
unknown committed
2099
  DBUG_RETURN(error);
unknown's avatar
unknown committed
2100 2101
}

2102 2103 2104 2105 2106 2107 2108 2109 2110 2111

int ha_berkeley::rename_table(const char * from, const char * to)
{
  int error;
  char from_buff[FN_REFLEN];
  char to_buff[FN_REFLEN];

  if ((error= db_create(&file, db_env, 0)))
    my_errno= error;
  else
2112 2113
  {
    /* On should not do a file->close() after rename returns */
2114 2115 2116 2117
    error= file->rename(file, 
			fn_format(from_buff, from, "", ha_berkeley_ext, 2 | 4),
			NULL, fn_format(to_buff, to, "", ha_berkeley_ext,
					2 | 4), 0);
2118
  }
2119 2120 2121 2122
  return error;
}


unknown's avatar
unknown committed
2123 2124 2125 2126 2127 2128 2129 2130
/*
  How many seeks it will take to read through the table
  This is to be comparable to the number returned by records_in_range so
  that we can decide if we should scan the table or use keys.
*/

double ha_berkeley::scan_time()
{
2131
  return rows2double(records/3);
2132
}
unknown's avatar
unknown committed
2133

unknown's avatar
unknown committed
2134 2135
ha_rows ha_berkeley::records_in_range(uint keynr, key_range *start_key,
                                      key_range *end_key)
unknown's avatar
unknown committed
2136 2137 2138
{
  DBT key;
  DB_KEY_RANGE start_range, end_range;
2139
  DB *kfile=key_file[keynr];
unknown's avatar
unknown committed
2140
  double start_pos,end_pos,rows;
2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169
  bool error;
  KEY *key_info= &table->key_info[keynr];
  DBUG_ENTER("ha_berkeley::records_in_range");

  /* Ensure we get maximum range, even for varchar keys with different space */
  key_info->handler.bdb_return_if_eq= -1;
  error= ((start_key && kfile->key_range(kfile,transaction,
                                         pack_key(&key, keynr, key_buff,
                                                  start_key->key,
                                                  start_key->length),
                                         &start_range,0)));
  if (error)
  {
    key_info->handler.bdb_return_if_eq= 0;
    // Better than returning an error
    DBUG_RETURN(HA_BERKELEY_RANGE_COUNT);       /* purecov: inspected */
  }
  key_info->handler.bdb_return_if_eq= 1;
  error= (end_key && kfile->key_range(kfile,transaction,
                                      pack_key(&key, keynr, key_buff,
                                               end_key->key,
                                               end_key->length),
                                      &end_range,0));
  key_info->handler.bdb_return_if_eq= 0;
  if (error)
  {
    // Better than returning an error
    DBUG_RETURN(HA_BERKELEY_RANGE_COUNT);       /* purecov: inspected */
  }
unknown's avatar
unknown committed
2170 2171

  if (!start_key)
unknown's avatar
unknown committed
2172 2173
    start_pos= 0.0;
  else if (start_key->flag == HA_READ_KEY_EXACT)
unknown's avatar
unknown committed
2174 2175 2176 2177 2178
    start_pos=start_range.less;
  else
    start_pos=start_range.less+start_range.equal;

  if (!end_key)
unknown's avatar
unknown committed
2179 2180
    end_pos= 1.0;
  else if (end_key->flag == HA_READ_BEFORE_KEY)
unknown's avatar
unknown committed
2181 2182 2183 2184 2185
    end_pos=end_range.less;
  else
    end_pos=end_range.less+end_range.equal;
  rows=(end_pos-start_pos)*records;
  DBUG_PRINT("exit",("rows: %g",rows));
2186
  DBUG_RETURN((ha_rows)(rows <= 1.0 ? 1 : rows));
unknown's avatar
unknown committed
2187 2188
}

2189

2190
ulonglong ha_berkeley::get_auto_increment()
2191
{
2192
  ulonglong nr=1;				// Default if error or new key
2193 2194
  int error;
  (void) ha_berkeley::extra(HA_EXTRA_KEYREAD);
2195 2196

  /* Set 'active_index' */
2197
  ha_berkeley::index_init(table->s->next_number_index, 0);
2198

2199
  if (!table->s->next_number_key_offset)
2200 2201 2202 2203 2204
  {						// Autoincrement at key-start
    error=ha_berkeley::index_last(table->record[1]);
  }
  else
  {
2205
    DBT row,old_key;
2206 2207 2208 2209 2210 2211
    bzero((char*) &row,sizeof(row));
    KEY *key_info= &table->key_info[active_index];

    /* Reading next available number for a sub key */
    ha_berkeley::create_key(&last_key, active_index,
			    key_buff, table->record[0],
2212
			    table->s->next_number_key_offset);
2213
    /* Store for compare */
2214
    memcpy(old_key.data=key_buff2, key_buff, (old_key.size=last_key.size));
2215
    old_key.app_private=(void*) key_info;
2216
    error=1;
2217
    {
2218 2219 2220
      /* Modify the compare so that we will find the next key */
      key_info->handler.bdb_return_if_eq= 1;
      /* We lock the next key as the new key will probl. be on the same page */
unknown's avatar
unknown committed
2221
      error=cursor->c_get(cursor, &last_key, &row, DB_SET_RANGE | DB_RMW);
2222 2223 2224 2225 2226 2227 2228 2229
      key_info->handler.bdb_return_if_eq= 0;
      if (!error || error == DB_NOTFOUND)
      {
	/*
	  Now search go one step back and then we should have found the
	  biggest key with the given prefix
	  */
	error=1;
unknown's avatar
unknown committed
2230 2231 2232
	if (!cursor->c_get(cursor, &last_key, &row, DB_PREV | DB_RMW) &&
	    !berkeley_cmp_packed_key(key_file[active_index], &old_key,
				     &last_key))
2233 2234
	{
	  error=0;				// Found value
2235
	  unpack_key((char*) table->record[1], &last_key, active_index);
2236 2237
	}
      }
2238 2239
    }
  }
2240
  if (!error)
2241 2242
    nr= (ulonglong)
      table->next_number_field->val_int_offset(table->s->rec_buff_length)+1;
2243 2244 2245 2246 2247
  ha_berkeley::index_end();
  (void) ha_berkeley::extra(HA_EXTRA_NO_KEYREAD);
  return nr;
}

unknown's avatar
unknown committed
2248 2249 2250 2251 2252 2253
void ha_berkeley::print_error(int error, myf errflag)
{
  if (error == DB_LOCK_DEADLOCK)
    error=HA_ERR_LOCK_DEADLOCK;
  handler::print_error(error,errflag);
}
2254 2255 2256 2257 2258

/****************************************************************************
	 Analyzing, checking, and optimizing tables
****************************************************************************/

2259
#ifdef NOT_YET
2260 2261 2262
static void print_msg(THD *thd, const char *table_name, const char *op_name,
		      const char *msg_type, const char *fmt, ...)
{
2263
  Protocol *protocol= thd->protocol;
2264 2265 2266 2267 2268 2269 2270 2271 2272
  char msgbuf[256];
  msgbuf[0] = 0;
  va_list args;
  va_start(args,fmt);

  my_vsnprintf(msgbuf, sizeof(msgbuf), fmt, args);
  msgbuf[sizeof(msgbuf) - 1] = 0; // healthy paranoia
  DBUG_PRINT(msg_type,("message: %s",msgbuf));

unknown's avatar
unknown committed
2273
  protocol->set_nfields(4);
2274 2275 2276 2277 2278 2279
  protocol->prepare_for_resend();
  protocol->store(table_name);
  protocol->store(op_name);
  protocol->store(msg_type);
  protocol->store(msgbuf);
  if (protocol->write())
unknown's avatar
SCRUM  
unknown committed
2280
    thd->killed=THD::KILL_CONNECTION;
2281
}
2282
#endif
2283 2284 2285 2286

int ha_berkeley::analyze(THD* thd, HA_CHECK_OPT* check_opt)
{
  uint i;
2287
  DB_BTREE_STAT *stat=0;
unknown's avatar
unknown committed
2288
  DB_TXN_STAT *txn_stat_ptr= 0;
2289
  berkeley_trx_data *trx=(berkeley_trx_data *)thd->ha_data[berkeley_hton.slot];
unknown's avatar
unknown committed
2290
  DBUG_ASSERT(trx);
unknown's avatar
unknown committed
2291

2292 2293 2294 2295 2296 2297 2298 2299 2300
  /*
   Original bdb documentation says:
   "The DB->stat method cannot be transaction-protected.
   For this reason, it should be called in a thread of
   control that has no open cursors or active transactions."
   So, let's check if there are any changes have been done since
   the beginning of the transaction..
  */

unknown's avatar
unknown committed
2301 2302 2303 2304
  if (!db_env->txn_stat(db_env, &txn_stat_ptr, 0) &&
      txn_stat_ptr && txn_stat_ptr->st_nactive>=2)
  {
    DB_TXN_ACTIVE *atxn_stmt= 0, *atxn_all= 0;
unknown's avatar
unknown committed
2305

2306 2307
    u_int32_t all_id= trx->all->id(trx->all);
    u_int32_t stmt_id= trx->stmt->id(trx->stmt);
unknown's avatar
unknown committed
2308

unknown's avatar
unknown committed
2309 2310 2311 2312 2313 2314 2315
    DB_TXN_ACTIVE *cur= txn_stat_ptr->st_txnarray;
    DB_TXN_ACTIVE *end= cur + txn_stat_ptr->st_nactive;
    for (; cur!=end && (!atxn_stmt || !atxn_all); cur++)
    {
      if (cur->txnid==all_id) atxn_all= cur;
      if (cur->txnid==stmt_id) atxn_stmt= cur;
    }
unknown's avatar
unknown committed
2316

unknown's avatar
unknown committed
2317 2318 2319 2320 2321 2322 2323 2324
    if (atxn_stmt && atxn_all &&
	log_compare(&atxn_stmt->lsn,&atxn_all->lsn))
    {
      free(txn_stat_ptr);
      return HA_ADMIN_REJECT;
    }
    free(txn_stat_ptr);
  }
2325

2326
  for (i=0 ; i < table->s->keys ; i++)
2327
  {
unknown's avatar
unknown committed
2328 2329 2330 2331 2332
    if (stat)
    {
      free(stat);
      stat=0;
    }
2333
    if ((key_file[i]->stat)(key_file[i], NULL, (void*) &stat, 0))
2334
      goto err; /* purecov: inspected */
unknown's avatar
unknown committed
2335 2336
    share->rec_per_key[i]= (stat->bt_ndata /
			    (stat->bt_nkeys ? stat->bt_nkeys : 1));
2337
  }
unknown's avatar
unknown committed
2338
  /* A hidden primary key is not in key_file[] */
2339
  if (hidden_primary_key)
unknown's avatar
unknown committed
2340 2341 2342 2343 2344 2345
  {
    if (stat)
    {
      free(stat);
      stat=0;
    }
2346
    if ((file->stat)(file, NULL, (void*) &stat, 0))
2347
      goto err; /* purecov: inspected */
unknown's avatar
unknown committed
2348
  }
2349
  pthread_mutex_lock(&share->mutex);
unknown's avatar
unknown committed
2350
  share->rows=stat->bt_ndata;
2351 2352 2353
  share->status|=STATUS_BDB_ANALYZE;		// Save status on close
  share->version++;				// Update stat in table
  pthread_mutex_unlock(&share->mutex);
unknown's avatar
unknown committed
2354 2355 2356
  update_status(share,table);			// Write status to file
  if (stat)
    free(stat);
2357 2358
  return ((share->status & STATUS_BDB_ANALYZE) ? HA_ADMIN_FAILED :
	  HA_ADMIN_OK);
unknown's avatar
unknown committed
2359 2360

err:
2361 2362 2363
  if (stat) /* purecov: inspected */
    free(stat); /* purecov: inspected */
  return HA_ADMIN_FAILED; /* purecov: inspected */
2364 2365 2366 2367 2368 2369 2370 2371 2372 2373
}

int ha_berkeley::optimize(THD* thd, HA_CHECK_OPT* check_opt)
{
  return ha_berkeley::analyze(thd,check_opt);
}


int ha_berkeley::check(THD* thd, HA_CHECK_OPT* check_opt)
{
unknown's avatar
unknown committed
2374 2375 2376 2377 2378
  DBUG_ENTER("ha_berkeley::check");

  DBUG_RETURN(HA_ADMIN_NOT_IMPLEMENTED);

#ifdef NOT_YET
2379 2380 2381
  char name_buff[FN_REFLEN];
  int error;
  DB *tmp_file;
unknown's avatar
unknown committed
2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399
  /*
    To get this to work we need to ensure that no running transaction is
    using the table. We also need to create a new environment without
    locking for this.
  */

  /* We must open the file again to be able to check it! */
  if ((error=db_create(&tmp_file, db_env, 0)))
  {
    print_msg(thd, table->real_name, "check", "error",
	      "Got error %d creating environment",error);
    DBUG_RETURN(HA_ADMIN_FAILED);
  }

  /* Compare the overall structure */
  tmp_file->set_bt_compare(tmp_file,
			   (hidden_primary_key ? berkeley_cmp_hidden_key :
			    berkeley_cmp_packed_key));
2400
  tmp_file->app_private= (void*) (table->key_info+table->primary_key);
2401
  fn_format(name_buff,share->table_name,"", ha_berkeley_ext, 2 | 4);
unknown's avatar
unknown committed
2402 2403
  if ((error=tmp_file->verify(tmp_file, name_buff, NullS, (FILE*) 0,
			      hidden_primary_key ? 0 : DB_NOORDERCHK)))
2404 2405 2406
  {
    print_msg(thd, table->real_name, "check", "error",
	      "Got error %d checking file structure",error);
unknown's avatar
unknown committed
2407 2408
    tmp_file->close(tmp_file,0);
    DBUG_RETURN(HA_ADMIN_CORRUPT);
2409
  }
unknown's avatar
unknown committed
2410 2411 2412 2413

  /* Check each index */
  tmp_file->set_bt_compare(tmp_file, berkeley_cmp_packed_key);
  for (uint index=0,i=0 ; i < table->keys ; i++)
2414
  {
unknown's avatar
unknown committed
2415 2416 2417 2418 2419 2420 2421 2422
    char part[7];
    if (i == primary_key)
      strmov(part,"main");
    else
      sprintf(part,"key%02d",++index);
    tmp_file->app_private= (void*) (table->key_info+i);
    if ((error=tmp_file->verify(tmp_file, name_buff, part, (FILE*) 0,
				DB_ORDERCHKONLY)))
2423 2424
    {
      print_msg(thd, table->real_name, "check", "error",
unknown's avatar
unknown committed
2425 2426 2427 2428 2429
		"Key %d was not in order (Error: %d)",
		index+ test(i >= primary_key),
		error);
      tmp_file->close(tmp_file,0);
      DBUG_RETURN(HA_ADMIN_CORRUPT);
2430 2431
    }
  }
unknown's avatar
unknown committed
2432 2433 2434
  tmp_file->close(tmp_file,0);
  DBUG_RETURN(HA_ADMIN_OK);
#endif
2435 2436
}

unknown's avatar
unknown committed
2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448
/****************************************************************************
 Handling the shared BDB_SHARE structure that is needed to provide table
 locking.
****************************************************************************/

static byte* bdb_get_key(BDB_SHARE *share,uint *length,
			 my_bool not_used __attribute__((unused)))
{
  *length=share->table_name_length;
  return (byte*) share->table_name;
}

2449
static BDB_SHARE *get_share(const char *table_name, TABLE *table)
unknown's avatar
unknown committed
2450 2451 2452
{
  BDB_SHARE *share;
  pthread_mutex_lock(&bdb_mutex);
unknown's avatar
unknown committed
2453
  uint length=(uint) strlen(table_name);
2454 2455
  if (!(share=(BDB_SHARE*) hash_search(&bdb_open_tables, (byte*) table_name,
				       length)))
unknown's avatar
unknown committed
2456
  {
2457
    ulong *rec_per_key;
2458 2459 2460
    char *tmp_name;
    DB **key_file;
    u_int32_t *key_type;
2461
    uint keys= table->s->keys;
unknown's avatar
unknown committed
2462

2463 2464 2465
    if ((share=(BDB_SHARE *)
	 my_multi_malloc(MYF(MY_WME | MY_ZEROFILL),
			 &share, sizeof(*share),
2466
			 &rec_per_key, keys * sizeof(ha_rows),
2467
			 &tmp_name, length+1,
2468 2469
			 &key_file, (keys+1) * sizeof(*key_file),
			 &key_type, (keys+1) * sizeof(u_int32_t),
2470
			 NullS)))
unknown's avatar
unknown committed
2471
    {
2472 2473
      share->rec_per_key = rec_per_key;
      share->table_name = tmp_name;
unknown's avatar
unknown committed
2474 2475
      share->table_name_length=length;
      strmov(share->table_name,table_name);
2476 2477
      share->key_file = key_file;
      share->key_type = key_type;
unknown's avatar
SCRUM  
unknown committed
2478
      if (my_hash_insert(&bdb_open_tables, (byte*) share))
unknown's avatar
unknown committed
2479
      {
2480 2481 2482
	pthread_mutex_unlock(&bdb_mutex); /* purecov: inspected */
	my_free((gptr) share,0); /* purecov: inspected */
	return 0; /* purecov: inspected */
unknown's avatar
unknown committed
2483 2484
      }
      thr_lock_init(&share->lock);
2485
      pthread_mutex_init(&share->mutex,MY_MUTEX_INIT_FAST);
unknown's avatar
unknown committed
2486 2487 2488 2489 2490 2491
    }
  }
  pthread_mutex_unlock(&bdb_mutex);
  return share;
}

unknown's avatar
unknown committed
2492 2493
static int free_share(BDB_SHARE *share, TABLE *table, uint hidden_primary_key,
		      bool mutex_is_locked)
unknown's avatar
unknown committed
2494
{
2495
  int error, result = 0;
2496
  uint keys= table->s->keys + test(hidden_primary_key);
unknown's avatar
unknown committed
2497
  pthread_mutex_lock(&bdb_mutex);
unknown's avatar
unknown committed
2498
  if (mutex_is_locked)
2499
    pthread_mutex_unlock(&share->mutex); /* purecov: inspected */
unknown's avatar
unknown committed
2500 2501
  if (!--share->use_count)
  {
2502
    DB **key_file = share->key_file;
2503
    update_status(share,table);
2504
    /* this does share->file->close() implicitly */
2505
    for (uint i=0; i < keys; i++)
2506 2507
    {
      if (key_file[i] && (error=key_file[i]->close(key_file[i],0)))
2508
	result=error; /* purecov: inspected */
2509 2510 2511
    }
    if (share->status_block &&
	(error = share->status_block->close(share->status_block,0)))
2512
      result = error; /* purecov: inspected */
2513
    hash_delete(&bdb_open_tables, (byte*) share);
unknown's avatar
unknown committed
2514
    thr_lock_delete(&share->lock);
2515
    pthread_mutex_destroy(&share->mutex);
unknown's avatar
unknown committed
2516 2517 2518
    my_free((gptr) share, MYF(0));
  }
  pthread_mutex_unlock(&bdb_mutex);
2519
  return result;
unknown's avatar
unknown committed
2520 2521
}

2522 2523 2524 2525
/*
  Get status information that is stored in the 'status' sub database
  and the max used value for the hidden primary key.
*/
2526

2527
void ha_berkeley::get_status()
2528
{
2529 2530 2531 2532 2533 2534 2535
  if (!test_all_bits(share->status,(STATUS_PRIMARY_KEY_INIT |
				    STATUS_ROW_COUNT_INIT)))
  {
    pthread_mutex_lock(&share->mutex);
    if (!(share->status & STATUS_PRIMARY_KEY_INIT))
    {
      (void) extra(HA_EXTRA_KEYREAD);
2536
      index_init(primary_key, 0);
2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549
      if (!index_last(table->record[1]))
	share->auto_ident=uint5korr(current_ident);
      index_end();
      (void) extra(HA_EXTRA_NO_KEYREAD);
    }
    if (! share->status_block)
    {
      char name_buff[FN_REFLEN];
      uint open_mode= (((table->db_stat & HA_READ_ONLY) ? DB_RDONLY : 0)
		       | DB_THREAD);
      fn_format(name_buff, share->table_name,"", ha_berkeley_ext, 2 | 4);
      if (!db_create(&share->status_block, db_env, 0))
      {
unknown's avatar
unknown committed
2550
	if (share->status_block->open(share->status_block, NULL, name_buff,
unknown's avatar
unknown committed
2551
				      "status", DB_BTREE, open_mode, 0))
2552
	{
2553 2554
	  share->status_block->close(share->status_block, 0); /* purecov: inspected */
	  share->status_block=0; /* purecov: inspected */
2555 2556 2557 2558 2559
	}
      }
    }
    if (!(share->status & STATUS_ROW_COUNT_INIT) && share->status_block)
    {
2560 2561
      share->org_rows= share->rows=
	table->s->max_rows ? table->s->max_rows : HA_BERKELEY_MAX_ROWS;
2562
      if (!share->status_block->cursor(share->status_block, 0, &cursor, 0))
2563 2564
      {
	DBT row;
unknown's avatar
unknown committed
2565
	char rec_buff[64];
2566 2567 2568
	bzero((char*) &row,sizeof(row));
	bzero((char*) &last_key,sizeof(last_key));
	row.data=rec_buff;
unknown's avatar
unknown committed
2569
	row.ulen=sizeof(rec_buff);
2570 2571 2572 2573
	row.flags=DB_DBT_USERMEM;
	if (!cursor->c_get(cursor, &last_key, &row, DB_FIRST))
	{
	  uint i;
unknown's avatar
unknown committed
2574
	  uchar *pos=(uchar*) row.data;
2575
	  share->org_rows=share->rows=uint4korr(pos); pos+=4;
2576
	  for (i=0 ; i < table->s->keys ; i++)
2577
	  {
2578 2579
	    share->rec_per_key[i]=uint4korr(pos);
            pos+=4;
2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591
	  }
	}
	cursor->c_close(cursor);
      }
      cursor=0;					// Safety
    }
    share->status|= STATUS_PRIMARY_KEY_INIT | STATUS_ROW_COUNT_INIT;
    pthread_mutex_unlock(&share->mutex);
  }
}


unknown's avatar
unknown committed
2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608
static int write_status(DB *status_block, char *buff, uint length)
{
  DBT row,key;
  int error;
  const char *key_buff="status";

  bzero((char*) &row,sizeof(row));
  bzero((char*) &key,sizeof(key));
  row.data=buff;
  key.data=(void*) key_buff;
  key.size=sizeof(key_buff);
  row.size=length;
  error=status_block->put(status_block, 0, &key, &row, 0);
  return error;
}


2609 2610 2611 2612 2613
static void update_status(BDB_SHARE *share, TABLE *table)
{
  DBUG_ENTER("update_status");
  if (share->rows != share->org_rows ||
      (share->status & STATUS_BDB_ANALYZE))
2614
  {
2615 2616 2617 2618 2619 2620 2621 2622
    pthread_mutex_lock(&share->mutex);
    if (!share->status_block)
    {
      /*
	Create sub database 'status' if it doesn't exist from before
	(This '*should*' always exist for table created with MySQL)
      */

2623 2624 2625 2626
      char name_buff[FN_REFLEN]; /* purecov: inspected */
      if (db_create(&share->status_block, db_env, 0)) /* purecov: inspected */
	goto end; /* purecov: inspected */
      share->status_block->set_flags(share->status_block,0); /* purecov: inspected */
unknown's avatar
unknown committed
2627
      if (share->status_block->open(share->status_block, NULL,
2628 2629 2630
				    fn_format(name_buff,share->table_name,"",
					      ha_berkeley_ext,2 | 4),
				    "status", DB_BTREE,
2631 2632
				    DB_THREAD | DB_CREATE, my_umask)) /* purecov: inspected */
	goto end; /* purecov: inspected */
2633 2634
    }
    {
unknown's avatar
unknown committed
2635
      char rec_buff[4+MAX_KEY*4], *pos=rec_buff;
2636
      int4store(pos,share->rows); pos+=4;
2637
      for (uint i=0 ; i < table->s->keys ; i++)
2638 2639 2640
      {
	int4store(pos,share->rec_per_key[i]); pos+=4;
      }
unknown's avatar
unknown committed
2641 2642 2643
      DBUG_PRINT("info",("updating status for %s",share->table_name));
      (void) write_status(share->status_block, rec_buff,
			  (uint) (pos-rec_buff));
2644
      share->status&= ~STATUS_BDB_ANALYZE;
unknown's avatar
unknown committed
2645
      share->org_rows=share->rows;
2646 2647 2648
    }
end:
    pthread_mutex_unlock(&share->mutex);
2649
  }
2650
  DBUG_VOID_RETURN;
2651 2652
}

2653

2654 2655 2656 2657 2658
/*
  Return an estimated of the number of rows in the table.
  Used when sorting to allocate buffers and by the optimizer.
*/

unknown's avatar
unknown committed
2659
ha_rows ha_berkeley::estimate_rows_upper_bound()
2660
{
2661
  return share->rows + HA_BERKELEY_EXTRA_ROWS;
2662 2663
}

2664 2665 2666 2667 2668 2669 2670
int ha_berkeley::cmp_ref(const byte *ref1, const byte *ref2)
{
  if (hidden_primary_key)
    return memcmp(ref1, ref2, BDB_HIDDEN_PRIMARY_KEY_LENGTH);

  int result;
  Field *field;
2671
  KEY *key_info=table->key_info+table->s->primary_key;
2672 2673 2674 2675 2676 2677 2678
  KEY_PART_INFO *key_part=key_info->key_part;
  KEY_PART_INFO *end=key_part+key_info->key_parts;

  for (; key_part != end; key_part++)
  {
    field=  key_part->field; 
    result= field->pack_cmp((const char*)ref1, (const char*)ref2, 
2679
                            key_part->length, 0);
2680 2681
    if (result)
      return result;
2682 2683
    ref1+= field->packed_col_length((const char*)ref1, key_part->length);
    ref2+= field->packed_col_length((const char*)ref2, key_part->length);
2684 2685 2686 2687 2688
  }

  return 0;
}

unknown's avatar
unknown committed
2689 2690 2691 2692 2693 2694 2695 2696 2697 2698

bool ha_berkeley::check_if_incompatible_data(HA_CREATE_INFO *info,
					     uint table_changes)
{
  if (table_changes < IS_EQUAL_YES)
    return COMPATIBLE_DATA_NO;
  return COMPATIBLE_DATA_YES;
}