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

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

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

unknown's avatar
unknown committed
13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
   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 */


/* Handler-calling-functions */

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

#include "mysql_priv.h"
#include "ha_heap.h"
#include "ha_myisam.h"
#include "ha_myisammrg.h"
28
#ifdef HAVE_ISAM
unknown's avatar
unknown committed
29 30 31 32 33 34
#include "ha_isam.h"
#include "ha_isammrg.h"
#endif
#ifdef HAVE_BERKELEY_DB
#include "ha_berkeley.h"
#endif
35 36 37
#ifdef HAVE_EXAMPLE_DB
#include "examples/ha_example.h"
#endif
38 39 40
#ifdef HAVE_ARCHIVE_DB
#include "examples/ha_archive.h"
#endif
41 42 43
#ifdef HAVE_CSV_DB
#include "examples/ha_tina.h"
#endif
44
#ifdef HAVE_INNOBASE_DB
45
#include "ha_innodb.h"
46
#endif
unknown's avatar
unknown committed
47 48 49
#ifdef HAVE_NDBCLUSTER_DB
#include "ha_ndbcluster.h"
#endif
50 51 52
#ifdef HAVE_FEDERATED_DB
#include "ha_federated.h"
#endif
unknown's avatar
unknown committed
53 54 55 56 57 58 59
#include <myisampack.h>
#include <errno.h>

	/* static functions defined in this file */

static int NEAR_F delete_file(const char *name,const char *ext,int extflag);

60
ulong ha_read_count, ha_discover_count;
unknown's avatar
unknown committed
61

62
static SHOW_COMP_OPTION have_yes= SHOW_OPTION_YES;
unknown's avatar
unknown committed
63

64
struct show_table_type_st sys_table_types[]=
unknown's avatar
unknown committed
65
{
66
  {"MyISAM",	&have_yes,
unknown's avatar
unknown committed
67
   "Default engine as of MySQL 3.23 with great performance", DB_TYPE_MYISAM},
68
  {"HEAP",	&have_yes,
unknown's avatar
unknown committed
69
   "Alias for MEMORY", DB_TYPE_HEAP},
70
  {"MEMORY",	&have_yes,
unknown's avatar
unknown committed
71
   "Hash based, stored in memory, useful for temporary tables", DB_TYPE_HEAP},
72 73 74 75 76
  {"MERGE",	&have_yes,
   "Collection of identical MyISAM tables", DB_TYPE_MRG_MYISAM},
  {"MRG_MYISAM",&have_yes,
   "Alias for MERGE", DB_TYPE_MRG_MYISAM},
  {"ISAM",	&have_isam,
unknown's avatar
unknown committed
77
   "Obsolete storage engine, now replaced by MyISAM", DB_TYPE_ISAM},
78
  {"MRG_ISAM",  &have_isam,
unknown's avatar
unknown committed
79
   "Obsolete storage engine, now replaced by MERGE", DB_TYPE_MRG_ISAM},
80
  {"InnoDB",	&have_innodb,
unknown's avatar
unknown committed
81
   "Supports transactions, row-level locking, and foreign keys", DB_TYPE_INNODB},
82 83 84 85 86 87
  {"INNOBASE",	&have_innodb,
   "Alias for INNODB", DB_TYPE_INNODB},
  {"BDB",	&have_berkeley_db,
   "Supports transactions and page-level locking", DB_TYPE_BERKELEY_DB},
  {"BERKELEYDB",&have_berkeley_db,
   "Alias for BDB", DB_TYPE_BERKELEY_DB},
unknown's avatar
unknown committed
88
  {"NDBCLUSTER", &have_ndbcluster,
unknown's avatar
unknown committed
89
   "Clustered, fault-tolerant, memory-based tables", DB_TYPE_NDBCLUSTER},
unknown's avatar
unknown committed
90 91
  {"NDB", &have_ndbcluster,
   "Alias for NDBCLUSTER", DB_TYPE_NDBCLUSTER},
92 93
  {"EXAMPLE",&have_example_db,
   "Example storage engine", DB_TYPE_EXAMPLE_DB},
94 95
  {"ARCHIVE",&have_archive_db,
   "Archive storage engine", DB_TYPE_ARCHIVE_DB},
96 97
  {"CSV",&have_csv_db,
   "CSV storage engine", DB_TYPE_CSV_DB},
98 99
  {"FEDERATED",&have_federated_db,
   "Federated MySQL storage engine", DB_TYPE_FEDERATED_DB},
100
  {NullS, NULL, NullS, DB_TYPE_UNKNOWN}
unknown's avatar
unknown committed
101
};
102

unknown's avatar
unknown committed
103 104 105 106
const char *ha_row_type[] = {
  "", "FIXED", "DYNAMIC", "COMPRESSED","?","?","?"
};

unknown's avatar
unknown committed
107
const char *tx_isolation_names[] =
108 109 110
{ "READ-UNCOMMITTED", "READ-COMMITTED", "REPEATABLE-READ", "SERIALIZABLE",
  NullS};
TYPELIB tx_isolation_typelib= {array_elements(tx_isolation_names)-1,"",
111
			       tx_isolation_names, NULL};
unknown's avatar
unknown committed
112

113
static TYPELIB known_extensions= {0,"known_exts", NULL, NULL};
114
uint known_extensions_id= 0;
115

116 117
enum db_type ha_resolve_by_name(const char *name, uint namelen)
{
118
  THD *thd= current_thd;
119 120
  if (thd && !my_strcasecmp(&my_charset_latin1, name, "DEFAULT")) {
    return (enum db_type) thd->variables.table_type;
121 122 123 124 125 126
  }
  
  show_table_type_st *types;
  for (types= sys_table_types; types->type; types++)
  {
    if (!my_strcasecmp(&my_charset_latin1, name, types->type))
127
      return (enum db_type) types->db_type;
128 129 130 131
  }
  return DB_TYPE_UNKNOWN;
}

unknown's avatar
unknown committed
132
const char *ha_get_storage_engine(enum db_type db_type)
133 134 135 136 137 138 139 140 141 142 143
{
  show_table_type_st *types;
  for (types= sys_table_types; types->type; types++)
  {
    if (db_type == types->db_type)
      return types->type;
  }
  
  return "none";
}

unknown's avatar
unknown committed
144 145 146 147
	/* Use other database handler if databasehandler is not incompiled */

enum db_type ha_checktype(enum db_type database_type)
{
148
  show_table_type_st *types;
149
  THD *thd= current_thd;
150 151 152
  for (types= sys_table_types; types->type; types++)
  {
    if ((database_type == types->db_type) && 
unknown's avatar
unknown committed
153
	(*types->value == SHOW_OPTION_YES))
154 155 156
      return database_type;
  }

unknown's avatar
unknown committed
157 158 159
  switch (database_type) {
#ifndef NO_HASH
  case DB_TYPE_HASH:
160
    return (database_type);
161
#endif
162 163
  case DB_TYPE_MRG_ISAM:
    return (DB_TYPE_MRG_MYISAM);
unknown's avatar
unknown committed
164 165 166
  default:
    break;
  }
167
  
168 169 170 171 172
  return ((enum db_type) thd->variables.table_type != DB_TYPE_UNKNOWN ?
          (enum db_type) thd->variables.table_type :
          (enum db_type) global_system_variables.table_type !=
          DB_TYPE_UNKNOWN ?
          (enum db_type) global_system_variables.table_type : DB_TYPE_MYISAM);
unknown's avatar
unknown committed
173 174 175 176 177 178 179
} /* ha_checktype */


handler *get_new_handler(TABLE *table, enum db_type db_type)
{
  switch (db_type) {
#ifndef NO_HASH
180 181
  case DB_TYPE_HASH:
    return new ha_hash(table);
unknown's avatar
unknown committed
182
#endif
183
#ifdef HAVE_ISAM
unknown's avatar
unknown committed
184 185 186 187
  case DB_TYPE_MRG_ISAM:
    return new ha_isammrg(table);
  case DB_TYPE_ISAM:
    return new ha_isam(table);
188 189 190
#else
  case DB_TYPE_MRG_ISAM:
    return new ha_myisammrg(table);
unknown's avatar
unknown committed
191 192 193 194
#endif
#ifdef HAVE_BERKELEY_DB
  case DB_TYPE_BERKELEY_DB:
    return new ha_berkeley(table);
195 196
#endif
#ifdef HAVE_INNOBASE_DB
197
  case DB_TYPE_INNODB:
198
    return new ha_innobase(table);
199 200 201 202
#endif
#ifdef HAVE_EXAMPLE_DB
  case DB_TYPE_EXAMPLE_DB:
    return new ha_example(table);
203
#endif
204 205 206
#ifdef HAVE_ARCHIVE_DB
  case DB_TYPE_ARCHIVE_DB:
    return new ha_archive(table);
unknown's avatar
Merge  
unknown committed
207
#endif
208 209 210 211
#ifdef HAVE_FEDERATED_DB
  case DB_TYPE_FEDERATED_DB:
    return new ha_federated(table);
#endif
212 213 214 215
#ifdef HAVE_CSV_DB
  case DB_TYPE_CSV_DB:
    return new ha_tina(table);
#endif
unknown's avatar
unknown committed
216 217 218
#ifdef HAVE_NDBCLUSTER_DB
  case DB_TYPE_NDBCLUSTER:
    return new ha_ndbcluster(table);
unknown's avatar
unknown committed
219 220 221 222
#endif
  case DB_TYPE_HEAP:
    return new ha_heap(table);
  default:					// should never happen
223 224 225 226 227 228 229 230
  {
    enum db_type def=(enum db_type) current_thd->variables.table_type;
    /* Try first with 'default table type' */
    if (db_type != def)
      return get_new_handler(table, def);
  }
  /* Fall back to MyISAM */
  case DB_TYPE_MYISAM:
unknown's avatar
unknown committed
231 232 233 234 235 236
    return new ha_myisam(table);
  case DB_TYPE_MRG_MYISAM:
    return new ha_myisammrg(table);
  }
}

