ha_berkeley.cc 72.2 KB
Newer Older
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1
/* Copyright (C) 2000 MySQL AB & MySQL Finland AB & TCX DataKonsult AB
2

bk@work.mysql.com's avatar
bk@work.mysql.com 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.
7

bk@work.mysql.com's avatar
bk@work.mysql.com 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.
12

bk@work.mysql.com's avatar
bk@work.mysql.com 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.
24
  - DB_DBT_USERMEM should be used for fixed length tables
bk@work.mysql.com's avatar
bk@work.mysql.com 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.
28 29 30
  - Get a more accurate count of the number of rows (estimate_number_of_rows()).
    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.
bk@work.mysql.com's avatar
bk@work.mysql.com 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.
bk@work.mysql.com's avatar
bk@work.mysql.com 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
46
    MySQL closes a table that is updated by a not commited transaction.
bk@work.mysql.com's avatar
bk@work.mysql.com committed
47 48 49 50 51 52 53 54 55 56 57 58 59 60
*/


#ifdef __GNUC__
#pragma implementation				// gcc: Class implementation
#endif

#include "mysql_priv.h"
#ifdef HAVE_BERKELEY_DB
#include <m_ctype.h>
#include <myisampack.h>
#include <assert.h>
#include <hash.h>
#include "ha_berkeley.h"
61
#include "sql_manager.h"
62
#include <stdarg.h>
bk@work.mysql.com's avatar
bk@work.mysql.com committed
63 64

#define HA_BERKELEY_ROWS_IN_TABLE 10000 /* to get optimization right */
65
#define HA_BERKELEY_RANGE_COUNT   100
66
#define HA_BERKELEY_MAX_ROWS	  10000000 /* Max rows in table */
67 68 69 70 71 72 73
/* extra rows for estimate_number_of_rows() */
#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
bk@work.mysql.com's avatar
bk@work.mysql.com committed
74 75

const char *ha_berkeley_ext=".db";
76
bool berkeley_skip=0,berkeley_shared_data=0;
monty@donna.mysql.com's avatar
monty@donna.mysql.com committed
77 78
u_int32_t berkeley_init_flags= DB_PRIVATE | DB_RECOVER, berkeley_env_flags=0,
          berkeley_lock_type=DB_LOCK_DEFAULT;
79
ulong berkeley_cache_size, berkeley_log_buffer_size, berkeley_log_file_size=0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
80 81
char *berkeley_home, *berkeley_tmpdir, *berkeley_logdir;
long berkeley_lock_scan_time=0;
82
ulong berkeley_trans_retry=1;
83
ulong berkeley_max_lock;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
84 85 86 87 88 89
pthread_mutex_t bdb_mutex;

static DB_ENV *db_env;
static HASH bdb_open_tables;

const char *berkeley_lock_names[] =
90
{ "DEFAULT", "OLDEST","RANDOM","YOUNGEST",0 };
bk@work.mysql.com's avatar
bk@work.mysql.com committed
91 92
u_int32_t berkeley_lock_types[]=
{ DB_LOCK_DEFAULT, DB_LOCK_OLDEST, DB_LOCK_RANDOM };
93
TYPELIB berkeley_lock_typelib= {array_elements(berkeley_lock_names)-1,"",
bk@work.mysql.com's avatar
bk@work.mysql.com committed
94 95 96 97 98
				berkeley_lock_names};

static void berkeley_print_error(const char *db_errpfx, char *buffer);
static byte* bdb_get_key(BDB_SHARE *share,uint *length,
			 my_bool not_used __attribute__((unused)));
99
static BDB_SHARE *get_share(const char *table_name, TABLE *table);
100 101
static int free_share(BDB_SHARE *share, TABLE *table, uint hidden_primary_key,
		      bool mutex_is_locked);
102
static int write_status(DB *status_block, char *buff, uint length);
103
static void update_status(BDB_SHARE *share, TABLE *table);
104
static void berkeley_noticecall(DB_ENV *db_env, db_notices notice);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
105 106


107

bk@work.mysql.com's avatar
bk@work.mysql.com committed
108 109 110 111 112 113 114 115 116 117
/* General functions */

bool berkeley_init(void)
{
  DBUG_ENTER("berkeley_init");

  if (!berkeley_tmpdir)
    berkeley_tmpdir=mysql_tmpdir;
  if (!berkeley_home)
    berkeley_home=mysql_real_data_home;
118 119
  DBUG_PRINT("bdb",("berkeley_home: %s",mysql_real_data_home));

120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136
  /*
    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);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
137 138

  if (db_env_create(&db_env,0))
monty@donna.mysql.com's avatar
monty@donna.mysql.com committed
139
    DBUG_RETURN(1); /* purecov: inspected */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
140 141
  db_env->set_errcall(db_env,berkeley_print_error);
  db_env->set_errpfx(db_env,"bdb");
142
  db_env->set_noticecall(db_env, berkeley_noticecall);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
143 144
  db_env->set_tmp_dir(db_env, berkeley_tmpdir);
  db_env->set_data_dir(db_env, mysql_data_home);
monty@donna.mysql.com's avatar
monty@donna.mysql.com committed
145
  db_env->set_flags(db_env, berkeley_env_flags, 1);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
146
  if (berkeley_logdir)
monty@donna.mysql.com's avatar
monty@donna.mysql.com committed
147
    db_env->set_lg_dir(db_env, berkeley_logdir); /* purecov: tested */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
148 149 150 151 152

  if (opt_endinfo)
    db_env->set_verbose(db_env,
			DB_VERB_CHKPOINT | DB_VERB_DEADLOCK | DB_VERB_RECOVERY,
			1);
153

bk@work.mysql.com's avatar
bk@work.mysql.com committed
154
  db_env->set_cachesize(db_env, 0, berkeley_cache_size, 0);
155 156
  db_env->set_lg_max(db_env, berkeley_log_file_size);
  db_env->set_lg_bsize(db_env, berkeley_log_buffer_size);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
157
  db_env->set_lk_detect(db_env, berkeley_lock_type);
158 159
  if (berkeley_max_lock)
    db_env->set_lk_max(db_env, berkeley_max_lock);
160

bk@work.mysql.com's avatar
bk@work.mysql.com committed
161 162
  if (db_env->open(db_env,
		   berkeley_home,
163
		   berkeley_init_flags |  DB_INIT_LOCK |
bk@work.mysql.com's avatar
bk@work.mysql.com committed
164
		   DB_INIT_LOG | DB_INIT_MPOOL | DB_INIT_TXN |
165
		   DB_CREATE | DB_THREAD, 0666))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
166
  {
monty@donna.mysql.com's avatar
monty@donna.mysql.com committed
167 168
    db_env->close(db_env,0); /* purecov: inspected */
    db_env=0; /* purecov: inspected */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
169
  }
170

bk@work.mysql.com's avatar
bk@work.mysql.com committed
171 172
  (void) hash_init(&bdb_open_tables,32,0,0,
		   (hash_get_key) bdb_get_key,0,0);
173
  pthread_mutex_init(&bdb_mutex,MY_MUTEX_INIT_FAST);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
174 175 176 177 178 179 180 181 182
  DBUG_RETURN(db_env == 0);
}


bool berkeley_end(void)
{
  int error;
  DBUG_ENTER("berkeley_end");
  if (!db_env)
monty@donna.mysql.com's avatar
monty@donna.mysql.com committed
183
    return 1; /* purecov: tested */
184
  berkeley_cleanup_log_files();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
185 186 187 188 189 190 191 192 193 194 195 196 197 198
  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 != 0);
}

bool berkeley_flush_logs()
{
  int error;
  bool result=0;
  DBUG_ENTER("berkeley_flush_logs");
  if ((error=log_flush(db_env,0)))
  {
199 200
    my_error(ER_ERROR_DURING_FLUSH_LOGS,MYF(0),error); /* purecov: inspected */
    result=1; /* purecov: inspected */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
201 202 203
  }
  if ((error=txn_checkpoint(db_env,0,0,0)))
  {
204 205
    my_error(ER_ERROR_DURING_CHECKPOINT,MYF(0),error); /* purecov: inspected */
    result=1; /* purecov: inspected */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
206 207 208 209 210
  }
  DBUG_RETURN(result);
}


211
int berkeley_commit(THD *thd, void *trans)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
212 213
{
  DBUG_ENTER("berkeley_commit");
214 215
  DBUG_PRINT("trans",("ending transaction %s",
		      trans == thd->transaction.stmt.bdb_tid ? "stmt" : "all"));
216
  int error=txn_commit((DB_TXN*) trans,0);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
217 218
#ifndef DBUG_OFF
  if (error)
219
    DBUG_PRINT("error",("error: %d",error)); /* purecov: inspected */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
220 221 222 223
#endif
  DBUG_RETURN(error);
}

224
int berkeley_rollback(THD *thd, void *trans)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
225 226
{
  DBUG_ENTER("berkeley_rollback");
227 228
  DBUG_PRINT("trans",("aborting transaction %s",
		      trans == thd->transaction.stmt.bdb_tid ? "stmt" : "all"));
229
  int error=txn_abort((DB_TXN*) trans);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
230 231 232
  DBUG_RETURN(error);
}

tim@cane.mysql.fi's avatar
tim@cane.mysql.fi committed
233 234 235

int berkeley_show_logs(THD *thd)
{
236
  char **all_logs, **free_logs, **a, **f;
tim@cane.mysql.fi's avatar
tim@cane.mysql.fi committed
237
  String *packet= &thd->packet;
238 239 240
  int error=1;
  MEM_ROOT show_logs_root;
  MEM_ROOT *old_root=my_pthread_getspecific_ptr(MEM_ROOT*,THR_MALLOC);
tim@cane.mysql.fi's avatar
tim@cane.mysql.fi committed
241 242
  DBUG_ENTER("berkeley_show_logs");

243
  init_sql_alloc(&show_logs_root, 1024, 1024);
244 245 246
  my_pthread_setspecific_ptr(THR_MALLOC,&show_logs_root);

  if ((error= log_archive(db_env, &all_logs, DB_ARCH_ABS | DB_ARCH_LOG,
247
			  (void* (*)(size_t)) sql_alloc)) ||
248
      (error= log_archive(db_env, &free_logs, DB_ARCH_ABS, 
249
			  (void* (*)(size_t)) sql_alloc)))
tim@cane.mysql.fi's avatar
tim@cane.mysql.fi committed
250 251 252
  {
    DBUG_PRINT("error", ("log_archive failed (error %d)", error));
    db_env->err(db_env, error, "log_archive: DB_ARCH_ABS");
monty@donna.mysql.com's avatar
monty@donna.mysql.com committed
253 254
    if (error== DB_NOTFOUND)
      error=0;					// No log files
255
    goto err;
tim@cane.mysql.fi's avatar
tim@cane.mysql.fi committed
256
  }
monty@donna.mysql.com's avatar
monty@donna.mysql.com committed
257 258
  /* Error is 0 here */
  if (all_logs)
tim@cane.mysql.fi's avatar
tim@cane.mysql.fi committed
259
  {
monty@donna.mysql.com's avatar
monty@donna.mysql.com committed
260
    for (a = all_logs, f = free_logs; *a; ++a)
tim@cane.mysql.fi's avatar
tim@cane.mysql.fi committed
261
    {
monty@donna.mysql.com's avatar
monty@donna.mysql.com committed
262 263 264 265 266 267 268 269 270 271
      packet->length(0);
      net_store_data(packet,*a);
      net_store_data(packet,"BDB");
      if (f && *f && strcmp(*a, *f) == 0)
      {
	++f;
	net_store_data(packet, SHOW_LOG_STATUS_FREE);
      }
      else
	net_store_data(packet, SHOW_LOG_STATUS_INUSE);
tim@cane.mysql.fi's avatar
tim@cane.mysql.fi committed
272

monty@donna.mysql.com's avatar
monty@donna.mysql.com committed
273 274 275 276 277 278
      if (my_net_write(&thd->net,(char*) packet->ptr(),packet->length()))
      {
	error=1;
	goto err;
      }
    }
tim@cane.mysql.fi's avatar
tim@cane.mysql.fi committed
279
  }
280
err:
tim@cane.mysql.fi's avatar
tim@cane.mysql.fi committed
281
  free_root(&show_logs_root,MYF(0));
282 283
  my_pthread_setspecific_ptr(THR_MALLOC,old_root);
  DBUG_RETURN(error);
tim@cane.mysql.fi's avatar
tim@cane.mysql.fi committed
284
}
bk@work.mysql.com's avatar
bk@work.mysql.com committed
285 286 287

static void berkeley_print_error(const char *db_errpfx, char *buffer)
{
288
  sql_print_error("%s:  %s",db_errpfx,buffer); /* purecov: tested */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
289 290
}

291 292 293 294
static void berkeley_noticecall(DB_ENV *db_env, db_notices notice)
{
  switch (notice)
  {
295
  case DB_NOTICE_LOGFILE_CHANGED: /* purecov: tested */
296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312
    pthread_mutex_lock(&LOCK_manager);
    manager_status |= MANAGER_BERKELEY_LOG_CLEANUP;
    pthread_mutex_unlock(&LOCK_manager);
    pthread_cond_signal(&COND_manager);
    break;
  }
}

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

  /* XXX: Probably this should be done somewhere else, and
   * should be tunable by the user. */
  if ((error = txn_checkpoint(db_env, 0, 0, 0)))
313
    my_error(ER_ERROR_DURING_CHECKPOINT, MYF(0), error); /* purecov: inspected */
314 315 316

  if ((error = log_archive(db_env, &names, DB_ARCH_ABS, NULL)) != 0)
  {
317 318 319
    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 */
320 321 322
  }

  if (names)
monty@donna.mysql.com's avatar
monty@donna.mysql.com committed
323 324 325 326
  {						/* purecov: tested */
    char **np;					/* purecov: tested */
    for (np = names; *np; ++np)			/* purecov: tested */
      my_delete(*np, MYF(MY_WME));		/* purecov: tested */
327

monty@donna.mysql.com's avatar
monty@donna.mysql.com committed
328
    free(names);				/* purecov: tested */
329 330 331 332
  }

  DBUG_VOID_RETURN;
}
bk@work.mysql.com's avatar
bk@work.mysql.com committed
333 334 335 336 337 338 339 340 341 342


/*****************************************************************************
** Berkeley DB tables
*****************************************************************************/

const char **ha_berkeley::bas_ext() const
{ static const char *ext[]= { ha_berkeley_ext, NullS }; return ext; }


343
static int
344
berkeley_cmp_hidden_key(DB* file, const DBT *new_key, const DBT *saved_key)
345 346 347
{
  ulonglong a=uint5korr((char*) new_key->data);
  ulonglong b=uint5korr((char*) saved_key->data);
348
  return  a < b ? -1 : (a > b ? 1 : 0);
349 350
}

bk@work.mysql.com's avatar
bk@work.mysql.com committed
351
static int
352
berkeley_cmp_packed_key(DB *file, const DBT *new_key, const DBT *saved_key)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
353
{
354 355
  KEY *key=	      (new_key->app_private ? (KEY*) new_key->app_private :
		       (KEY*) (file->app_private));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
356 357 358 359 360
  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;

361
  for (; key_part != end && (int) key_length > 0; key_part++)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
362 363 364 365
  {
    int cmp;
    if (key_part->null_bit)
    {
366 367
      if (*new_key_ptr != *saved_key_ptr++)
	return ((int) *new_key_ptr - (int) saved_key_ptr[-1]);
368
      key_length--;
369 370
      if (!*new_key_ptr++)
	continue;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
371 372 373 374
    }
    if ((cmp=key_part->field->pack_cmp(new_key_ptr,saved_key_ptr,
				       key_part->length)))
      return cmp;
375 376
    uint length=key_part->field->packed_col_length(new_key_ptr,
						   key_part->length);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
377 378
    new_key_ptr+=length;
    key_length-=length;
379 380
    saved_key_ptr+=key_part->field->packed_col_length(saved_key_ptr,
						      key_part->length);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
381
  }
382
  return key->handler.bdb_return_if_eq;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
383 384 385
}


386 387
/* The following is not yet used; Should be used for fixed length keys */

388
#ifdef NOT_YET
bk@work.mysql.com's avatar
bk@work.mysql.com committed
389
static int
390
berkeley_cmp_fix_length_key(DB *file, const DBT *new_key, const DBT *saved_key)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
391
{
392 393
  KEY *key=	      (new_key->app_private ? (KEY*) new_key->app_private :
		       (KEY*) (file->app_private));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
394 395 396 397 398
  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;

399
  for (; key_part != end && (int) key_length > 0 ; key_part++)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
400 401 402 403 404 405 406 407
  {
    int cmp;
    if ((cmp=key_part->field->pack_cmp(new_key_ptr,saved_key_ptr,0)))
      return cmp;
    new_key_ptr+=key_part->length;
    key_length-= key_part->length;
    saved_key_ptr+=key_part->length;
  }
408
  return key->handler.bdb_return_if_eq;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
409
}
410
#endif
bk@work.mysql.com's avatar
bk@work.mysql.com committed
411

412 413 414 415 416 417
/* 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,
418
		*end=key_part+key_info->key_parts;
419

420
  for (; key_part != end && (int) key_length > 0; key_part++)
421 422 423 424 425
  {
    int cmp;
    if (key_part->null_bit)
    {
      key_length--;
426 427 428 429
      /*
	With the current usage, the following case will always be FALSE,
	because NULL keys are sorted before any other key
      */
430 431 432
      if (*key != (table->record[0][key_part->null_offset] &
		   key_part->null_bit) ? 0 : 1)
	return 1;
433
      if (!*key++)				// Null value
434 435 436 437
	continue;
    }
    if ((cmp=key_part->field->pack_cmp(key,key_part->length)))
      return cmp;
438
    uint length=key_part->field->packed_col_length(key,key_part->length);
439 440 441
    key+=length;
    key_length-=length;
  }
442
  return 0;					// Identical keys
443 444 445
}


446
int ha_berkeley::open(const char *name, int mode, uint test_if_locked)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
447 448 449 450 451 452
{
  char name_buff[FN_REFLEN];
  uint open_mode=(mode == O_RDONLY ? DB_RDONLY : 0) | DB_THREAD;
  int error;
  DBUG_ENTER("ha_berkeley::open");

453 454 455 456 457
  /* Open primary key */
  hidden_primary_key=0;
  if ((primary_key=table->primary_key) >= MAX_KEY)
  {						// No primary key
    primary_key=table->keys;
458
    key_used_on_scan=MAX_KEY;
459 460
    ref_length=hidden_primary_key=BDB_HIDDEN_PRIMARY_KEY_LENGTH;
  }
461 462
  else
    key_used_on_scan=primary_key;
463

bk@work.mysql.com's avatar
bk@work.mysql.com committed
464
  /* Need some extra memory in case of packed keys */
465
  uint max_key_length= table->max_key_length + MAX_REF_PARTS*3;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
466 467 468 469 470
  if (!(alloc_ptr=
	my_multi_malloc(MYF(MY_WME),
			&key_buff,  max_key_length,
			&key_buff2, max_key_length,
			&primary_key_buff,
471 472
			(hidden_primary_key ? 0 :
			 table->key_info[table->primary_key].key_length),
bk@work.mysql.com's avatar
bk@work.mysql.com committed
473
			NullS)))
474
    DBUG_RETURN(1); /* purecov: inspected */
475 476 477
  if (!(rec_buff= (byte*) my_malloc((alloced_rec_buff_length=
				     table->rec_buff_length),
				    MYF(MY_WME))))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
478
  {
479 480
    my_free(alloc_ptr,MYF(0)); /* purecov: inspected */
    DBUG_RETURN(1); /* purecov: inspected */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
481 482
  }

483
  /* Init shared structure */
484
  if (!(share=get_share(name,table)))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
485
  {
486
    my_free((char*) rec_buff,MYF(0)); /* purecov: inspected */
487 488
    my_free(alloc_ptr,MYF(0)); /* purecov: inspected */
    DBUG_RETURN(1); /* purecov: inspected */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
489 490
  }
  thr_lock_data_init(&share->lock,&lock,(void*) 0);
491 492
  key_file = share->key_file;
  key_type = share->key_type;
493
  bzero((char*) &current_row,sizeof(current_row));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
494

495 496 497 498
  /* Fill in shared structure, if needed */
  pthread_mutex_lock(&share->mutex);
  file = share->file;
  if (!share->use_count++)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
499
  {
500 501
    if ((error=db_create(&file, db_env, 0)))
    {
502
      free_share(share,table, hidden_primary_key,1); /* purecov: inspected */
503
      my_free((char*) rec_buff,MYF(0)); /* purecov: inspected */
504 505 506
      my_free(alloc_ptr,MYF(0)); /* purecov: inspected */
      my_errno=error; /* purecov: inspected */
      DBUG_RETURN(1); /* purecov: inspected */
507 508 509 510 511 512 513 514 515 516 517 518
    }
    share->file = file;

    file->set_bt_compare(file,
			 (hidden_primary_key ? berkeley_cmp_hidden_key :
			  berkeley_cmp_packed_key));
    if (!hidden_primary_key)
      file->app_private= (void*) (table->key_info+table->primary_key);
    if ((error=(file->open(file, fn_format(name_buff,name,"", ha_berkeley_ext,
					   2 | 4),
			   "main", DB_BTREE, open_mode,0))))
    {
519
      free_share(share,table, hidden_primary_key,1); /* purecov: inspected */
520
      my_free((char*) rec_buff,MYF(0)); /* purecov: inspected */
521 522 523
      my_free(alloc_ptr,MYF(0)); /* purecov: inspected */
      my_errno=error; /* purecov: inspected */
      DBUG_RETURN(1); /* purecov: inspected */
524
    }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
525

526
    /* Open other keys;  These are part of the share structure */
527 528 529 530 531 532 533 534 535 536 537
    key_file[primary_key]=file;
    key_type[primary_key]=DB_NOOVERWRITE;

    DB **ptr=key_file;
    for (uint i=0, used_keys=0; i < table->keys ; i++, ptr++)
    {
      char part[7];
      if (i != primary_key)
      {
	if ((error=db_create(ptr, db_env, 0)))
	{
monty@donna.mysql.com's avatar
monty@donna.mysql.com committed
538 539 540
	  close();				/* purecov: inspected */
	  my_errno=error;			/* purecov: inspected */
	  DBUG_RETURN(1);			/* purecov: inspected */
541 542 543 544 545 546
	}
	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))
547 548
	{
	  DBUG_PRINT("bdb",("Setting DB_DUP for key %u", i));
549
	  (*ptr)->set_flags(*ptr, DB_DUP);
550
	}
551 552 553
	if ((error=((*ptr)->open(*ptr, name_buff, part, DB_BTREE,
				 open_mode, 0))))
	{
monty@donna.mysql.com's avatar
monty@donna.mysql.com committed
554 555 556
	  close();				/* purecov: inspected */
	  my_errno=error;			/* purecov: inspected */
	  DBUG_RETURN(1);			/* purecov: inspected */
557 558 559 560
	}
      }
    }
    /* Calculate pack_length of primary key */