unknown's avatar
unknown committed
237 238 239 240 241
bool ha_caching_allowed(THD* thd, char* table_key,
                        uint key_length, uint8 cache_type)
{
#ifdef HAVE_INNOBASE_DB
  if (cache_type == HA_CACHE_TBL_ASKTRANSACT)
242
    return innobase_query_caching_of_table_permitted(thd, table_key, key_length);
unknown's avatar
unknown committed
243
#endif
244
  return 1;
unknown's avatar
unknown committed
245 246
}

unknown's avatar
unknown committed
247 248
int ha_init()
{
249
  int error= 0;
unknown's avatar
unknown committed
250
#ifdef HAVE_BERKELEY_DB
251
  if (have_berkeley_db == SHOW_OPTION_YES)
unknown's avatar
unknown committed
252
  {
253 254 255 256 257
    if (berkeley_init())
    {
      have_berkeley_db= SHOW_OPTION_DISABLED;	// If we couldn't use handler
      error= 1;
    }
258
    else
259
      opt_using_transactions=1;
unknown's avatar
unknown committed
260
  }
261 262
#endif
#ifdef HAVE_INNOBASE_DB
263
  if (have_innodb == SHOW_OPTION_YES)
264
  {
unknown's avatar
unknown committed
265
    if (innobase_init())
266 267 268 269
    {
      have_innodb= SHOW_OPTION_DISABLED;	// If we couldn't use handler
      error= 1;
    }
270
    else
271
      opt_using_transactions=1;
272
  }
unknown's avatar
unknown committed
273 274 275 276 277 278 279 280 281 282 283 284
#endif
#ifdef HAVE_NDBCLUSTER_DB
  if (have_ndbcluster == SHOW_OPTION_YES)
  {
    if (ndbcluster_init())
    {
      have_ndbcluster= SHOW_OPTION_DISABLED;
      error= 1;
    }
    else
      opt_using_transactions=1;
  }
unknown's avatar
unknown committed
285
#endif
286
  return error;
unknown's avatar
unknown committed
287 288 289 290 291 292 293 294 295 296 297
}

	/* close, flush or restart databases */
	/* Ignore this for other databases than ours */

int ha_panic(enum ha_panic_function flag)
{
  int error=0;
#ifndef NO_HASH
  error|=h_panic(flag);			/* fix hash */
#endif
298 299
#ifdef HAVE_ISAM
  error|=mrg_panic(flag);
unknown's avatar
unknown committed
300
  error|=nisam_panic(flag);
301 302
#endif
  error|=heap_panic(flag);
unknown's avatar
unknown committed
303 304 305
  error|=mi_panic(flag);
  error|=myrg_panic(flag);
#ifdef HAVE_BERKELEY_DB
306
  if (have_berkeley_db == SHOW_OPTION_YES)
unknown's avatar
unknown committed
307
    error|=berkeley_end();
308 309
#endif
#ifdef HAVE_INNOBASE_DB
310
  if (have_innodb == SHOW_OPTION_YES)
311
    error|=innobase_end();
unknown's avatar
unknown committed
312 313 314 315
#endif
#ifdef HAVE_NDBCLUSTER_DB
  if (have_ndbcluster == SHOW_OPTION_YES)
    error|=ndbcluster_end();
unknown's avatar
unknown committed
316 317 318 319
#endif
  return error;
} /* ha_panic */

320 321 322
void ha_drop_database(char* path)
{
#ifdef HAVE_INNOBASE_DB
323
  if (have_innodb == SHOW_OPTION_YES)
324 325
    innobase_drop_database(path);
#endif
unknown's avatar
unknown committed
326 327 328 329
#ifdef HAVE_NDBCLUSTER_DB
  if (have_ndbcluster == SHOW_OPTION_YES)
    ndbcluster_drop_database(path);
#endif
330
}
unknown's avatar
unknown committed
331

332 333 334
void ha_close_connection(THD* thd)
{
#ifdef HAVE_INNOBASE_DB
335
  if (have_innodb == SHOW_OPTION_YES)
unknown's avatar
unknown committed
336
    innobase_close_connection(thd);
337
#endif
unknown's avatar
unknown committed
338 339 340 341
#ifdef HAVE_NDBCLUSTER_DB
  if (have_ndbcluster == SHOW_OPTION_YES)
    ndbcluster_close_connection(thd);
#endif
342 343
}

344
/*
unknown's avatar
unknown committed
345
  This is used to commit or rollback a single statement depending on the value
unknown's avatar
unknown committed
346 347 348 349 350
  of error. Note that if the autocommit is on, then the following call inside
  InnoDB will commit or rollback the whole transaction (= the statement). The
  autocommit mechanism built into InnoDB is based on counting locks, but if
  the user has used LOCK TABLES then that mechanism does not know to do the
  commit.
351 352
*/

unknown's avatar
unknown committed
353 354 355
int ha_autocommit_or_rollback(THD *thd, int error)
{
  DBUG_ENTER("ha_autocommit_or_rollback");
356
#ifdef USING_TRANSACTIONS
357
  if (opt_using_transactions)
unknown's avatar
unknown committed
358
  {
359 360 361 362 363 364 365
    if (!error)
    {
      if (ha_commit_stmt(thd))
	error=1;
    }
    else
      (void) ha_rollback_stmt(thd);
unknown's avatar
unknown committed
366

unknown's avatar
unknown committed
367
    thd->variables.tx_isolation=thd->session_tx_isolation;
unknown's avatar
unknown committed
368 369 370 371 372
  }
#endif
  DBUG_RETURN(error);
}

unknown's avatar
unknown committed
373 374 375
/*
  This function is called when MySQL writes the log segment of a
  transaction to the binlog. It is called when the LOCK_log mutex is
376
  reserved. Here we communicate to transactional table handlers what
unknown's avatar
unknown committed
377 378 379 380 381
  binlog position corresponds to the current transaction. The handler
  can store it and in recovery print to the user, so that the user
  knows from what position in the binlog to start possible
  roll-forward, for example, if the crashed server was a slave in
  replication. This function also calls the commit of the table
382
  handler, because the order of transactions in the log of the table
unknown's avatar
unknown committed
383
  handler must be the same as in the binlog.
unknown's avatar
unknown committed
384 385 386
  NOTE that to eliminate the bottleneck of the group commit, we do not
  flush the handler log files here, but only later in a call of
  ha_commit_complete().
unknown's avatar
unknown committed
387 388

  arguments:
389
  thd:           the thread handle of the current connection
unknown's avatar
unknown committed
390 391
  log_file_name: latest binlog file name
  end_offset:	 the offset in the binlog file up to which we wrote
392
  return value:  0 if success, 1 if error
unknown's avatar
unknown committed
393
*/
394

unknown's avatar
unknown committed
395 396 397
int ha_report_binlog_offset_and_commit(THD *thd,
				       char *log_file_name,
				       my_off_t end_offset)
398
{
unknown's avatar
unknown committed
399 400
  int  error= 0;
#ifdef HAVE_INNOBASE_DB
401 402
  THD_TRANS *trans;
  trans = &thd->transaction.all;
403
  if (trans->innodb_active_trans)
404
  {
405 406 407 408 409 410
    /*
      If we updated some InnoDB tables (innodb_active_trans is true), the
      binlog coords will be reported into InnoDB during the InnoDB commit
      (innobase_report_binlog_offset_and_commit). But if we updated only
      non-InnoDB tables, we need an explicit call to report it.
    */
411
    if ((error=innobase_report_binlog_offset_and_commit(thd,
412 413 414
                                                        trans->innobase_tid,
                                                        log_file_name,
                                                        end_offset)))
415 416 417 418 419
    {
      my_error(ER_ERROR_DURING_COMMIT, MYF(0), error);
      error=1;
    }
  }
420 421
  else if (opt_innodb_safe_binlog) // Don't report if not useful
    innobase_store_binlog_offset_and_flush_log(log_file_name, end_offset);
422 423 424
#endif
  return error;
}
425

unknown's avatar
unknown committed
426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450
/*
  Flushes the handler log files (if my.cnf settings do not free us from it)
  after we have called ha_report_binlog_offset_and_commit(). To eliminate
  the bottleneck from the group commit, this should be called when
  LOCK_log has been released in log.cc.

  arguments:
  thd:           the thread handle of the current connection
  return value:  always 0
*/

int ha_commit_complete(THD *thd)
{
#ifdef HAVE_INNOBASE_DB
  THD_TRANS *trans;
  trans = &thd->transaction.all;
  if (trans->innobase_tid)
  {
    innobase_commit_complete(trans->innobase_tid);

    trans->innodb_active_trans=0;
  }
#endif
  return 0;
}
451

452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479
/*
  This function should be called when MySQL sends rows of a SELECT result set
  or the EOF mark to the client. It releases a possible adaptive hash index
  S-latch held by thd in InnoDB and also releases a possible InnoDB query
  FIFO ticket to enter InnoDB. To save CPU time, InnoDB allows a thd to
  keep them over several calls of the InnoDB handler interface when a join
  is executed. But when we let the control to pass to the client they have
  to be released because if the application program uses mysql_use_result(),
  it may deadlock on the S-latch if the application on another connection
  performs another SQL query. In MySQL-4.1 this is even more important because
  there a connection can have several SELECT queries open at the same time.

  arguments:
  thd:           the thread handle of the current connection
  return value:  always 0
*/

int ha_release_temporary_latches(THD *thd)
{
#ifdef HAVE_INNOBASE_DB
  THD_TRANS *trans;
  trans = &thd->transaction.all;
  if (trans->innobase_tid)
    innobase_release_temporary_latches(trans->innobase_tid);
#endif
  return 0;
}

480 481 482 483 484 485 486 487 488 489 490 491 492 493 494

/* 
  Export statistics for different engines. Currently we use it only for
  InnoDB.
*/