561
    share->fixed_length_primary_key=1;
562 563 564 565 566
    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;
567
      for (; key_part != end ; key_part++)
568
	ref_length+= key_part->field->max_packed_col_length(key_part->length);
569
      share->fixed_length_primary_key=
570 571 572
	(ref_length == table->key_info[primary_key].key_length);
      share->status|=STATUS_PRIMARY_KEY_INIT;
    }    
573
    share->ref_length=ref_length;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
574
  }
575
  ref_length=share->ref_length;			// If second open
576
  pthread_mutex_unlock(&share->mutex);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
577 578 579

  transaction=0;
  cursor=0;
580
  key_read=0;
581
  block_size=8192;				// Berkeley DB block size
582
  share->fixed_length_row=!(table->db_create_options & HA_OPTION_PACK_RECORD);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
583

584
  get_status();
585
  info(HA_STATUS_NO_LOCK | HA_STATUS_VARIABLE | HA_STATUS_CONST);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
586 587 588 589 590 591 592 593
  DBUG_RETURN(0);
}


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

594
  my_free((char*) rec_buff,MYF(MY_ALLOW_ZERO_PTR));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
595
  my_free(alloc_ptr,MYF(MY_ALLOW_ZERO_PTR));
596
  ha_berkeley::extra(HA_EXTRA_RESET);		// current_row buffer
597
  DBUG_RETURN(free_share(share,table, hidden_primary_key,0));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
598 599 600 601 602 603 604 605 606 607 608 609
}


/* 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))))
610
      return 1; /* purecov: inspected */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
611 612 613 614 615 616 617 618 619 620 621 622 623
    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)
{
  ulong length=table->reclength + table->fields*2;
  for (Field_blob **ptr=table->blob_field ; *ptr ; ptr++)
624
    length+= (*ptr)->get_length((char*) buf+(*ptr)->offset())+2;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
625 626 627 628 629 630 631 632 633 634 635 636 637
  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.
*/

638
int ha_berkeley::pack_row(DBT *row, const byte *record, bool new_row)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
639 640
{
  bzero((char*) row,sizeof(*row));
641
  if (share->fixed_length_row)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
642 643
  {
    row->data=(void*) record;
644 645 646 647 648 649 650 651
    row->size=table->reclength+hidden_primary_key;
    if (hidden_primary_key)
    {
      if (new_row)
	get_auto_primary_key(current_ident);
      memcpy_fixed((char*) record+table->reclength, (char*) current_ident,
		   BDB_HIDDEN_PRIMARY_KEY_LENGTH);
    }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
652 653 654 655 656
    return 0;
  }
  if (table->blob_fields)
  {
    if (fix_rec_buff_for_blob(max_row_length(record)))
657
      return HA_ERR_OUT_OF_MEM; /* purecov: inspected */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
658 659 660 661 662 663 664
  }

  /* Copy null bits */
  memcpy(rec_buff, record, table->null_bytes);
  byte *ptr=rec_buff + table->null_bytes;

  for (Field **field=table->field ; *field ; field++)
665 666
    ptr=(byte*) (*field)->pack((char*) ptr,
			       (char*) record + (*field)->offset());
667 668 669 670 671 672 673 674 675

  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;
  }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
676 677 678 679 680 681 682 683
  row->data=rec_buff;
  row->size= (size_t) (ptr - rec_buff);
  return 0;
}


void ha_berkeley::unpack_row(char *record, DBT *row)
{
684
  if (share->fixed_length_row)
685
    memcpy(record,(char*) row->data,table->reclength+hidden_primary_key);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
686 687 688 689 690 691 692 693 694 695 696 697
  else
  {
    /* Copy null bits */
    const char *ptr= (const char*) row->data;
    memcpy(record, ptr, table->null_bytes);
    ptr+=table->null_bytes;
    for (Field **field=table->field ; *field ; field++)
      ptr= (*field)->unpack(record + (*field)->offset(), ptr);
  }
}


698 699 700 701 702 703
/* Store the key and the primary key into the row */

void ha_berkeley::unpack_key(char *record, DBT *key, uint index)
{
  KEY *key_info=table->key_info+index;
  KEY_PART_INFO *key_part= key_info->key_part,
704
		*end=key_part+key_info->key_parts;
705 706

  char *pos=(char*) key->data;
707
  for (; key_part != end; key_part++)
708 709 710 711 712 713 714 715 716 717 718 719 720 721 722
  {
    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;
    }
723 724
    pos= (char*) key_part->field->unpack_key(record + key_part->field->offset(),
                                             pos, key_part->length);
725 726 727 728
  }
}


bk@work.mysql.com's avatar
bk@work.mysql.com committed
729 730 731 732 733
/*
  Create a packed key from from a row
  This will never fail as the key buffer is pre allocated.
*/

734 735
DBT *ha_berkeley::create_key(DBT *key, uint keynr, char *buff,
			     const byte *record, int key_length)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
736
{
737 738 739
  bzero((char*) key,sizeof(*key));
  if (hidden_primary_key && keynr == primary_key)
  {
740
    /* We don't need to set app_private here */
741 742 743 744 745
    key->data=current_ident;
    key->size=BDB_HIDDEN_PRIMARY_KEY_LENGTH;
    return key;
  }

bk@work.mysql.com's avatar
bk@work.mysql.com committed
746 747 748
  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;
749
  DBUG_ENTER("create_key");
bk@work.mysql.com's avatar
bk@work.mysql.com committed
750 751

  key->data=buff;
752
  key->app_private= key_info;
753
  for (; key_part != end && key_length > 0; key_part++)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
754 755 756 757 758 759 760 761 762 763 764 765
  {
    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
    }
766
    buff=key_part->field->pack_key(buff,(char*) (record + key_part->offset),
767
				   key_part->length);
768
    key_length-=key_part->length;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785
  }
  key->size= (buff  - (char*) key->data);
  DBUG_DUMP("key",(char*) key->data, key->size);
  DBUG_RETURN(key);
}


/*
  Create a packed key from from a MySQL unpacked key
*/

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;
786
  DBUG_ENTER("bdb:pack_key");
bk@work.mysql.com's avatar
bk@work.mysql.com committed
787 788 789

  bzero((char*) key,sizeof(*key));
  key->data=buff;
790
  key->app_private= (void*) key_info;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
791 792 793

  for (; key_part != end && (int) key_length > 0 ; key_part++)
  {
794
    uint offset=0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
795 796 797 798 799 800 801 802 803
    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;
      }
804
      offset=1;					// Data is at key_ptr+1
805
    }
806
    buff=key_part->field->pack_key_from_key_image(buff,(char*) key_ptr+offset,
807
						  key_part->length);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827
    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");

  statistic_increment(ha_write_count,&LOCK_status);
  if (table->time_stamp)
    update_timestamp(record+table->time_stamp-1);
  if (table->next_number_field && record == table->record[0])
    update_auto_increment();
828
  if ((error=pack_row(&row, record,1)))
829
    DBUG_RETURN(error); /* purecov: inspected */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
830

831
  if (table->keys + test(hidden_primary_key) == 1)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
832
  {
833 834
    error=file->put(file, transaction, create_key(&prim_key, primary_key,
						  key_buff, record),
bk@work.mysql.com's avatar
bk@work.mysql.com committed
835
		    &row, key_type[primary_key]);
monty@donna.mysql.com's avatar
monty@donna.mysql.com committed
836
    last_dup_key=primary_key;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
837 838 839
  }
  else
  {
840
    DB_TXN *sub_trans = transaction;
841 842
    /* Don't use sub transactions in temporary tables (in_use == 0) */
    ulong thd_options = table->in_use ? table->in_use->options : 0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
843 844
    for (uint retry=0 ; retry < berkeley_trans_retry ; retry++)
    {
845 846 847
      key_map changed_keys = 0;
      if (using_ignore && (thd_options & OPTION_INTERNAL_SUBTRANSACTIONS))
      {
848 849 850
	if ((error=txn_begin(db_env, transaction, &sub_trans, 0))) /* purecov: deadcode */
	  break; /* purecov: deadcode */
	DBUG_PRINT("trans",("starting subtransaction")); /* purecov: deadcode */
851
      }
852 853
      if (!(error=file->put(file, sub_trans, create_key(&prim_key, primary_key,
							key_buff, record),
bk@work.mysql.com's avatar
bk@work.mysql.com committed
854 855
			    &row, key_type[primary_key])))
      {
856 857
	changed_keys |= (key_map) 1 << primary_key;
	for (uint keynr=0 ; keynr < table->keys ; keynr++)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
858 859 860 861
	{
	  if (keynr == primary_key)
	    continue;
	  if ((error=key_file[keynr]->put(key_file[keynr], sub_trans,
862 863
					  create_key(&key, keynr, key_buff2,
						     record),
bk@work.mysql.com's avatar
bk@work.mysql.com committed
864 865 866 867 868
					  &prim_key, key_type[keynr])))
	  {
	    last_dup_key=keynr;
	    break;
	  }
869
	  changed_keys |= (key_map) 1 << keynr;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
870 871
	}
      }
monty@donna.mysql.com's avatar
monty@donna.mysql.com committed
872 873
      else
	last_dup_key=primary_key;
874
      if (error)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
875 876 877
      {
	/* Remove inserted row */
	DBUG_PRINT("error",("Got error %d",error));
878
	if (using_ignore)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
879
	{
880 881 882
	  int new_error = 0;
	  if (thd_options & OPTION_INTERNAL_SUBTRANSACTIONS)
	  {
883 884
	    DBUG_PRINT("trans",("aborting subtransaction")); /* purecov: deadcode */
	    new_error=txn_abort(sub_trans); /* purecov: deadcode */
885 886 887 888 889 890 891 892 893
	  }
	  else if (changed_keys)
	  {
	    new_error = 0;
	    for (uint keynr=0; changed_keys; keynr++, changed_keys >>= 1)
	    {
	      if (changed_keys & 1)
	      {
		if ((new_error = remove_key(sub_trans, keynr, record,
894
					    &prim_key)))
895
		  break; /* purecov: inspected */
896 897 898 899 900
	      }
	    }
	  }
	  if (new_error)
	  {
901 902
	    error=new_error;			// This shouldn't happen /* purecov: inspected */
	    break; /* purecov: inspected */
903
	  }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
904 905
	}
      }
906 907
      else if (using_ignore && (thd_options & OPTION_INTERNAL_SUBTRANSACTIONS))
      {
908 909
	DBUG_PRINT("trans",("committing subtransaction")); /* purecov: deadcode */
	error=txn_commit(sub_trans, 0); /* purecov: deadcode */
910
      }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
911 912 913 914 915 916
      if (error != DB_LOCK_DEADLOCK)
	break;
    }
  }
  if (error == DB_KEYEXIST)
    error=HA_ERR_FOUND_DUPP_KEY;
917 918
  else if (!error)
    changed_rows++;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
919 920 921 922 923 924 925 926 927 928 929 930
  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;

931
  for (; key_part != end ; key_part++)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
932 933 934 935 936 937 938 939 940
  {
    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;
    }
    if (key_part->key_part_flag & (HA_BLOB_PART | HA_VAR_LENGTH))
    {
941

942 943
      if (key_part->field->cmp_binary((char*) (old_row + key_part->offset),
				      (char*) (new_row + key_part->offset),
bk@work.mysql.com's avatar
bk@work.mysql.com committed
944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959
				      (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.
960
  Clobbers key_buff2
bk@work.mysql.com's avatar
bk@work.mysql.com committed
961 962 963
*/

int ha_berkeley::update_primary_key(DB_TXN *trans, bool primary_key_changed,
964 965 966
				    const byte * old_row, DBT *old_key,
				    const byte * new_row, DBT *new_key,
				    ulong thd_options, bool local_using_ignore)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
967
{
968
  DBT row;
969
  int error;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
970 971 972 973 974 975
  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
976
    if (!(error=remove_key(trans, primary_key, old_row, old_key)))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
977
    {
978 979 980 981 982 983 984 985 986 987 988 989 990 991
      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;
	  if (local_using_ignore &&
	      !(thd_options & OPTION_INTERNAL_SUBTRANSACTIONS))
	  {
	    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])))
992
	      error=new_error;                  // fatal error /* purecov: inspected */
993 994 995
	  }
	}
      }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
996 997 998 999 1000
    }
  }
  else
  {
    // Primary key didn't change;  just update the row data
1001 1002
    if (!(error=pack_row(&row, new_row, 0)))
      error=file->put(file, trans, new_key, &row, 0);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1003
  }
1004
  DBUG_RETURN(error);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1005 1006
}

1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020
/*
  Restore changed keys, when a non-fatal error aborts the insert/update
  of one row.
  Clobbers keybuff2
*/

int ha_berkeley::restore_keys(DB_TXN *trans, key_map changed_keys,
			      uint primary_key,
			      const byte *old_row, DBT *old_key,
			      const byte *new_row, DBT *new_key,
			      ulong thd_options)
{
  int error;
  DBT tmp_key;
1021
  uint keynr;
1022 1023 1024 1025 1026 1027
  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,
				old_row, old_key, thd_options, FALSE)))
1028
    goto err; /* purecov: inspected */
1029 1030 1031 1032 1033 1034

  /* 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. */
1035
  for (keynr=0; changed_keys; keynr++, changed_keys >>= 1)
1036 1037 1038 1039
  {
    if (changed_keys & 1)
    {
      if (changed_keys != 1 &&
1040
	  (error = remove_key(trans, keynr, new_row, new_key)))
1041
	break; /* purecov: inspected */
1042 1043 1044 1045
      if ((error = key_file[keynr]->put(key_file[keynr], trans,
					create_key(&tmp_key, keynr, key_buff2,
						   old_row),
					old_key, key_type[keynr])))
1046
	break; /* purecov: inspected */
1047 1048
    }
  }
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
1049

1050
err:
monty@bitch.mysql.fi's avatar
monty@bitch.mysql.fi committed
1051
  DBUG_ASSERT(error != DB_KEYEXIST);
1052 1053
  DBUG_RETURN(error);
}
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1054 1055 1056 1057


int ha_berkeley::update_row(const byte * old_row, byte * new_row)
{
1058
  DBT prim_key, key, old_prim_key;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1059 1060
  int error;
  DB_TXN *sub_trans;
1061
  ulong thd_options = table->in_use ? table->in_use->options : 0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1062 1063
  bool primary_key_changed;
  DBUG_ENTER("update_row");
monty@donna.mysql.com's avatar
monty@donna.mysql.com committed
1064
  LINT_INIT(error);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1065 1066 1067 1068

  statistic_increment(ha_update_count,&LOCK_status);
  if (table->time_stamp)
    update_timestamp(new_row+table->time_stamp-1);
1069 1070 1071 1072 1073 1074 1075

  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;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1076
    old_prim_key=prim_key;
1077 1078 1079
  }
  else
  {
1080
    create_key(&prim_key, primary_key, key_buff, new_row);
1081

1082
    if ((primary_key_changed=key_cmp(primary_key, old_row, new_row)))
1083
      create_key(&old_prim_key, primary_key, primary_key_buff, old_row);
1084 1085 1086
    else
      old_prim_key=prim_key;
  }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1087

1088
  sub_trans = transaction;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1089 1090
  for (uint retry=0 ; retry < berkeley_trans_retry ; retry++)
  {
1091 1092 1093
    key_map changed_keys = 0;
    if (using_ignore &&	(thd_options & OPTION_INTERNAL_SUBTRANSACTIONS))
    {
1094 1095 1096
      if ((error=txn_begin(db_env, transaction, &sub_trans, 0))) /* purecov: deadcode */
	break; /* purecov: deadcode */
      DBUG_PRINT("trans",("starting subtransaction")); /* purecov: deadcode */
1097
    }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1098 1099
    /* Start by updating the primary key */
    if (!(error=update_primary_key(sub_trans, primary_key_changed,
1100 1101 1102
				   old_row, &old_prim_key,
				   new_row, &prim_key,
				   thd_options, using_ignore)))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1103 1104 1105 1106 1107 1108 1109 1110
    {
      // Update all other keys
      for (uint keynr=0 ; keynr < table->keys ; keynr++)
      {
	if (keynr == primary_key)
	  continue;
	if (key_cmp(keynr, old_row, new_row) || primary_key_changed)
	{
1111
	  if ((error=remove_key(sub_trans, keynr, old_row, &old_prim_key)))
1112
	  {
1113
	    if (using_ignore && /* purecov: inspected */
1114 1115 1116 1117 1118 1119 1120 1121
		(thd_options & OPTION_INTERNAL_SUBTRANSACTIONS))
            {
	      int new_error;
	      DBUG_PRINT("trans",("aborting subtransaction"));
	      new_error=txn_abort(sub_trans);
	      if (new_error)
		error = new_error;
	    }
1122
	    DBUG_RETURN(error);			// Fatal error /* purecov: inspected */
1123 1124 1125
	  }
	  changed_keys |= (key_map)1 << keynr;
	  if ((error=key_file[keynr]->put(key_file[keynr], sub_trans,
1126
					  create_key(&key, keynr, key_buff2,
1127
						     new_row),
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1128 1129 1130 1131 1132 1133 1134 1135
					  &prim_key, key_type[keynr])))
	  {
	    last_dup_key=keynr;
	    break;
	  }
	}
      }
    }
1136
    if (error)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1137 1138
    {
      /* Remove inserted row */
1139 1140 1141 1142 1143 1144
      DBUG_PRINT("error",("Got error %d",error));
      if (using_ignore)
      {
	int new_error = 0;
	if (thd_options & OPTION_INTERNAL_SUBTRANSACTIONS)
	{
1145 1146
	  DBUG_PRINT("trans",("aborting subtransaction")); /* purecov: deadcode */
	  new_error=txn_abort(sub_trans); /* purecov: deadcode */
1147 1148 1149 1150 1151 1152 1153
	}
	else if (changed_keys)
	  new_error=restore_keys(transaction, changed_keys, primary_key,
				 old_row, &old_prim_key, new_row, &prim_key,
				 thd_options);
	if (new_error)
	{
1154 1155
	  error=new_error;			// This shouldn't happen /* purecov: inspected */
	  break; /* purecov: inspected */
1156 1157 1158 1159 1160
	}
      }
    }
    else if (using_ignore && (thd_options & OPTION_INTERNAL_SUBTRANSACTIONS))
    {
1161 1162
      DBUG_PRINT("trans",("committing subtransaction")); /* purecov: deadcode */
      error=txn_commit(sub_trans, 0); /* purecov: deadcode */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178
    }
    if (error != DB_LOCK_DEADLOCK)
      break;
  }
  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.