int ha_update_statistics()
{
#ifdef HAVE_INNOBASE_DB
  if (opt_innodb)
    innodb_export_status();
#endif
  return 0;
}

495
int ha_commit_trans(THD *thd, THD_TRANS* trans)
unknown's avatar
unknown committed
496 497
{
  int error=0;
498
  DBUG_ENTER("ha_commit_trans");
499
#ifdef USING_TRANSACTIONS
500
  if (opt_using_transactions)
501
  {
unknown's avatar
unknown committed
502
    bool transaction_commited= 0;
503
    bool operation_done= 0, need_start_waiters= 0;
504

505
    /* If transaction has done some updates to tables */
506 507
    if (trans == &thd->transaction.all && mysql_bin_log.is_open() &&
        my_b_tell(&thd->transaction.trans_log))
508
    {
509
      if ((error= wait_if_global_read_lock(thd, 0, 0)))
510
      {
511 512 513
        /*
          Note that ROLLBACK [TO SAVEPOINT] does not have this test; it's
          because ROLLBACK never updates data, so needn't wait on the lock.
514
        */
515 516 517 518 519 520 521 522
        my_error(ER_ERROR_DURING_COMMIT, MYF(0), error);
        error= 1;
      }
      else
        need_start_waiters= 1;
      if (mysql_bin_log.is_open())
      {
        mysql_bin_log.write(thd, &thd->transaction.trans_log, 1);
unknown's avatar
unknown committed
523 524 525 526 527 528 529 530 531 532
        statistic_increment(binlog_cache_use, &LOCK_status);
        if (thd->transaction.trans_log.disk_writes != 0)
        {
          /* 
            We have to do this after addition of trans_log to main binlog since
            this operation can cause flushing of end of trans_log to disk. 
          */
          statistic_increment(binlog_cache_disk_use, &LOCK_status);
          thd->transaction.trans_log.disk_writes= 0;
        }
533 534 535
        reinit_io_cache(&thd->transaction.trans_log,
                        WRITE_CACHE, (my_off_t) 0, 0, 1);
        thd->transaction.trans_log.end_of_file= max_binlog_cache_size;
536
      }
537
    }
unknown's avatar
unknown committed
538 539 540 541 542
#ifdef HAVE_NDBCLUSTER_DB
    if (trans->ndb_tid)
    {
      if ((error=ndbcluster_commit(thd,trans->ndb_tid)))
      {
543
	if (error == -1)
544 545
	  my_message(ER_ERROR_DURING_COMMIT, ER(ER_ERROR_DURING_COMMIT),
		     MYF(0));
unknown's avatar
unknown committed
546 547 548 549 550 551 552
        error=1;
      }
      if (trans == &thd->transaction.all)
        operation_done= transaction_commited= 1;
      trans->ndb_tid=0;
    }
#endif
unknown's avatar
unknown committed
553
#ifdef HAVE_BERKELEY_DB
554
    if (trans->bdb_tid)
unknown's avatar
unknown committed
555
    {
556 557 558 559 560
      if ((error=berkeley_commit(thd,trans->bdb_tid)))
      {
	my_error(ER_ERROR_DURING_COMMIT, MYF(0), error);
	error=1;
      }
561
      else
562 563
	if (!(thd->options & OPTION_BEGIN))
	  transaction_commited= 1; 
564
      trans->bdb_tid=0;
unknown's avatar
unknown committed
565
    }
566 567
#endif
#ifdef HAVE_INNOBASE_DB
568
    if (trans->innobase_tid)
569
    {
570 571 572 573 574
      if ((error=innobase_commit(thd,trans->innobase_tid)))
      {
	my_error(ER_ERROR_DURING_COMMIT, MYF(0), error);
	error=1;
      }
unknown's avatar
unknown committed
575
      trans->innodb_active_trans=0;
unknown's avatar
unknown committed
576
      if (trans == &thd->transaction.all)
577
	operation_done= transaction_commited= 1;
578
    }
579
#endif
unknown's avatar
unknown committed
580
#ifdef HAVE_QUERY_CACHE
unknown's avatar
unknown committed
581
    if (transaction_commited && thd->transaction.changed_tables)
582
      query_cache.invalidate(thd->transaction.changed_tables);
unknown's avatar
unknown committed
583
#endif /*HAVE_QUERY_CACHE*/
584
    if (error && trans == &thd->transaction.all && mysql_bin_log.is_open())
unknown's avatar
unknown committed
585
      sql_print_error("Got error during commit;  Binlog is not up to date!");
unknown's avatar
unknown committed
586
    thd->variables.tx_isolation=thd->session_tx_isolation;
587
    if (operation_done)
588
    {
589
      statistic_increment(thd->status_var.ha_commit_count,&LOCK_status);
590 591
      thd->transaction.cleanup();
    }
592 593
    if (need_start_waiters)
      start_waiting_global_read_lock(thd);
594
  }
595
#endif // using transactions
unknown's avatar
unknown committed
596 597 598
  DBUG_RETURN(error);
}

599

600
int ha_rollback_trans(THD *thd, THD_TRANS *trans)
unknown's avatar
unknown committed
601 602
{
  int error=0;
603
  DBUG_ENTER("ha_rollback_trans");
604 605
#ifdef USING_TRANSACTIONS
  if (opt_using_transactions)
unknown's avatar
unknown committed
606
  {
607
    bool operation_done=0;
608 609 610 611 612 613
    /*
      As rollback can be 30 times slower than insert in InnoDB, and user may
      not know there's rollback (if it's because of a dupl row), better warn.
    */
    const char *save_proc_info= thd->proc_info;
    thd->proc_info= "Rolling back";
unknown's avatar
unknown committed
614 615 616 617 618
#ifdef HAVE_NDBCLUSTER_DB
    if (trans->ndb_tid)
    {
      if ((error=ndbcluster_rollback(thd, trans->ndb_tid)))
      {
619
	if (error == -1)
unknown's avatar
unknown committed
620 621
	  my_message(ER_ERROR_DURING_ROLLBACK, ER(ER_ERROR_DURING_ROLLBACK),
                     MYF(0));
unknown's avatar
unknown committed
622 623 624 625 626 627
        error=1;
      }
      trans->ndb_tid = 0;
      operation_done=1;
    }
#endif
628 629
#ifdef HAVE_BERKELEY_DB
    if (trans->bdb_tid)
unknown's avatar
unknown committed
630
    {
631 632 633 634 635 636
      if ((error=berkeley_rollback(thd, trans->bdb_tid)))
      {
	my_error(ER_ERROR_DURING_ROLLBACK, MYF(0), error);
	error=1;
      }
      trans->bdb_tid=0;
637
      operation_done=1;
unknown's avatar
unknown committed
638
    }
639 640
#endif
#ifdef HAVE_INNOBASE_DB
641
    if (trans->innobase_tid)
642
    {
643 644 645 646 647
      if ((error=innobase_rollback(thd, trans->innobase_tid)))
      {
	my_error(ER_ERROR_DURING_ROLLBACK, MYF(0), error);
	error=1;
      }
unknown's avatar
unknown committed
648
      trans->innodb_active_trans=0;
649
      operation_done=1;
650
    }
unknown's avatar
unknown committed
651
#endif
652
    if ((trans == &thd->transaction.all) && mysql_bin_log.is_open())
unknown's avatar
unknown committed
653 654
    {
      /* 
655 656 657 658 659
         Update the binary log with a BEGIN/ROLLBACK block if we have
         cached some queries and we updated some non-transactional
         table. Such cases should be rare (updating a
         non-transactional table inside a transaction...).  Count disk
         writes to trans_log in any case.
unknown's avatar
unknown committed
660
      */
661 662 663 664 665 666 667 668 669 670 671 672 673 674 675
      if (my_b_tell(&thd->transaction.trans_log))
      {
        if (unlikely(thd->options & OPTION_STATUS_NO_TRANS_UPDATE))
          mysql_bin_log.write(thd, &thd->transaction.trans_log, 0);
        statistic_increment(binlog_cache_use, &LOCK_status);
        if (thd->transaction.trans_log.disk_writes != 0)
        {
          /* 
            We have to do this after addition of trans_log to main binlog since
            this operation can cause flushing of end of trans_log to disk. 
          */
          statistic_increment(binlog_cache_disk_use, &LOCK_status);
          thd->transaction.trans_log.disk_writes= 0;
        }
      }
unknown's avatar
unknown committed
676
      /* Flushed or not, empty the binlog cache */
677
      reinit_io_cache(&thd->transaction.trans_log,
unknown's avatar
unknown committed
678 679
                      WRITE_CACHE, (my_off_t) 0, 0, 1);
      thd->transaction.trans_log.end_of_file= max_binlog_cache_size;
680 681
      if (operation_done)
        thd->transaction.cleanup();
unknown's avatar
unknown committed
682
    }
unknown's avatar
unknown committed
683
    thd->variables.tx_isolation=thd->session_tx_isolation;
684
    if (operation_done)
unknown's avatar
unknown committed
685
      statistic_increment(thd->status_var.ha_rollback_count,&LOCK_status);
686
    thd->proc_info= save_proc_info;
687 688
  }
#endif /* USING_TRANSACTIONS */
unknown's avatar
unknown committed
689 690 691
  DBUG_RETURN(error);
}

unknown's avatar
unknown committed
692 693