*/

1179
int ha_berkeley::remove_key(DB_TXN *trans, uint keynr, const byte *record,
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1180 1181 1182 1183 1184 1185 1186
			    DBT *prim_key)
{
  int error;
  DBT key;
  DBUG_ENTER("remove_key");
  DBUG_PRINT("enter",("index: %d",keynr));

monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
1187 1188 1189 1190 1191
  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))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1192
  {						// Unique key
monty@bitch.mysql.fi's avatar
monty@bitch.mysql.fi committed
1193
    DBUG_ASSERT(keynr == primary_key || prim_key->data != key_buff2);
1194
    error=key_file[keynr]->del(key_file[keynr], trans,
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1195 1196
			       keynr == primary_key ?
			       prim_key :
1197
			       create_key(&key, keynr, key_buff2, record),
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1198 1199 1200 1201 1202 1203 1204 1205 1206
			       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
    */
monty@bitch.mysql.fi's avatar
monty@bitch.mysql.fi committed
1207
    DBUG_ASSERT(keynr != primary_key && prim_key->data != key_buff2);
1208
    DBC *tmp_cursor;
1209 1210
    if (!(error=key_file[keynr]->cursor(key_file[keynr], trans,
					&tmp_cursor, 0)))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1211
    {
1212
      if (!(error=tmp_cursor->c_get(tmp_cursor,
1213 1214
                                    create_key(&key, keynr, key_buff2, record),
                                    prim_key, DB_GET_BOTH | DB_RMW)))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1215
      {					// This shouldn't happen
1216
	error=tmp_cursor->c_del(tmp_cursor,0);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1217
      }
1218
      int result=tmp_cursor->c_close(tmp_cursor);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229
      if (!error)
	error=result;
    }
  }
  DBUG_RETURN(error);
}


/* Delete all keys for new_record */

int ha_berkeley::remove_keys(DB_TXN *trans, const byte *record,
1230
			     DBT *new_record, DBT *prim_key, key_map keys)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1231
{
1232 1233
  int result = 0;
  for (uint keynr=0; keys; keynr++, keys>>=1)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1234 1235 1236
  {
    if (keys & 1)
    {
1237
      int new_error=remove_key(trans, keynr, record, prim_key);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1238 1239
      if (new_error)
      {
1240 1241
	result=new_error;			// Return last error /* purecov: inspected */
	break;					// Let rollback correct things /* purecov: inspected */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253
      }
    }
  }
  return result;
}


int ha_berkeley::delete_row(const byte * record)
{
  int error;
  DBT row, prim_key;
  key_map keys=table->keys_in_use;
1254
  ulong thd_options = table->in_use ? table->in_use->options : 0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1255 1256
  DBUG_ENTER("delete_row");
  statistic_increment(ha_delete_count,&LOCK_status);
1257

1258
  if ((error=pack_row(&row, record, 0)))
1259
    DBUG_RETURN((error)); /* purecov: inspected */
1260
  create_key(&prim_key, primary_key, key_buff, record);
1261 1262 1263
  if (hidden_primary_key)
    keys|= (key_map) 1 << primary_key;

1264 1265 1266
  /* Subtransactions may be used in order to retry the delete in
     case we get a DB_LOCK_DEADLOCK error. */
  DB_TXN *sub_trans = transaction;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1267 1268
  for (uint retry=0 ; retry < berkeley_trans_retry ; retry++)
  {
1269 1270
    if (thd_options & OPTION_INTERNAL_SUBTRANSACTIONS)
    {
1271 1272 1273
      if ((error=txn_begin(db_env, transaction, &sub_trans, 0))) /* purecov: deadcode */
	break; /* purecov: deadcode */
      DBUG_PRINT("trans",("starting sub transaction")); /* purecov: deadcode */
1274 1275 1276
    }
    error=remove_keys(sub_trans, record, &row, &prim_key, keys);
    if (!error && (thd_options & OPTION_INTERNAL_SUBTRANSACTIONS))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1277
    {
1278 1279
      DBUG_PRINT("trans",("ending sub transaction")); /* purecov: deadcode */
      error=txn_commit(sub_trans, 0); /* purecov: deadcode */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1280 1281
    }
    if (error)
1282
    { /* purecov: inspected */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1283
      DBUG_PRINT("error",("Got error %d",error));
1284
      if (thd_options & OPTION_INTERNAL_SUBTRANSACTIONS)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1285
      {
1286 1287 1288 1289 1290 1291 1292 1293
	/* retry */
	int new_error;
	DBUG_PRINT("trans",("aborting subtransaction"));
	if ((new_error=txn_abort(sub_trans)))
	{
	  error=new_error;			// This shouldn't happen
	  break;
	}
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1294
      }
1295 1296
      else
	break;					// No retry - return error
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1297 1298 1299 1300
    }
    if (error != DB_LOCK_DEADLOCK)
      break;
  }
monty@donna.mysql.com's avatar
monty@donna.mysql.com committed
1301
#ifdef CANT_COUNT_DELETED_ROWS
1302 1303
  if (!error)
    changed_rows--;
monty@donna.mysql.com's avatar
monty@donna.mysql.com committed
1304
#endif
1305
  DBUG_RETURN(error);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1306 1307 1308 1309 1310 1311
}


int ha_berkeley::index_init(uint keynr)
{
  int error;
1312
  DBUG_ENTER("ha_berkeley::index_init");
1313
  DBUG_PRINT("enter",("table: '%s'  key: %d", table->real_name, keynr));
1314 1315 1316 1317 1318 1319

  /*
    Under some very rare conditions (like full joins) we may already have
    an active cursor at this point
  */
  if (cursor)
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
1320 1321
  {
    DBUG_PRINT("note",("Closing active cursor"));
1322
    cursor->c_close(cursor);
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
1323
  }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1324
  active_index=keynr;
1325 1326 1327 1328
  if ((error=key_file[keynr]->cursor(key_file[keynr], transaction, &cursor,
				     table->reginfo.lock_type >
				     TL_WRITE_ALLOW_READ ?
				     0 : 0)))
1329
    cursor=0;				// Safety /* purecov: inspected */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1330 1331 1332 1333 1334 1335 1336
  bzero((char*) &last_key,sizeof(last_key));
  DBUG_RETURN(error);
}

int ha_berkeley::index_end()
{
  int error=0;
1337
  DBUG_ENTER("ha_berkely::index_end");
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1338 1339
  if (cursor)
  {
1340
    DBUG_PRINT("enter",("table: '%s'", table->real_name));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1341 1342 1343 1344 1345 1346 1347 1348 1349 1350
    error=cursor->c_close(cursor);
    cursor=0;
  }
  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,
1351
			  DBT *found_key, bool read_next)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1352
{
1353
  DBUG_ENTER("ha_berkeley::read_row");
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1354 1355 1356 1357 1358 1359 1360
  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);
  }
1361 1362 1363 1364 1365
  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;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1366 1367
  if (keynr != primary_key)
  {
1368 1369 1370 1371 1372 1373 1374 1375 1376
    /* 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);
    }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1377 1378
    DBT key;
    bzero((char*) &key,sizeof(key));
1379
    key.data=key_buff;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1380
    key.size=row->size;
1381
    key.app_private= (void*) (table->key_info+primary_key);
1382
    memcpy(key_buff,row->data,row->size);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1383 1384 1385 1386
    /* Read the data into current_row */
    current_row.flags=DB_DBT_REALLOC;
    if ((error=file->get(file, transaction, &key, &current_row, 0)))
    {
1387 1388
      table->status=STATUS_NOT_FOUND; /* purecov: inspected */
      DBUG_RETURN(error == DB_NOTFOUND ? HA_ERR_CRASHED : error); /* purecov: inspected */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1389 1390 1391 1392 1393 1394 1395 1396
    }
    row= &current_row;
  }
  unpack_row(buf,row);
  DBUG_RETURN(0);
}


1397 1398
/* This is only used to read whole keys */

bk@work.mysql.com's avatar
bk@work.mysql.com committed
1399 1400 1401 1402 1403 1404
int ha_berkeley::index_read_idx(byte * buf, uint keynr, const byte * key,
				uint key_len, enum ha_rkey_function find_flag)
{
  statistic_increment(ha_read_key_count,&LOCK_status);
  DBUG_ENTER("index_read_idx");
  current_row.flags=DB_DBT_REALLOC;
1405
  active_index= (uint) -1;
1406
  DBUG_RETURN(read_row(key_file[keynr]->get(key_file[keynr], transaction,
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1407 1408 1409
				 pack_key(&last_key, keynr, key_buff, key,
					  key_len),
				 &current_row,0),
1410
		       (char*) buf, keynr, &current_row, &last_key, 0));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1411 1412 1413 1414 1415 1416 1417
}