/*
unknown's avatar
unknown committed
694 695 696 697 698 699 700 701 702 703
  Rolls the current transaction back to a savepoint.
  Return value: 0 if success, 1 if there was not a savepoint of the given
  name.
  NOTE: how do we handle this (unlikely but legal) case:
  [transaction] + [update to non-trans table] + [rollback to savepoint] ?
  The problem occurs when a savepoint is before the update to the
  non-transactional table. Then when there's a rollback to the savepoint, if we
  simply truncate the binlog cache, we lose the part of the binlog cache where
  the update is. If we want to not lose it, we need to write the SAVEPOINT
  command and the ROLLBACK TO SAVEPOINT command to the binlog cache. The latter
704 705 706 707 708 709
  is easy: it's just write at the end of the binlog cache, but the former
  should be *inserted* to the place where the user called SAVEPOINT. The
  solution is that when the user calls SAVEPOINT, we write it to the binlog
  cache (so no need to later insert it). As transactions are never intermixed
  in the binary log (i.e. they are serialized), we won't have conflicts with
  savepoint names when using mysqlbinlog or in the slave SQL thread.
unknown's avatar
unknown committed
710 711 712 713 714
  Then when ROLLBACK TO SAVEPOINT is called, if we updated some
  non-transactional table, we don't truncate the binlog cache but instead write
  ROLLBACK TO SAVEPOINT to it; otherwise we truncate the binlog cache (which
  will chop the SAVEPOINT command from the binlog cache, which is good as in
  that case there is no need to have it in the binlog).
unknown's avatar
unknown committed
715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737
*/

int ha_rollback_to_savepoint(THD *thd, char *savepoint_name)
{
  my_off_t binlog_cache_pos=0;
  bool operation_done=0;
  int error=0;
  DBUG_ENTER("ha_rollback_to_savepoint");
#ifdef USING_TRANSACTIONS
  if (opt_using_transactions)
  {
#ifdef HAVE_INNOBASE_DB
    /*
    Retrieve the trans_log binlog cache position corresponding to the
    savepoint, and if the rollback is successful inside InnoDB reset the write
    position in the binlog cache to what it was at the savepoint.
    */
    if ((error=innobase_rollback_to_savepoint(thd, savepoint_name,
						  &binlog_cache_pos)))
    {
      my_error(ER_ERROR_DURING_ROLLBACK, MYF(0), error);
      error=1;
    }
738
    else if (mysql_bin_log.is_open())
unknown's avatar
unknown committed
739 740 741 742 743 744 745 746 747
    {
      /* 
         Write ROLLBACK TO SAVEPOINT to the binlog cache if we have updated some
         non-transactional table. Otherwise, truncate the binlog cache starting
         from the SAVEPOINT command.
      */
      if (unlikely((thd->options & OPTION_STATUS_NO_TRANS_UPDATE) &&
                   my_b_tell(&thd->transaction.trans_log)))
      {
748
        Query_log_event qinfo(thd, thd->query, thd->query_length, TRUE, FALSE);
unknown's avatar
unknown committed
749 750 751 752 753 754 755
        if (mysql_bin_log.write(&qinfo))
          error= 1;
      }
      else
        reinit_io_cache(&thd->transaction.trans_log, WRITE_CACHE,
                        binlog_cache_pos, 0, 0);
    }
unknown's avatar
unknown committed
756 757 758
    operation_done=1;
#endif
    if (operation_done)
759
      statistic_increment(thd->status_var.ha_rollback_count,&LOCK_status);
unknown's avatar
unknown committed
760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778
  }
#endif /* USING_TRANSACTIONS */

  DBUG_RETURN(error);
}


/*
Sets a transaction savepoint.
Return value: always 0, that is, succeeds always
*/

int ha_savepoint(THD *thd, char *savepoint_name)
{
  int error=0;
  DBUG_ENTER("ha_savepoint");
#ifdef USING_TRANSACTIONS
  if (opt_using_transactions)
  {
779
    /* Write it to the binary log (see comments of ha_rollback_to_savepoint) */
unknown's avatar
unknown committed
780 781
    if (mysql_bin_log.is_open())
    {
782 783 784 785
#ifdef HAVE_INNOBASE_DB
      innobase_savepoint(thd,savepoint_name,
                         my_b_tell(&thd->transaction.trans_log));
#endif
786
      Query_log_event qinfo(thd, thd->query, thd->query_length, TRUE, FALSE);
unknown's avatar
unknown committed
787 788 789
      if (mysql_bin_log.write(&qinfo))
	error= 1;
    }
790 791 792 793
#ifdef HAVE_INNOBASE_DB
    else
      innobase_savepoint(thd,savepoint_name,0);
#endif
unknown's avatar
unknown committed
794 795 796 797 798
  }
#endif /* USING_TRANSACTIONS */
  DBUG_RETURN(error);
}

799 800 801 802 803 804 805 806 807 808 809 810

int ha_start_consistent_snapshot(THD *thd)
{
#ifdef HAVE_INNOBASE_DB
  if ((have_innodb == SHOW_OPTION_YES) &&
      !innobase_start_trx_and_assign_read_view(thd))
    return 0;
#endif
  /*
    Same idea as when one wants to CREATE TABLE in one engine which does not
    exist:
  */
811 812 813
  push_warning(thd, MYSQL_ERROR::WARN_LEVEL_WARN, ER_UNKNOWN_ERROR,
               "This MySQL server does not support any "
               "consistent-read capable storage engine");
814 815 816 817
  return 0;
}


unknown's avatar
unknown committed
818 819 820 821
bool ha_flush_logs()
{
  bool result=0;
#ifdef HAVE_BERKELEY_DB
822
  if ((have_berkeley_db == SHOW_OPTION_YES) &&
823
      berkeley_flush_logs())
unknown's avatar
unknown committed
824
    result=1;
825 826
#endif
#ifdef HAVE_INNOBASE_DB
827
  if ((have_innodb == SHOW_OPTION_YES) &&
828
      innobase_flush_logs())
829
    result=1;
unknown's avatar
unknown committed
830 831 832 833
#endif
  return result;
}

unknown's avatar
unknown committed
834 835 836 837
/*
  This should return ENOENT if the file doesn't exists.
  The .frm file will be deleted only if we return 0 or ENOENT
*/
unknown's avatar
unknown committed
838 839 840

int ha_delete_table(enum db_type table_type, const char *path)
{
841
  handler *file;
unknown's avatar
unknown committed
842
  char tmp_path[FN_REFLEN];
843 844 845 846

  /* DB_TYPE_UNKNOWN is used in ALTER TABLE when renaming only .frm files */
  if (table_type == DB_TYPE_UNKNOWN ||
      ! (file=get_new_handler((TABLE*) 0, table_type)))
unknown's avatar
unknown committed
847
    return ENOENT;
848

unknown's avatar
unknown committed
849 850 851 852
  if (lower_case_table_names == 2 && !(file->table_flags() & HA_FILE_BASED))
  {
    /* Ensure that table handler get path in lower case */
    strmov(tmp_path, path);
853
    my_casedn_str(files_charset_info, tmp_path);
unknown's avatar
unknown committed
854 855
    path= tmp_path;
  }
unknown's avatar
unknown committed
856 857 858 859
  int error=file->delete_table(path);
  delete file;
  return error;
}
unknown's avatar
unknown committed
860

unknown's avatar
unknown committed
861

unknown's avatar
unknown committed
862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925
void ha_store_ptr(byte *buff, uint pack_length, my_off_t pos)
{
  switch (pack_length) {
#if SIZEOF_OFF_T > 4
  case 8: mi_int8store(buff,pos); break;
  case 7: mi_int7store(buff,pos); break;
  case 6: mi_int6store(buff,pos); break;
  case 5: mi_int5store(buff,pos); break;
#endif
  case 4: mi_int4store(buff,pos); break;
  case 3: mi_int3store(buff,pos); break;
  case 2: mi_int2store(buff,(uint) pos); break;
  case 1: buff[0]= (uchar) pos; break;
  }
  return;
}

my_off_t ha_get_ptr(byte *ptr, uint pack_length)
{
  my_off_t pos;
  switch (pack_length) {
#if SIZEOF_OFF_T > 4
  case 8:
    pos= (my_off_t) mi_uint8korr(ptr);
    break;
  case 7:
    pos= (my_off_t) mi_uint7korr(ptr);
    break;
  case 6:
    pos= (my_off_t) mi_uint6korr(ptr);
    break;
  case 5:
    pos= (my_off_t) mi_uint5korr(ptr);
    break;
#endif
  case 4:
    pos= (my_off_t) mi_uint4korr(ptr);
    break;
  case 3:
    pos= (my_off_t) mi_uint3korr(ptr);
    break;
  case 2:
    pos= (my_off_t) mi_uint2korr(ptr);
    break;
  case 1:
    pos= (my_off_t) mi_uint2korr(ptr);
    break;
  default:
    pos=0;					// Impossible
    break;
  }
 return pos;
}

/****************************************************************************
** General handler functions
****************************************************************************/

	/* Open database-handler. Try O_RDONLY if can't open as O_RDWR */
	/* Don't wait for locks if not HA_OPEN_WAIT_IF_LOCKED is set */

int handler::ha_open(const char *name, int mode, int test_if_locked)
{
  int error;
926
  DBUG_ENTER("handler::ha_open");
927
  DBUG_PRINT("enter",("name: %s  db_type: %d  db_stat: %d  mode: %d  lock_test: %d",
928 929
		      name, table->db_type, table->db_stat, mode,
		      test_if_locked));
unknown's avatar
unknown committed
930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948

  if ((error=open(name,mode,test_if_locked)))
  {
    if ((error == EACCES || error == EROFS) && mode == O_RDWR &&
	(table->db_stat & HA_TRY_READ_ONLY))
    {
      table->db_stat|=HA_READ_ONLY;
      error=open(name,O_RDONLY,test_if_locked);
    }
  }
  if (error)
  {
    my_errno=error;			/* Safeguard */
    DBUG_PRINT("error",("error: %d  errno: %d",error,errno));
  }
  else
  {
    if (table->db_options_in_use & HA_OPTION_READ_ONLY_DATA)
      table->db_stat|=HA_READ_ONLY;
949 950
    (void) extra(HA_EXTRA_NO_READCHECK);	// Not needed in SQL

unknown's avatar
unknown committed
951
    if (!alloc_root_inited(&table->mem_root))	// If temporary table
952
      ref=(byte*) sql_alloc(ALIGN_SIZE(ref_length)*2);
unknown's avatar
unknown committed
953 954 955
    else
      ref=(byte*) alloc_root(&table->mem_root, ALIGN_SIZE(ref_length)*2);
    if (!ref)
unknown's avatar
unknown committed
956 957 958 959 960 961 962 963 964 965
    {
      close();
      error=HA_ERR_OUT_OF_MEM;
    }
    else
      dupp_ref=ref+ALIGN_SIZE(ref_length);
  }
  DBUG_RETURN(error);
}

966 967 968 969 970
/*
  Read first row (only) from a table
  This is never called for InnoDB or BDB tables, as these table types
  has the HA_NOT_EXACT_COUNT set.
*/
unknown's avatar
unknown committed
971

972
int handler::read_first_row(byte * buf, uint primary_key)
unknown's avatar
unknown committed
973 974
{
  register int error;
975
  DBUG_ENTER("handler::read_first_row");
unknown's avatar
unknown committed
976

977
  statistic_increment(current_thd->status_var.ha_read_first_count,&LOCK_status);
978 979 980 981

  /*
    If there is very few deleted rows in the table, find the first row by
    scanning the table.
982
    TODO remove the test for HA_READ_ORDER
983
  */
984 985
  if (deleted < 10 || primary_key >= MAX_KEY ||
      !(index_flags(primary_key, 0, 0) & HA_READ_ORDER))
986
  {
unknown's avatar
unknown committed
987
    (void) ha_rnd_init(1);
988
    while ((error= rnd_next(buf)) == HA_ERR_RECORD_DELETED) ;
unknown's avatar
unknown committed
989
    (void) ha_rnd_end();
990 991 992 993
  }
  else
  {
    /* Find the first row through the primary key */
unknown's avatar
unknown committed
994
    (void) ha_index_init(primary_key);
995
    error=index_first(buf);
unknown's avatar
unknown committed
996
    (void) ha_index_end();
997
  }
unknown's avatar
unknown committed
998 999 1000 1001
  DBUG_RETURN(error);
}


1002
/*
1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059
  Generate the next auto-increment number based on increment and offset
  
  In most cases increment= offset= 1, in which case we get:
  1,2,3,4,5,...
  If increment=10 and offset=5 and previous number is 1, we get:
  1,5,15,25,35,...
*/

inline ulonglong
next_insert_id(ulonglong nr,struct system_variables *variables)
{
  nr= (((nr+ variables->auto_increment_increment -
         variables->auto_increment_offset)) /
       (ulonglong) variables->auto_increment_increment);
  return (nr* (ulonglong) variables->auto_increment_increment +
          variables->auto_increment_offset);
}


/*
  Updates columns with type NEXT_NUMBER if:

  - If column value is set to NULL (in which case
    auto_increment_field_not_null is 0)
  - If column is set to 0 and (sql_mode & MODE_NO_AUTO_VALUE_ON_ZERO) is not
    set. In the future we will only set NEXT_NUMBER fields if one sets them
    to NULL (or they are not included in the insert list).


  There are two different cases when the above is true:

  - thd->next_insert_id == 0  (This is the normal case)
    In this case we set the set the column for the first row to the value
    next_insert_id(get_auto_increment(column))) which is normally
    max-used-column-value +1.

    We call get_auto_increment() only for the first row in a multi-row
    statement. For the following rows we generate new numbers based on the
    last used number.

  - thd->next_insert_id != 0.  This happens when we have read a statement
    from the binary log or when one has used SET LAST_INSERT_ID=#.

    In this case we will set the column to the value of next_insert_id.
    The next row will be given the id
    next_insert_id(next_insert_id)

    The idea is that generated auto_increment values are predictable and
    independent of the column values in the table.  This is needed to be
    able to replicate into a table that already has rows with a higher
    auto-increment value than the one that is inserted.

    After we have already generated an auto-increment number and the user
    inserts a column with a higher value than the last used one, we will
    start counting from the inserted value.

    thd->next_insert_id is cleared after it's been used for a statement.
1060
*/
unknown's avatar
unknown committed
1061 1062 1063

void handler::update_auto_increment()
{
1064 1065 1066
  ulonglong nr;
  THD *thd= table->in_use;
  struct system_variables *variables= &thd->variables;
1067
  DBUG_ENTER("handler::update_auto_increment");
1068 1069 1070 1071 1072 1073 1074 1075

  /*
    We must save the previous value to be able to restore it if the
    row was not inserted
  */
  thd->prev_insert_id= thd->next_insert_id;

  if ((nr= table->next_number_field->val_int()) != 0 ||
unknown's avatar
unknown committed
1076
      table->auto_increment_field_not_null &&
1077
      thd->variables.sql_mode & MODE_NO_AUTO_VALUE_ON_ZERO)
1078
  {
1079
    /* Clear flag for next row */
unknown's avatar
unknown committed
1080
    table->auto_increment_field_not_null= FALSE;
1081
    /* Mark that we didn't generate a new value **/
1082
    auto_increment_column_changed=0;
1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093

    /* Update next_insert_id if we have already generated a value */
    if (thd->clear_next_insert_id && nr >= thd->next_insert_id)
    {
      if (variables->auto_increment_increment != 1)
        nr= next_insert_id(nr, variables);
      else
        nr++;
      thd->next_insert_id= nr;
      DBUG_PRINT("info",("next_insert_id: %lu", (ulong) nr));
    }
unknown's avatar
unknown committed
1094
    DBUG_VOID_RETURN;
1095
  }
unknown's avatar
unknown committed
1096
  table->auto_increment_field_not_null= FALSE;
1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115
  if (!(nr= thd->next_insert_id))
  {
    nr= get_auto_increment();
    if (variables->auto_increment_increment != 1)
      nr= next_insert_id(nr-1, variables);
    /*
      Update next row based on the found value. This way we don't have to
      call the handler for every generated auto-increment value on a
      multi-row statement
    */
    thd->next_insert_id= nr;
  }

  DBUG_PRINT("info",("auto_increment: %lu", (ulong) nr));

  /* Mark that we should clear next_insert_id before next stmt */
  thd->clear_next_insert_id= 1;

  if (!table->next_number_field->store((longlong) nr))
1116
    thd->insert_id((ulonglong) nr);
1117 1118
  else
    thd->insert_id(table->next_number_field->val_int());
1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137

  /*
    We can't set next_insert_id if the auto-increment key is not the
    first key part, as there is no guarantee that the first parts will be in
    sequence
  */
  if (!table->next_number_key_offset)
  {
    /*
      Set next insert id to point to next auto-increment value to be able to
      handle multi-row statements
      This works even if auto_increment_increment > 1
    */
    thd->next_insert_id= next_insert_id(nr, variables);
  }
  else
    thd->next_insert_id= 0;

  /* Mark that we generated a new value */
1138
  auto_increment_column_changed=1;
unknown's avatar
unknown committed
1139 1140 1141
  DBUG_VOID_RETURN;
}

1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155
/*
  restore_auto_increment

  In case of error on write, we restore the last used next_insert_id value
  because the previous value was not used.
*/

void handler::restore_auto_increment()
{
  THD *thd= table->in_use;
  if (thd->next_insert_id)
    thd->next_insert_id= thd->prev_insert_id;
}

unknown's avatar
unknown committed
1156

1157
ulonglong handler::get_auto_increment()
unknown's avatar
unknown committed
1158
{
1159
  ulonglong nr;
unknown's avatar
unknown committed
1160
  int error;
unknown's avatar
unknown committed
1161

unknown's avatar
unknown committed
1162 1163
  (void) extra(HA_EXTRA_KEYREAD);
  index_init(table->next_number_index);
unknown's avatar
unknown committed
1164 1165 1166 1167 1168 1169 1170
  if (!table->next_number_key_offset)
  {						// Autoincrement at key-start
    error=index_last(table->record[1]);
  }
  else
  {
    byte key[MAX_KEY_LENGTH];
1171 1172
    key_copy(key, table->record[0],
             table->key_info + table->next_number_index,
unknown's avatar
unknown committed
1173 1174 1175 1176 1177
             table->next_number_key_offset);
    error=index_read(table->record[1], key, table->next_number_key_offset,
                     HA_READ_PREFIX_LAST);
  }

unknown's avatar
unknown committed
1178 1179 1180
  if (error)
    nr=1;
  else
1181 1182
    nr=((ulonglong) table->next_number_field->
        val_int_offset(table->rec_buff_length)+1);
unknown's avatar
unknown committed
1183
  index_end();
unknown's avatar
unknown committed
1184
  (void) extra(HA_EXTRA_NO_KEYREAD);
unknown's avatar
unknown committed
1185 1186 1187 1188 1189 1190 1191
  return nr;
}

	/* Print error that we got from handler function */