int ha_berkeley::index_read(byte * buf, const byte * key,
			    uint key_len, enum ha_rkey_function find_flag)
{
  DBT row;
1418
  int error;
1419
  KEY *key_info= &table->key_info[active_index];
1420
  DBUG_ENTER("ha_berkeley::index_read");
1421

bk@work.mysql.com's avatar
bk@work.mysql.com committed
1422 1423
  statistic_increment(ha_read_key_count,&LOCK_status);
  bzero((char*) &row,sizeof(row));
1424
  if (key_len == key_info->key_length)
1425
  {
1426 1427
    if (find_flag == HA_READ_AFTER_KEY)
      key_info->handler.bdb_return_if_eq= 1;
1428 1429 1430 1431
    error=read_row(cursor->c_get(cursor, pack_key(&last_key,
						  active_index,
						  key_buff,
						  key, key_len),
1432 1433 1434
				 &row,
				 (find_flag == HA_READ_KEY_EXACT ?
				  DB_SET : DB_SET_RANGE)),
1435
		   (char*) buf, active_index, &row, (DBT*) 0, 0);
1436
    key_info->handler.bdb_return_if_eq= 0;
1437 1438 1439 1440 1441 1442
  }
  else
  {
    /* read of partial key */
    pack_key(&last_key, active_index, key_buff, key, key_len);
    /* Store for compare */
1443
    memcpy(key_buff2, key_buff, (key_len=last_key.size));
1444 1445 1446 1447 1448 1449
    /*
      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);
1450
    error=read_row(cursor->c_get(cursor, &last_key, &row, DB_SET_RANGE),
1451
		   (char*) buf, active_index, &row, (DBT*) 0, 0);
1452
    key_info->handler.bdb_return_if_eq= 0;
1453 1454
    if (!error && find_flag == HA_READ_KEY_EXACT)
    {
1455 1456
      /* 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))
1457 1458 1459 1460
	error=HA_ERR_KEY_NOT_FOUND;
    }
  }
  DBUG_RETURN(error);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1461 1462
}

1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493
/*
  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");

  statistic_increment(ha_read_key_count,&LOCK_status);
  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);
}

bk@work.mysql.com's avatar
bk@work.mysql.com committed
1494 1495 1496 1497 1498 1499 1500 1501

int ha_berkeley::index_next(byte * buf)
{
  DBT row;
  DBUG_ENTER("index_next");
  statistic_increment(ha_read_next_count,&LOCK_status);
  bzero((char*) &row,sizeof(row));
  DBUG_RETURN(read_row(cursor->c_get(cursor, &last_key, &row, DB_NEXT),
1502
		       (char*) buf, active_index, &row, &last_key, 1));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513
}

int ha_berkeley::index_next_same(byte * buf, const byte *key, uint keylen)
{
  DBT row;
  int error;
  DBUG_ENTER("index_next_same");
  statistic_increment(ha_read_next_count,&LOCK_status);
  bzero((char*) &row,sizeof(row));
  if (keylen == table->key_info[active_index].key_length)
    error=read_row(cursor->c_get(cursor, &last_key, &row, DB_NEXT_DUP),
1514
		   (char*) buf, active_index, &row, &last_key, 1);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1515 1516 1517
  else
  {
    error=read_row(cursor->c_get(cursor, &last_key, &row, DB_NEXT),
1518
		   (char*) buf, active_index, &row, &last_key, 1);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532
    if (!error && ::key_cmp(table, key, active_index, keylen))
      error=HA_ERR_END_OF_FILE;
  }
  DBUG_RETURN(error);
}


int ha_berkeley::index_prev(byte * buf)
{
  DBT row;
  DBUG_ENTER("index_prev");
  statistic_increment(ha_read_prev_count,&LOCK_status);
  bzero((char*) &row,sizeof(row));
  DBUG_RETURN(read_row(cursor->c_get(cursor, &last_key, &row, DB_PREV),
1533
		       (char*) buf, active_index, &row, &last_key, 1));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1534
}
1535

bk@work.mysql.com's avatar
bk@work.mysql.com committed
1536 1537 1538 1539 1540 1541 1542 1543

int ha_berkeley::index_first(byte * buf)
{
  DBT row;
  DBUG_ENTER("index_first");
  statistic_increment(ha_read_first_count,&LOCK_status);
  bzero((char*) &row,sizeof(row));
  DBUG_RETURN(read_row(cursor->c_get(cursor, &last_key, &row, DB_FIRST),
1544
		       (char*) buf, active_index, &row, &last_key, 1));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1545 1546 1547 1548 1549 1550 1551 1552 1553
}

int ha_berkeley::index_last(byte * buf)
{
  DBT row;
  DBUG_ENTER("index_last");
  statistic_increment(ha_read_last_count,&LOCK_status);
  bzero((char*) &row,sizeof(row));
  DBUG_RETURN(read_row(cursor->c_get(cursor, &last_key, &row, DB_LAST),
1554
		       (char*) buf, active_index, &row, &last_key, 0));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1555 1556 1557 1558
}

int ha_berkeley::rnd_init(bool scan)
{
1559
  DBUG_ENTER("rnd_init");
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1560
  current_row.flags=DB_DBT_REALLOC;
1561
  DBUG_RETURN(index_init(primary_key));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575
}

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

int ha_berkeley::rnd_next(byte *buf)
{
  DBT row;
  DBUG_ENTER("rnd_next");
  statistic_increment(ha_read_rnd_next_count,&LOCK_status);
  bzero((char*) &row,sizeof(row));
  DBUG_RETURN(read_row(cursor->c_get(cursor, &last_key, &row, DB_NEXT),
1576
		       (char*) buf, primary_key, &row, &last_key, 1));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1577 1578 1579 1580 1581
}


DBT *ha_berkeley::get_pos(DBT *to, byte *pos)
{
1582
  /* We don't need to set app_private here */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1583 1584 1585
  bzero((char*) to,sizeof(*to));

  to->data=pos;
1586
  if (share->fixed_length_primary_key)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1587 1588 1589 1590 1591 1592
    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;

1593
    for (; key_part != end ; key_part++)
1594
      pos+=key_part->field->packed_col_length((char*) pos,key_part->length);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1595 1596 1597 1598 1599 1600 1601 1602 1603 1604
    to->size= (uint) (pos- (byte*) to->data);
  }
  return to;
}


int ha_berkeley::rnd_pos(byte * buf, byte *pos)
{
  DBT db_pos;
  statistic_increment(ha_read_rnd_count,&LOCK_status);
1605
  DBUG_ENTER("ha_berkeley::rnd_pos");
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1606

1607
  active_index= (uint) -1;			// Don't delete via cursor
1608 1609 1610 1611
  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));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1612 1613
}

1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635
/*
  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
*/

bk@work.mysql.com's avatar
bk@work.mysql.com committed
1636 1637 1638
void ha_berkeley::position(const byte *record)
{
  DBT key;
1639
  DBUG_ENTER("ha_berkeley::position");
1640
  if (hidden_primary_key)
1641 1642
  {
    DBUG_ASSERT(ref_length == BDB_HIDDEN_PRIMARY_KEY_LENGTH);
1643
    memcpy_fixed(ref, (char*) current_ident, BDB_HIDDEN_PRIMARY_KEY_LENGTH);
1644
  }
1645
  else
1646
  {
1647
    create_key(&key, primary_key, (char*) ref, record);
1648 1649 1650 1651
    if (key.size < ref_length)
      bzero(ref + key.size, ref_length - key.size);
  }
  DBUG_VOID_RETURN;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1652 1653 1654 1655 1656
}


void ha_berkeley::info(uint flag)
{
1657
  DBUG_ENTER("ha_berkeley::info");
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1658 1659
  if (flag & HA_STATUS_VARIABLE)
  {
1660
    records = share->rows + changed_rows; // Just to get optimisations right
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1661 1662
    deleted = 0;
  }
1663 1664 1665 1666 1667 1668 1669 1670 1671
  if ((flag & HA_STATUS_CONST) || version != share->version)
  {
    version=share->version;
    for (uint i=0 ; i < table->keys ; i++)
    {
      table->key_info[i].rec_per_key[table->key_info[i].key_parts-1]=
	share->rec_per_key[i];
    }
  }
1672 1673 1674
  /* Don't return key if we got an error for the internal primary key */
  if (flag & HA_STATUS_ERRKEY && last_dup_key < table->keys)
    errkey= last_dup_key;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1675 1676 1677 1678 1679 1680
  DBUG_VOID_RETURN;
}


int ha_berkeley::extra(enum ha_extra_function operation)
{
1681 1682 1683 1684
  switch (operation) {
  case HA_EXTRA_RESET:
  case HA_EXTRA_RESET_STATE:
    key_read=0;
1685
    using_ignore=0;
1686 1687 1688 1689 1690 1691 1692 1693 1694
    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;
      }
    }
1695 1696 1697 1698 1699 1700 1701
    break;
  case HA_EXTRA_KEYREAD:
    key_read=1;					// Query satisfied with key
    break;
  case HA_EXTRA_NO_KEYREAD:
    key_read=0;
    break;
1702 1703 1704 1705 1706 1707
  case HA_EXTRA_IGNORE_DUP_KEY:
    using_ignore=1;
    break;
  case HA_EXTRA_NO_IGNORE_DUP_KEY:
    using_ignore=0;
    break;
1708 1709 1710
  default:
    break;
  }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1711 1712 1713
  return 0;
}

1714

bk@work.mysql.com's avatar
bk@work.mysql.com committed
1715 1716
int ha_berkeley::reset(void)
{
1717
  key_read=0;					// Reset to state after open
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1718 1719 1720 1721 1722 1723 1724
  return 0;
}


/*
  As MySQL will execute an external lock for every new table it uses
  we can use this to start the transactions.
1725 1726 1727 1728
  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.
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1729 1730 1731 1732 1733 1734 1735 1736
*/

int ha_berkeley::external_lock(THD *thd, int lock_type)
{
  int error=0;
  DBUG_ENTER("ha_berkeley::external_lock");
  if (lock_type != F_UNLCK)
  {
1737
    if (!thd->transaction.bdb_lock_count++)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1738
    {
1739
      DBUG_ASSERT(thd->transaction.stmt.bdb_tid == 0);
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
1740
      transaction=0;				// Safety
1741
      /* First table lock, start transaction */
1742
      if ((thd->options & (OPTION_NOT_AUTOCOMMIT | OPTION_BEGIN |
1743
			   OPTION_TABLE_LOCK)) &&
1744 1745 1746
	  !thd->transaction.all.bdb_tid)
      {
	/* We have to start a master transaction */
1747
	DBUG_PRINT("trans",("starting transaction all"));
1748 1749 1750 1751
	if ((error=txn_begin(db_env, 0,
			     (DB_TXN**) &thd->transaction.all.bdb_tid,
			     0)))
	{
1752 1753
	  thd->transaction.bdb_lock_count--;	// We didn't get the lock /* purecov: inspected */
	  DBUG_RETURN(error); /* purecov: inspected */
1754
	}
1755 1756
	if (thd->in_lock_tables)
	  DBUG_RETURN(0);			// Don't create stmt trans
1757
      }
1758
      DBUG_PRINT("trans",("starting transaction stmt"));
1759 1760 1761
      if ((error=txn_begin(db_env,
			   (DB_TXN*) thd->transaction.all.bdb_tid,
			   (DB_TXN**) &thd->transaction.stmt.bdb_tid,
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1762
			   0)))
1763 1764
      {
	/* We leave the possible master transaction open */
1765 1766
	thd->transaction.bdb_lock_count--;	// We didn't get the lock /* purecov: inspected */
	DBUG_RETURN(error); /* purecov: inspected */
1767
      }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1768
    }
1769
    transaction= (DB_TXN*) thd->transaction.stmt.bdb_tid;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1770 1771 1772 1773
  }
  else
  {
    lock.type=TL_UNLOCK;			// Unlocked
1774
    thread_safe_add(share->rows, changed_rows, &share->mutex);
1775
    changed_rows=0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1776 1777
    if (!--thd->transaction.bdb_lock_count)
    {
1778
      if (thd->transaction.stmt.bdb_tid)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1779
      {
1780
	/*
1781
	   F_UNLOCK is done without a transaction commit / rollback.
1782 1783
	   This happens if the thread didn't update any rows
	   We must in this case commit the work to keep the row locks
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1784
	*/
1785 1786 1787
	DBUG_PRINT("trans",("commiting non-updating transaction"));
	error=txn_commit((DB_TXN*) thd->transaction.stmt.bdb_tid,0);
	thd->transaction.stmt.bdb_tid=0;
1788
	transaction=0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1789 1790 1791 1792
      }
    }
  }
  DBUG_RETURN(error);
1793
}
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1794