void handler::print_error(int error, myf errflag)
{
1192
  DBUG_ENTER("handler::print_error");
unknown's avatar
unknown committed
1193 1194 1195 1196
  DBUG_PRINT("enter",("error: %d",error));

  int textno=ER_GET_ERRNO;
  switch (error) {
1197 1198 1199
  case EACCES:
    textno=ER_OPEN_AS_READONLY;
    break;
unknown's avatar
unknown committed
1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210
  case EAGAIN:
    textno=ER_FILE_USED;
    break;
  case ENOENT:
    textno=ER_FILE_NOT_FOUND;
    break;
  case HA_ERR_KEY_NOT_FOUND:
  case HA_ERR_NO_ACTIVE_RECORD:
  case HA_ERR_END_OF_FILE:
    textno=ER_KEY_NOT_FOUND;
    break;
unknown's avatar
unknown committed
1211
  case HA_ERR_WRONG_MRG_TABLE_DEF:
unknown's avatar
unknown committed
1212 1213 1214 1215 1216 1217 1218 1219 1220
    textno=ER_WRONG_MRG_TABLE;
    break;
  case HA_ERR_FOUND_DUPP_KEY:
  {
    uint key_nr=get_dup_key(error);
    if ((int) key_nr >= 0)
    {
      /* Write the dupplicated key in the error message */
      char key[MAX_KEY_LENGTH];
1221
      String str(key,sizeof(key),system_charset_info);
unknown's avatar
unknown committed
1222
      key_unpack(&str,table,(uint) key_nr);
unknown's avatar
unknown committed
1223
      uint max_length=MYSQL_ERRMSG_SIZE-(uint) strlen(ER(ER_DUP_ENTRY));
unknown's avatar
unknown committed
1224 1225 1226 1227 1228
      if (str.length() >= max_length)
      {
	str.length(max_length-4);
	str.append("...");
      }
1229
      my_error(ER_DUP_ENTRY, MYF(0), str.c_ptr(), key_nr+1);
unknown's avatar
unknown committed
1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243
      DBUG_VOID_RETURN;
    }
    textno=ER_DUP_KEY;
    break;
  }
  case HA_ERR_FOUND_DUPP_UNIQUE:
    textno=ER_DUP_UNIQUE;
    break;
  case HA_ERR_RECORD_CHANGED:
    textno=ER_CHECKREAD;
    break;
  case HA_ERR_CRASHED:
    textno=ER_NOT_KEYFILE;
    break;
1244 1245 1246 1247 1248 1249
  case HA_ERR_CRASHED_ON_USAGE:
    textno=ER_CRASHED_ON_USAGE;
    break;
  case HA_ERR_CRASHED_ON_REPAIR:
    textno=ER_CRASHED_ON_REPAIR;
    break;
unknown's avatar
unknown committed
1250
  case HA_ERR_OUT_OF_MEM:
unknown's avatar
unknown committed
1251
    my_message(ER_OUT_OF_RESOURCES, ER(ER_OUT_OF_RESOURCES), errflag);
unknown's avatar
unknown committed
1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264
    DBUG_VOID_RETURN;
  case HA_ERR_WRONG_COMMAND:
    textno=ER_ILLEGAL_HA;
    break;
  case HA_ERR_OLD_FILE:
    textno=ER_OLD_KEYFILE;
    break;
  case HA_ERR_UNSUPPORTED:
    textno=ER_UNSUPPORTED_EXTENSION;
    break;
  case HA_ERR_RECORD_FILE_FULL:
    textno=ER_RECORD_FILE_FULL;
    break;
1265 1266 1267 1268 1269 1270
  case HA_ERR_LOCK_WAIT_TIMEOUT:
    textno=ER_LOCK_WAIT_TIMEOUT;
    break;
  case HA_ERR_LOCK_TABLE_FULL:
    textno=ER_LOCK_TABLE_FULL;
    break;
1271 1272 1273
  case HA_ERR_LOCK_DEADLOCK:
    textno=ER_LOCK_DEADLOCK;
    break;
1274 1275 1276
  case HA_ERR_READ_ONLY_TRANSACTION:
    textno=ER_READ_ONLY_TRANSACTION;
    break;
unknown's avatar
Merge  
unknown committed
1277 1278 1279 1280 1281 1282 1283 1284 1285
  case HA_ERR_CANNOT_ADD_FOREIGN:
    textno=ER_CANNOT_ADD_FOREIGN;
    break;
  case HA_ERR_ROW_IS_REFERENCED:
    textno=ER_ROW_IS_REFERENCED;
    break;
  case HA_ERR_NO_REFERENCED_ROW:
    textno=ER_NO_REFERENCED_ROW;
    break;
1286 1287
  case HA_ERR_NO_SUCH_TABLE:
  {
unknown's avatar
unknown committed
1288 1289 1290 1291 1292
    /*
      We have to use path to find database name instead of using
      table->table_cache_key because if the table didn't exist, then
      table_cache_key was not set up
    */
1293 1294 1295 1296 1297
    char *db;
    char buff[FN_REFLEN];
    uint length=dirname_part(buff,table->path);
    buff[length-1]=0;
    db=buff+dirname_length(buff);
1298
    my_error(ER_NO_SUCH_TABLE, MYF(0), db, table->table_name);
1299 1300
    break;
  }
unknown's avatar
unknown committed
1301 1302
  default:
    {
1303 1304 1305
      /* The error was "unknown" to this function.
	 Ask handler if it has got a message for this error */
      bool temporary= FALSE;
1306 1307 1308
      String str;
      temporary= get_error_message(error, &str);
      if (!str.is_empty())
1309
      {
1310
	const char* engine= table_type();
1311
	if (temporary)
1312
	  my_error(ER_GET_TEMPORARY_ERRMSG, MYF(0), error, str.ptr(), engine);
1313
	else
1314
	  my_error(ER_GET_ERRMSG, MYF(0), error, str.ptr(), engine);
1315 1316 1317
      }
      else       
	my_error(ER_GET_ERRNO,errflag,error);
unknown's avatar
unknown committed
1318 1319 1320
      DBUG_VOID_RETURN;
    }
  }
1321
  my_error(textno, errflag, table->table_name, error);
unknown's avatar
unknown committed
1322 1323 1324
  DBUG_VOID_RETURN;
}

unknown's avatar
unknown committed
1325

1326 1327 1328 1329
/* 
   Return an error message specific to this handler
   
   SYNOPSIS
1330 1331
   error        error code previously returned by handler
   buf          Pointer to String where to add error message
1332
   
1333
   Returns true if this is a temporary error
1334 1335
 */

1336
bool handler::get_error_message(int error, String* buf)
1337
{
unknown's avatar
unknown committed
1338
  return FALSE;
1339 1340 1341
}


unknown's avatar
unknown committed
1342
/* Return key if error because of duplicated keys */
unknown's avatar
unknown committed
1343 1344 1345

uint handler::get_dup_key(int error)
{
1346
  DBUG_ENTER("handler::get_dup_key");
unknown's avatar
unknown committed
1347 1348 1349 1350 1351 1352
  table->file->errkey  = (uint) -1;
  if (error == HA_ERR_FOUND_DUPP_KEY || error == HA_ERR_FOUND_DUPP_UNIQUE)
    info(HA_STATUS_ERRKEY | HA_STATUS_NO_LOCK);
  DBUG_RETURN(table->file->errkey);
}

unknown's avatar
unknown committed
1353

unknown's avatar
unknown committed
1354 1355
int handler::delete_table(const char *name)
{
unknown's avatar
unknown committed
1356
  int error=0;
unknown's avatar
unknown committed
1357 1358 1359
  for (const char **ext=bas_ext(); *ext ; ext++)
  {
    if (delete_file(name,*ext,2))
unknown's avatar
unknown committed
1360 1361 1362 1363
    {
      if ((error=errno) != ENOENT)
	break;
    }
unknown's avatar
unknown committed
1364
  }
unknown's avatar
unknown committed
1365
  return error;
unknown's avatar
unknown committed
1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379
}


int handler::rename_table(const char * from, const char * to)
{
  DBUG_ENTER("handler::rename_table");
  for (const char **ext=bas_ext(); *ext ; ext++)
  {
    if (rename_file_ext(from,to,*ext))
      DBUG_RETURN(my_errno);
  }
  DBUG_RETURN(0);
}

unknown's avatar
unknown committed
1380
/*
1381
  Tell the handler to turn on or off transaction in the handler
1382
*/
unknown's avatar
unknown committed
1383

1384
int ha_enable_transaction(THD *thd, bool on)
1385 1386 1387
{
  int error=0;

1388 1389
  DBUG_ENTER("ha_enable_transaction");
  thd->transaction.on= on;
1390 1391 1392
  DBUG_RETURN(error);
}

unknown's avatar
unknown committed
1393 1394 1395 1396 1397
int handler::index_next_same(byte *buf, const byte *key, uint keylen)
{
  int error;
  if (!(error=index_next(buf)))
  {
unknown's avatar
unknown committed
1398
    if (key_cmp_if_same(table, key, active_index, keylen))
unknown's avatar
unknown committed
1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411
    {
      table->status=STATUS_NOT_FOUND;
      error=HA_ERR_END_OF_FILE;
    }
  }
  return error;
}


/****************************************************************************
** Some general functions that isn't in the handler class
****************************************************************************/

unknown's avatar
unknown committed
1412 1413 1414 1415
/*
  Initiates table-file and calls apropriate database-creator
  Returns 1 if something got wrong
*/
unknown's avatar
unknown committed
1416 1417 1418 1419 1420 1421

int ha_create_table(const char *name, HA_CREATE_INFO *create_info,
		    bool update_create_info)
{
  int error;
  TABLE table;
unknown's avatar
unknown committed
1422
  char name_buff[FN_REFLEN];
unknown's avatar
unknown committed
1423 1424
  DBUG_ENTER("ha_create_table");

1425
  if (openfrm(current_thd, name,"",0,(uint) READ_ALL, 0, &table))
unknown's avatar
unknown committed
1426 1427 1428 1429 1430
    DBUG_RETURN(1);
  if (update_create_info)
  {
    update_create_info_from_table(create_info, &table);
  }
unknown's avatar
unknown committed
1431 1432 1433 1434 1435
  if (lower_case_table_names == 2 &&
      !(table.file->table_flags() & HA_FILE_BASED))
  {
    /* Ensure that handler gets name in lower case */
    strmov(name_buff, name);
1436
    my_casedn_str(files_charset_info, name_buff);
unknown's avatar
unknown committed
1437 1438 1439
    name= name_buff;
  }

unknown's avatar
unknown committed
1440 1441
  error=table.file->create(name,&table,create_info);
  VOID(closefrm(&table));
unknown's avatar
unknown committed
1442
  if (error)
1443
    my_error(ER_CANT_CREATE_TABLE, MYF(ME_BELL+ME_WAITTANG), name,error);
unknown's avatar
unknown committed
1444 1445 1446
  DBUG_RETURN(error != 0);
}

1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463
/*
  Try to discover table from engine and 
  if found, write the frm file to disk.
  
  RETURN VALUES:
   0 : Table existed in engine and created 
       on disk if so requested
   1 : Table does not exist
  >1 : error

*/