1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807

/*
  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.
*/

int ha_berkeley::start_stmt(THD *thd)
{
  int error=0;
  DBUG_ENTER("ha_berkeley::start_stmt");
  if (!thd->transaction.stmt.bdb_tid)
  {
1808
    DBUG_PRINT("trans",("starting transaction stmt"));
1809 1810 1811 1812
    error=txn_begin(db_env, (DB_TXN*) thd->transaction.all.bdb_tid,
		    (DB_TXN**) &thd->transaction.stmt.bdb_tid,
		    0);
  }
1813
  transaction= (DB_TXN*) thd->transaction.stmt.bdb_tid;
1814 1815 1816 1817
  DBUG_RETURN(error);
}


1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845
/*
  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.
*/

bk@work.mysql.com's avatar
bk@work.mysql.com committed
1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857

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;
    lock.type=lock_type;
1858 1859
    lock_on_read= ((table->reginfo.lock_type > TL_WRITE_ALLOW_READ) ? DB_RMW :
		   0);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1860 1861 1862 1863 1864 1865 1866 1867 1868
  }
  *to++= &lock;
  return to;
}


static int create_sub_table(const char *table_name, const char *sub_name,
			    DBTYPE type, int flags)
{
1869
  int error;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1870 1871
  DB *file;
  DBUG_ENTER("create_sub_table");
1872
  DBUG_PRINT("enter",("sub_name: %s  flags: %d",sub_name, flags));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1873 1874 1875 1876 1877 1878 1879 1880

  if (!(error=db_create(&file, db_env, 0)))
  {
    file->set_flags(file, flags);
    error=(file->open(file, table_name, sub_name, type,
		      DB_THREAD | DB_CREATE, my_umask));
    if (error)
    {
1881 1882 1883
      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 */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1884 1885 1886 1887 1888 1889
    }
    else
      (void) file->close(file,0);
  }
  else
  {
1890
    DBUG_PRINT("error",("Got error: %d when creting table",error)); /* purecov: inspected */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1891 1892
  }
  if (error)
1893
    my_errno=error; /* purecov: inspected */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1894 1895 1896 1897 1898 1899 1900 1901 1902
  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];
1903
  uint index=1;
1904
  int error;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1905 1906 1907 1908 1909
  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 */
1910 1911
  if ((error= create_sub_table(name_buff,"main",DB_BTREE,0)))
    DBUG_RETURN(error); /* purecov: inspected */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1912

1913
  primary_key=table->primary_key;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1914
  /* Create the keys */
1915
  for (uint i=0; i < form->keys; i++)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1916
  {
1917 1918 1919
    if (i != primary_key)
    {
      sprintf(part,"key%02d",index++);
1920 1921 1922 1923
      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 */
1924
    }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1925 1926 1927 1928
  }

  /* 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) */
1929 1930

  DB *status_block;
1931
  if (!(error=(db_create(&status_block, db_env, 0))))
1932
  {
1933 1934
    if (!(error=(status_block->open(status_block, name_buff,
				    "status", DB_BTREE, DB_CREATE, 0))))
1935 1936 1937 1938
    {
      char rec_buff[4+MAX_KEY*4];
      uint length= 4+ table->keys*4;
      bzero(rec_buff, length);
1939
      error= write_status(status_block, rec_buff, length);
1940 1941 1942 1943
      status_block->close(status_block,0);
    }
  }
  DBUG_RETURN(error);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1944 1945 1946
}


1947

bk@work.mysql.com's avatar
bk@work.mysql.com committed
1948 1949 1950 1951
int ha_berkeley::delete_table(const char *name)
{
  int error;
  char name_buff[FN_REFLEN];
1952
  DBUG_ENTER("delete_table");
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1953
  if ((error=db_create(&file, db_env, 0)))
1954
    my_errno=error; /* purecov: inspected */
1955 1956 1957
  else
    error=file->remove(file,fn_format(name_buff,name,"",ha_berkeley_ext,2 | 4),
		       NULL,0);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1958
  file=0;					// Safety
1959
  DBUG_RETURN(error);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1960 1961
}

1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981
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
  {
    /* On should not do a file->close() after rename returns */
    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);
  }
  return error;
}


bk@work.mysql.com's avatar
bk@work.mysql.com committed
1982 1983 1984 1985 1986 1987 1988 1989
/*
  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()
{
1990
  return rows2double(records/3);
1991
}
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1992 1993 1994 1995 1996 1997 1998 1999 2000

ha_rows ha_berkeley::records_in_range(int keynr,
				      const byte *start_key,uint start_key_len,
				      enum ha_rkey_function start_search_flag,
				      const byte *end_key,uint end_key_len,
				      enum ha_rkey_function end_search_flag)
{
  DBT key;
  DB_KEY_RANGE start_range, end_range;
2001
  DB *kfile=key_file[keynr];
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2002 2003
  double start_pos,end_pos,rows;
  DBUG_ENTER("records_in_range");
2004 2005 2006 2007 2008 2009 2010 2011 2012

  if ((start_key && kfile->key_range(kfile,transaction,
				     pack_key(&key, keynr, key_buff, start_key,
					      start_key_len),
				     &start_range,0)) ||
      (end_key && kfile->key_range(kfile,transaction,
				   pack_key(&key, keynr, key_buff, end_key,
					    end_key_len),
				   &end_range,0)))
2013
    DBUG_RETURN(HA_BERKELEY_RANGE_COUNT); // Better than returning an error /* purecov: inspected */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032

  if (!start_key)
    start_pos=0.0;
  else if (start_search_flag == HA_READ_KEY_EXACT)
    start_pos=start_range.less;
  else
    start_pos=start_range.less+start_range.equal;

  if (!end_key)
    end_pos=1.0;
  else if (end_search_flag == HA_READ_BEFORE_KEY)
    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));
  DBUG_RETURN(rows <= 1.0 ? (ha_rows) 1 : (ha_rows) rows);
}

2033 2034 2035 2036 2037 2038

longlong ha_berkeley::get_auto_increment()
{
  longlong nr=1;				// Default if error or new key
  int error;
  (void) ha_berkeley::extra(HA_EXTRA_KEYREAD);
2039 2040

  /* Set 'active_index' */
2041 2042 2043 2044 2045 2046 2047 2048
  ha_berkeley::index_init(table->next_number_index);

  if (!table->next_number_key_offset)
  {						// Autoincrement at key-start
    error=ha_berkeley::index_last(table->record[1]);
  }
  else
  {
2049
    DBT row,old_key;
2050 2051 2052 2053 2054 2055 2056 2057
    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],
			    table->next_number_key_offset);
    /* Store for compare */
2058
    memcpy(old_key.data=key_buff2, key_buff, (old_key.size=last_key.size));
2059
    old_key.app_private=(void*) key_info;
2060
    error=1;
2061
    {
2062 2063 2064
      /* 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 */
2065
      error=cursor->c_get(cursor, &last_key, &row, DB_SET_RANGE | DB_RMW);
2066 2067 2068 2069 2070 2071 2072 2073
      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;
2074 2075 2076
	if (!cursor->c_get(cursor, &last_key, &row, DB_PREV | DB_RMW) &&
	    !berkeley_cmp_packed_key(key_file[active_index], &old_key,
				     &last_key))
2077 2078
	{
	  error=0;				// Found value
2079
	  unpack_key((char*) table->record[1], &last_key, active_index);
2080 2081
	}
      }
2082 2083
    }
  }
2084 2085 2086
  if (!error)
    nr=(longlong)
      table->next_number_field->val_int_offset(table->rec_buff_length)+1;
2087 2088 2089 2090 2091
  ha_berkeley::index_end();
  (void) ha_berkeley::extra(HA_EXTRA_NO_KEYREAD);
  return nr;
}

2092 2093 2094 2095 2096 2097
void ha_berkeley::print_error(int error, myf errflag)
{
  if (error == DB_LOCK_DEADLOCK)
    error=HA_ERR_LOCK_DEADLOCK;
  handler::print_error(error,errflag);
}
2098 2099 2100 2101 2102

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

2103
#ifdef NOT_YET
2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126
static void print_msg(THD *thd, const char *table_name, const char *op_name,
		      const char *msg_type, const char *fmt, ...)
{
  String* packet = &thd->packet;
  packet->length(0);
  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));

  net_store_data(packet, table_name);
  net_store_data(packet, op_name);
  net_store_data(packet, msg_type);
  net_store_data(packet, msgbuf);
  if (my_net_write(&thd->net, (char*)thd->packet.ptr(),
		   thd->packet.length()))
    thd->killed=1;
}
2127
#endif
2128 2129 2130

int ha_berkeley::analyze(THD* thd, HA_CHECK_OPT* check_opt)
{
2131
  DB_BTREE_STAT *stat=0;
2132
  uint i;
vva@eagle.mysql.r18.ru's avatar
vva@eagle.mysql.r18.ru committed
2133 2134
  DB_TXN_STAT *txn_stat_ptr= 0;

2135 2136 2137 2138 2139 2140 2141 2142 2143
  /*
   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..
  */

vva@eagle.mysql.r18.ru's avatar
vva@eagle.mysql.r18.ru committed
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 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179
  /*
    If it's a merge conflict here (4.0->4.1), please ignore it!

    The reason of the conflict is the difference between versions of bdb:
    mysql-4.0 uses bdb 3.2.9
    mysql-4.1 uses bdb 4.1.24
    Older one has global functions txn_stat and txn_id but
    newer one has DB_ENV->txn_stat and DB_TXN->id
  */
  if (!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;
    
    DB_TXN *txn_all= (DB_TXN*) thd->transaction.all.bdb_tid;
    u_int32_t all_id= txn_id(txn_all);
    
    DB_TXN *txn_stmt= (DB_TXN*) thd->transaction.stmt.bdb_tid;
    u_int32_t stmt_id= txn_id(txn_stmt);
    
    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;
    }
    
    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);
  }