int ha_create_table_from_engine(THD* thd, 
				const char *db, 
				const char *name,
				bool create_if_found)
{
unknown's avatar
unknown committed
1464 1465 1466
  int error;
  const void *frmblob;
  uint frmlen;
1467 1468 1469 1470
  char path[FN_REFLEN];
  HA_CREATE_INFO create_info;
  TABLE table;
  DBUG_ENTER("ha_create_table_from_engine");
unknown's avatar
unknown committed
1471 1472
  DBUG_PRINT("enter", ("name '%s'.'%s'  create_if_found: %d",
                       db, name, create_if_found));
1473 1474 1475 1476 1477

  bzero((char*) &create_info,sizeof(create_info));

  if ((error= ha_discover(thd, db, name, &frmblob, &frmlen)))
    DBUG_RETURN(error); 
unknown's avatar
unknown committed
1478 1479 1480 1481
  /*
    Table exists in handler
    frmblob and frmlen are set
  */
1482

unknown's avatar
unknown committed
1483
  if (create_if_found)
1484 1485 1486 1487 1488 1489
  {
    (void)strxnmov(path,FN_REFLEN,mysql_data_home,"/",db,"/",name,NullS);
    // Save the frm file    
    if ((error = writefrm(path, frmblob, frmlen)))
      goto err_end;

1490
    if (openfrm(thd, path,"",0,(uint) READ_ALL, 0, &table))
1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507
      DBUG_RETURN(1);

    update_create_info_from_table(&create_info, &table);
    create_info.table_options|= HA_CREATE_FROM_ENGINE;

    if (lower_case_table_names == 2 &&
	!(table.file->table_flags() & HA_FILE_BASED))
    {
      /* Ensure that handler gets name in lower case */
      my_casedn_str(files_charset_info, path);
    }
    
    error=table.file->create(path,&table,&create_info);
    VOID(closefrm(&table));
  }

err_end:
1508
  my_free((char*) frmblob, MYF(MY_ALLOW_ZERO_PTR));
1509 1510 1511
  DBUG_RETURN(error);  
}

1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536
static int NEAR_F delete_file(const char *name,const char *ext,int extflag)
{
  char buff[FN_REFLEN];
  VOID(fn_format(buff,name,"",ext,extflag | 4));
  return(my_delete_with_symlink(buff,MYF(MY_WME)));
}

void st_ha_check_opt::init()
{
  flags= sql_flags= 0;
  sort_buffer_size = current_thd->variables.myisam_sort_buff_size;
}


/*****************************************************************************
  Key cache handling.

  This code is only relevant for ISAM/MyISAM tables

  key_cache->cache may be 0 only in the case where a key cache is not
  initialized or when we where not able to init the key cache in a previous
  call to ha_init_key_cache() (probably out of memory)
*****************************************************************************/

/* Init a key cache if it has not been initied before */
unknown's avatar
unknown committed
1537

1538

unknown's avatar
unknown committed
1539
int ha_init_key_cache(const char *name, KEY_CACHE *key_cache)
unknown's avatar
unknown committed
1540
{
1541 1542
  DBUG_ENTER("ha_init_key_cache");

unknown's avatar
unknown committed
1543
  if (!key_cache->key_cache_inited)
1544 1545
  {
    pthread_mutex_lock(&LOCK_global_system_variables);
unknown's avatar
unknown committed
1546 1547 1548 1549
    long tmp_buff_size= (long) key_cache->param_buff_size;
    long tmp_block_size= (long) key_cache->param_block_size;
    uint division_limit= key_cache->param_division_limit;
    uint age_threshold=  key_cache->param_age_threshold;
1550
    pthread_mutex_unlock(&LOCK_global_system_variables);
unknown's avatar
unknown committed
1551
    DBUG_RETURN(!init_key_cache(key_cache,
1552 1553
				tmp_block_size,
				tmp_buff_size,
unknown's avatar
unknown committed
1554
				division_limit, age_threshold));
1555
  }
1556
  DBUG_RETURN(0);
unknown's avatar
unknown committed
1557 1558
}

1559 1560 1561

/* Resize key cache */

unknown's avatar
unknown committed
1562
int ha_resize_key_cache(KEY_CACHE *key_cache)
unknown's avatar
unknown committed
1563
{
1564 1565
  DBUG_ENTER("ha_resize_key_cache");

unknown's avatar
unknown committed
1566
  if (key_cache->key_cache_inited)
1567 1568
  {
    pthread_mutex_lock(&LOCK_global_system_variables);
unknown's avatar
unknown committed
1569 1570 1571 1572
    long tmp_buff_size= (long) key_cache->param_buff_size;
    long tmp_block_size= (long) key_cache->param_block_size;
    uint division_limit= key_cache->param_division_limit;
    uint age_threshold=  key_cache->param_age_threshold;
1573
    pthread_mutex_unlock(&LOCK_global_system_variables);
unknown's avatar
unknown committed
1574 1575 1576
    DBUG_RETURN(!resize_key_cache(key_cache, tmp_block_size,
				  tmp_buff_size,
				  division_limit, age_threshold));
1577
  }
1578
  DBUG_RETURN(0);
1579 1580
}

1581 1582 1583

/* Change parameters for key cache (like size) */

unknown's avatar
unknown committed
1584
int ha_change_key_cache_param(KEY_CACHE *key_cache)
1585
{
unknown's avatar
unknown committed
1586 1587 1588 1589 1590 1591 1592 1593
  if (key_cache->key_cache_inited)
  {
    pthread_mutex_lock(&LOCK_global_system_variables);
    uint division_limit= key_cache->param_division_limit;
    uint age_threshold=  key_cache->param_age_threshold;
    pthread_mutex_unlock(&LOCK_global_system_variables);
    change_key_cache_param(key_cache, division_limit, age_threshold);
  }
1594 1595
  return 0;
}
unknown's avatar
unknown committed
1596

1597 1598
/* Free memory allocated by a key cache */

unknown's avatar
unknown committed
1599
int ha_end_key_cache(KEY_CACHE *key_cache)
unknown's avatar
unknown committed
1600
{
unknown's avatar
unknown committed
1601
  end_key_cache(key_cache, 1);		// Can never fail
1602
  return 0;
unknown's avatar
unknown committed
1603
}
unknown's avatar
unknown committed
1604

1605
/* Move all tables from one key cache to another one */
unknown's avatar
unknown committed
1606

unknown's avatar
unknown committed
1607 1608
int ha_change_key_cache(KEY_CACHE *old_key_cache,
			KEY_CACHE *new_key_cache)
unknown's avatar
unknown committed
1609
{
1610 1611
  mi_change_key_cache(old_key_cache, new_key_cache);
  return 0;
unknown's avatar
unknown committed
1612
}
1613 1614


unknown's avatar
unknown committed
1615 1616
/*
  Try to discover one table from handler(s)
unknown's avatar
unknown committed
1617 1618 1619 1620

  RETURN
    0  ok. In this case *frmblob and *frmlen are set
    1  error.  frmblob and frmlen may not be set
unknown's avatar
unknown committed
1621 1622
*/

unknown's avatar
unknown committed
1623 1624
int ha_discover(THD *thd, const char *db, const char *name,
		const void **frmblob, uint *frmlen)
unknown's avatar
unknown committed
1625 1626 1627
{
  int error= 1; // Table does not exist in any handler
  DBUG_ENTER("ha_discover");
1628
  DBUG_PRINT("enter", ("db: %s, name: %s", db, name));
unknown's avatar
unknown committed
1629 1630
#ifdef HAVE_NDBCLUSTER_DB
  if (have_ndbcluster == SHOW_OPTION_YES)
1631
    error= ndbcluster_discover(thd, db, name, frmblob, frmlen);
unknown's avatar
unknown committed
1632 1633 1634 1635 1636 1637 1638
#endif
  if (!error)
    statistic_increment(ha_discover_count,&LOCK_status);
  DBUG_RETURN(error);
}


1639
/*
1640 1641 1642
  Call this function in order to give the handler the possiblity 
  to ask engine if there are any new tables that should be written to disk 
  or any dropped tables that need to be removed from disk
1643 1644
*/

1645 1646
int
ha_find_files(THD *thd,const char *db,const char *path,
unknown's avatar
unknown committed
1647
	      const char *wild, bool dir, List<char> *files)
1648 1649
{
  int error= 0;
1650 1651 1652
  DBUG_ENTER("ha_find_files");
  DBUG_PRINT("enter", ("db: %s, path: %s, wild: %s, dir: %d", 
		       db, path, wild, dir));
1653 1654
#ifdef HAVE_NDBCLUSTER_DB
  if (have_ndbcluster == SHOW_OPTION_YES)
unknown's avatar
unknown committed
1655
    error= ndbcluster_find_files(thd, db, path, wild, dir, files);
1656 1657
#endif
  DBUG_RETURN(error);
1658 1659
  
  
1660 1661
}

unknown's avatar
unknown committed
1662 1663
#ifdef NOT_YET_USED

1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684
/*
  Ask handler if the table exists in engine

  RETURN
    0                   Table does not exist
    1                   Table exists
    #                   Error code

 */
int ha_table_exists(THD* thd, const char* db, const char* name)
{
  int error= 2;
  DBUG_ENTER("ha_table_exists");
  DBUG_PRINT("enter", ("db: %s, name: %s", db, name));
#ifdef HAVE_NDBCLUSTER_DB
  if (have_ndbcluster == SHOW_OPTION_YES)
    error= ndbcluster_table_exists(thd, db, name);
#endif
  DBUG_RETURN(error);
}

unknown's avatar
unknown committed
1685
#endif
1686 1687


unknown's avatar
unknown committed
1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812
/*
  Read the first row of a multi-range set.

  SYNOPSIS
    read_multi_range_first()
    found_range_p       Returns a pointer to the element in 'ranges' that
                        corresponds to the returned row.
    ranges              An array of KEY_MULTI_RANGE range descriptions.
    range_count         Number of ranges in 'ranges'.
    sorted		If result should be sorted per key.
    buffer              A HANDLER_BUFFER for internal handler usage.

  NOTES
    Record is read into table->record[0].
    *found_range_p returns a valid value only if read_multi_range_first()
    returns 0.
    Sorting is done within each range. If you want an overall sort, enter
    'ranges' with sorted ranges.

  RETURN
    0			OK, found a row
    HA_ERR_END_OF_FILE	No rows in range
    #			Error code
*/

int handler::read_multi_range_first(KEY_MULTI_RANGE **found_range_p,
                                    KEY_MULTI_RANGE *ranges, uint range_count,
                                    bool sorted, HANDLER_BUFFER *buffer)
{
  int result= HA_ERR_END_OF_FILE;
  DBUG_ENTER("handler::read_multi_range_first");
  multi_range_sorted= sorted;
  multi_range_buffer= buffer;

  for (multi_range_curr= ranges, multi_range_end= ranges + range_count;
       multi_range_curr < multi_range_end;
       multi_range_curr++)
  {
    result= read_range_first(multi_range_curr->start_key.length ?
                             &multi_range_curr->start_key : 0,
                             multi_range_curr->end_key.length ?
                             &multi_range_curr->end_key : 0,
                             test(multi_range_curr->range_flag & EQ_RANGE),
                             multi_range_sorted);
    if (result != HA_ERR_END_OF_FILE)
      break;
  }

  *found_range_p= multi_range_curr;
  DBUG_PRINT("exit",("result %d", result));
  DBUG_RETURN(result);
}


/*
  Read the next row of a multi-range set.

  SYNOPSIS
    read_multi_range_next()
    found_range_p       Returns a pointer to the element in 'ranges' that
                        corresponds to the returned row.

  NOTES
    Record is read into table->record[0].
    *found_range_p returns a valid value only if read_multi_range_next()
    returns 0.

  RETURN
    0			OK, found a row
    HA_ERR_END_OF_FILE	No (more) rows in range
    #			Error code
*/

int handler::read_multi_range_next(KEY_MULTI_RANGE **found_range_p)
{
  int result;
  DBUG_ENTER("handler::read_multi_range_next");

  /* We should not be called after the last call returned EOF. */
  DBUG_ASSERT(multi_range_curr < multi_range_end);

  do
  {
    /* Save a call if there can be only one row in range. */
    if (multi_range_curr->range_flag != (UNIQUE_RANGE | EQ_RANGE))
    {
      result= read_range_next();

      /* On success or non-EOF errors jump to the end. */
      if (result != HA_ERR_END_OF_FILE)
        break;
    }
    else
    {
      /*
        We need to set this for the last range only, but checking this
        condition is more expensive than just setting the result code.
      */
      result= HA_ERR_END_OF_FILE;
    }

    /* Try the next range(s) until one matches a record. */
    for (multi_range_curr++;
         multi_range_curr < multi_range_end;
         multi_range_curr++)
    {
      result= read_range_first(multi_range_curr->start_key.length ?
                               &multi_range_curr->start_key : 0,
                               multi_range_curr->end_key.length ?
                               &multi_range_curr->end_key : 0,
                               test(multi_range_curr->range_flag & EQ_RANGE),
                               multi_range_sorted);
      if (result != HA_ERR_END_OF_FILE)
        break;
    }
  }
  while ((result == HA_ERR_END_OF_FILE) &&
         (multi_range_curr < multi_range_end));

  *found_range_p= multi_range_curr;
  DBUG_PRINT("exit",("handler::read_multi_range_next: result %d", result));
  DBUG_RETURN(result);
}


1813 1814 1815 1816 1817 1818 1819 1820
/*
  Read first row between two ranges.
  Store ranges for future calls to read_range_next

  SYNOPSIS
    read_range_first()
    start_key		Start key. Is 0 if no min range
    end_key		End key.  Is 0 if no max range
unknown's avatar
unknown committed
1821
    eq_range_arg	Set to 1 if start_key == end_key		
1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834
    sorted		Set to 1 if result should be sorted per key

  NOTES
    Record is read into table->record[0]

  RETURN
    0			Found row
    HA_ERR_END_OF_FILE	No rows in range
    #			Error code
*/

int handler::read_range_first(const key_range *start_key,
			      const key_range *end_key,
unknown's avatar
unknown committed
1835
			      bool eq_range_arg, bool sorted)
1836 1837 1838 1839
{
  int result;
  DBUG_ENTER("handler::read_range_first");

unknown's avatar
unknown committed
1840
  eq_range= eq_range_arg;
1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858
  end_range= 0;
  if (end_key)
  {
    end_range= &save_end_range;
    save_end_range= *end_key;
    key_compare_result_on_equal= ((end_key->flag == HA_READ_BEFORE_KEY) ? 1 :
				  (end_key->flag == HA_READ_AFTER_KEY) ? -1 : 0);
  }
  range_key_part= table->key_info[active_index].key_part;

  if (!start_key)			// Read first record
    result= index_first(table->record[0]);
  else
    result= index_read(table->record[0],
		       start_key->key,
		       start_key->length,
		       start_key->flag);
  if (result)
unknown's avatar
unknown committed
1859 1860 1861
    DBUG_RETURN((result == HA_ERR_KEY_NOT_FOUND) 
		? HA_ERR_END_OF_FILE
		: result);
1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881

  DBUG_RETURN (compare_key(end_range) <= 0 ? 0 : HA_ERR_END_OF_FILE);
}


/*
  Read next row between two ranges.

  SYNOPSIS
    read_range_next()

  NOTES
    Record is read into table->record[0]

  RETURN
    0			Found row
    HA_ERR_END_OF_FILE	No rows in range
    #			Error code
*/

unknown's avatar
unknown committed
1882
int handler::read_range_next()
1883 1884 1885 1886 1887
{
  int result;
  DBUG_ENTER("handler::read_range_next");

  if (eq_range)
unknown's avatar
unknown committed
1888 1889 1890 1891 1892 1893 1894
  {
    /* We trust that index_next_same always gives a row in range */
    DBUG_RETURN(index_next_same(table->record[0],
                                end_range->key,
                                end_range->length));
  }
  result= index_next(table->record[0]);
1895 1896 1897 1898 1899 1900 1901
  if (result)
    DBUG_RETURN(result);
  DBUG_RETURN(compare_key(end_range) <= 0 ? 0 : HA_ERR_END_OF_FILE);
}


/*
unknown's avatar
unknown committed
1902
  Compare if found key (in row) is over max-value
1903 1904 1905

  SYNOPSIS
    compare_key
unknown's avatar
unknown committed
1906
    range		range to compare to row. May be 0 for no range
1907 1908
 
  NOTES
unknown's avatar
unknown committed
1909
    See key.cc::key_cmp() for details
1910 1911

  RETURN
unknown's avatar
unknown committed
1912 1913
    The return value is SIGN(key_in_row - range_key):

1914 1915 1916 1917 1918 1919 1920
    0			Key is equal to range or 'range' == 0 (no range)
   -1			Key is less than range
    1			Key is larger than range
*/

int handler::compare_key(key_range *range)
{
unknown's avatar
unknown committed
1921
  int cmp;
1922 1923
  if (!range)
    return 0;					// No max range
unknown's avatar
unknown committed
1924 1925 1926 1927
  cmp= key_cmp(range_key_part, range->key, range->length);
  if (!cmp)
    cmp= key_compare_result_on_equal;
  return cmp;
1928
}
unknown's avatar
unknown committed
1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940

int handler::index_read_idx(byte * buf, uint index, const byte * key,
			     uint key_len, enum ha_rkey_function find_flag)
{
  int error= ha_index_init(index);
  if (!error)
    error= index_read(buf, key, key_len, find_flag);
  if (!error)
    error= ha_index_end();
  return error;
}

1941

1942 1943 1944 1945 1946 1947 1948 1949
/*
  Returns a list of all known extensions.

  SYNOPSIS
    ha_known_exts()
 
  NOTES
    No mutexes, worst case race is a minor surplus memory allocation
1950 1951
    We have to recreate the extension map if mysqld is restarted (for example
    within libmysqld)
1952 1953 1954 1955

  RETURN VALUE
    pointer		pointer to TYPELIB structure
*/
1956

1957 1958
TYPELIB *ha_known_exts(void)
{
1959
  if (!known_extensions.type_names || mysys_usage_id != known_extensions_id)
1960 1961 1962 1963
  {
    show_table_type_st *types;
    List<char> found_exts;
    List_iterator_fast<char> it(found_exts);
1964 1965 1966 1967
    const char **ext, *old_ext;

    known_extensions_id= mysys_usage_id;
    found_exts.push_back((char*) ".db");
1968 1969 1970 1971 1972 1973 1974
    for (types= sys_table_types; types->type; types++)
    {      
      if (*types->value == SHOW_OPTION_YES)
      {
	handler *file= get_new_handler(0,(enum db_type) types->db_type);
	for (ext= file->bas_ext(); *ext; ext++)
	{
1975 1976 1977
	  while ((old_ext= it++))
          {
	    if (!strcmp(old_ext, *ext))
1978
	      break;
1979 1980 1981
          }
	  if (!old_ext)
	    found_exts.push_back((char *) *ext);
1982 1983 1984 1985 1986 1987

	  it.rewind();
	}
	delete file;
      }
    }
1988 1989 1990
    ext= (const char **) my_once_alloc(sizeof(char *)*
                                       (found_exts.elements+1),
                                       MYF(MY_WME | MY_FAE));
1991 1992 1993 1994
    
    DBUG_ASSERT(ext);
    known_extensions.count= found_exts.elements;
    known_extensions.type_names= ext;
1995 1996 1997 1998

    while ((old_ext= it++))
      *ext++= old_ext;
    *ext= 0;
1999 2000 2001
  }
  return &known_extensions;
}