2180 2181 2182

  for (i=0 ; i < table->keys ; i++)
  {
2183 2184 2185 2186 2187
    if (stat)
    {
      free(stat);
      stat=0;
    }
2188
    if ((key_file[i]->stat)(key_file[i], (void*) &stat, 0, 0))
2189
      goto err; /* purecov: inspected */
2190 2191
    share->rec_per_key[i]= (stat->bt_ndata /
			    (stat->bt_nkeys ? stat->bt_nkeys : 1));
2192
  }
2193
  /* A hidden primary key is not in key_file[] */
2194
  if (hidden_primary_key)
2195 2196 2197 2198 2199 2200
  {
    if (stat)
    {
      free(stat);
      stat=0;
    }
2201
    if ((file->stat)(file, (void*) &stat, 0, 0))
2202
      goto err; /* purecov: inspected */
2203
  }
2204
  pthread_mutex_lock(&share->mutex);
2205
  share->rows=stat->bt_ndata;
2206 2207 2208
  share->status|=STATUS_BDB_ANALYZE;		// Save status on close
  share->version++;				// Update stat in table
  pthread_mutex_unlock(&share->mutex);
2209 2210 2211
  update_status(share,table);			// Write status to file
  if (stat)
    free(stat);
2212 2213
  return ((share->status & STATUS_BDB_ANALYZE) ? HA_ADMIN_FAILED :
	  HA_ADMIN_OK);
2214 2215

err:
2216 2217 2218
  if (stat) /* purecov: inspected */
    free(stat); /* purecov: inspected */
  return HA_ADMIN_FAILED; /* purecov: inspected */
2219 2220 2221 2222 2223 2224 2225 2226 2227 2228
}

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)
{
2229 2230 2231 2232 2233
  DBUG_ENTER("ha_berkeley::check");

  DBUG_RETURN(HA_ADMIN_NOT_IMPLEMENTED);

#ifdef NOT_YET
2234 2235 2236
  char name_buff[FN_REFLEN];
  int error;
  DB *tmp_file;
2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254
  /*
    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));
2255
  tmp_file->app_private= (void*) (table->key_info+table->primary_key);
2256
  fn_format(name_buff,share->table_name,"", ha_berkeley_ext, 2 | 4);
2257 2258
  if ((error=tmp_file->verify(tmp_file, name_buff, NullS, (FILE*) 0,
			      hidden_primary_key ? 0 : DB_NOORDERCHK)))
2259 2260 2261
  {
    print_msg(thd, table->real_name, "check", "error",
	      "Got error %d checking file structure",error);
2262 2263
    tmp_file->close(tmp_file,0);
    DBUG_RETURN(HA_ADMIN_CORRUPT);
2264
  }
2265 2266 2267 2268

  /* Check each index */
  tmp_file->set_bt_compare(tmp_file, berkeley_cmp_packed_key);
  for (uint index=0,i=0 ; i < table->keys ; i++)
2269
  {
2270 2271 2272 2273 2274 2275 2276 2277
    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)))
2278 2279
    {
      print_msg(thd, table->real_name, "check", "error",
2280 2281 2282 2283 2284
		"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);
2285 2286
    }
  }
2287 2288 2289
  tmp_file->close(tmp_file,0);
  DBUG_RETURN(HA_ADMIN_OK);
#endif
2290 2291
}

bk@work.mysql.com's avatar
bk@work.mysql.com committed
2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303
/****************************************************************************
 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;
}

2304
static BDB_SHARE *get_share(const char *table_name, TABLE *table)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2305 2306 2307
{
  BDB_SHARE *share;
  pthread_mutex_lock(&bdb_mutex);
2308
  uint length=(uint) strlen(table_name);
2309 2310
  if (!(share=(BDB_SHARE*) hash_search(&bdb_open_tables, (byte*) table_name,
				       length)))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2311
  {
2312
    ulong *rec_per_key;
2313 2314 2315
    char *tmp_name;
    DB **key_file;
    u_int32_t *key_type;
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
2316

2317 2318 2319 2320 2321 2322 2323 2324
    if ((share=(BDB_SHARE *)
	 my_multi_malloc(MYF(MY_WME | MY_ZEROFILL),
			 &share, sizeof(*share),
			 &rec_per_key, table->keys * sizeof(ha_rows),
			 &tmp_name, length+1,
			 &key_file, (table->keys+1) * sizeof(*key_file),
			 &key_type, (table->keys+1) * sizeof(u_int32_t),
			 NullS)))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2325
    {
2326 2327
      share->rec_per_key = rec_per_key;
      share->table_name = tmp_name;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2328 2329
      share->table_name_length=length;
      strmov(share->table_name,table_name);
2330 2331
      share->key_file = key_file;
      share->key_type = key_type;
2332
      if (hash_insert(&bdb_open_tables, (byte*) share))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2333
      {
2334 2335 2336
	pthread_mutex_unlock(&bdb_mutex); /* purecov: inspected */
	my_free((gptr) share,0); /* purecov: inspected */
	return 0; /* purecov: inspected */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2337 2338
      }
      thr_lock_init(&share->lock);
2339
      pthread_mutex_init(&share->mutex,MY_MUTEX_INIT_FAST);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2340 2341 2342 2343 2344 2345
    }
  }
  pthread_mutex_unlock(&bdb_mutex);
  return share;
}

2346 2347
static int free_share(BDB_SHARE *share, TABLE *table, uint hidden_primary_key,
		      bool mutex_is_locked)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2348
{
2349
  int error, result = 0;
2350
  uint keys=table->keys + test(hidden_primary_key);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2351
  pthread_mutex_lock(&bdb_mutex);
2352
  if (mutex_is_locked)
2353
    pthread_mutex_unlock(&share->mutex); /* purecov: inspected */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2354 2355
  if (!--share->use_count)
  {
2356
    DB **key_file = share->key_file;
2357
    update_status(share,table);
2358
    /* this does share->file->close() implicitly */
2359
    for (uint i=0; i < keys; i++)
2360 2361
    {
      if (key_file[i] && (error=key_file[i]->close(key_file[i],0)))
2362
	result=error; /* purecov: inspected */
2363 2364 2365
    }
    if (share->status_block &&
	(error = share->status_block->close(share->status_block,0)))
2366
      result = error; /* purecov: inspected */
2367
    hash_delete(&bdb_open_tables, (byte*) share);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2368
    thr_lock_delete(&share->lock);
2369
    pthread_mutex_destroy(&share->mutex);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2370 2371 2372
    my_free((gptr) share, MYF(0));
  }
  pthread_mutex_unlock(&bdb_mutex);
2373
  return result;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2374 2375
}

2376 2377 2378 2379
/*
  Get status information that is stored in the 'status' sub database
  and the max used value for the hidden primary key.
*/
2380

2381
void ha_berkeley::get_status()
2382
{
2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403
  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);
      index_init(primary_key);
      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))
      {
2404 2405
	if (share->status_block->open(share->status_block, name_buff,
				      "status", DB_BTREE, open_mode, 0))
2406
	{
2407 2408
	  share->status_block->close(share->status_block, 0); /* purecov: inspected */
	  share->status_block=0; /* purecov: inspected */
2409 2410 2411 2412 2413 2414 2415
	}
      }
    }
    if (!(share->status & STATUS_ROW_COUNT_INIT) && share->status_block)
    {
      share->org_rows=share->rows=
	table->max_rows ? table->max_rows : HA_BERKELEY_MAX_ROWS;
2416
      if (!share->status_block->cursor(share->status_block, 0, &cursor, 0))
2417 2418
      {
	DBT row;
2419
	char rec_buff[64];
2420 2421 2422
	bzero((char*) &row,sizeof(row));
	bzero((char*) &last_key,sizeof(last_key));
	row.data=rec_buff;
2423
	row.ulen=sizeof(rec_buff);
2424 2425 2426 2427
	row.flags=DB_DBT_USERMEM;
	if (!cursor->c_get(cursor, &last_key, &row, DB_FIRST))
	{
	  uint i;
2428
	  uchar *pos=(uchar*) row.data;
2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444
	  share->org_rows=share->rows=uint4korr(pos); pos+=4;
	  for (i=0 ; i < table->keys ; i++)
	  {
	    share->rec_per_key[i]=uint4korr(pos); pos+=4;
	  }
	}
	cursor->c_close(cursor);
      }
      cursor=0;					// Safety
    }
    share->status|= STATUS_PRIMARY_KEY_INIT | STATUS_ROW_COUNT_INIT;
    pthread_mutex_unlock(&share->mutex);
  }
}


2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461
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;
}


2462 2463 2464 2465 2466
static void update_status(BDB_SHARE *share, TABLE *table)
{
  DBUG_ENTER("update_status");
  if (share->rows != share->org_rows ||
      (share->status & STATUS_BDB_ANALYZE))
2467
  {
2468 2469 2470 2471 2472 2473 2474 2475
    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)
      */

2476 2477 2478 2479
      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 */
2480 2481 2482 2483
      if (share->status_block->open(share->status_block,
				    fn_format(name_buff,share->table_name,"",
					      ha_berkeley_ext,2 | 4),
				    "status", DB_BTREE,
2484 2485
				    DB_THREAD | DB_CREATE, my_umask)) /* purecov: inspected */
	goto end; /* purecov: inspected */
2486 2487
    }
    {
2488
      char rec_buff[4+MAX_KEY*4], *pos=rec_buff;
2489
      int4store(pos,share->rows); pos+=4;
2490
      for (uint i=0 ; i < table->keys ; i++)
2491 2492 2493
      {
	int4store(pos,share->rec_per_key[i]); pos+=4;
      }
2494 2495 2496
      DBUG_PRINT("info",("updating status for %s",share->table_name));
      (void) write_status(share->status_block, rec_buff,
			  (uint) (pos-rec_buff));
2497
      share->status&= ~STATUS_BDB_ANALYZE;
2498
      share->org_rows=share->rows;
2499 2500 2501
    }
end:
    pthread_mutex_unlock(&share->mutex);
2502
  }
2503
  DBUG_VOID_RETURN;
2504 2505
}

2506 2507 2508 2509 2510 2511 2512
/*
  Return an estimated of the number of rows in the table.
  Used when sorting to allocate buffers and by the optimizer.
*/

ha_rows ha_berkeley::estimate_number_of_rows()
{
2513
  return share->rows + HA_BERKELEY_EXTRA_ROWS;
2514 2515
}

bk@work.mysql.com's avatar
bk@work.mysql.com committed
2516
#endif /* HAVE_BERKELEY_DB */