~drizzle-trunk/drizzle/development

« back to all changes in this revision

Viewing changes to drizzled/handler.cc

  • Committer: Lee
  • Date: 2009-01-01 03:07:33 UTC
  • mto: (758.1.3 devel)
  • mto: This revision was merged to the branch mainline in revision 759.
  • Revision ID: lbieber@lbieber-desktop-20090101030733-fb411b55f07vij8q
more header file cleanup

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
1
/* -*- mode: c++; c-basic-offset: 2; indent-tabs-mode: nil; -*-
2
2
 *  vim:expandtab:shiftwidth=2:tabstop=2:smarttab:
3
3
 *
4
 
 *  Copyright (C) 2008 Sun Microsystems, Inc.
 
4
 *  Copyright (C) 2008 Sun Microsystems
5
5
 *
6
6
 *  This program is free software; you can redistribute it and/or modify
7
7
 *  it under the terms of the GNU General Public License as published by
18
18
 */
19
19
 
20
20
/**
21
 
  @file Cursor.cc
 
21
  @file handler.cc
22
22
 
23
23
  Handler-calling-functions
24
24
*/
25
25
 
26
 
#include <config.h>
27
 
 
28
 
#include <fcntl.h>
29
 
 
 
26
#include <drizzled/server_includes.h>
 
27
#include <libdrizzle/libdrizzle.h>
 
28
#include <mysys/hash.h>
30
29
#include <drizzled/error.h>
31
 
#include <drizzled/field/epoch.h>
32
30
#include <drizzled/gettext.h>
33
 
#include <drizzled/internal/my_sys.h>
34
 
#include <drizzled/item/empty_string.h>
35
 
#include <drizzled/item/int.h>
36
 
#include <drizzled/lock.h>
37
 
#include <drizzled/message/table.h>
38
 
#include <drizzled/my_hash.h>
39
 
#include <drizzled/optimizer/cost_vector.h>
40
 
#include <drizzled/plugin/client.h>
41
 
#include <drizzled/plugin/event_observer.h>
42
 
#include <drizzled/plugin/storage_engine.h>
 
31
#include <drizzled/data_home.h>
43
32
#include <drizzled/probes.h>
 
33
#include <drizzled/sql_parse.h>
 
34
#include <drizzled/cost_vect.h>
 
35
#include CMATH_H
44
36
#include <drizzled/session.h>
45
37
#include <drizzled/sql_base.h>
46
 
#include <drizzled/sql_parse.h>
47
 
#include <drizzled/transaction_services.h>
48
 
 
49
 
using namespace std;
50
 
 
51
 
namespace drizzled
52
 
{
 
38
#include <drizzled/replicator.h>
 
39
#include <drizzled/lock.h>
 
40
#include <drizzled/item/int.h>
 
41
#include <drizzled/item/empty_string.h>
 
42
#include <drizzled/unireg.h> // for mysql_frm_type
 
43
 
 
44
#if defined(CMATH_NAMESPACE)
 
45
using namespace CMATH_NAMESPACE;
 
46
#endif
 
47
 
 
48
 
 
49
extern HASH open_cache;
 
50
 
 
51
KEY_CREATE_INFO default_key_create_info= { HA_KEY_ALG_UNDEF, 0, {NULL,0}, {NULL,0} };
 
52
 
 
53
/* number of entries in handlertons[] */
 
54
uint32_t total_ha= 0;
 
55
/* number of storage engines (from handlertons[]) that support 2pc */
 
56
uint32_t total_ha_2pc= 0;
 
57
/* size of savepoint storage area (see ha_init) */
 
58
uint32_t savepoint_alloc_size= 0;
 
59
 
 
60
const char *ha_row_type[] = {
 
61
  "", "FIXED", "DYNAMIC", "COMPRESSED", "REDUNDANT", "COMPACT", "PAGE", "?","?","?"
 
62
};
 
63
 
 
64
const char *tx_isolation_names[] =
 
65
{ "READ-UNCOMMITTED", "READ-COMMITTED", "REPEATABLE-READ", "SERIALIZABLE",
 
66
  NULL};
 
67
 
 
68
TYPELIB tx_isolation_typelib= {array_elements(tx_isolation_names)-1,"",
 
69
                               tx_isolation_names, NULL};
 
70
 
 
71
static TYPELIB known_extensions= {0,"known_exts", NULL, NULL};
 
72
uint32_t known_extensions_id= 0;
 
73
 
 
74
 
 
75
/**
 
76
  Register handler error messages for use with my_error().
 
77
 
 
78
  @retval
 
79
    0           OK
 
80
  @retval
 
81
    !=0         Error
 
82
*/
 
83
 
 
84
int ha_init_errors(void)
 
85
{
 
86
#define SETMSG(nr, msg) errmsgs[(nr) - HA_ERR_FIRST]= (msg)
 
87
  const char    **errmsgs;
 
88
 
 
89
  /* Allocate a pointer array for the error message strings. */
 
90
  /* Zerofill it to avoid uninitialized gaps. */
 
91
  if (! (errmsgs= (const char**) malloc(HA_ERR_ERRORS * sizeof(char*))))
 
92
    return 1;
 
93
  memset(errmsgs, 0, HA_ERR_ERRORS * sizeof(char *));
 
94
 
 
95
  /* Set the dedicated error messages. */
 
96
  SETMSG(HA_ERR_KEY_NOT_FOUND,          ER(ER_KEY_NOT_FOUND));
 
97
  SETMSG(HA_ERR_FOUND_DUPP_KEY,         ER(ER_DUP_KEY));
 
98
  SETMSG(HA_ERR_RECORD_CHANGED,         "Update wich is recoverable");
 
99
  SETMSG(HA_ERR_WRONG_INDEX,            "Wrong index given to function");
 
100
  SETMSG(HA_ERR_CRASHED,                ER(ER_NOT_KEYFILE));
 
101
  SETMSG(HA_ERR_WRONG_IN_RECORD,        ER(ER_CRASHED_ON_USAGE));
 
102
  SETMSG(HA_ERR_OUT_OF_MEM,             "Table handler out of memory");
 
103
  SETMSG(HA_ERR_NOT_A_TABLE,            "Incorrect file format '%.64s'");
 
104
  SETMSG(HA_ERR_WRONG_COMMAND,          "Command not supported");
 
105
  SETMSG(HA_ERR_OLD_FILE,               ER(ER_OLD_KEYFILE));
 
106
  SETMSG(HA_ERR_NO_ACTIVE_RECORD,       "No record read in update");
 
107
  SETMSG(HA_ERR_RECORD_DELETED,         "Intern record deleted");
 
108
  SETMSG(HA_ERR_RECORD_FILE_FULL,       ER(ER_RECORD_FILE_FULL));
 
109
  SETMSG(HA_ERR_INDEX_FILE_FULL,        "No more room in index file '%.64s'");
 
110
  SETMSG(HA_ERR_END_OF_FILE,            "End in next/prev/first/last");
 
111
  SETMSG(HA_ERR_UNSUPPORTED,            ER(ER_ILLEGAL_HA));
 
112
  SETMSG(HA_ERR_TO_BIG_ROW,             "Too big row");
 
113
  SETMSG(HA_WRONG_CREATE_OPTION,        "Wrong create option");
 
114
  SETMSG(HA_ERR_FOUND_DUPP_UNIQUE,      ER(ER_DUP_UNIQUE));
 
115
  SETMSG(HA_ERR_UNKNOWN_CHARSET,        "Can't open charset");
 
116
  SETMSG(HA_ERR_WRONG_MRG_TABLE_DEF,    ER(ER_WRONG_MRG_TABLE));
 
117
  SETMSG(HA_ERR_CRASHED_ON_REPAIR,      ER(ER_CRASHED_ON_REPAIR));
 
118
  SETMSG(HA_ERR_CRASHED_ON_USAGE,       ER(ER_CRASHED_ON_USAGE));
 
119
  SETMSG(HA_ERR_LOCK_WAIT_TIMEOUT,      ER(ER_LOCK_WAIT_TIMEOUT));
 
120
  SETMSG(HA_ERR_LOCK_TABLE_FULL,        ER(ER_LOCK_TABLE_FULL));
 
121
  SETMSG(HA_ERR_READ_ONLY_TRANSACTION,  ER(ER_READ_ONLY_TRANSACTION));
 
122
  SETMSG(HA_ERR_LOCK_DEADLOCK,          ER(ER_LOCK_DEADLOCK));
 
123
  SETMSG(HA_ERR_CANNOT_ADD_FOREIGN,     ER(ER_CANNOT_ADD_FOREIGN));
 
124
  SETMSG(HA_ERR_NO_REFERENCED_ROW,      ER(ER_NO_REFERENCED_ROW_2));
 
125
  SETMSG(HA_ERR_ROW_IS_REFERENCED,      ER(ER_ROW_IS_REFERENCED_2));
 
126
  SETMSG(HA_ERR_NO_SAVEPOINT,           "No savepoint with that name");
 
127
  SETMSG(HA_ERR_NON_UNIQUE_BLOCK_SIZE,  "Non unique key block size");
 
128
  SETMSG(HA_ERR_NO_SUCH_TABLE,          "No such table: '%.64s'");
 
129
  SETMSG(HA_ERR_TABLE_EXIST,            ER(ER_TABLE_EXISTS_ERROR));
 
130
  SETMSG(HA_ERR_NO_CONNECTION,          "Could not connect to storage engine");
 
131
  SETMSG(HA_ERR_TABLE_DEF_CHANGED,      ER(ER_TABLE_DEF_CHANGED));
 
132
  SETMSG(HA_ERR_FOREIGN_DUPLICATE_KEY,  "FK constraint would lead to duplicate key");
 
133
  SETMSG(HA_ERR_TABLE_NEEDS_UPGRADE,    ER(ER_TABLE_NEEDS_UPGRADE));
 
134
  SETMSG(HA_ERR_TABLE_READONLY,         ER(ER_OPEN_AS_READONLY));
 
135
  SETMSG(HA_ERR_AUTOINC_READ_FAILED,    ER(ER_AUTOINC_READ_FAILED));
 
136
  SETMSG(HA_ERR_AUTOINC_ERANGE,         ER(ER_WARN_DATA_OUT_OF_RANGE));
 
137
 
 
138
  /* Register the error messages for use with my_error(). */
 
139
  return my_error_register(errmsgs, HA_ERR_FIRST, HA_ERR_LAST);
 
140
}
 
141
 
 
142
 
 
143
/**
 
144
  Unregister handler error messages.
 
145
 
 
146
  @retval
 
147
    0           OK
 
148
  @retval
 
149
    !=0         Error
 
150
*/
 
151
static int ha_finish_errors(void)
 
152
{
 
153
  const char    **errmsgs;
 
154
 
 
155
  /* Allocate a pointer array for the error message strings. */
 
156
  if (! (errmsgs= my_error_unregister(HA_ERR_FIRST, HA_ERR_LAST)))
 
157
    return 1;
 
158
  free((unsigned char*) errmsgs);
 
159
  return 0;
 
160
}
 
161
 
 
162
int ha_init()
 
163
{
 
164
  int error= 0;
 
165
 
 
166
  assert(total_ha < MAX_HA);
 
167
  /*
 
168
    Check if there is a transaction-capable storage engine besides the
 
169
    binary log (which is considered a transaction-capable storage engine in
 
170
    counting total_ha)
 
171
  */
 
172
  opt_using_transactions= total_ha>(uint32_t)opt_bin_log;
 
173
  savepoint_alloc_size+= sizeof(SAVEPOINT);
 
174
  return(error);
 
175
}
 
176
 
 
177
int ha_end()
 
178
{
 
179
  int error= 0;
 
180
 
 
181
  /*
 
182
    This should be eventualy based  on the graceful shutdown flag.
 
183
    So if flag is equal to HA_PANIC_CLOSE, the deallocate
 
184
    the errors.
 
185
  */
 
186
  if (ha_finish_errors())
 
187
    error= 1;
 
188
 
 
189
  return(error);
 
190
}
 
191
 
 
192
static bool dropdb_handlerton(Session *unused1 __attribute__((unused)),
 
193
                              plugin_ref plugin,
 
194
                              void *path)
 
195
{
 
196
  handlerton *hton= plugin_data(plugin, handlerton *);
 
197
  if (hton->state == SHOW_OPTION_YES && hton->drop_database)
 
198
    hton->drop_database(hton, (char *)path);
 
199
  return false;
 
200
}
 
201
 
 
202
 
 
203
void ha_drop_database(char* path)
 
204
{
 
205
  plugin_foreach(NULL, dropdb_handlerton, DRIZZLE_STORAGE_ENGINE_PLUGIN, path);
 
206
}
 
207
 
 
208
 
 
209
static bool closecon_handlerton(Session *session, plugin_ref plugin,
 
210
                                void *unused __attribute__((unused)))
 
211
{
 
212
  handlerton *hton= plugin_data(plugin, handlerton *);
 
213
  /*
 
214
    there's no need to rollback here as all transactions must
 
215
    be rolled back already
 
216
  */
 
217
  if (hton->state == SHOW_OPTION_YES && hton->close_connection &&
 
218
      session_get_ha_data(session, hton))
 
219
    hton->close_connection(hton, session);
 
220
  return false;
 
221
}
 
222
 
 
223
 
 
224
/**
 
225
  @note
 
226
    don't bother to rollback here, it's done already
 
227
*/
 
228
void ha_close_connection(Session* session)
 
229
{
 
230
  plugin_foreach(session, closecon_handlerton, DRIZZLE_STORAGE_ENGINE_PLUGIN, 0);
 
231
}
 
232
 
 
233
/* ========================================================================
 
234
 ======================= TRANSACTIONS ===================================*/
 
235
 
 
236
/**
 
237
  Transaction handling in the server
 
238
  ==================================
 
239
 
 
240
  In each client connection, MySQL maintains two transactional
 
241
  states:
 
242
  - a statement transaction,
 
243
  - a standard, also called normal transaction.
 
244
 
 
245
  Historical note
 
246
  ---------------
 
247
  "Statement transaction" is a non-standard term that comes
 
248
  from the times when MySQL supported BerkeleyDB storage engine.
 
249
 
 
250
  First of all, it should be said that in BerkeleyDB auto-commit
 
251
  mode auto-commits operations that are atomic to the storage
 
252
  engine itself, such as a write of a record, and are too
 
253
  high-granular to be atomic from the application perspective
 
254
  (MySQL). One SQL statement could involve many BerkeleyDB
 
255
  auto-committed operations and thus BerkeleyDB auto-commit was of
 
256
  little use to MySQL.
 
257
 
 
258
  Secondly, instead of SQL standard savepoints, BerkeleyDB
 
259
  provided the concept of "nested transactions". In a nutshell,
 
260
  transactions could be arbitrarily nested, but when the parent
 
261
  transaction was committed or aborted, all its child (nested)
 
262
  transactions were handled committed or aborted as well.
 
263
  Commit of a nested transaction, in turn, made its changes
 
264
  visible, but not durable: it destroyed the nested transaction,
 
265
  all its changes would become available to the parent and
 
266
  currently active nested transactions of this parent.
 
267
 
 
268
  So the mechanism of nested transactions was employed to
 
269
  provide "all or nothing" guarantee of SQL statements
 
270
  required by the standard.
 
271
  A nested transaction would be created at start of each SQL
 
272
  statement, and destroyed (committed or aborted) at statement
 
273
  end. Such nested transaction was internally referred to as
 
274
  a "statement transaction" and gave birth to the term.
 
275
 
 
276
  <Historical note ends>
 
277
 
 
278
  Since then a statement transaction is started for each statement
 
279
  that accesses transactional tables or uses the binary log.  If
 
280
  the statement succeeds, the statement transaction is committed.
 
281
  If the statement fails, the transaction is rolled back. Commits
 
282
  of statement transactions are not durable -- each such
 
283
  transaction is nested in the normal transaction, and if the
 
284
  normal transaction is rolled back, the effects of all enclosed
 
285
  statement transactions are undone as well.  Technically,
 
286
  a statement transaction can be viewed as a savepoint which is
 
287
  maintained automatically in order to make effects of one
 
288
  statement atomic.
 
289
 
 
290
  The normal transaction is started by the user and is ended
 
291
  usually upon a user request as well. The normal transaction
 
292
  encloses transactions of all statements issued between
 
293
  its beginning and its end.
 
294
  In autocommit mode, the normal transaction is equivalent
 
295
  to the statement transaction.
 
296
 
 
297
  Since MySQL supports PSEA (pluggable storage engine
 
298
  architecture), more than one transactional engine can be
 
299
  active at a time. Hence transactions, from the server
 
300
  point of view, are always distributed. In particular,
 
301
  transactional state is maintained independently for each
 
302
  engine. In order to commit a transaction the two phase
 
303
  commit protocol is employed.
 
304
 
 
305
  Not all statements are executed in context of a transaction.
 
306
  Administrative and status information statements do not modify
 
307
  engine data, and thus do not start a statement transaction and
 
308
  also have no effect on the normal transaction. Examples of such
 
309
  statements are SHOW STATUS and RESET SLAVE.
 
310
 
 
311
  Similarly DDL statements are not transactional,
 
312
  and therefore a transaction is [almost] never started for a DDL
 
313
  statement. The difference between a DDL statement and a purely
 
314
  administrative statement though is that a DDL statement always
 
315
  commits the current transaction before proceeding, if there is
 
316
  any.
 
317
 
 
318
  At last, SQL statements that work with non-transactional
 
319
  engines also have no effect on the transaction state of the
 
320
  connection. Even though they are written to the binary log,
 
321
  and the binary log is, overall, transactional, the writes
 
322
  are done in "write-through" mode, directly to the binlog
 
323
  file, followed with a OS cache sync, in other words,
 
324
  bypassing the binlog undo log (translog).
 
325
  They do not commit the current normal transaction.
 
326
  A failure of a statement that uses non-transactional tables
 
327
  would cause a rollback of the statement transaction, but
 
328
  in case there no non-transactional tables are used,
 
329
  no statement transaction is started.
 
330
 
 
331
  Data layout
 
332
  -----------
 
333
 
 
334
  The server stores its transaction-related data in
 
335
  session->transaction. This structure has two members of type
 
336
  Session_TRANS. These members correspond to the statement and
 
337
  normal transactions respectively:
 
338
 
 
339
  - session->transaction.stmt contains a list of engines
 
340
  that are participating in the given statement
 
341
  - session->transaction.all contains a list of engines that
 
342
  have participated in any of the statement transactions started
 
343
  within the context of the normal transaction.
 
344
  Each element of the list contains a pointer to the storage
 
345
  engine, engine-specific transactional data, and engine-specific
 
346
  transaction flags.
 
347
 
 
348
  In autocommit mode session->transaction.all is empty.
 
349
  Instead, data of session->transaction.stmt is
 
350
  used to commit/rollback the normal transaction.
 
351
 
 
352
  The list of registered engines has a few important properties:
 
353
  - no engine is registered in the list twice
 
354
  - engines are present in the list a reverse temporal order --
 
355
  new participants are always added to the beginning of the list.
 
356
 
 
357
  Transaction life cycle
 
358
  ----------------------
 
359
 
 
360
  When a new connection is established, session->transaction
 
361
  members are initialized to an empty state.
 
362
  If a statement uses any tables, all affected engines
 
363
  are registered in the statement engine list. In
 
364
  non-autocommit mode, the same engines are registered in
 
365
  the normal transaction list.
 
366
  At the end of the statement, the server issues a commit
 
367
  or a roll back for all engines in the statement list.
 
368
  At this point transaction flags of an engine, if any, are
 
369
  propagated from the statement list to the list of the normal
 
370
  transaction.
 
371
  When commit/rollback is finished, the statement list is
 
372
  cleared. It will be filled in again by the next statement,
 
373
  and emptied again at the next statement's end.
 
374
 
 
375
  The normal transaction is committed in a similar way
 
376
  (by going over all engines in session->transaction.all list)
 
377
  but at different times:
 
378
  - upon COMMIT SQL statement is issued by the user
 
379
  - implicitly, by the server, at the beginning of a DDL statement
 
380
  or SET AUTOCOMMIT={0|1} statement.
 
381
 
 
382
  The normal transaction can be rolled back as well:
 
383
  - if the user has requested so, by issuing ROLLBACK SQL
 
384
  statement
 
385
  - if one of the storage engines requested a rollback
 
386
  by setting session->transaction_rollback_request. This may
 
387
  happen in case, e.g., when the transaction in the engine was
 
388
  chosen a victim of the internal deadlock resolution algorithm
 
389
  and rolled back internally. When such a situation happens, there
 
390
  is little the server can do and the only option is to rollback
 
391
  transactions in all other participating engines.  In this case
 
392
  the rollback is accompanied by an error sent to the user.
 
393
 
 
394
  As follows from the use cases above, the normal transaction
 
395
  is never committed when there is an outstanding statement
 
396
  transaction. In most cases there is no conflict, since
 
397
  commits of the normal transaction are issued by a stand-alone
 
398
  administrative or DDL statement, thus no outstanding statement
 
399
  transaction of the previous statement exists. Besides,
 
400
  all statements that manipulate with the normal transaction
 
401
  are prohibited in stored functions and triggers, therefore
 
402
  no conflicting situation can occur in a sub-statement either.
 
403
  The remaining rare cases when the server explicitly has
 
404
  to commit the statement transaction prior to committing the normal
 
405
  one cover error-handling scenarios (see for example
 
406
  SQLCOM_LOCK_TABLES).
 
407
 
 
408
  When committing a statement or a normal transaction, the server
 
409
  either uses the two-phase commit protocol, or issues a commit
 
410
  in each engine independently. The two-phase commit protocol
 
411
  is used only if:
 
412
  - all participating engines support two-phase commit (provide
 
413
    handlerton::prepare PSEA API call) and
 
414
  - transactions in at least two engines modify data (i.e. are
 
415
  not read-only).
 
416
 
 
417
  Note that the two phase commit is used for
 
418
  statement transactions, even though they are not durable anyway.
 
419
  This is done to ensure logical consistency of data in a multiple-
 
420
  engine transaction.
 
421
  For example, imagine that some day MySQL supports unique
 
422
  constraint checks deferred till the end of statement. In such
 
423
  case a commit in one of the engines may yield ER_DUP_KEY,
 
424
  and MySQL should be able to gracefully abort statement
 
425
  transactions of other participants.
 
426
 
 
427
  After the normal transaction has been committed,
 
428
  session->transaction.all list is cleared.
 
429
 
 
430
  When a connection is closed, the current normal transaction, if
 
431
  any, is rolled back.
 
432
 
 
433
  Roles and responsibilities
 
434
  --------------------------
 
435
 
 
436
  The server has no way to know that an engine participates in
 
437
  the statement and a transaction has been started
 
438
  in it unless the engine says so. Thus, in order to be
 
439
  a part of a transaction, the engine must "register" itself.
 
440
  This is done by invoking trans_register_ha() server call.
 
441
  Normally the engine registers itself whenever handler::external_lock()
 
442
  is called. trans_register_ha() can be invoked many times: if
 
443
  an engine is already registered, the call does nothing.
 
444
  In case autocommit is not set, the engine must register itself
 
445
  twice -- both in the statement list and in the normal transaction
 
446
  list.
 
447
  In which list to register is a parameter of trans_register_ha().
 
448
 
 
449
  Note, that although the registration interface in itself is
 
450
  fairly clear, the current usage practice often leads to undesired
 
451
  effects. E.g. since a call to trans_register_ha() in most engines
 
452
  is embedded into implementation of handler::external_lock(), some
 
453
  DDL statements start a transaction (at least from the server
 
454
  point of view) even though they are not expected to. E.g.
 
455
  CREATE TABLE does not start a transaction, since
 
456
  handler::external_lock() is never called during CREATE TABLE. But
 
457
  CREATE TABLE ... SELECT does, since handler::external_lock() is
 
458
  called for the table that is being selected from. This has no
 
459
  practical effects currently, but must be kept in mind
 
460
  nevertheless.
 
461
 
 
462
  Once an engine is registered, the server will do the rest
 
463
  of the work.
 
464
 
 
465
  During statement execution, whenever any of data-modifying
 
466
  PSEA API methods is used, e.g. handler::write_row() or
 
467
  handler::update_row(), the read-write flag is raised in the
 
468
  statement transaction for the involved engine.
 
469
  Currently All PSEA calls are "traced", and the data can not be
 
470
  changed in a way other than issuing a PSEA call. Important:
 
471
  unless this invariant is preserved the server will not know that
 
472
  a transaction in a given engine is read-write and will not
 
473
  involve the two-phase commit protocol!
 
474
 
 
475
  At the end of a statement, server call
 
476
  ha_autocommit_or_rollback() is invoked. This call in turn
 
477
  invokes handlerton::prepare() for every involved engine.
 
478
  Prepare is followed by a call to handlerton::commit_one_phase()
 
479
  If a one-phase commit will suffice, handlerton::prepare() is not
 
480
  invoked and the server only calls handlerton::commit_one_phase().
 
481
  At statement commit, the statement-related read-write engine
 
482
  flag is propagated to the corresponding flag in the normal
 
483
  transaction.  When the commit is complete, the list of registered
 
484
  engines is cleared.
 
485
 
 
486
  Rollback is handled in a similar fashion.
 
487
 
 
488
  Additional notes on DDL and the normal transaction.
 
489
  ---------------------------------------------------
 
490
 
 
491
  DDLs and operations with non-transactional engines
 
492
  do not "register" in session->transaction lists, and thus do not
 
493
  modify the transaction state. Besides, each DDL in
 
494
  MySQL is prefixed with an implicit normal transaction commit
 
495
  (a call to end_active_trans()), and thus leaves nothing
 
496
  to modify.
 
497
  However, as it has been pointed out with CREATE TABLE .. SELECT,
 
498
  some DDL statements can start a *new* transaction.
 
499
 
 
500
  Behaviour of the server in this case is currently badly
 
501
  defined.
 
502
  DDL statements use a form of "semantic" logging
 
503
  to maintain atomicity: if CREATE TABLE .. SELECT failed,
 
504
  the newly created table is deleted.
 
505
  In addition, some DDL statements issue interim transaction
 
506
  commits: e.g. ALTER Table issues a commit after data is copied
 
507
  from the original table to the internal temporary table. Other
 
508
  statements, e.g. CREATE TABLE ... SELECT do not always commit
 
509
  after itself.
 
510
  And finally there is a group of DDL statements such as
 
511
  RENAME/DROP Table that doesn't start a new transaction
 
512
  and doesn't commit.
 
513
 
 
514
  This diversity makes it hard to say what will happen if
 
515
  by chance a stored function is invoked during a DDL --
 
516
  whether any modifications it makes will be committed or not
 
517
  is not clear. Fortunately, SQL grammar of few DDLs allows
 
518
  invocation of a stored function.
 
519
 
 
520
  A consistent behaviour is perhaps to always commit the normal
 
521
  transaction after all DDLs, just like the statement transaction
 
522
  is always committed at the end of all statements.
 
523
*/
 
524
 
 
525
/**
 
526
  Register a storage engine for a transaction.
 
527
 
 
528
  Every storage engine MUST call this function when it starts
 
529
  a transaction or a statement (that is it must be called both for the
 
530
  "beginning of transaction" and "beginning of statement").
 
531
  Only storage engines registered for the transaction/statement
 
532
  will know when to commit/rollback it.
 
533
 
 
534
  @note
 
535
    trans_register_ha is idempotent - storage engine may register many
 
536
    times per transaction.
 
537
 
 
538
*/
 
539
void trans_register_ha(Session *session, bool all, handlerton *ht_arg)
 
540
{
 
541
  Session_TRANS *trans;
 
542
  Ha_trx_info *ha_info;
 
543
 
 
544
  if (all)
 
545
  {
 
546
    trans= &session->transaction.all;
 
547
    session->server_status|= SERVER_STATUS_IN_TRANS;
 
548
  }
 
549
  else
 
550
    trans= &session->transaction.stmt;
 
551
 
 
552
  ha_info= session->ha_data[ht_arg->slot].ha_info + static_cast<unsigned>(all);
 
553
 
 
554
  if (ha_info->is_started())
 
555
    return; /* already registered, return */
 
556
 
 
557
  ha_info->register_ha(trans, ht_arg);
 
558
 
 
559
  trans->no_2pc|=(ht_arg->prepare==0);
 
560
  if (session->transaction.xid_state.xid.is_null())
 
561
    session->transaction.xid_state.xid.set(session->query_id);
 
562
 
 
563
  return;
 
564
}
 
565
 
 
566
/**
 
567
  @retval
 
568
    0   ok
 
569
  @retval
 
570
    1   error, transaction was rolled back
 
571
*/
 
572
int ha_prepare(Session *session)
 
573
{
 
574
  int error=0, all=1;
 
575
  Session_TRANS *trans=all ? &session->transaction.all : &session->transaction.stmt;
 
576
  Ha_trx_info *ha_info= trans->ha_list;
 
577
  if (ha_info)
 
578
  {
 
579
    for (; ha_info; ha_info= ha_info->next())
 
580
    {
 
581
      int err;
 
582
      handlerton *ht= ha_info->ht();
 
583
      status_var_increment(session->status_var.ha_prepare_count);
 
584
      if (ht->prepare)
 
585
      {
 
586
        if ((err= ht->prepare(ht, session, all)))
 
587
        {
 
588
          my_error(ER_ERROR_DURING_COMMIT, MYF(0), err);
 
589
          ha_rollback_trans(session, all);
 
590
          error=1;
 
591
          break;
 
592
        }
 
593
      }
 
594
      else
 
595
      {
 
596
        push_warning_printf(session, DRIZZLE_ERROR::WARN_LEVEL_WARN,
 
597
                            ER_ILLEGAL_HA, ER(ER_ILLEGAL_HA),
 
598
                            ha_resolve_storage_engine_name(ht));
 
599
      }
 
600
    }
 
601
  }
 
602
  return(error);
 
603
}
 
604
 
 
605
/**
 
606
  Check if we can skip the two-phase commit.
 
607
 
 
608
  A helper function to evaluate if two-phase commit is mandatory.
 
609
  As a side effect, propagates the read-only/read-write flags
 
610
  of the statement transaction to its enclosing normal transaction.
 
611
 
 
612
  @retval true   we must run a two-phase commit. Returned
 
613
                 if we have at least two engines with read-write changes.
 
614
  @retval false  Don't need two-phase commit. Even if we have two
 
615
                 transactional engines, we can run two independent
 
616
                 commits if changes in one of the engines are read-only.
 
617
*/
 
618
 
 
619
static
 
620
bool
 
621
ha_check_and_coalesce_trx_read_only(Session *session, Ha_trx_info *ha_list,
 
622
                                    bool all)
 
623
{
 
624
  /* The number of storage engines that have actual changes. */
 
625
  unsigned rw_ha_count= 0;
 
626
  Ha_trx_info *ha_info;
 
627
 
 
628
  for (ha_info= ha_list; ha_info; ha_info= ha_info->next())
 
629
  {
 
630
    if (ha_info->is_trx_read_write())
 
631
      ++rw_ha_count;
 
632
 
 
633
    if (! all)
 
634
    {
 
635
      Ha_trx_info *ha_info_all= &session->ha_data[ha_info->ht()->slot].ha_info[1];
 
636
      assert(ha_info != ha_info_all);
 
637
      /*
 
638
        Merge read-only/read-write information about statement
 
639
        transaction to its enclosing normal transaction. Do this
 
640
        only if in a real transaction -- that is, if we know
 
641
        that ha_info_all is registered in session->transaction.all.
 
642
        Since otherwise we only clutter the normal transaction flags.
 
643
      */
 
644
      if (ha_info_all->is_started()) /* false if autocommit. */
 
645
        ha_info_all->coalesce_trx_with(ha_info);
 
646
    }
 
647
    else if (rw_ha_count > 1)
 
648
    {
 
649
      /*
 
650
        It is a normal transaction, so we don't need to merge read/write
 
651
        information up, and the need for two-phase commit has been
 
652
        already established. Break the loop prematurely.
 
653
      */
 
654
      break;
 
655
    }
 
656
  }
 
657
  return rw_ha_count > 1;
 
658
}
 
659
 
 
660
 
 
661
/**
 
662
  @retval
 
663
    0   ok
 
664
  @retval
 
665
    1   transaction was rolled back
 
666
  @retval
 
667
    2   error during commit, data may be inconsistent
 
668
 
 
669
  @todo
 
670
    Since we don't support nested statement transactions in 5.0,
 
671
    we can't commit or rollback stmt transactions while we are inside
 
672
    stored functions or triggers. So we simply do nothing now.
 
673
    TODO: This should be fixed in later ( >= 5.1) releases.
 
674
*/
 
675
int ha_commit_trans(Session *session, bool all)
 
676
{
 
677
  int error= 0, cookie= 0;
 
678
  /*
 
679
    'all' means that this is either an explicit commit issued by
 
680
    user, or an implicit commit issued by a DDL.
 
681
  */
 
682
  Session_TRANS *trans= all ? &session->transaction.all : &session->transaction.stmt;
 
683
  bool is_real_trans= all || session->transaction.all.ha_list == 0;
 
684
  Ha_trx_info *ha_info= trans->ha_list;
 
685
  my_xid xid= session->transaction.xid_state.xid.get_my_xid();
 
686
 
 
687
  /*
 
688
    We must not commit the normal transaction if a statement
 
689
    transaction is pending. Otherwise statement transaction
 
690
    flags will not get propagated to its normal transaction's
 
691
    counterpart.
 
692
  */
 
693
  assert(session->transaction.stmt.ha_list == NULL ||
 
694
              trans == &session->transaction.stmt);
 
695
 
 
696
  if (ha_info)
 
697
  {
 
698
    bool must_2pc;
 
699
 
 
700
    if (is_real_trans && wait_if_global_read_lock(session, 0, 0))
 
701
    {
 
702
      ha_rollback_trans(session, all);
 
703
      return(1);
 
704
    }
 
705
 
 
706
    must_2pc= ha_check_and_coalesce_trx_read_only(session, ha_info, all);
 
707
 
 
708
    if (!trans->no_2pc && must_2pc)
 
709
    {
 
710
      for (; ha_info && !error; ha_info= ha_info->next())
 
711
      {
 
712
        int err;
 
713
        handlerton *ht= ha_info->ht();
 
714
        /*
 
715
          Do not call two-phase commit if this particular
 
716
          transaction is read-only. This allows for simpler
 
717
          implementation in engines that are always read-only.
 
718
        */
 
719
        if (! ha_info->is_trx_read_write())
 
720
          continue;
 
721
        /*
 
722
          Sic: we know that prepare() is not NULL since otherwise
 
723
          trans->no_2pc would have been set.
 
724
        */
 
725
        if ((err= ht->prepare(ht, session, all)))
 
726
        {
 
727
          my_error(ER_ERROR_DURING_COMMIT, MYF(0), err);
 
728
          error= 1;
 
729
        }
 
730
        status_var_increment(session->status_var.ha_prepare_count);
 
731
      }
 
732
      if (error || (is_real_trans && xid &&
 
733
                    (error= !(cookie= tc_log->log_xid(session, xid)))))
 
734
      {
 
735
        ha_rollback_trans(session, all);
 
736
        error= 1;
 
737
        goto end;
 
738
      }
 
739
    }
 
740
    error=ha_commit_one_phase(session, all) ? (cookie ? 2 : 1) : 0;
 
741
    if (cookie)
 
742
      tc_log->unlog(cookie, xid);
 
743
end:
 
744
    if (is_real_trans)
 
745
      start_waiting_global_read_lock(session);
 
746
  }
 
747
  return(error);
 
748
}
 
749
 
 
750
/**
 
751
  @note
 
752
  This function does not care about global read lock. A caller should.
 
753
*/
 
754
int ha_commit_one_phase(Session *session, bool all)
 
755
{
 
756
  int error=0;
 
757
  Session_TRANS *trans=all ? &session->transaction.all : &session->transaction.stmt;
 
758
  bool is_real_trans=all || session->transaction.all.ha_list == 0;
 
759
  Ha_trx_info *ha_info= trans->ha_list, *ha_info_next;
 
760
  if (ha_info)
 
761
  {
 
762
    for (; ha_info; ha_info= ha_info_next)
 
763
    {
 
764
      int err;
 
765
      handlerton *ht= ha_info->ht();
 
766
      if ((err= ht->commit(ht, session, all)))
 
767
      {
 
768
        my_error(ER_ERROR_DURING_COMMIT, MYF(0), err);
 
769
        error=1;
 
770
      }
 
771
      status_var_increment(session->status_var.ha_commit_count);
 
772
      ha_info_next= ha_info->next();
 
773
      ha_info->reset(); /* keep it conveniently zero-filled */
 
774
    }
 
775
    trans->ha_list= 0;
 
776
    trans->no_2pc=0;
 
777
    if (is_real_trans)
 
778
      session->transaction.xid_state.xid.null();
 
779
    if (all)
 
780
    {
 
781
      session->variables.tx_isolation=session->session_tx_isolation;
 
782
      session->transaction.cleanup();
 
783
    }
 
784
  }
 
785
  return(error);
 
786
}
 
787
 
 
788
 
 
789
int ha_rollback_trans(Session *session, bool all)
 
790
{
 
791
  int error=0;
 
792
  Session_TRANS *trans=all ? &session->transaction.all : &session->transaction.stmt;
 
793
  Ha_trx_info *ha_info= trans->ha_list, *ha_info_next;
 
794
  bool is_real_trans=all || session->transaction.all.ha_list == 0;
 
795
 
 
796
  /*
 
797
    We must not rollback the normal transaction if a statement
 
798
    transaction is pending.
 
799
  */
 
800
  assert(session->transaction.stmt.ha_list == NULL ||
 
801
              trans == &session->transaction.stmt);
 
802
 
 
803
  if (ha_info)
 
804
  {
 
805
    for (; ha_info; ha_info= ha_info_next)
 
806
    {
 
807
      int err;
 
808
      handlerton *ht= ha_info->ht();
 
809
      if ((err= ht->rollback(ht, session, all)))
 
810
      { // cannot happen
 
811
        my_error(ER_ERROR_DURING_ROLLBACK, MYF(0), err);
 
812
        error=1;
 
813
      }
 
814
      status_var_increment(session->status_var.ha_rollback_count);
 
815
      ha_info_next= ha_info->next();
 
816
      ha_info->reset(); /* keep it conveniently zero-filled */
 
817
    }
 
818
    trans->ha_list= 0;
 
819
    trans->no_2pc=0;
 
820
    if (is_real_trans)
 
821
      session->transaction.xid_state.xid.null();
 
822
    if (all)
 
823
    {
 
824
      session->variables.tx_isolation=session->session_tx_isolation;
 
825
      session->transaction.cleanup();
 
826
    }
 
827
  }
 
828
  if (all)
 
829
    session->transaction_rollback_request= false;
 
830
 
 
831
  /*
 
832
    If a non-transactional table was updated, warn; don't warn if this is a
 
833
    slave thread (because when a slave thread executes a ROLLBACK, it has
 
834
    been read from the binary log, so it's 100% sure and normal to produce
 
835
    error ER_WARNING_NOT_COMPLETE_ROLLBACK. If we sent the warning to the
 
836
    slave SQL thread, it would not stop the thread but just be printed in
 
837
    the error log; but we don't want users to wonder why they have this
 
838
    message in the error log, so we don't send it.
 
839
  */
 
840
  if (is_real_trans && session->transaction.all.modified_non_trans_table &&
 
841
      !session->slave_thread && session->killed != Session::KILL_CONNECTION)
 
842
    push_warning(session, DRIZZLE_ERROR::WARN_LEVEL_WARN,
 
843
                 ER_WARNING_NOT_COMPLETE_ROLLBACK,
 
844
                 ER(ER_WARNING_NOT_COMPLETE_ROLLBACK));
 
845
  return(error);
 
846
}
 
847
 
 
848
/**
 
849
  This is used to commit or rollback a single statement depending on
 
850
  the value of error.
 
851
 
 
852
  @note
 
853
    Note that if the autocommit is on, then the following call inside
 
854
    InnoDB will commit or rollback the whole transaction (= the statement). The
 
855
    autocommit mechanism built into InnoDB is based on counting locks, but if
 
856
    the user has used LOCK TABLES then that mechanism does not know to do the
 
857
    commit.
 
858
*/
 
859
int ha_autocommit_or_rollback(Session *session, int error)
 
860
{
 
861
  if (session->transaction.stmt.ha_list)
 
862
  {
 
863
    if (!error)
 
864
    {
 
865
      if (ha_commit_trans(session, 0))
 
866
        error=1;
 
867
    }
 
868
    else
 
869
    {
 
870
      (void) ha_rollback_trans(session, 0);
 
871
      if (session->transaction_rollback_request)
 
872
        (void) ha_rollback(session);
 
873
    }
 
874
 
 
875
    session->variables.tx_isolation=session->session_tx_isolation;
 
876
  }
 
877
  return(error);
 
878
}
 
879
 
 
880
 
 
881
struct xahton_st {
 
882
  XID *xid;
 
883
  int result;
 
884
};
 
885
 
 
886
static bool xacommit_handlerton(Session *unused1 __attribute__((unused)),
 
887
                                plugin_ref plugin,
 
888
                                void *arg)
 
889
{
 
890
  handlerton *hton= plugin_data(plugin, handlerton *);
 
891
  if (hton->state == SHOW_OPTION_YES && hton->recover)
 
892
  {
 
893
    hton->commit_by_xid(hton, ((struct xahton_st *)arg)->xid);
 
894
    ((struct xahton_st *)arg)->result= 0;
 
895
  }
 
896
  return false;
 
897
}
 
898
 
 
899
static bool xarollback_handlerton(Session *unused1 __attribute__((unused)),
 
900
                                  plugin_ref plugin,
 
901
                                  void *arg)
 
902
{
 
903
  handlerton *hton= plugin_data(plugin, handlerton *);
 
904
  if (hton->state == SHOW_OPTION_YES && hton->recover)
 
905
  {
 
906
    hton->rollback_by_xid(hton, ((struct xahton_st *)arg)->xid);
 
907
    ((struct xahton_st *)arg)->result= 0;
 
908
  }
 
909
  return false;
 
910
}
 
911
 
 
912
 
 
913
int ha_commit_or_rollback_by_xid(XID *xid, bool commit)
 
914
{
 
915
  struct xahton_st xaop;
 
916
  xaop.xid= xid;
 
917
  xaop.result= 1;
 
918
 
 
919
  plugin_foreach(NULL, commit ? xacommit_handlerton : xarollback_handlerton,
 
920
                 DRIZZLE_STORAGE_ENGINE_PLUGIN, &xaop);
 
921
 
 
922
  return xaop.result;
 
923
}
 
924
 
 
925
/**
 
926
  recover() step of xa.
 
927
 
 
928
  @note
 
929
    there are three modes of operation:
 
930
    - automatic recover after a crash
 
931
    in this case commit_list != 0, tc_heuristic_recover==0
 
932
    all xids from commit_list are committed, others are rolled back
 
933
    - manual (heuristic) recover
 
934
    in this case commit_list==0, tc_heuristic_recover != 0
 
935
    DBA has explicitly specified that all prepared transactions should
 
936
    be committed (or rolled back).
 
937
    - no recovery (MySQL did not detect a crash)
 
938
    in this case commit_list==0, tc_heuristic_recover == 0
 
939
    there should be no prepared transactions in this case.
 
940
*/
 
941
struct xarecover_st
 
942
{
 
943
  int len, found_foreign_xids, found_my_xids;
 
944
  XID *list;
 
945
  HASH *commit_list;
 
946
  bool dry_run;
 
947
};
 
948
 
 
949
static bool xarecover_handlerton(Session *unused __attribute__((unused)),
 
950
                                 plugin_ref plugin,
 
951
                                 void *arg)
 
952
{
 
953
  handlerton *hton= plugin_data(plugin, handlerton *);
 
954
  struct xarecover_st *info= (struct xarecover_st *) arg;
 
955
  int got;
 
956
 
 
957
  if (hton->state == SHOW_OPTION_YES && hton->recover)
 
958
  {
 
959
    while ((got= hton->recover(hton, info->list, info->len)) > 0 )
 
960
    {
 
961
      sql_print_information(_("Found %d prepared transaction(s) in %s"),
 
962
                            got, ha_resolve_storage_engine_name(hton));
 
963
      for (int i=0; i < got; i ++)
 
964
      {
 
965
        my_xid x=info->list[i].get_my_xid();
 
966
        if (!x) // not "mine" - that is generated by external TM
 
967
        {
 
968
          xid_cache_insert(info->list+i, XA_PREPARED);
 
969
          info->found_foreign_xids++;
 
970
          continue;
 
971
        }
 
972
        if (info->dry_run)
 
973
        {
 
974
          info->found_my_xids++;
 
975
          continue;
 
976
        }
 
977
        // recovery mode
 
978
        if (info->commit_list ?
 
979
            hash_search(info->commit_list, (unsigned char *)&x, sizeof(x)) != 0 :
 
980
            tc_heuristic_recover == TC_HEURISTIC_RECOVER_COMMIT)
 
981
        {
 
982
          hton->commit_by_xid(hton, info->list+i);
 
983
        }
 
984
        else
 
985
        {
 
986
          hton->rollback_by_xid(hton, info->list+i);
 
987
        }
 
988
      }
 
989
      if (got < info->len)
 
990
        break;
 
991
    }
 
992
  }
 
993
  return false;
 
994
}
 
995
 
 
996
int ha_recover(HASH *commit_list)
 
997
{
 
998
  struct xarecover_st info;
 
999
  info.found_foreign_xids= info.found_my_xids= 0;
 
1000
  info.commit_list= commit_list;
 
1001
  info.dry_run= (info.commit_list==0 && tc_heuristic_recover==0);
 
1002
  info.list= NULL;
 
1003
 
 
1004
  /* commit_list and tc_heuristic_recover cannot be set both */
 
1005
  assert(info.commit_list==0 || tc_heuristic_recover==0);
 
1006
  /* if either is set, total_ha_2pc must be set too */
 
1007
  assert(info.dry_run || total_ha_2pc>(uint32_t)opt_bin_log);
 
1008
 
 
1009
  if (total_ha_2pc <= (uint32_t)opt_bin_log)
 
1010
    return(0);
 
1011
 
 
1012
  if (info.commit_list)
 
1013
    sql_print_information(_("Starting crash recovery..."));
 
1014
 
 
1015
 
 
1016
#ifndef WILL_BE_DELETED_LATER
 
1017
 
 
1018
  /*
 
1019
    for now, only InnoDB supports 2pc. It means we can always safely
 
1020
    rollback all pending transactions, without risking inconsistent data
 
1021
  */
 
1022
 
 
1023
  assert(total_ha_2pc == (uint32_t) opt_bin_log+1); // only InnoDB and binlog
 
1024
  tc_heuristic_recover= TC_HEURISTIC_RECOVER_ROLLBACK; // forcing ROLLBACK
 
1025
  info.dry_run=false;
 
1026
#endif
 
1027
 
 
1028
 
 
1029
  for (info.len= MAX_XID_LIST_SIZE ;
 
1030
       info.list==0 && info.len > MIN_XID_LIST_SIZE; info.len/=2)
 
1031
  {
 
1032
    info.list=(XID *)malloc(info.len*sizeof(XID));
 
1033
  }
 
1034
  if (!info.list)
 
1035
  {
 
1036
    sql_print_error(ER(ER_OUTOFMEMORY), info.len*sizeof(XID));
 
1037
    return(1);
 
1038
  }
 
1039
 
 
1040
  plugin_foreach(NULL, xarecover_handlerton,
 
1041
                 DRIZZLE_STORAGE_ENGINE_PLUGIN, &info);
 
1042
 
 
1043
  free((unsigned char*)info.list);
 
1044
  if (info.found_foreign_xids)
 
1045
    sql_print_warning(_("Found %d prepared XA transactions"),
 
1046
                      info.found_foreign_xids);
 
1047
  if (info.dry_run && info.found_my_xids)
 
1048
  {
 
1049
    sql_print_error(_("Found %d prepared transactions! It means that drizzled "
 
1050
                    "was not shut down properly last time and critical "
 
1051
                    "recovery information (last binlog or %s file) was "
 
1052
                    "manually deleted after a crash. You have to start "
 
1053
                    "drizzled with the --tc-heuristic-recover switch to "
 
1054
                    "commit or rollback pending transactions."),
 
1055
                    info.found_my_xids, opt_tc_log_file);
 
1056
    return(1);
 
1057
  }
 
1058
  if (info.commit_list)
 
1059
    sql_print_information(_("Crash recovery finished."));
 
1060
  return(0);
 
1061
}
 
1062
 
 
1063
/**
 
1064
  return the list of XID's to a client, the same way SHOW commands do.
 
1065
 
 
1066
  @note
 
1067
    I didn't find in XA specs that an RM cannot return the same XID twice,
 
1068
    so mysql_xa_recover does not filter XID's to ensure uniqueness.
 
1069
    It can be easily fixed later, if necessary.
 
1070
*/
 
1071
bool mysql_xa_recover(Session *session)
 
1072
{
 
1073
  List<Item> field_list;
 
1074
  Protocol *protocol= session->protocol;
 
1075
  int i=0;
 
1076
  XID_STATE *xs;
 
1077
 
 
1078
  field_list.push_back(new Item_int("formatID", 0, MY_INT32_NUM_DECIMAL_DIGITS));
 
1079
  field_list.push_back(new Item_int("gtrid_length", 0, MY_INT32_NUM_DECIMAL_DIGITS));
 
1080
  field_list.push_back(new Item_int("bqual_length", 0, MY_INT32_NUM_DECIMAL_DIGITS));
 
1081
  field_list.push_back(new Item_empty_string("data",XIDDATASIZE));
 
1082
 
 
1083
  if (protocol->send_fields(&field_list,
 
1084
                            Protocol::SEND_NUM_ROWS | Protocol::SEND_EOF))
 
1085
    return(1);
 
1086
 
 
1087
  pthread_mutex_lock(&LOCK_xid_cache);
 
1088
  while ((xs= (XID_STATE*)hash_element(&xid_cache, i++)))
 
1089
  {
 
1090
    if (xs->xa_state==XA_PREPARED)
 
1091
    {
 
1092
      protocol->prepare_for_resend();
 
1093
      protocol->store_int64_t((int64_t)xs->xid.formatID, false);
 
1094
      protocol->store_int64_t((int64_t)xs->xid.gtrid_length, false);
 
1095
      protocol->store_int64_t((int64_t)xs->xid.bqual_length, false);
 
1096
      protocol->store(xs->xid.data, xs->xid.gtrid_length+xs->xid.bqual_length,
 
1097
                      &my_charset_bin);
 
1098
      if (protocol->write())
 
1099
      {
 
1100
        pthread_mutex_unlock(&LOCK_xid_cache);
 
1101
        return(1);
 
1102
      }
 
1103
    }
 
1104
  }
 
1105
 
 
1106
  pthread_mutex_unlock(&LOCK_xid_cache);
 
1107
  my_eof(session);
 
1108
  return(0);
 
1109
}
 
1110
 
 
1111
/**
 
1112
  @details
 
1113
  This function should be called when MySQL sends rows of a SELECT result set
 
1114
  or the EOF mark to the client. It releases a possible adaptive hash index
 
1115
  S-latch held by session in InnoDB and also releases a possible InnoDB query
 
1116
  FIFO ticket to enter InnoDB. To save CPU time, InnoDB allows a session to
 
1117
  keep them over several calls of the InnoDB handler interface when a join
 
1118
  is executed. But when we let the control to pass to the client they have
 
1119
  to be released because if the application program uses mysql_use_result(),
 
1120
  it may deadlock on the S-latch if the application on another connection
 
1121
  performs another SQL query. In MySQL-4.1 this is even more important because
 
1122
  there a connection can have several SELECT queries open at the same time.
 
1123
 
 
1124
  @param session           the thread handle of the current connection
 
1125
 
 
1126
  @return
 
1127
    always 0
 
1128
*/
 
1129
static bool release_temporary_latches(Session *session, plugin_ref plugin,
 
1130
                                      void *unused __attribute__((unused)))
 
1131
{
 
1132
  handlerton *hton= plugin_data(plugin, handlerton *);
 
1133
 
 
1134
  if (hton->state == SHOW_OPTION_YES && hton->release_temporary_latches)
 
1135
    hton->release_temporary_latches(hton, session);
 
1136
 
 
1137
  return false;
 
1138
}
 
1139
 
 
1140
 
 
1141
int ha_release_temporary_latches(Session *session)
 
1142
{
 
1143
  plugin_foreach(session, release_temporary_latches, DRIZZLE_STORAGE_ENGINE_PLUGIN,
 
1144
                 NULL);
 
1145
 
 
1146
  return 0;
 
1147
}
 
1148
 
 
1149
int ha_rollback_to_savepoint(Session *session, SAVEPOINT *sv)
 
1150
{
 
1151
  int error=0;
 
1152
  Session_TRANS *trans= &session->transaction.all;
 
1153
  Ha_trx_info *ha_info, *ha_info_next;
 
1154
 
 
1155
  trans->no_2pc=0;
 
1156
  /*
 
1157
    rolling back to savepoint in all storage engines that were part of the
 
1158
    transaction when the savepoint was set
 
1159
  */
 
1160
  for (ha_info= sv->ha_list; ha_info; ha_info= ha_info->next())
 
1161
  {
 
1162
    int err;
 
1163
    handlerton *ht= ha_info->ht();
 
1164
    assert(ht);
 
1165
    assert(ht->savepoint_set != 0);
 
1166
    if ((err= ht->savepoint_rollback(ht, session,
 
1167
                                     (unsigned char *)(sv+1)+ht->savepoint_offset)))
 
1168
    { // cannot happen
 
1169
      my_error(ER_ERROR_DURING_ROLLBACK, MYF(0), err);
 
1170
      error=1;
 
1171
    }
 
1172
    status_var_increment(session->status_var.ha_savepoint_rollback_count);
 
1173
    trans->no_2pc|= ht->prepare == 0;
 
1174
  }
 
1175
  /*
 
1176
    rolling back the transaction in all storage engines that were not part of
 
1177
    the transaction when the savepoint was set
 
1178
  */
 
1179
  for (ha_info= trans->ha_list; ha_info != sv->ha_list;
 
1180
       ha_info= ha_info_next)
 
1181
  {
 
1182
    int err;
 
1183
    handlerton *ht= ha_info->ht();
 
1184
    if ((err= ht->rollback(ht, session, !(0))))
 
1185
    { // cannot happen
 
1186
      my_error(ER_ERROR_DURING_ROLLBACK, MYF(0), err);
 
1187
      error=1;
 
1188
    }
 
1189
    status_var_increment(session->status_var.ha_rollback_count);
 
1190
    ha_info_next= ha_info->next();
 
1191
    ha_info->reset(); /* keep it conveniently zero-filled */
 
1192
  }
 
1193
  trans->ha_list= sv->ha_list;
 
1194
  return(error);
 
1195
}
 
1196
 
 
1197
/**
 
1198
  @note
 
1199
  according to the sql standard (ISO/IEC 9075-2:2003)
 
1200
  section "4.33.4 SQL-statements and transaction states",
 
1201
  SAVEPOINT is *not* transaction-initiating SQL-statement
 
1202
*/
 
1203
int ha_savepoint(Session *session, SAVEPOINT *sv)
 
1204
{
 
1205
  int error=0;
 
1206
  Session_TRANS *trans= &session->transaction.all;
 
1207
  Ha_trx_info *ha_info= trans->ha_list;
 
1208
  for (; ha_info; ha_info= ha_info->next())
 
1209
  {
 
1210
    int err;
 
1211
    handlerton *ht= ha_info->ht();
 
1212
    assert(ht);
 
1213
    if (! ht->savepoint_set)
 
1214
    {
 
1215
      my_error(ER_CHECK_NOT_IMPLEMENTED, MYF(0), "SAVEPOINT");
 
1216
      error=1;
 
1217
      break;
 
1218
    }
 
1219
    if ((err= ht->savepoint_set(ht, session, (unsigned char *)(sv+1)+ht->savepoint_offset)))
 
1220
    { // cannot happen
 
1221
      my_error(ER_GET_ERRNO, MYF(0), err);
 
1222
      error=1;
 
1223
    }
 
1224
    status_var_increment(session->status_var.ha_savepoint_count);
 
1225
  }
 
1226
  /*
 
1227
    Remember the list of registered storage engines. All new
 
1228
    engines are prepended to the beginning of the list.
 
1229
  */
 
1230
  sv->ha_list= trans->ha_list;
 
1231
  return(error);
 
1232
}
 
1233
 
 
1234
int ha_release_savepoint(Session *session, SAVEPOINT *sv)
 
1235
{
 
1236
  int error=0;
 
1237
  Ha_trx_info *ha_info= sv->ha_list;
 
1238
 
 
1239
  for (; ha_info; ha_info= ha_info->next())
 
1240
  {
 
1241
    int err;
 
1242
    handlerton *ht= ha_info->ht();
 
1243
    /* Savepoint life time is enclosed into transaction life time. */
 
1244
    assert(ht);
 
1245
    if (!ht->savepoint_release)
 
1246
      continue;
 
1247
    if ((err= ht->savepoint_release(ht, session,
 
1248
                                    (unsigned char *)(sv+1) + ht->savepoint_offset)))
 
1249
    { // cannot happen
 
1250
      my_error(ER_GET_ERRNO, MYF(0), err);
 
1251
      error=1;
 
1252
    }
 
1253
  }
 
1254
  return(error);
 
1255
}
 
1256
 
 
1257
 
 
1258
static bool snapshot_handlerton(Session *session, plugin_ref plugin, void *arg)
 
1259
{
 
1260
  handlerton *hton= plugin_data(plugin, handlerton *);
 
1261
  if (hton->state == SHOW_OPTION_YES &&
 
1262
      hton->start_consistent_snapshot)
 
1263
  {
 
1264
    hton->start_consistent_snapshot(hton, session);
 
1265
    *((bool *)arg)= false;
 
1266
  }
 
1267
  return false;
 
1268
}
 
1269
 
 
1270
int ha_start_consistent_snapshot(Session *session)
 
1271
{
 
1272
  bool warn= true;
 
1273
 
 
1274
  plugin_foreach(session, snapshot_handlerton, DRIZZLE_STORAGE_ENGINE_PLUGIN, &warn);
 
1275
 
 
1276
  /*
 
1277
    Same idea as when one wants to CREATE TABLE in one engine which does not
 
1278
    exist:
 
1279
  */
 
1280
  if (warn)
 
1281
    push_warning(session, DRIZZLE_ERROR::WARN_LEVEL_WARN, ER_UNKNOWN_ERROR,
 
1282
                 "This Drizzle server does not support any "
 
1283
                 "consistent-read capable storage engine");
 
1284
  return 0;
 
1285
}
 
1286
 
 
1287
 
 
1288
static bool flush_handlerton(Session *session __attribute__((unused)),
 
1289
                             plugin_ref plugin,
 
1290
                             void *arg __attribute__((unused)))
 
1291
{
 
1292
  handlerton *hton= plugin_data(plugin, handlerton *);
 
1293
  if (hton->state == SHOW_OPTION_YES && hton->flush_logs &&
 
1294
      hton->flush_logs(hton))
 
1295
    return true;
 
1296
  return false;
 
1297
}
 
1298
 
 
1299
 
 
1300
bool ha_flush_logs(handlerton *db_type)
 
1301
{
 
1302
  if (db_type == NULL)
 
1303
  {
 
1304
    if (plugin_foreach(NULL, flush_handlerton,
 
1305
                          DRIZZLE_STORAGE_ENGINE_PLUGIN, 0))
 
1306
      return true;
 
1307
  }
 
1308
  else
 
1309
  {
 
1310
    if (db_type->state != SHOW_OPTION_YES ||
 
1311
        (db_type->flush_logs && db_type->flush_logs(db_type)))
 
1312
      return true;
 
1313
  }
 
1314
  return false;
 
1315
}
 
1316
 
 
1317
static const char *check_lowercase_names(handler *file, const char *path,
 
1318
                                         char *tmp_path)
 
1319
{
 
1320
  if (lower_case_table_names != 2 || (file->ha_table_flags() & HA_FILE_BASED))
 
1321
    return path;
 
1322
 
 
1323
  /* Ensure that table handler get path in lower case */
 
1324
  if (tmp_path != path)
 
1325
    strcpy(tmp_path, path);
 
1326
 
 
1327
  /*
 
1328
    we only should turn into lowercase database/table part
 
1329
    so start the process after homedirectory
 
1330
  */
 
1331
  my_casedn_str(files_charset_info, tmp_path + drizzle_data_home_len);
 
1332
  return tmp_path;
 
1333
}
 
1334
 
 
1335
 
 
1336
/**
 
1337
  An interceptor to hijack the text of the error message without
 
1338
  setting an error in the thread. We need the text to present it
 
1339
  in the form of a warning to the user.
 
1340
*/
 
1341
 
 
1342
struct Ha_delete_table_error_handler: public Internal_error_handler
 
1343
{
 
1344
public:
 
1345
  virtual bool handle_error(uint32_t sql_errno,
 
1346
                            const char *message,
 
1347
                            DRIZZLE_ERROR::enum_warning_level level,
 
1348
                            Session *session);
 
1349
  char buff[DRIZZLE_ERRMSG_SIZE];
 
1350
};
 
1351
 
 
1352
 
 
1353
bool
 
1354
Ha_delete_table_error_handler::
 
1355
handle_error(uint32_t sql_errno  __attribute__((unused)),
 
1356
             const char *message,
 
1357
             DRIZZLE_ERROR::enum_warning_level level __attribute__((unused)),
 
1358
             Session *session __attribute__((unused)))
 
1359
{
 
1360
  /* Grab the error message */
 
1361
  strncpy(buff, message, sizeof(buff)-1);
 
1362
  return true;
 
1363
}
 
1364
 
 
1365
 
 
1366
struct handlerton_delete_table_args {
 
1367
  Session *session;
 
1368
  const char *path;
 
1369
  handler *file;
 
1370
  int error;
 
1371
};
 
1372
 
 
1373
static bool deletetable_handlerton(Session *unused1 __attribute__((unused)),
 
1374
                                   plugin_ref plugin,
 
1375
                                   void *args)
 
1376
{
 
1377
  struct handlerton_delete_table_args *dtargs= (struct handlerton_delete_table_args *) args;
 
1378
 
 
1379
  Session *session= dtargs->session;
 
1380
  const char *path= dtargs->path;
 
1381
 
 
1382
  handler *file;
 
1383
  char tmp_path[FN_REFLEN];
 
1384
 
 
1385
  if(dtargs->error!=ENOENT) /* already deleted table */
 
1386
    return false;
 
1387
 
 
1388
  handlerton *table_type= plugin_data(plugin, handlerton *);
 
1389
 
 
1390
  if(!table_type)
 
1391
    return false;
 
1392
 
 
1393
  if(!(table_type->state == SHOW_OPTION_YES && table_type->create))
 
1394
    return false;
 
1395
 
 
1396
  if ((file= table_type->create(table_type, NULL, session->mem_root)))
 
1397
    file->init();
 
1398
  else
 
1399
    return false;
 
1400
 
 
1401
  path= check_lowercase_names(file, path, tmp_path);
 
1402
  int error= file->ha_delete_table(path);
 
1403
 
 
1404
  if(error!=ENOENT)
 
1405
  {
 
1406
    dtargs->error= error;
 
1407
    if(dtargs->file)
 
1408
      delete dtargs->file;
 
1409
    dtargs->file= file;
 
1410
    return true;
 
1411
  }
 
1412
 
 
1413
  return false;
 
1414
}
 
1415
 
 
1416
/**
 
1417
  This should return ENOENT if the file doesn't exists.
 
1418
  The .frm file will be deleted only if we return 0 or ENOENT
 
1419
*/
 
1420
int ha_delete_table(Session *session, const char *path,
 
1421
                    const char *db, const char *alias, bool generate_warning)
 
1422
{
 
1423
  TABLE_SHARE dummy_share;
 
1424
  Table dummy_table;
 
1425
 
 
1426
  struct handlerton_delete_table_args dtargs;
 
1427
  dtargs.error= ENOENT;
 
1428
  dtargs.session= session;
 
1429
  dtargs.path= path;
 
1430
  dtargs.file= NULL;
 
1431
 
 
1432
  plugin_foreach(NULL, deletetable_handlerton, DRIZZLE_STORAGE_ENGINE_PLUGIN,
 
1433
                 &dtargs);
 
1434
 
 
1435
  memset(&dummy_table, 0, sizeof(dummy_table));
 
1436
  memset(&dummy_share, 0, sizeof(dummy_share));
 
1437
  dummy_table.s= &dummy_share;
 
1438
 
 
1439
  if (dtargs.error && generate_warning)
 
1440
  {
 
1441
    /*
 
1442
      Because file->print_error() use my_error() to generate the error message
 
1443
      we use an internal error handler to intercept it and store the text
 
1444
      in a temporary buffer. Later the message will be presented to user
 
1445
      as a warning.
 
1446
    */
 
1447
    Ha_delete_table_error_handler ha_delete_table_error_handler;
 
1448
 
 
1449
    /* Fill up strucutures that print_error may need */
 
1450
    dummy_share.path.str= (char*) path;
 
1451
    dummy_share.path.length= strlen(path);
 
1452
    dummy_share.db.str= (char*) db;
 
1453
    dummy_share.db.length= strlen(db);
 
1454
    dummy_share.table_name.str= (char*) alias;
 
1455
    dummy_share.table_name.length= strlen(alias);
 
1456
    dummy_table.alias= alias;
 
1457
 
 
1458
    handler *file= dtargs.file;
 
1459
    file->change_table_ptr(&dummy_table, &dummy_share);
 
1460
 
 
1461
    session->push_internal_handler(&ha_delete_table_error_handler);
 
1462
    file->print_error(dtargs.error, 0);
 
1463
 
 
1464
    session->pop_internal_handler();
 
1465
 
 
1466
    /*
 
1467
      XXX: should we convert *all* errors to warnings here?
 
1468
      What if the error is fatal?
 
1469
    */
 
1470
    push_warning(session, DRIZZLE_ERROR::WARN_LEVEL_ERROR, dtargs.error,
 
1471
                ha_delete_table_error_handler.buff);
 
1472
  }
 
1473
 
 
1474
  if(dtargs.file)
 
1475
    delete dtargs.file;
 
1476
 
 
1477
  return dtargs.error;
 
1478
}
53
1479
 
54
1480
/****************************************************************************
55
 
** General Cursor functions
 
1481
** General handler functions
56
1482
****************************************************************************/
57
 
Cursor::Cursor(plugin::StorageEngine &engine_arg,
58
 
               Table &arg)
59
 
  : table(arg),
60
 
    engine(engine_arg),
61
 
    estimation_rows_to_insert(0),
62
 
    ref(0),
63
 
    key_used_on_scan(MAX_KEY), active_index(MAX_KEY),
64
 
    ref_length(sizeof(internal::my_off_t)),
65
 
    inited(NONE),
66
 
    locked(false),
67
 
    next_insert_id(0), insert_id_for_cur_row(0)
68
 
{ }
69
 
 
70
 
Cursor::~Cursor(void)
71
 
{
72
 
  assert(locked == false);
73
 
  /* TODO: assert(inited == NONE); */
74
 
}
75
 
 
76
 
 
77
 
/*
78
 
 * @note this only used in
79
 
 * optimizer::QuickRangeSelect::init_ror_merged_scan(bool reuse_handler) as
80
 
 * of the writing of this comment. -Brian
81
 
 */
82
 
Cursor *Cursor::clone(memory::Root *mem_root)
83
 
{
84
 
  Cursor *new_handler= getTable()->getMutableShare()->db_type()->getCursor(*getTable());
85
 
 
 
1483
handler *handler::clone(MEM_ROOT *mem_root)
 
1484
{
 
1485
  handler *new_handler= get_new_handler(table->s, mem_root, table->s->db_type());
86
1486
  /*
87
 
    Allocate Cursor->ref here because otherwise ha_open will allocate it
 
1487
    Allocate handler->ref here because otherwise ha_open will allocate it
88
1488
    on this->table->mem_root and we will not be able to reclaim that memory
89
 
    when the clone Cursor object is destroyed.
 
1489
    when the clone handler object is destroyed.
90
1490
  */
91
 
  if (!(new_handler->ref= (unsigned char*) mem_root->alloc_root(ALIGN_SIZE(ref_length)*2)))
 
1491
  if (!(new_handler->ref= (unsigned char*) alloc_root(mem_root, ALIGN_SIZE(ref_length)*2)))
92
1492
    return NULL;
93
 
 
94
 
  identifier::Table identifier(getTable()->getShare()->getSchemaName(),
95
 
                             getTable()->getShare()->getTableName(),
96
 
                             getTable()->getShare()->getType());
97
 
 
98
 
  if (new_handler && !new_handler->ha_open(identifier,
99
 
                                           getTable()->getDBStat(),
 
1493
  if (new_handler && !new_handler->ha_open(table,
 
1494
                                           table->s->normalized_path.str,
 
1495
                                           table->getDBStat(),
100
1496
                                           HA_OPEN_IGNORE_IF_LOCKED))
101
1497
    return new_handler;
102
1498
  return NULL;
103
1499
}
104
1500
 
105
 
/*
106
 
  DESCRIPTION
107
 
    given a buffer with a key value, and a map of keyparts
108
 
    that are present in this value, returns the length of the value
109
 
*/
110
 
uint32_t Cursor::calculate_key_len(uint32_t key_position, key_part_map keypart_map_arg)
111
 
{
112
 
  /* works only with key prefixes */
113
 
  assert(((keypart_map_arg + 1) & keypart_map_arg) == 0);
114
 
 
115
 
  const KeyPartInfo *key_part_found= getTable()->getShare()->getKeyInfo(key_position).key_part;
116
 
  const KeyPartInfo *end_key_part_found= key_part_found + getTable()->getShare()->getKeyInfo(key_position).key_parts;
117
 
  uint32_t length= 0;
118
 
 
119
 
  while (key_part_found < end_key_part_found && keypart_map_arg)
120
 
  {
121
 
    length+= key_part_found->store_length;
122
 
    keypart_map_arg >>= 1;
123
 
    key_part_found++;
124
 
  }
125
 
  return length;
126
 
}
127
 
 
128
 
int Cursor::startIndexScan(uint32_t idx, bool sorted)
 
1501
int handler::ha_index_init(uint32_t idx, bool sorted)
129
1502
{
130
1503
  int result;
131
 
  assert(inited == NONE);
132
 
  if (!(result= doStartIndexScan(idx, sorted)))
 
1504
  assert(inited==NONE);
 
1505
  if (!(result= index_init(idx, sorted)))
133
1506
    inited=INDEX;
134
1507
  end_range= NULL;
135
 
  return result;
 
1508
  return(result);
136
1509
}
137
1510
 
138
 
int Cursor::endIndexScan()
 
1511
int handler::ha_index_end()
139
1512
{
140
1513
  assert(inited==INDEX);
141
1514
  inited=NONE;
142
1515
  end_range= NULL;
143
 
  return(doEndIndexScan());
 
1516
  return(index_end());
144
1517
}
145
1518
 
146
 
int Cursor::startTableScan(bool scan)
 
1519
int handler::ha_rnd_init(bool scan)
147
1520
{
148
1521
  int result;
149
1522
  assert(inited==NONE || (inited==RND && scan));
150
 
  inited= (result= doStartTableScan(scan)) ? NONE: RND;
151
 
 
152
 
  return result;
 
1523
  inited= (result= rnd_init(scan)) ? NONE: RND;
 
1524
  return(result);
153
1525
}
154
1526
 
155
 
int Cursor::endTableScan()
 
1527
int handler::ha_rnd_end()
156
1528
{
157
1529
  assert(inited==RND);
158
1530
  inited=NONE;
159
 
  return(doEndTableScan());
160
 
}
161
 
 
162
 
int Cursor::ha_index_or_rnd_end()
163
 
{
164
 
  return inited == INDEX ? endIndexScan() : inited == RND ? endTableScan() : 0;
165
 
}
166
 
 
167
 
void Cursor::ha_start_bulk_insert(ha_rows rows)
 
1531
  return(rnd_end());
 
1532
}
 
1533
 
 
1534
int handler::ha_index_or_rnd_end()
 
1535
{
 
1536
  return inited == INDEX ? ha_index_end() : inited == RND ? ha_rnd_end() : 0;
 
1537
}
 
1538
 
 
1539
handler::Table_flags handler::ha_table_flags() const
 
1540
{
 
1541
  return cached_table_flags;
 
1542
}
 
1543
 
 
1544
void handler::ha_start_bulk_insert(ha_rows rows)
168
1545
{
169
1546
  estimation_rows_to_insert= rows;
170
1547
  start_bulk_insert(rows);
171
1548
}
172
1549
 
173
 
int Cursor::ha_end_bulk_insert()
 
1550
int handler::ha_end_bulk_insert()
174
1551
{
175
1552
  estimation_rows_to_insert= 0;
176
1553
  return end_bulk_insert();
177
1554
}
178
1555
 
179
 
const key_map *Cursor::keys_to_use_for_scanning()
 
1556
void handler::change_table_ptr(Table *table_arg, TABLE_SHARE *share)
 
1557
{
 
1558
  table= table_arg;
 
1559
  table_share= share;
 
1560
}
 
1561
 
 
1562
const key_map *handler::keys_to_use_for_scanning()
180
1563
{
181
1564
  return &key_map_empty;
182
1565
}
183
1566
 
184
 
bool Cursor::has_transactions()
185
 
{
186
 
  return (getTable()->getShare()->db_type()->check_flag(HTON_BIT_DOES_TRANSACTIONS));
187
 
}
188
 
 
189
 
void Cursor::ha_statistic_increment(uint64_t system_status_var::*offset) const
190
 
{
191
 
  (getTable()->in_use->status_var.*offset)++;
192
 
}
193
 
 
194
 
void **Cursor::ha_data(Session *session) const
195
 
{
196
 
  return session->getEngineData(getEngine());
197
 
}
198
 
 
199
 
bool Cursor::is_fatal_error(int error, uint32_t flags)
 
1567
bool handler::has_transactions()
 
1568
{
 
1569
  return (ha_table_flags() & HA_NO_TRANSACTIONS) == 0;
 
1570
}
 
1571
 
 
1572
void handler::ha_statistic_increment(ulong SSV::*offset) const
 
1573
{
 
1574
  status_var_increment(table->in_use->status_var.*offset);
 
1575
}
 
1576
 
 
1577
void **handler::ha_data(Session *session) const
 
1578
{
 
1579
  return session_ha_data(session, ht);
 
1580
}
 
1581
 
 
1582
Session *handler::ha_session(void) const
 
1583
{
 
1584
  assert(!table || !table->in_use || table->in_use == current_session);
 
1585
  return (table && table->in_use) ? table->in_use : current_session;
 
1586
}
 
1587
 
 
1588
 
 
1589
bool handler::is_fatal_error(int error, uint32_t flags)
200
1590
{
201
1591
  if (!error ||
202
1592
      ((flags & HA_CHECK_DUP_KEY) &&
207
1597
}
208
1598
 
209
1599
 
210
 
ha_rows Cursor::records() { return stats.records; }
211
 
uint64_t Cursor::tableSize() { return stats.index_file_length + stats.data_file_length; }
212
 
uint64_t Cursor::rowSize() { return getTable()->getRecordLength() + getTable()->sizeFields(); }
213
 
 
214
 
int Cursor::doOpen(const identifier::Table &identifier, int mode, uint32_t test_if_locked)
215
 
{
216
 
  return open(identifier.getPath().c_str(), mode, test_if_locked);
217
 
}
 
1600
ha_rows handler::records() { return stats.records; }
218
1601
 
219
1602
/**
220
 
  Open database-Cursor.
 
1603
  Open database-handler.
221
1604
 
222
1605
  Try O_RDONLY if cannot open as O_RDWR
223
1606
  Don't wait for locks if not HA_OPEN_WAIT_IF_LOCKED is set
224
1607
*/
225
 
int Cursor::ha_open(const identifier::Table &identifier,
226
 
                    int mode,
227
 
                    int test_if_locked)
 
1608
int handler::ha_open(Table *table_arg, const char *name, int mode,
 
1609
                     int test_if_locked)
228
1610
{
229
1611
  int error;
230
1612
 
231
 
  if ((error= doOpen(identifier, mode, test_if_locked)))
 
1613
  table= table_arg;
 
1614
  assert(table->s == table_share);
 
1615
  assert(alloc_root_inited(&table->mem_root));
 
1616
 
 
1617
  if ((error=open(name,mode,test_if_locked)))
232
1618
  {
233
1619
    if ((error == EACCES || error == EROFS) && mode == O_RDWR &&
234
 
        (getTable()->db_stat & HA_TRY_READ_ONLY))
 
1620
        (table->db_stat & HA_TRY_READ_ONLY))
235
1621
    {
236
 
      getTable()->db_stat|=HA_READ_ONLY;
237
 
      error= doOpen(identifier, O_RDONLY,test_if_locked);
 
1622
      table->db_stat|=HA_READ_ONLY;
 
1623
      error=open(name,O_RDONLY,test_if_locked);
238
1624
    }
239
1625
  }
240
1626
  if (error)
241
1627
  {
242
 
    errno= error;                            /* Safeguard */
 
1628
    my_errno= error;                            /* Safeguard */
243
1629
  }
244
1630
  else
245
1631
  {
246
 
    if (getTable()->getShare()->db_options_in_use & HA_OPTION_READ_ONLY_DATA)
247
 
      getTable()->db_stat|=HA_READ_ONLY;
 
1632
    if (table->s->db_options_in_use & HA_OPTION_READ_ONLY_DATA)
 
1633
      table->db_stat|=HA_READ_ONLY;
248
1634
    (void) extra(HA_EXTRA_NO_READCHECK);        // Not needed in SQL
249
1635
 
250
 
    /* ref is already allocated for us if we're called from Cursor::clone() */
251
 
    if (!ref && !(ref= (unsigned char*) getTable()->alloc_root(ALIGN_SIZE(ref_length)*2)))
 
1636
    /* ref is already allocated for us if we're called from handler::clone() */
 
1637
    if (!ref && !(ref= (unsigned char*) alloc_root(&table->mem_root,
 
1638
                                          ALIGN_SIZE(ref_length)*2)))
252
1639
    {
253
1640
      close();
254
1641
      error=HA_ERR_OUT_OF_MEM;
255
1642
    }
256
1643
    else
257
1644
      dup_ref=ref+ALIGN_SIZE(ref_length);
 
1645
    cached_table_flags= table_flags();
258
1646
  }
259
 
  return error;
 
1647
  return(error);
 
1648
}
 
1649
 
 
1650
/**
 
1651
  one has to use this method when to find
 
1652
  random position by record as the plain
 
1653
  position() call doesn't work for some
 
1654
  handlers for random position
 
1655
*/
 
1656
 
 
1657
int handler::rnd_pos_by_record(unsigned char *record)
 
1658
{
 
1659
  register int error;
 
1660
 
 
1661
  position(record);
 
1662
  if (inited && (error= ha_index_end()))
 
1663
    return(error);
 
1664
  if ((error= ha_rnd_init(false)))
 
1665
    return(error);
 
1666
 
 
1667
  return(rnd_pos(record, ref));
260
1668
}
261
1669
 
262
1670
/**
265
1673
  This is never called for InnoDB tables, as these table types
266
1674
  has the HA_STATS_RECORDS_IS_EXACT set.
267
1675
*/
268
 
int Cursor::read_first_row(unsigned char * buf, uint32_t primary_key)
 
1676
int handler::read_first_row(unsigned char * buf, uint32_t primary_key)
269
1677
{
270
 
  int error;
 
1678
  register int error;
271
1679
 
272
 
  ha_statistic_increment(&system_status_var::ha_read_first_count);
 
1680
  ha_statistic_increment(&SSV::ha_read_first_count);
273
1681
 
274
1682
  /*
275
1683
    If there is very few deleted rows in the table, find the first row by
276
1684
    scanning the table.
277
 
    @todo remove the test for HA_READ_ORDER
 
1685
    TODO remove the test for HA_READ_ORDER
278
1686
  */
279
1687
  if (stats.deleted < 10 || primary_key >= MAX_KEY ||
280
 
      !(getTable()->index_flags(primary_key) & HA_READ_ORDER))
 
1688
      !(index_flags(primary_key, 0, 0) & HA_READ_ORDER))
281
1689
  {
282
 
    error= startTableScan(1);
283
 
    if (error == 0)
284
 
    {
285
 
      while ((error= rnd_next(buf)) == HA_ERR_RECORD_DELETED) ;
286
 
      (void) endTableScan();
287
 
    }
 
1690
    (void) ha_rnd_init(1);
 
1691
    while ((error= rnd_next(buf)) == HA_ERR_RECORD_DELETED) ;
 
1692
    (void) ha_rnd_end();
288
1693
  }
289
1694
  else
290
1695
  {
291
1696
    /* Find the first row through the primary key */
292
 
    error= startIndexScan(primary_key, 0);
293
 
    if (error == 0)
294
 
    {
295
 
      error=index_first(buf);
296
 
      (void) endIndexScan();
297
 
    }
 
1697
    (void) ha_index_init(primary_key, 0);
 
1698
    error=index_first(buf);
 
1699
    (void) ha_index_end();
298
1700
  }
299
 
  return error;
 
1701
  return(error);
300
1702
}
301
1703
 
302
1704
/**
311
1713
  @verbatim 1,5,15,25,35,... @endverbatim
312
1714
*/
313
1715
inline uint64_t
314
 
compute_next_insert_id(uint64_t nr, drizzle_system_variables *variables)
 
1716
compute_next_insert_id(uint64_t nr,struct system_variables *variables)
315
1717
{
316
1718
  if (variables->auto_increment_increment == 1)
317
1719
    return (nr+1); // optimization of the formula below
323
1725
}
324
1726
 
325
1727
 
326
 
void Cursor::adjust_next_insert_id_after_explicit_value(uint64_t nr)
 
1728
void handler::adjust_next_insert_id_after_explicit_value(uint64_t nr)
327
1729
{
328
1730
  /*
329
1731
    If we have set Session::next_insert_id previously and plan to insert an
331
1733
    Session::next_insert_id to be greater than the explicit value.
332
1734
  */
333
1735
  if ((next_insert_id > 0) && (nr >= next_insert_id))
334
 
    set_next_insert_id(compute_next_insert_id(nr, &getTable()->in_use->variables));
 
1736
    set_next_insert_id(compute_next_insert_id(nr, &table->in_use->variables));
335
1737
}
336
1738
 
337
1739
 
351
1753
    The number X if it exists, "nr" otherwise.
352
1754
*/
353
1755
inline uint64_t
354
 
prev_insert_id(uint64_t nr, drizzle_system_variables *variables)
 
1756
prev_insert_id(uint64_t nr, struct system_variables *variables)
355
1757
{
356
1758
  if (unlikely(nr < variables->auto_increment_offset))
357
1759
  {
376
1778
 
377
1779
  Updates columns with type NEXT_NUMBER if:
378
1780
 
379
 
  - If column value is set to NULL (in which case auto_increment_field_not_null is false)
 
1781
  - If column value is set to NULL (in which case
 
1782
    auto_increment_field_not_null is 0)
380
1783
  - If column is set to 0 and (sql_mode & MODE_NO_AUTO_VALUE_ON_ZERO) is not
381
1784
    set. In the future we will only set NEXT_NUMBER fields if one sets them
382
1785
    to NULL (or they are not included in the insert list).
397
1800
    reserved for us.
398
1801
 
399
1802
  - In both cases, for the following rows we use those reserved values without
400
 
    calling the Cursor again (we just progress in the interval, computing
 
1803
    calling the handler again (we just progress in the interval, computing
401
1804
    each new value from the previous one). Until we have exhausted them, then
402
1805
    we either take the next provided interval or call get_auto_increment()
403
1806
    again to reserve a new interval.
444
1847
#define AUTO_INC_DEFAULT_NB_MAX_BITS 16
445
1848
#define AUTO_INC_DEFAULT_NB_MAX ((1 << AUTO_INC_DEFAULT_NB_MAX_BITS) - 1)
446
1849
 
447
 
int Cursor::update_auto_increment()
 
1850
int handler::update_auto_increment()
448
1851
{
449
1852
  uint64_t nr, nb_reserved_values;
450
1853
  bool append= false;
451
 
  Session *session= getTable()->in_use;
452
 
  drizzle_system_variables *variables= &session->variables;
 
1854
  Session *session= table->in_use;
 
1855
  struct system_variables *variables= &session->variables;
453
1856
 
454
1857
  /*
455
1858
    next_insert_id is a "cursor" into the reserved interval, it may go greater
457
1860
  */
458
1861
  assert(next_insert_id >= auto_inc_interval_for_cur_row.minimum());
459
1862
 
460
 
  /* We check if auto_increment_field_not_null is false
461
 
     for an auto increment column, not a magic value like NULL is.
462
 
     same as sql_mode=NO_AUTO_VALUE_ON_ZERO */
463
 
 
464
 
  if ((nr= getTable()->next_number_field->val_int()) != 0
465
 
      || getTable()->auto_increment_field_not_null)
 
1863
  if ((nr= table->next_number_field->val_int()) != 0)
466
1864
  {
467
1865
    /*
468
1866
      Update next_insert_id if we had already generated a value in this
472
1870
    */
473
1871
    adjust_next_insert_id_after_explicit_value(nr);
474
1872
    insert_id_for_cur_row= 0; // didn't generate anything
475
 
 
476
 
    return 0;
 
1873
    return(0);
477
1874
  }
478
1875
 
479
1876
  if ((nr= next_insert_id) >= auto_inc_interval_for_cur_row.maximum())
489
1886
    else
490
1887
    {
491
1888
      /*
492
 
        Cursor::estimation_rows_to_insert was set by
493
 
        Cursor::ha_start_bulk_insert(); if 0 it means "unknown".
 
1889
        handler::estimation_rows_to_insert was set by
 
1890
        handler::ha_start_bulk_insert(); if 0 it means "unknown".
494
1891
      */
495
1892
      uint32_t nb_already_reserved_intervals=
496
1893
        session->auto_inc_intervals_in_cur_stmt_for_binlog.nb_elements();
516
1913
        {
517
1914
          nb_desired_values= AUTO_INC_DEFAULT_NB_ROWS *
518
1915
            (1 << nb_already_reserved_intervals);
519
 
          set_if_smaller(nb_desired_values, (uint64_t)AUTO_INC_DEFAULT_NB_MAX);
 
1916
          set_if_smaller(nb_desired_values, AUTO_INC_DEFAULT_NB_MAX);
520
1917
        }
521
1918
        else
522
1919
          nb_desired_values= AUTO_INC_DEFAULT_NB_MAX;
527
1924
                         nb_desired_values, &nr,
528
1925
                         &nb_reserved_values);
529
1926
      if (nr == ~(uint64_t) 0)
530
 
        return HA_ERR_AUTOINC_READ_FAILED;  // Mark failure
 
1927
        return(HA_ERR_AUTOINC_READ_FAILED);  // Mark failure
531
1928
 
532
1929
      /*
533
1930
        That rounding below should not be needed when all engines actually
540
1937
      nr= compute_next_insert_id(nr-1, variables);
541
1938
    }
542
1939
 
543
 
    if (getTable()->getShare()->next_number_keypart == 0)
 
1940
    if (table->s->next_number_keypart == 0)
544
1941
    {
545
1942
      /* We must defer the appending until "nr" has been possibly truncated */
546
1943
      append= true;
547
1944
    }
548
1945
  }
549
1946
 
550
 
  if (unlikely(getTable()->next_number_field->store((int64_t) nr, true)))
 
1947
  if (unlikely(table->next_number_field->store((int64_t) nr, true)))
551
1948
  {
552
1949
    /*
553
1950
      first test if the query was aborted due to strict mode constraints
554
1951
    */
555
 
    if (session->getKilled() == Session::KILL_BAD_DATA)
556
 
      return HA_ERR_AUTOINC_ERANGE;
 
1952
    if (session->killed == Session::KILL_BAD_DATA)
 
1953
      return(HA_ERR_AUTOINC_ERANGE);
557
1954
 
558
1955
    /*
559
1956
      field refused this value (overflow) and truncated it, use the result of
563
1960
      bother shifting the right bound (anyway any other value from this
564
1961
      interval will cause a duplicate key).
565
1962
    */
566
 
    nr= prev_insert_id(getTable()->next_number_field->val_int(), variables);
567
 
    if (unlikely(getTable()->next_number_field->store((int64_t) nr, true)))
568
 
      nr= getTable()->next_number_field->val_int();
 
1963
    nr= prev_insert_id(table->next_number_field->val_int(), variables);
 
1964
    if (unlikely(table->next_number_field->store((int64_t) nr, true)))
 
1965
      nr= table->next_number_field->val_int();
569
1966
  }
570
1967
  if (append)
571
1968
  {
587
1984
  */
588
1985
  set_next_insert_id(compute_next_insert_id(nr, variables));
589
1986
 
590
 
  return 0;
591
 
}
592
 
 
593
 
 
594
 
/**
595
 
  Reserves an interval of auto_increment values from the Cursor.
 
1987
  return(0);
 
1988
}
 
1989
 
 
1990
 
 
1991
/**
 
1992
  MySQL signal that it changed the column bitmap
 
1993
 
 
1994
  This is for handlers that needs to setup their own column bitmaps.
 
1995
  Normally the handler should set up their own column bitmaps in
 
1996
  index_init() or rnd_init() and in any column_bitmaps_signal() call after
 
1997
  this.
 
1998
 
 
1999
  The handler is allowed to do changes to the bitmap after a index_init or
 
2000
  rnd_init() call is made as after this, MySQL will not use the bitmap
 
2001
  for any program logic checking.
 
2002
*/
 
2003
void handler::column_bitmaps_signal()
 
2004
{
 
2005
  return;
 
2006
}
 
2007
 
 
2008
 
 
2009
/**
 
2010
  Reserves an interval of auto_increment values from the handler.
596
2011
 
597
2012
  offset and increment means that we want values to be of the form
598
2013
  offset + N * increment, where N>=0 is integer.
603
2018
  @param offset
604
2019
  @param increment
605
2020
  @param nb_desired_values   how many values we want
606
 
  @param first_value         (OUT) the first value reserved by the Cursor
607
 
  @param nb_reserved_values  (OUT) how many values the Cursor reserved
 
2021
  @param first_value         (OUT) the first value reserved by the handler
 
2022
  @param nb_reserved_values  (OUT) how many values the handler reserved
608
2023
*/
609
 
 
610
 
void Cursor::ha_release_auto_increment()
 
2024
void handler::get_auto_increment(uint64_t offset __attribute__((unused)),
 
2025
                                 uint64_t increment __attribute__((unused)),
 
2026
                                 uint64_t nb_desired_values __attribute__((unused)),
 
2027
                                 uint64_t *first_value,
 
2028
                                 uint64_t *nb_reserved_values)
 
2029
{
 
2030
  uint64_t nr;
 
2031
  int error;
 
2032
 
 
2033
  (void) extra(HA_EXTRA_KEYREAD);
 
2034
  table->mark_columns_used_by_index_no_reset(table->s->next_number_index,
 
2035
                                        table->read_set);
 
2036
  column_bitmaps_signal();
 
2037
  index_init(table->s->next_number_index, 1);
 
2038
  if (table->s->next_number_keypart == 0)
 
2039
  {                                             // Autoincrement at key-start
 
2040
    error=index_last(table->record[1]);
 
2041
    /*
 
2042
      MySQL implicitely assumes such method does locking (as MySQL decides to
 
2043
      use nr+increment without checking again with the handler, in
 
2044
      handler::update_auto_increment()), so reserves to infinite.
 
2045
    */
 
2046
    *nb_reserved_values= UINT64_MAX;
 
2047
  }
 
2048
  else
 
2049
  {
 
2050
    unsigned char key[MAX_KEY_LENGTH];
 
2051
    key_copy(key, table->record[0],
 
2052
             table->key_info + table->s->next_number_index,
 
2053
             table->s->next_number_key_offset);
 
2054
    error= index_read_map(table->record[1], key,
 
2055
                          make_prev_keypart_map(table->s->next_number_keypart),
 
2056
                          HA_READ_PREFIX_LAST);
 
2057
    /*
 
2058
      MySQL needs to call us for next row: assume we are inserting ("a",null)
 
2059
      here, we return 3, and next this statement will want to insert
 
2060
      ("b",null): there is no reason why ("b",3+1) would be the good row to
 
2061
      insert: maybe it already exists, maybe 3+1 is too large...
 
2062
    */
 
2063
    *nb_reserved_values= 1;
 
2064
  }
 
2065
 
 
2066
  if (error)
 
2067
    nr=1;
 
2068
  else
 
2069
    nr= ((uint64_t) table->next_number_field->
 
2070
         val_int_offset(table->s->rec_buff_length)+1);
 
2071
  index_end();
 
2072
  (void) extra(HA_EXTRA_NO_KEYREAD);
 
2073
  *first_value= nr;
 
2074
}
 
2075
 
 
2076
 
 
2077
void handler::ha_release_auto_increment()
611
2078
{
612
2079
  release_auto_increment();
613
2080
  insert_id_for_cur_row= 0;
619
2086
      this statement used forced auto_increment values if there were some,
620
2087
      wipe them away for other statements.
621
2088
    */
622
 
    getTable()->in_use->auto_inc_intervals_forced.empty();
623
 
  }
624
 
}
625
 
 
626
 
void Cursor::drop_table(const char *)
 
2089
    table->in_use->auto_inc_intervals_forced.empty();
 
2090
  }
 
2091
}
 
2092
 
 
2093
 
 
2094
void handler::print_keydup_error(uint32_t key_nr, const char *msg)
 
2095
{
 
2096
  /* Write the duplicated key in the error message */
 
2097
  char key[MAX_KEY_LENGTH];
 
2098
  String str(key,sizeof(key),system_charset_info);
 
2099
 
 
2100
  if (key_nr == MAX_KEY)
 
2101
  {
 
2102
    /* Key is unknown */
 
2103
    str.copy("", 0, system_charset_info);
 
2104
    my_printf_error(ER_DUP_ENTRY, msg, MYF(0), str.c_ptr(), "*UNKNOWN*");
 
2105
  }
 
2106
  else
 
2107
  {
 
2108
    /* Table is opened and defined at this point */
 
2109
    key_unpack(&str,table,(uint) key_nr);
 
2110
    uint32_t max_length=DRIZZLE_ERRMSG_SIZE-(uint) strlen(msg);
 
2111
    if (str.length() >= max_length)
 
2112
    {
 
2113
      str.length(max_length-4);
 
2114
      str.append(STRING_WITH_LEN("..."));
 
2115
    }
 
2116
    my_printf_error(ER_DUP_ENTRY, msg,
 
2117
                    MYF(0), str.c_ptr(), table->key_info[key_nr].name);
 
2118
  }
 
2119
}
 
2120
 
 
2121
 
 
2122
/**
 
2123
  Print error that we got from handler function.
 
2124
 
 
2125
  @note
 
2126
    In case of delete table it's only safe to use the following parts of
 
2127
    the 'table' structure:
 
2128
    - table->s->path
 
2129
    - table->alias
 
2130
*/
 
2131
void handler::print_error(int error, myf errflag)
 
2132
{
 
2133
  int textno=ER_GET_ERRNO;
 
2134
  switch (error) {
 
2135
  case EACCES:
 
2136
    textno=ER_OPEN_AS_READONLY;
 
2137
    break;
 
2138
  case EAGAIN:
 
2139
    textno=ER_FILE_USED;
 
2140
    break;
 
2141
  case ENOENT:
 
2142
    textno=ER_FILE_NOT_FOUND;
 
2143
    break;
 
2144
  case HA_ERR_KEY_NOT_FOUND:
 
2145
  case HA_ERR_NO_ACTIVE_RECORD:
 
2146
  case HA_ERR_END_OF_FILE:
 
2147
    textno=ER_KEY_NOT_FOUND;
 
2148
    break;
 
2149
  case HA_ERR_WRONG_MRG_TABLE_DEF:
 
2150
    textno=ER_WRONG_MRG_TABLE;
 
2151
    break;
 
2152
  case HA_ERR_FOUND_DUPP_KEY:
 
2153
  {
 
2154
    uint32_t key_nr=get_dup_key(error);
 
2155
    if ((int) key_nr >= 0)
 
2156
    {
 
2157
      print_keydup_error(key_nr, ER(ER_DUP_ENTRY_WITH_KEY_NAME));
 
2158
      return;
 
2159
    }
 
2160
    textno=ER_DUP_KEY;
 
2161
    break;
 
2162
  }
 
2163
  case HA_ERR_FOREIGN_DUPLICATE_KEY:
 
2164
  {
 
2165
    uint32_t key_nr= get_dup_key(error);
 
2166
    if ((int) key_nr >= 0)
 
2167
    {
 
2168
      uint32_t max_length;
 
2169
      /* Write the key in the error message */
 
2170
      char key[MAX_KEY_LENGTH];
 
2171
      String str(key,sizeof(key),system_charset_info);
 
2172
      /* Table is opened and defined at this point */
 
2173
      key_unpack(&str,table,(uint) key_nr);
 
2174
      max_length= (DRIZZLE_ERRMSG_SIZE-
 
2175
                   (uint) strlen(ER(ER_FOREIGN_DUPLICATE_KEY)));
 
2176
      if (str.length() >= max_length)
 
2177
      {
 
2178
        str.length(max_length-4);
 
2179
        str.append(STRING_WITH_LEN("..."));
 
2180
      }
 
2181
      my_error(ER_FOREIGN_DUPLICATE_KEY, MYF(0), table_share->table_name.str,
 
2182
        str.c_ptr(), key_nr+1);
 
2183
      return;
 
2184
    }
 
2185
    textno= ER_DUP_KEY;
 
2186
    break;
 
2187
  }
 
2188
  case HA_ERR_FOUND_DUPP_UNIQUE:
 
2189
    textno=ER_DUP_UNIQUE;
 
2190
    break;
 
2191
  case HA_ERR_RECORD_CHANGED:
 
2192
    textno=ER_CHECKREAD;
 
2193
    break;
 
2194
  case HA_ERR_CRASHED:
 
2195
    textno=ER_NOT_KEYFILE;
 
2196
    break;
 
2197
  case HA_ERR_WRONG_IN_RECORD:
 
2198
    textno= ER_CRASHED_ON_USAGE;
 
2199
    break;
 
2200
  case HA_ERR_CRASHED_ON_USAGE:
 
2201
    textno=ER_CRASHED_ON_USAGE;
 
2202
    break;
 
2203
  case HA_ERR_NOT_A_TABLE:
 
2204
    textno= error;
 
2205
    break;
 
2206
  case HA_ERR_CRASHED_ON_REPAIR:
 
2207
    textno=ER_CRASHED_ON_REPAIR;
 
2208
    break;
 
2209
  case HA_ERR_OUT_OF_MEM:
 
2210
    textno=ER_OUT_OF_RESOURCES;
 
2211
    break;
 
2212
  case HA_ERR_WRONG_COMMAND:
 
2213
    textno=ER_ILLEGAL_HA;
 
2214
    break;
 
2215
  case HA_ERR_OLD_FILE:
 
2216
    textno=ER_OLD_KEYFILE;
 
2217
    break;
 
2218
  case HA_ERR_UNSUPPORTED:
 
2219
    textno=ER_UNSUPPORTED_EXTENSION;
 
2220
    break;
 
2221
  case HA_ERR_RECORD_FILE_FULL:
 
2222
  case HA_ERR_INDEX_FILE_FULL:
 
2223
    textno=ER_RECORD_FILE_FULL;
 
2224
    break;
 
2225
  case HA_ERR_LOCK_WAIT_TIMEOUT:
 
2226
    textno=ER_LOCK_WAIT_TIMEOUT;
 
2227
    break;
 
2228
  case HA_ERR_LOCK_TABLE_FULL:
 
2229
    textno=ER_LOCK_TABLE_FULL;
 
2230
    break;
 
2231
  case HA_ERR_LOCK_DEADLOCK:
 
2232
    textno=ER_LOCK_DEADLOCK;
 
2233
    break;
 
2234
  case HA_ERR_READ_ONLY_TRANSACTION:
 
2235
    textno=ER_READ_ONLY_TRANSACTION;
 
2236
    break;
 
2237
  case HA_ERR_CANNOT_ADD_FOREIGN:
 
2238
    textno=ER_CANNOT_ADD_FOREIGN;
 
2239
    break;
 
2240
  case HA_ERR_ROW_IS_REFERENCED:
 
2241
  {
 
2242
    String str;
 
2243
    get_error_message(error, &str);
 
2244
    my_error(ER_ROW_IS_REFERENCED_2, MYF(0), str.c_ptr_safe());
 
2245
    return;
 
2246
  }
 
2247
  case HA_ERR_NO_REFERENCED_ROW:
 
2248
  {
 
2249
    String str;
 
2250
    get_error_message(error, &str);
 
2251
    my_error(ER_NO_REFERENCED_ROW_2, MYF(0), str.c_ptr_safe());
 
2252
    return;
 
2253
  }
 
2254
  case HA_ERR_TABLE_DEF_CHANGED:
 
2255
    textno=ER_TABLE_DEF_CHANGED;
 
2256
    break;
 
2257
  case HA_ERR_NO_SUCH_TABLE:
 
2258
    my_error(ER_NO_SUCH_TABLE, MYF(0), table_share->db.str,
 
2259
             table_share->table_name.str);
 
2260
    return;
 
2261
  case HA_ERR_RBR_LOGGING_FAILED:
 
2262
    textno= ER_BINLOG_ROW_LOGGING_FAILED;
 
2263
    break;
 
2264
  case HA_ERR_DROP_INDEX_FK:
 
2265
  {
 
2266
    const char *ptr= "???";
 
2267
    uint32_t key_nr= get_dup_key(error);
 
2268
    if ((int) key_nr >= 0)
 
2269
      ptr= table->key_info[key_nr].name;
 
2270
    my_error(ER_DROP_INDEX_FK, MYF(0), ptr);
 
2271
    return;
 
2272
  }
 
2273
  case HA_ERR_TABLE_NEEDS_UPGRADE:
 
2274
    textno=ER_TABLE_NEEDS_UPGRADE;
 
2275
    break;
 
2276
  case HA_ERR_TABLE_READONLY:
 
2277
    textno= ER_OPEN_AS_READONLY;
 
2278
    break;
 
2279
  case HA_ERR_AUTOINC_READ_FAILED:
 
2280
    textno= ER_AUTOINC_READ_FAILED;
 
2281
    break;
 
2282
  case HA_ERR_AUTOINC_ERANGE:
 
2283
    textno= ER_WARN_DATA_OUT_OF_RANGE;
 
2284
    break;
 
2285
  case HA_ERR_LOCK_OR_ACTIVE_TRANSACTION:
 
2286
    my_message(ER_LOCK_OR_ACTIVE_TRANSACTION,
 
2287
               ER(ER_LOCK_OR_ACTIVE_TRANSACTION), MYF(0));
 
2288
    return;
 
2289
    break;
 
2290
  default:
 
2291
    {
 
2292
      /* The error was "unknown" to this function.
 
2293
         Ask handler if it has got a message for this error */
 
2294
      bool temporary= false;
 
2295
      String str;
 
2296
      temporary= get_error_message(error, &str);
 
2297
      if (!str.is_empty())
 
2298
      {
 
2299
        const char* engine= table_type();
 
2300
        if (temporary)
 
2301
          my_error(ER_GET_TEMPORARY_ERRMSG, MYF(0), error, str.ptr(), engine);
 
2302
        else
 
2303
          my_error(ER_GET_ERRMSG, MYF(0), error, str.ptr(), engine);
 
2304
      }
 
2305
      else
 
2306
        my_error(ER_GET_ERRNO,errflag,error);
 
2307
      return;
 
2308
    }
 
2309
  }
 
2310
  my_error(textno, errflag, table_share->table_name.str, error);
 
2311
  return;
 
2312
}
 
2313
 
 
2314
 
 
2315
/**
 
2316
  Return an error message specific to this handler.
 
2317
 
 
2318
  @param error  error code previously returned by handler
 
2319
  @param buf    pointer to String where to add error message
 
2320
 
 
2321
  @return
 
2322
    Returns true if this is a temporary error
 
2323
*/
 
2324
bool handler::get_error_message(int error __attribute__((unused)),
 
2325
                                String* buf __attribute__((unused)))
 
2326
{
 
2327
  return false;
 
2328
}
 
2329
 
 
2330
 
 
2331
int handler::ha_check_for_upgrade(HA_CHECK_OPT *check_opt)
 
2332
{
 
2333
  KEY *keyinfo, *keyend;
 
2334
  KEY_PART_INFO *keypart, *keypartend;
 
2335
 
 
2336
  if (!table->s->mysql_version)
 
2337
  {
 
2338
    /* check for blob-in-key error */
 
2339
    keyinfo= table->key_info;
 
2340
    keyend= table->key_info + table->s->keys;
 
2341
    for (; keyinfo < keyend; keyinfo++)
 
2342
    {
 
2343
      keypart= keyinfo->key_part;
 
2344
      keypartend= keypart + keyinfo->key_parts;
 
2345
      for (; keypart < keypartend; keypart++)
 
2346
      {
 
2347
        if (!keypart->fieldnr)
 
2348
          continue;
 
2349
        Field *field= table->field[keypart->fieldnr-1];
 
2350
        if (field->type() == DRIZZLE_TYPE_BLOB)
 
2351
        {
 
2352
          if (check_opt->sql_flags & TT_FOR_UPGRADE)
 
2353
            check_opt->flags= T_MEDIUM;
 
2354
          return HA_ADMIN_NEEDS_CHECK;
 
2355
        }
 
2356
      }
 
2357
    }
 
2358
  }
 
2359
  return check_for_upgrade(check_opt);
 
2360
}
 
2361
 
 
2362
 
 
2363
/* Code left, but Drizzle has no legacy yet (while MySQL did) */
 
2364
int handler::check_old_types()
 
2365
{
 
2366
  return 0;
 
2367
}
 
2368
 
 
2369
/**
 
2370
  @return
 
2371
    key if error because of duplicated keys
 
2372
*/
 
2373
uint32_t handler::get_dup_key(int error)
 
2374
{
 
2375
  table->file->errkey  = (uint) -1;
 
2376
  if (error == HA_ERR_FOUND_DUPP_KEY || error == HA_ERR_FOREIGN_DUPLICATE_KEY ||
 
2377
      error == HA_ERR_FOUND_DUPP_UNIQUE ||
 
2378
      error == HA_ERR_DROP_INDEX_FK)
 
2379
    info(HA_STATUS_ERRKEY | HA_STATUS_NO_LOCK);
 
2380
  return(table->file->errkey);
 
2381
}
 
2382
 
 
2383
 
 
2384
/**
 
2385
  Delete all files with extension from bas_ext().
 
2386
 
 
2387
  @param name           Base name of table
 
2388
 
 
2389
  @note
 
2390
    We assume that the handler may return more extensions than
 
2391
    was actually used for the file.
 
2392
 
 
2393
  @retval
 
2394
    0   If we successfully deleted at least one file from base_ext and
 
2395
    didn't get any other errors than ENOENT
 
2396
  @retval
 
2397
    !0  Error
 
2398
*/
 
2399
int handler::delete_table(const char *name)
 
2400
{
 
2401
  int error= 0;
 
2402
  int enoent_or_zero= ENOENT;                   // Error if no file was deleted
 
2403
  char buff[FN_REFLEN];
 
2404
 
 
2405
  for (const char **ext=bas_ext(); *ext ; ext++)
 
2406
  {
 
2407
    fn_format(buff, name, "", *ext, MY_UNPACK_FILENAME|MY_APPEND_EXT);
 
2408
    if (my_delete_with_symlink(buff, MYF(0)))
 
2409
    {
 
2410
      if ((error= my_errno) != ENOENT)
 
2411
        break;
 
2412
    }
 
2413
    else
 
2414
      enoent_or_zero= 0;                        // No error for ENOENT
 
2415
    error= enoent_or_zero;
 
2416
  }
 
2417
  return error;
 
2418
}
 
2419
 
 
2420
 
 
2421
int handler::rename_table(const char * from, const char * to)
 
2422
{
 
2423
  int error= 0;
 
2424
  for (const char **ext= bas_ext(); *ext ; ext++)
 
2425
  {
 
2426
    if (rename_file_ext(from, to, *ext))
 
2427
    {
 
2428
      if ((error=my_errno) != ENOENT)
 
2429
        break;
 
2430
      error= 0;
 
2431
    }
 
2432
  }
 
2433
  return error;
 
2434
}
 
2435
 
 
2436
 
 
2437
void handler::drop_table(const char *name)
627
2438
{
628
2439
  close();
 
2440
  delete_table(name);
629
2441
}
630
2442
 
631
2443
 
644
2456
  @retval
645
2457
    HA_ADMIN_NOT_IMPLEMENTED
646
2458
*/
647
 
int Cursor::ha_check(Session *, HA_CHECK_OPT *)
 
2459
int handler::ha_check(Session *session, HA_CHECK_OPT *check_opt)
648
2460
{
 
2461
  int error;
 
2462
 
 
2463
  if ((table->s->mysql_version >= DRIZZLE_VERSION_ID) &&
 
2464
      (check_opt->sql_flags & TT_FOR_UPGRADE))
 
2465
    return 0;
 
2466
 
 
2467
  if (table->s->mysql_version < DRIZZLE_VERSION_ID)
 
2468
  {
 
2469
    if ((error= check_old_types()))
 
2470
      return error;
 
2471
    error= ha_check_for_upgrade(check_opt);
 
2472
    if (error && (error != HA_ADMIN_NEEDS_CHECK))
 
2473
      return error;
 
2474
    if (!error && (check_opt->sql_flags & TT_FOR_UPGRADE))
 
2475
      return 0;
 
2476
  }
 
2477
  if ((error= check(session, check_opt)))
 
2478
    return error;
649
2479
  return HA_ADMIN_OK;
650
2480
}
651
2481
 
656
2486
 
657
2487
inline
658
2488
void
659
 
Cursor::setTransactionReadWrite()
 
2489
handler::mark_trx_read_write()
660
2490
{
661
 
  ResourceContext *resource_context;
662
 
 
663
 
  /*
664
 
   * If the cursor has not context for execution then there should be no
665
 
   * possible resource to gain (and if there is... then there is a bug such
666
 
   * that in_use should have been set.
667
 
 */
668
 
  if (not getTable()->in_use)
669
 
    return;
670
 
 
671
 
  resource_context= getTable()->in_use->getResourceContext(getEngine());
 
2491
  Ha_trx_info *ha_info= &ha_session()->ha_data[ht->slot].ha_info[0];
672
2492
  /*
673
2493
    When a storage engine method is called, the transaction must
674
2494
    have been started, unless it's a DDL call, for which the
677
2497
    Unfortunately here we can't know know for sure if the engine
678
2498
    has registered the transaction or not, so we must check.
679
2499
  */
680
 
  if (resource_context->isStarted())
 
2500
  if (ha_info->is_started())
681
2501
  {
682
 
    resource_context->markModifiedData();
 
2502
    /*
 
2503
      table_share can be NULL in ha_delete_table(). See implementation
 
2504
      of standalone function ha_delete_table() in sql_base.cc.
 
2505
    */
 
2506
    if (table_share == NULL || table_share->tmp_table == NO_TMP_TABLE)
 
2507
      ha_info->set_trx_read_write();
683
2508
  }
684
2509
}
685
2510
 
686
2511
 
687
2512
/**
 
2513
  Repair table: public interface.
 
2514
 
 
2515
  @sa handler::repair()
 
2516
*/
 
2517
 
 
2518
int handler::ha_repair(Session* session, HA_CHECK_OPT* check_opt)
 
2519
{
 
2520
  int result;
 
2521
 
 
2522
  mark_trx_read_write();
 
2523
 
 
2524
  if ((result= repair(session, check_opt)))
 
2525
    return result;
 
2526
  return HA_ADMIN_OK;
 
2527
}
 
2528
 
 
2529
 
 
2530
/**
 
2531
  Bulk update row: public interface.
 
2532
 
 
2533
  @sa handler::bulk_update_row()
 
2534
*/
 
2535
 
 
2536
int
 
2537
handler::ha_bulk_update_row(const unsigned char *old_data, unsigned char *new_data,
 
2538
                            uint32_t *dup_key_found)
 
2539
{
 
2540
  mark_trx_read_write();
 
2541
 
 
2542
  return bulk_update_row(old_data, new_data, dup_key_found);
 
2543
}
 
2544
 
 
2545
 
 
2546
/**
688
2547
  Delete all rows: public interface.
689
2548
 
690
 
  @sa Cursor::delete_all_rows()
691
 
 
692
 
  @note
693
 
 
694
 
  This is now equalivalent to TRUNCATE TABLE.
 
2549
  @sa handler::delete_all_rows()
695
2550
*/
696
2551
 
697
2552
int
698
 
Cursor::ha_delete_all_rows()
 
2553
handler::ha_delete_all_rows()
699
2554
{
700
 
  setTransactionReadWrite();
701
 
 
702
 
  int result= delete_all_rows();
703
 
 
704
 
  if (result == 0)
705
 
  {
706
 
    /** 
707
 
     * Trigger post-truncate notification to plugins... 
708
 
     *
709
 
     * @todo Make TransactionServices generic to AfterTriggerServices
710
 
     * or similar...
711
 
     */
712
 
    Session *const session= getTable()->in_use;
713
 
    TransactionServices &transaction_services= TransactionServices::singleton();
714
 
    transaction_services.truncateTable(*session, *getTable());
715
 
  }
716
 
 
717
 
  return result;
 
2555
  mark_trx_read_write();
 
2556
 
 
2557
  return delete_all_rows();
718
2558
}
719
2559
 
720
2560
 
721
2561
/**
722
2562
  Reset auto increment: public interface.
723
2563
 
724
 
  @sa Cursor::reset_auto_increment()
 
2564
  @sa handler::reset_auto_increment()
725
2565
*/
726
2566
 
727
2567
int
728
 
Cursor::ha_reset_auto_increment(uint64_t value)
 
2568
handler::ha_reset_auto_increment(uint64_t value)
729
2569
{
730
 
  setTransactionReadWrite();
 
2570
  mark_trx_read_write();
731
2571
 
732
2572
  return reset_auto_increment(value);
733
2573
}
734
2574
 
735
2575
 
736
2576
/**
 
2577
  Optimize table: public interface.
 
2578
 
 
2579
  @sa handler::optimize()
 
2580
*/
 
2581
 
 
2582
int
 
2583
handler::ha_optimize(Session* session, HA_CHECK_OPT* check_opt)
 
2584
{
 
2585
  mark_trx_read_write();
 
2586
 
 
2587
  return optimize(session, check_opt);
 
2588
}
 
2589
 
 
2590
 
 
2591
/**
737
2592
  Analyze table: public interface.
738
2593
 
739
 
  @sa Cursor::analyze()
 
2594
  @sa handler::analyze()
740
2595
*/
741
2596
 
742
2597
int
743
 
Cursor::ha_analyze(Session* session, HA_CHECK_OPT*)
744
 
{
745
 
  setTransactionReadWrite();
746
 
 
747
 
  return analyze(session);
748
 
}
 
2598
handler::ha_analyze(Session* session, HA_CHECK_OPT* check_opt)
 
2599
{
 
2600
  mark_trx_read_write();
 
2601
 
 
2602
  return analyze(session, check_opt);
 
2603
}
 
2604
 
 
2605
 
 
2606
/**
 
2607
  Check and repair table: public interface.
 
2608
 
 
2609
  @sa handler::check_and_repair()
 
2610
*/
 
2611
 
 
2612
bool
 
2613
handler::ha_check_and_repair(Session *session)
 
2614
{
 
2615
  mark_trx_read_write();
 
2616
 
 
2617
  return check_and_repair(session);
 
2618
}
 
2619
 
749
2620
 
750
2621
/**
751
2622
  Disable indexes: public interface.
752
2623
 
753
 
  @sa Cursor::disable_indexes()
 
2624
  @sa handler::disable_indexes()
754
2625
*/
755
2626
 
756
2627
int
757
 
Cursor::ha_disable_indexes(uint32_t mode)
 
2628
handler::ha_disable_indexes(uint32_t mode)
758
2629
{
759
 
  setTransactionReadWrite();
 
2630
  mark_trx_read_write();
760
2631
 
761
2632
  return disable_indexes(mode);
762
2633
}
765
2636
/**
766
2637
  Enable indexes: public interface.
767
2638
 
768
 
  @sa Cursor::enable_indexes()
 
2639
  @sa handler::enable_indexes()
769
2640
*/
770
2641
 
771
2642
int
772
 
Cursor::ha_enable_indexes(uint32_t mode)
 
2643
handler::ha_enable_indexes(uint32_t mode)
773
2644
{
774
 
  setTransactionReadWrite();
 
2645
  mark_trx_read_write();
775
2646
 
776
2647
  return enable_indexes(mode);
777
2648
}
780
2651
/**
781
2652
  Discard or import tablespace: public interface.
782
2653
 
783
 
  @sa Cursor::discard_or_import_tablespace()
 
2654
  @sa handler::discard_or_import_tablespace()
784
2655
*/
785
2656
 
786
2657
int
787
 
Cursor::ha_discard_or_import_tablespace(bool discard)
 
2658
handler::ha_discard_or_import_tablespace(bool discard)
788
2659
{
789
 
  setTransactionReadWrite();
 
2660
  mark_trx_read_write();
790
2661
 
791
2662
  return discard_or_import_tablespace(discard);
792
2663
}
793
2664
 
 
2665
 
 
2666
/**
 
2667
  Prepare for alter: public interface.
 
2668
 
 
2669
  Called to prepare an *online* ALTER.
 
2670
 
 
2671
  @sa handler::prepare_for_alter()
 
2672
*/
 
2673
 
 
2674
void
 
2675
handler::ha_prepare_for_alter()
 
2676
{
 
2677
  mark_trx_read_write();
 
2678
 
 
2679
  prepare_for_alter();
 
2680
}
 
2681
 
 
2682
 
 
2683
/**
 
2684
  Rename table: public interface.
 
2685
 
 
2686
  @sa handler::rename_table()
 
2687
*/
 
2688
 
 
2689
int
 
2690
handler::ha_rename_table(const char *from, const char *to)
 
2691
{
 
2692
  mark_trx_read_write();
 
2693
 
 
2694
  return rename_table(from, to);
 
2695
}
 
2696
 
 
2697
 
 
2698
/**
 
2699
  Delete table: public interface.
 
2700
 
 
2701
  @sa handler::delete_table()
 
2702
*/
 
2703
 
 
2704
int
 
2705
handler::ha_delete_table(const char *name)
 
2706
{
 
2707
  mark_trx_read_write();
 
2708
 
 
2709
  return delete_table(name);
 
2710
}
 
2711
 
 
2712
 
794
2713
/**
795
2714
  Drop table in the engine: public interface.
796
2715
 
797
 
  @sa Cursor::drop_table()
 
2716
  @sa handler::drop_table()
798
2717
*/
799
2718
 
800
2719
void
801
 
Cursor::closeMarkForDelete(const char *name)
 
2720
handler::ha_drop_table(const char *name)
802
2721
{
803
 
  setTransactionReadWrite();
 
2722
  mark_trx_read_write();
804
2723
 
805
2724
  return drop_table(name);
806
2725
}
807
2726
 
808
 
int Cursor::index_next_same(unsigned char *buf, const unsigned char *key, uint32_t keylen)
 
2727
 
 
2728
/**
 
2729
  Create a table in the engine: public interface.
 
2730
 
 
2731
  @sa handler::create()
 
2732
*/
 
2733
 
 
2734
int
 
2735
handler::ha_create(const char *name, Table *form, HA_CREATE_INFO *info)
 
2736
{
 
2737
  mark_trx_read_write();
 
2738
 
 
2739
  return create(name, form, info);
 
2740
}
 
2741
 
 
2742
 
 
2743
/**
 
2744
  Create handler files for CREATE TABLE: public interface.
 
2745
 
 
2746
  @sa handler::create_handler_files()
 
2747
*/
 
2748
 
 
2749
int
 
2750
handler::ha_create_handler_files(const char *name, const char *old_name,
 
2751
                        int action_flag, HA_CREATE_INFO *info)
 
2752
{
 
2753
  mark_trx_read_write();
 
2754
 
 
2755
  return create_handler_files(name, old_name, action_flag, info);
 
2756
}
 
2757
 
 
2758
 
 
2759
/**
 
2760
  Tell the storage engine that it is allowed to "disable transaction" in the
 
2761
  handler. It is a hint that ACID is not required - it is used in NDB for
 
2762
  ALTER Table, for example, when data are copied to temporary table.
 
2763
  A storage engine may treat this hint any way it likes. NDB for example
 
2764
  starts to commit every now and then automatically.
 
2765
  This hint can be safely ignored.
 
2766
*/
 
2767
int ha_enable_transaction(Session *session, bool on)
 
2768
{
 
2769
  int error=0;
 
2770
 
 
2771
  if ((session->transaction.on= on))
 
2772
  {
 
2773
    /*
 
2774
      Now all storage engines should have transaction handling enabled.
 
2775
      But some may have it enabled all the time - "disabling" transactions
 
2776
      is an optimization hint that storage engine is free to ignore.
 
2777
      So, let's commit an open transaction (if any) now.
 
2778
    */
 
2779
    if (!(error= ha_commit_trans(session, 0)))
 
2780
      error= end_trans(session, COMMIT);
 
2781
  }
 
2782
  return(error);
 
2783
}
 
2784
 
 
2785
int handler::index_next_same(unsigned char *buf, const unsigned char *key, uint32_t keylen)
809
2786
{
810
2787
  int error;
811
2788
  if (!(error=index_next(buf)))
812
2789
  {
813
 
    ptrdiff_t ptrdiff= buf - getTable()->getInsertRecord();
 
2790
    my_ptrdiff_t ptrdiff= buf - table->record[0];
814
2791
    unsigned char *save_record_0= NULL;
815
 
    KeyInfo *key_info= NULL;
816
 
    KeyPartInfo *key_part;
817
 
    KeyPartInfo *key_part_end= NULL;
 
2792
    KEY *key_info= NULL;
 
2793
    KEY_PART_INFO *key_part;
 
2794
    KEY_PART_INFO *key_part_end= NULL;
818
2795
 
819
2796
    /*
820
 
      key_cmp_if_same() compares table->getInsertRecord() against 'key'.
821
 
      In parts it uses table->getInsertRecord() directly, in parts it uses
822
 
      field objects with their local pointers into table->getInsertRecord().
823
 
      If 'buf' is distinct from table->getInsertRecord(), we need to move
824
 
      all record references. This is table->getInsertRecord() itself and
 
2797
      key_cmp_if_same() compares table->record[0] against 'key'.
 
2798
      In parts it uses table->record[0] directly, in parts it uses
 
2799
      field objects with their local pointers into table->record[0].
 
2800
      If 'buf' is distinct from table->record[0], we need to move
 
2801
      all record references. This is table->record[0] itself and
825
2802
      the field pointers of the fields used in this key.
826
2803
    */
827
2804
    if (ptrdiff)
828
2805
    {
829
 
      save_record_0= getTable()->getInsertRecord();
830
 
      getTable()->record[0]= buf;
831
 
      key_info= getTable()->key_info + active_index;
 
2806
      save_record_0= table->record[0];
 
2807
      table->record[0]= buf;
 
2808
      key_info= table->key_info + active_index;
832
2809
      key_part= key_info->key_part;
833
2810
      key_part_end= key_part + key_info->key_parts;
834
2811
      for (; key_part < key_part_end; key_part++)
838
2815
      }
839
2816
    }
840
2817
 
841
 
    if (key_cmp_if_same(getTable(), key, active_index, keylen))
 
2818
    if (key_cmp_if_same(table, key, active_index, keylen))
842
2819
    {
843
 
      getTable()->status=STATUS_NOT_FOUND;
 
2820
      table->status=STATUS_NOT_FOUND;
844
2821
      error=HA_ERR_END_OF_FILE;
845
2822
    }
846
2823
 
847
2824
    /* Move back if necessary. */
848
2825
    if (ptrdiff)
849
2826
    {
850
 
      getTable()->record[0]= save_record_0;
 
2827
      table->record[0]= save_record_0;
851
2828
      for (key_part= key_info->key_part; key_part < key_part_end; key_part++)
852
2829
        key_part->field->move_field_offset(-ptrdiff);
853
2830
    }
854
2831
  }
855
 
  return error;
 
2832
  return(error);
856
2833
}
857
2834
 
858
2835
 
859
2836
/****************************************************************************
860
 
** Some general functions that isn't in the Cursor class
 
2837
** Some general functions that isn't in the handler class
861
2838
****************************************************************************/
862
2839
 
863
2840
/**
 
2841
  Initiates table-file and calls appropriate database-creator.
 
2842
 
 
2843
  @retval
 
2844
   0  ok
 
2845
  @retval
 
2846
   1  error
 
2847
*/
 
2848
int ha_create_table(Session *session, const char *path,
 
2849
                    const char *db, const char *table_name,
 
2850
                    HA_CREATE_INFO *create_info,
 
2851
                    bool update_create_info)
 
2852
{
 
2853
  int error= 1;
 
2854
  Table table;
 
2855
  char name_buff[FN_REFLEN];
 
2856
  const char *name;
 
2857
  TABLE_SHARE share;
 
2858
 
 
2859
  init_tmp_table_share(session, &share, db, 0, table_name, path);
 
2860
  if (open_table_def(session, &share, 0) ||
 
2861
      open_table_from_share(session, &share, "", 0, (uint) READ_ALL, 0, &table,
 
2862
                            OTM_CREATE))
 
2863
    goto err;
 
2864
 
 
2865
  if (update_create_info)
 
2866
    table.updateCreateInfo(create_info);
 
2867
 
 
2868
  name= check_lowercase_names(table.file, share.path.str, name_buff);
 
2869
 
 
2870
  error= table.file->ha_create(name, &table, create_info);
 
2871
  closefrm(&table, 0);
 
2872
  if (error)
 
2873
  {
 
2874
    sprintf(name_buff,"%s.%s",db,table_name);
 
2875
    my_error(ER_CANT_CREATE_TABLE, MYF(ME_BELL+ME_WAITTANG), name_buff, error);
 
2876
  }
 
2877
err:
 
2878
  free_table_share(&share);
 
2879
  return(error != 0);
 
2880
}
 
2881
 
 
2882
void st_ha_check_opt::init()
 
2883
{
 
2884
  flags= sql_flags= 0;
 
2885
  sort_buffer_size = current_session->variables.myisam_sort_buff_size;
 
2886
}
 
2887
 
 
2888
 
 
2889
/*****************************************************************************
 
2890
  Key cache handling.
 
2891
 
 
2892
  This code is only relevant for ISAM/MyISAM tables
 
2893
 
 
2894
  key_cache->cache may be 0 only in the case where a key cache is not
 
2895
  initialized or when we where not able to init the key cache in a previous
 
2896
  call to ha_init_key_cache() (probably out of memory)
 
2897
*****************************************************************************/
 
2898
 
 
2899
/**
 
2900
  Init a key cache if it has not been initied before.
 
2901
*/
 
2902
int ha_init_key_cache(const char *name __attribute__((unused)),
 
2903
                      KEY_CACHE *key_cache)
 
2904
{
 
2905
  if (!key_cache->key_cache_inited)
 
2906
  {
 
2907
    pthread_mutex_lock(&LOCK_global_system_variables);
 
2908
    uint32_t tmp_buff_size= (uint32_t) key_cache->param_buff_size;
 
2909
    uint32_t tmp_block_size= (uint) key_cache->param_block_size;
 
2910
    uint32_t division_limit= key_cache->param_division_limit;
 
2911
    uint32_t age_threshold=  key_cache->param_age_threshold;
 
2912
    pthread_mutex_unlock(&LOCK_global_system_variables);
 
2913
    return(!init_key_cache(key_cache,
 
2914
                                tmp_block_size,
 
2915
                                tmp_buff_size,
 
2916
                                division_limit, age_threshold));
 
2917
  }
 
2918
  return(0);
 
2919
}
 
2920
 
 
2921
 
 
2922
/**
 
2923
  Resize key cache.
 
2924
*/
 
2925
int ha_resize_key_cache(KEY_CACHE *key_cache)
 
2926
{
 
2927
  if (key_cache->key_cache_inited)
 
2928
  {
 
2929
    pthread_mutex_lock(&LOCK_global_system_variables);
 
2930
    long tmp_buff_size= (long) key_cache->param_buff_size;
 
2931
    long tmp_block_size= (long) key_cache->param_block_size;
 
2932
    uint32_t division_limit= key_cache->param_division_limit;
 
2933
    uint32_t age_threshold=  key_cache->param_age_threshold;
 
2934
    pthread_mutex_unlock(&LOCK_global_system_variables);
 
2935
    return(!resize_key_cache(key_cache, tmp_block_size,
 
2936
                                  tmp_buff_size,
 
2937
                                  division_limit, age_threshold));
 
2938
  }
 
2939
  return(0);
 
2940
}
 
2941
 
 
2942
 
 
2943
/**
 
2944
  Change parameters for key cache (like size)
 
2945
*/
 
2946
int ha_change_key_cache_param(KEY_CACHE *key_cache)
 
2947
{
 
2948
  if (key_cache->key_cache_inited)
 
2949
  {
 
2950
    pthread_mutex_lock(&LOCK_global_system_variables);
 
2951
    uint32_t division_limit= key_cache->param_division_limit;
 
2952
    uint32_t age_threshold=  key_cache->param_age_threshold;
 
2953
    pthread_mutex_unlock(&LOCK_global_system_variables);
 
2954
    change_key_cache_param(key_cache, division_limit, age_threshold);
 
2955
  }
 
2956
  return 0;
 
2957
}
 
2958
 
 
2959
/**
 
2960
  Free memory allocated by a key cache.
 
2961
*/
 
2962
int ha_end_key_cache(KEY_CACHE *key_cache)
 
2963
{
 
2964
  end_key_cache(key_cache, 1);          // Can never fail
 
2965
  return 0;
 
2966
}
 
2967
 
 
2968
/**
 
2969
  Move all tables from one key cache to another one.
 
2970
*/
 
2971
int ha_change_key_cache(KEY_CACHE *old_key_cache,
 
2972
                        KEY_CACHE *new_key_cache)
 
2973
{
 
2974
  mi_change_key_cache(old_key_cache, new_key_cache);
 
2975
  return 0;
 
2976
}
 
2977
 
 
2978
/**
 
2979
  Call this function in order to give the handler the possiblity
 
2980
  to ask engine if there are any new tables that should be written to disk
 
2981
  or any dropped tables that need to be removed from disk
 
2982
*/
 
2983
struct st_find_files_args
 
2984
{
 
2985
  const char *db;
 
2986
  const char *path;
 
2987
  const char *wild;
 
2988
  bool dir;
 
2989
  List<LEX_STRING> *files;
 
2990
};
 
2991
 
 
2992
/**
 
2993
  Ask handler if the table exists in engine.
 
2994
  @retval
 
2995
    HA_ERR_NO_SUCH_TABLE     Table does not exist
 
2996
  @retval
 
2997
    HA_ERR_TABLE_EXIST       Table exists
 
2998
  @retval
 
2999
    \#                  Error code
 
3000
*/
 
3001
struct st_table_exists_in_engine_args
 
3002
{
 
3003
  const char *db;
 
3004
  const char *name;
 
3005
  int err;
 
3006
  handlerton* hton;
 
3007
};
 
3008
 
 
3009
static bool table_exists_in_engine_handlerton(Session *session, plugin_ref plugin,
 
3010
                                              void *arg)
 
3011
{
 
3012
  st_table_exists_in_engine_args *vargs= (st_table_exists_in_engine_args *)arg;
 
3013
  handlerton *hton= plugin_data(plugin, handlerton *);
 
3014
 
 
3015
  int err= HA_ERR_NO_SUCH_TABLE;
 
3016
 
 
3017
  if (hton->state == SHOW_OPTION_YES && hton->table_exists_in_engine)
 
3018
    err = hton->table_exists_in_engine(hton, session, vargs->db, vargs->name);
 
3019
 
 
3020
  vargs->err = err;
 
3021
  if (vargs->err == HA_ERR_TABLE_EXIST)
 
3022
  {
 
3023
    vargs->hton= hton;
 
3024
    return true;
 
3025
  }
 
3026
 
 
3027
  return false;
 
3028
}
 
3029
 
 
3030
int ha_table_exists_in_engine(Session* session,
 
3031
                              const char* db, const char* name,
 
3032
                              handlerton **hton)
 
3033
{
 
3034
  st_table_exists_in_engine_args args= {db, name, HA_ERR_NO_SUCH_TABLE, NULL};
 
3035
  plugin_foreach(session, table_exists_in_engine_handlerton,
 
3036
                 DRIZZLE_STORAGE_ENGINE_PLUGIN, &args);
 
3037
 
 
3038
  if(args.err==HA_ERR_NO_SUCH_TABLE)
 
3039
  {
 
3040
    /* Default way of knowing if a table exists. (checking .frm exists) */
 
3041
 
 
3042
    char path[FN_REFLEN];
 
3043
    build_table_filename(path, sizeof(path),
 
3044
                         db, name, ".frm", 0);
 
3045
    if (!access(path, F_OK))
 
3046
      args.err= HA_ERR_TABLE_EXIST;
 
3047
    else
 
3048
      args.err= HA_ERR_NO_SUCH_TABLE;
 
3049
 
 
3050
    enum legacy_db_type table_type;
 
3051
    if(args.err==HA_ERR_TABLE_EXIST && mysql_frm_type(path, &table_type)==0)
 
3052
    {
 
3053
      args.hton= ha_resolve_by_legacy_type(session, table_type);
 
3054
    }
 
3055
  }
 
3056
 
 
3057
  if(hton)
 
3058
    *hton= args.hton;
 
3059
 
 
3060
  return(args.err);
 
3061
}
 
3062
 
 
3063
/**
864
3064
  Calculate cost of 'index only' scan for given index and number of records
865
3065
 
866
3066
  @param keynr    Index number
869
3069
  @note
870
3070
    It is assumed that we will read trough the whole key range and that all
871
3071
    key blocks are half full (normally things are much better). It is also
872
 
    assumed that each time we read the next key from the index, the Cursor
 
3072
    assumed that each time we read the next key from the index, the handler
873
3073
    performs a random seek, thus the cost is proportional to the number of
874
3074
    blocks read.
875
3075
 
876
3076
  @todo
877
 
    Consider joining this function and Cursor::read_time() into one
878
 
    Cursor::read_time(keynr, records, ranges, bool index_only) function.
 
3077
    Consider joining this function and handler::read_time() into one
 
3078
    handler::read_time(keynr, records, ranges, bool index_only) function.
879
3079
 
880
3080
  @return
881
3081
    Estimated cost of 'index only' scan
882
3082
*/
883
3083
 
884
 
double Cursor::index_only_read_time(uint32_t keynr, double key_records)
 
3084
double handler::index_only_read_time(uint32_t keynr, double records)
885
3085
{
 
3086
  double read_time;
886
3087
  uint32_t keys_per_block= (stats.block_size/2/
887
 
                        (getTable()->key_info[keynr].key_length + ref_length) + 1);
888
 
  return ((double) (key_records + keys_per_block-1) /
889
 
          (double) keys_per_block);
 
3088
                        (table->key_info[keynr].key_length + ref_length) + 1);
 
3089
  read_time=((double) (records + keys_per_block-1) /
 
3090
             (double) keys_per_block);
 
3091
  return read_time;
890
3092
}
891
3093
 
892
3094
 
913
3115
 
914
3116
  @note
915
3117
    This method (or an overriding one in a derived class) must check for
916
 
    session->getKilled() and return HA_POS_ERROR if it is not zero. This is required
 
3118
    session->killed and return HA_POS_ERROR if it is not zero. This is required
917
3119
    for a user to be able to interrupt the calculation by killing the
918
3120
    connection/query.
919
3121
 
926
3128
*/
927
3129
 
928
3130
ha_rows
929
 
Cursor::multi_range_read_info_const(uint32_t keyno, RANGE_SEQ_IF *seq,
 
3131
handler::multi_range_read_info_const(uint32_t keyno, RANGE_SEQ_IF *seq,
930
3132
                                     void *seq_init_param,
931
 
                                     uint32_t ,
932
 
                                     uint32_t *bufsz, uint32_t *flags, optimizer::CostVector *cost)
 
3133
                                     uint32_t n_ranges_arg __attribute__((unused)),
 
3134
                                     uint32_t *bufsz, uint32_t *flags, COST_VECT *cost)
933
3135
{
934
3136
  KEY_MULTI_RANGE range;
935
3137
  range_seq_t seq_it;
936
3138
  ha_rows rows, total_rows= 0;
937
3139
  uint32_t n_ranges=0;
 
3140
  Session *session= current_session;
938
3141
 
939
3142
  /* Default MRR implementation doesn't need buffer */
940
3143
  *bufsz= 0;
942
3145
  seq_it= seq->init(seq_init_param, n_ranges, *flags);
943
3146
  while (!seq->next(seq_it, &range))
944
3147
  {
 
3148
    if (unlikely(session->killed != 0))
 
3149
      return HA_POS_ERROR;
 
3150
 
945
3151
    n_ranges++;
946
3152
    key_range *min_endp, *max_endp;
947
3153
    {
968
3174
    /* The following calculation is the same as in multi_range_read_info(): */
969
3175
    *flags |= HA_MRR_USE_DEFAULT_IMPL;
970
3176
    cost->zero();
971
 
    cost->setAvgIOCost(1); /* assume random seeks */
 
3177
    cost->avg_io_cost= 1; /* assume random seeks */
972
3178
    if ((*flags & HA_MRR_INDEX_ONLY) && total_rows > 2)
973
 
      cost->setIOCount(index_only_read_time(keyno, (uint32_t)total_rows));
 
3179
      cost->io_count= index_only_read_time(keyno, (uint)total_rows);
974
3180
    else
975
 
      cost->setIOCount(read_time(keyno, n_ranges, total_rows));
976
 
    cost->setCpuCost((double) total_rows / TIME_FOR_COMPARE + 0.01);
 
3181
      cost->io_count= read_time(keyno, n_ranges, total_rows);
 
3182
    cost->cpu_cost= (double) total_rows / TIME_FOR_COMPARE + 0.01;
977
3183
  }
978
3184
  return total_rows;
979
3185
}
1013
3219
    other Error or can't perform the requested scan
1014
3220
*/
1015
3221
 
1016
 
int Cursor::multi_range_read_info(uint32_t keyno, uint32_t n_ranges, uint32_t n_rows,
1017
 
                                   uint32_t *bufsz, uint32_t *flags, optimizer::CostVector *cost)
 
3222
int handler::multi_range_read_info(uint32_t keyno, uint32_t n_ranges, uint32_t n_rows,
 
3223
                                   uint32_t *bufsz, uint32_t *flags, COST_VECT *cost)
1018
3224
{
1019
3225
  *bufsz= 0; /* Default implementation doesn't need a buffer */
1020
3226
 
1021
3227
  *flags |= HA_MRR_USE_DEFAULT_IMPL;
1022
3228
 
1023
3229
  cost->zero();
1024
 
  cost->setAvgIOCost(1); /* assume random seeks */
 
3230
  cost->avg_io_cost= 1; /* assume random seeks */
1025
3231
 
1026
3232
  /* Produce the same cost as non-MRR code does */
1027
3233
  if (*flags & HA_MRR_INDEX_ONLY)
1028
 
    cost->setIOCount(index_only_read_time(keyno, n_rows));
 
3234
    cost->io_count= index_only_read_time(keyno, n_rows);
1029
3235
  else
1030
 
    cost->setIOCount(read_time(keyno, n_ranges, n_rows));
 
3236
    cost->io_count= read_time(keyno, n_ranges, n_rows);
1031
3237
  return 0;
1032
3238
}
1033
3239
 
1051
3257
  @param buf             INOUT: memory buffer to be used
1052
3258
 
1053
3259
  @note
1054
 
    One must have called doStartIndexScan() before calling this function. Several
 
3260
    One must have called index_init() before calling this function. Several
1055
3261
    multi_range_read_init() calls may be made in course of one query.
1056
3262
 
1057
3263
    Until WL#2623 is done (see its text, section 3.2), the following will
1058
3264
    also hold:
1059
3265
    The caller will guarantee that if "seq->init == mrr_ranges_array_init"
1060
3266
    then seq_init_param is an array of n_ranges KEY_MULTI_RANGE structures.
1061
 
    This property will only be used by NDB Cursor until WL#2623 is done.
 
3267
    This property will only be used by NDB handler until WL#2623 is done.
1062
3268
 
1063
3269
    Buffer memory management is done according to the following scenario:
1064
3270
    The caller allocates the buffer and provides it to the callee by filling
1066
3272
    The callee consumes all or some fraction of the provided buffer space, and
1067
3273
    sets the HANDLER_BUFFER members accordingly.
1068
3274
    The callee may use the buffer memory until the next multi_range_read_init()
1069
 
    call is made, all records have been read, or until doEndIndexScan() call is
 
3275
    call is made, all records have been read, or until index_end() call is
1070
3276
    made, whichever comes first.
1071
3277
 
1072
3278
  @retval 0  OK
1074
3280
*/
1075
3281
 
1076
3282
int
1077
 
Cursor::multi_range_read_init(RANGE_SEQ_IF *seq_funcs, void *seq_init_param,
1078
 
                               uint32_t n_ranges, uint32_t mode)
 
3283
handler::multi_range_read_init(RANGE_SEQ_IF *seq_funcs, void *seq_init_param,
 
3284
                               uint32_t n_ranges, uint32_t mode,
 
3285
                               HANDLER_BUFFER *buf __attribute__((unused)))
1079
3286
{
1080
3287
  mrr_iter= seq_funcs->init(seq_init_param, n_ranges, mode);
1081
3288
  mrr_funcs= *seq_funcs;
1082
3289
  mrr_is_output_sorted= test(mode & HA_MRR_SORTED);
1083
3290
  mrr_have_range= false;
1084
 
 
1085
 
  return 0;
 
3291
  return(0);
1086
3292
}
1087
3293
 
1088
3294
 
1099
3305
  @retval other  Error code
1100
3306
*/
1101
3307
 
1102
 
int Cursor::multi_range_read_next(char **range_info)
 
3308
int handler::multi_range_read_next(char **range_info)
1103
3309
{
1104
3310
  int result= 0;
1105
3311
  int range_res= 0;
1106
3312
 
1107
 
  if (not mrr_have_range)
 
3313
  if (!mrr_have_range)
1108
3314
  {
1109
3315
    mrr_have_range= true;
1110
3316
    goto start;
1149
3355
  while ((result == HA_ERR_END_OF_FILE) && !range_res);
1150
3356
 
1151
3357
  *range_info= mrr_cur_range.ptr;
1152
 
  return result;
 
3358
  return(result);
 
3359
}
 
3360
 
 
3361
 
 
3362
/* **************************************************************************
 
3363
 * DS-MRR implementation
 
3364
 ***************************************************************************/
 
3365
 
 
3366
/**
 
3367
  DS-MRR: Initialize and start MRR scan
 
3368
 
 
3369
  Initialize and start the MRR scan. Depending on the mode parameter, this
 
3370
  may use default or DS-MRR implementation.
 
3371
 
 
3372
  @param h               Table handler to be used
 
3373
  @param key             Index to be used
 
3374
  @param seq_funcs       Interval sequence enumeration functions
 
3375
  @param seq_init_param  Interval sequence enumeration parameter
 
3376
  @param n_ranges        Number of ranges in the sequence.
 
3377
  @param mode            HA_MRR_* modes to use
 
3378
  @param buf             INOUT Buffer to use
 
3379
 
 
3380
  @retval 0     Ok, Scan started.
 
3381
  @retval other Error
 
3382
*/
 
3383
 
 
3384
int DsMrr_impl::dsmrr_init(handler *h, KEY *key,
 
3385
                           RANGE_SEQ_IF *seq_funcs, void *seq_init_param,
 
3386
                           uint32_t n_ranges, uint32_t mode, HANDLER_BUFFER *buf)
 
3387
{
 
3388
  uint32_t elem_size;
 
3389
  uint32_t keyno;
 
3390
  Item *pushed_cond= NULL;
 
3391
  handler *new_h2;
 
3392
  keyno= h->active_index;
 
3393
  assert(h2 == NULL);
 
3394
  if (mode & HA_MRR_USE_DEFAULT_IMPL || mode & HA_MRR_SORTED)
 
3395
  {
 
3396
    use_default_impl= true;
 
3397
    return(h->handler::multi_range_read_init(seq_funcs, seq_init_param,
 
3398
                                                  n_ranges, mode, buf));
 
3399
  }
 
3400
  rowids_buf= buf->buffer;
 
3401
  //psergey-todo: don't add key_length as it is not needed anymore
 
3402
  rowids_buf += key->key_length + h->ref_length;
 
3403
 
 
3404
  is_mrr_assoc= !test(mode & HA_MRR_NO_ASSOCIATION);
 
3405
  rowids_buf_end= buf->buffer_end;
 
3406
 
 
3407
  elem_size= h->ref_length + (int)is_mrr_assoc * sizeof(void*);
 
3408
  rowids_buf_last= rowids_buf +
 
3409
                      ((rowids_buf_end - rowids_buf)/ elem_size)*
 
3410
                      elem_size;
 
3411
  rowids_buf_end= rowids_buf_last;
 
3412
 
 
3413
  /* Create a separate handler object to do rndpos() calls. */
 
3414
  Session *session= current_session;
 
3415
  if (!(new_h2= h->clone(session->mem_root)) ||
 
3416
      new_h2->ha_external_lock(session, F_RDLCK))
 
3417
  {
 
3418
    delete new_h2;
 
3419
    return(1);
 
3420
  }
 
3421
 
 
3422
  if (keyno == h->pushed_idx_cond_keyno)
 
3423
    pushed_cond= h->pushed_idx_cond;
 
3424
  if (h->ha_index_end())
 
3425
  {
 
3426
    new_h2= h2;
 
3427
    goto error;
 
3428
  }
 
3429
 
 
3430
  h2= new_h2;
 
3431
  table->prepare_for_position();
 
3432
  new_h2->extra(HA_EXTRA_KEYREAD);
 
3433
 
 
3434
  if (h2->ha_index_init(keyno, false) ||
 
3435
      h2->handler::multi_range_read_init(seq_funcs, seq_init_param, n_ranges,
 
3436
                                         mode, buf))
 
3437
    goto error;
 
3438
  use_default_impl= false;
 
3439
 
 
3440
  if (pushed_cond)
 
3441
    h2->idx_cond_push(keyno, pushed_cond);
 
3442
  if (dsmrr_fill_buffer(new_h2))
 
3443
    goto error;
 
3444
 
 
3445
  /*
 
3446
    If the above call has scanned through all intervals in *seq, then
 
3447
    adjust *buf to indicate that the remaining buffer space will not be used.
 
3448
  */
 
3449
  if (dsmrr_eof)
 
3450
    buf->end_of_used_area= rowids_buf_last;
 
3451
 
 
3452
  if (h->ha_rnd_init(false))
 
3453
    goto error;
 
3454
 
 
3455
  return(0);
 
3456
error:
 
3457
  h2->ha_index_or_rnd_end();
 
3458
  h2->ha_external_lock(session, F_UNLCK);
 
3459
  h2->close();
 
3460
  delete h2;
 
3461
  return(1);
 
3462
}
 
3463
 
 
3464
 
 
3465
void DsMrr_impl::dsmrr_close()
 
3466
{
 
3467
  if (h2)
 
3468
  {
 
3469
    h2->ha_external_lock(current_session, F_UNLCK);
 
3470
    h2->close();
 
3471
    delete h2;
 
3472
    h2= NULL;
 
3473
  }
 
3474
  use_default_impl= true;
 
3475
  return;
 
3476
}
 
3477
 
 
3478
 
 
3479
static int rowid_cmp(void *h, unsigned char *a, unsigned char *b)
 
3480
{
 
3481
  return ((handler*)h)->cmp_ref(a, b);
 
3482
}
 
3483
 
 
3484
 
 
3485
/**
 
3486
  DS-MRR: Fill the buffer with rowids and sort it by rowid
 
3487
 
 
3488
  {This is an internal function of DiskSweep MRR implementation}
 
3489
  Scan the MRR ranges and collect ROWIDs (or {ROWID, range_id} pairs) into
 
3490
  buffer. When the buffer is full or scan is completed, sort the buffer by
 
3491
  rowid and return.
 
3492
 
 
3493
  The function assumes that rowids buffer is empty when it is invoked.
 
3494
 
 
3495
  @param h  Table handler
 
3496
 
 
3497
  @retval 0      OK, the next portion of rowids is in the buffer,
 
3498
                 properly ordered
 
3499
  @retval other  Error
 
3500
*/
 
3501
 
 
3502
int DsMrr_impl::dsmrr_fill_buffer(handler *unused __attribute__((unused)))
 
3503
{
 
3504
  char *range_info;
 
3505
  int res = 0;
 
3506
 
 
3507
  rowids_buf_cur= rowids_buf;
 
3508
  while ((rowids_buf_cur < rowids_buf_end) &&
 
3509
         !(res= h2->handler::multi_range_read_next(&range_info)))
 
3510
  {
 
3511
    /* Put rowid, or {rowid, range_id} pair into the buffer */
 
3512
    h2->position(table->record[0]);
 
3513
    memcpy(rowids_buf_cur, h2->ref, h2->ref_length);
 
3514
    rowids_buf_cur += h->ref_length;
 
3515
 
 
3516
    if (is_mrr_assoc)
 
3517
    {
 
3518
      memcpy(rowids_buf_cur, &range_info, sizeof(void*));
 
3519
      rowids_buf_cur += sizeof(void*);
 
3520
    }
 
3521
  }
 
3522
 
 
3523
  if (res && res != HA_ERR_END_OF_FILE)
 
3524
    return(res);
 
3525
  dsmrr_eof= test(res == HA_ERR_END_OF_FILE);
 
3526
 
 
3527
  /* Sort the buffer contents by rowid */
 
3528
  uint32_t elem_size= h->ref_length + (int)is_mrr_assoc * sizeof(void*);
 
3529
  uint32_t n_rowids= (rowids_buf_cur - rowids_buf) / elem_size;
 
3530
 
 
3531
  my_qsort2(rowids_buf, n_rowids, elem_size, (qsort2_cmp)rowid_cmp,
 
3532
            (void*)h);
 
3533
  rowids_buf_last= rowids_buf_cur;
 
3534
  rowids_buf_cur=  rowids_buf;
 
3535
  return(0);
 
3536
}
 
3537
 
 
3538
 
 
3539
/**
 
3540
  DS-MRR implementation: multi_range_read_next() function
 
3541
*/
 
3542
 
 
3543
int DsMrr_impl::dsmrr_next(handler *h, char **range_info)
 
3544
{
 
3545
  int res;
 
3546
 
 
3547
  if (use_default_impl)
 
3548
    return h->handler::multi_range_read_next(range_info);
 
3549
 
 
3550
  if (rowids_buf_cur == rowids_buf_last)
 
3551
  {
 
3552
    if (dsmrr_eof)
 
3553
    {
 
3554
      res= HA_ERR_END_OF_FILE;
 
3555
      goto end;
 
3556
    }
 
3557
    res= dsmrr_fill_buffer(h);
 
3558
    if (res)
 
3559
      goto end;
 
3560
  }
 
3561
 
 
3562
  /* Return EOF if there are no rowids in the buffer after re-fill attempt */
 
3563
  if (rowids_buf_cur == rowids_buf_last)
 
3564
  {
 
3565
    res= HA_ERR_END_OF_FILE;
 
3566
    goto end;
 
3567
  }
 
3568
 
 
3569
  res= h->rnd_pos(table->record[0], rowids_buf_cur);
 
3570
  rowids_buf_cur += h->ref_length;
 
3571
  if (is_mrr_assoc)
 
3572
  {
 
3573
    memcpy(range_info, rowids_buf_cur, sizeof(void*));
 
3574
    rowids_buf_cur += sizeof(void*);
 
3575
  }
 
3576
 
 
3577
end:
 
3578
  if (res)
 
3579
    dsmrr_close();
 
3580
  return res;
 
3581
}
 
3582
 
 
3583
 
 
3584
/**
 
3585
  DS-MRR implementation: multi_range_read_info() function
 
3586
*/
 
3587
int DsMrr_impl::dsmrr_info(uint32_t keyno, uint32_t n_ranges, uint32_t rows, uint32_t *bufsz,
 
3588
                           uint32_t *flags, COST_VECT *cost)
 
3589
{
 
3590
  int res;
 
3591
  uint32_t def_flags= *flags;
 
3592
  uint32_t def_bufsz= *bufsz;
 
3593
 
 
3594
  /* Get cost/flags/mem_usage of default MRR implementation */
 
3595
  res= h->handler::multi_range_read_info(keyno, n_ranges, rows, &def_bufsz,
 
3596
                                         &def_flags, cost);
 
3597
  assert(!res);
 
3598
 
 
3599
  if ((*flags & HA_MRR_USE_DEFAULT_IMPL) ||
 
3600
      choose_mrr_impl(keyno, rows, &def_flags, &def_bufsz, cost))
 
3601
  {
 
3602
    /* Default implementation is choosen */
 
3603
    *flags= def_flags;
 
3604
    *bufsz= def_bufsz;
 
3605
  }
 
3606
  return 0;
 
3607
}
 
3608
 
 
3609
 
 
3610
/**
 
3611
  DS-MRR Implementation: multi_range_read_info_const() function
 
3612
*/
 
3613
 
 
3614
ha_rows DsMrr_impl::dsmrr_info_const(uint32_t keyno, RANGE_SEQ_IF *seq,
 
3615
                                 void *seq_init_param, uint32_t n_ranges,
 
3616
                                 uint32_t *bufsz, uint32_t *flags, COST_VECT *cost)
 
3617
{
 
3618
  ha_rows rows;
 
3619
  uint32_t def_flags= *flags;
 
3620
  uint32_t def_bufsz= *bufsz;
 
3621
  /* Get cost/flags/mem_usage of default MRR implementation */
 
3622
  rows= h->handler::multi_range_read_info_const(keyno, seq, seq_init_param,
 
3623
                                                n_ranges, &def_bufsz,
 
3624
                                                &def_flags, cost);
 
3625
  if (rows == HA_POS_ERROR)
 
3626
  {
 
3627
    /* Default implementation can't perform MRR scan => we can't either */
 
3628
    return rows;
 
3629
  }
 
3630
 
 
3631
  /*
 
3632
    If HA_MRR_USE_DEFAULT_IMPL has been passed to us, that is an order to
 
3633
    use the default MRR implementation (we need it for UPDATE/DELETE).
 
3634
    Otherwise, make a choice based on cost and @@optimizer_use_mrr.
 
3635
  */
 
3636
  if ((*flags & HA_MRR_USE_DEFAULT_IMPL) ||
 
3637
      choose_mrr_impl(keyno, rows, flags, bufsz, cost))
 
3638
  {
 
3639
    *flags= def_flags;
 
3640
    *bufsz= def_bufsz;
 
3641
  }
 
3642
  else
 
3643
  {
 
3644
    *flags &= ~HA_MRR_USE_DEFAULT_IMPL;
 
3645
  }
 
3646
  return rows;
 
3647
}
 
3648
 
 
3649
 
 
3650
/**
 
3651
  Check if key has partially-covered columns
 
3652
 
 
3653
  We can't use DS-MRR to perform range scans when the ranges are over
 
3654
  partially-covered keys, because we'll not have full key part values
 
3655
  (we'll have their prefixes from the index) and will not be able to check
 
3656
  if we've reached the end the range.
 
3657
 
 
3658
  @param keyno  Key to check
 
3659
 
 
3660
  @todo
 
3661
    Allow use of DS-MRR in cases where the index has partially-covered
 
3662
    components but they are not used for scanning.
 
3663
 
 
3664
  @retval true   Yes
 
3665
  @retval false  No
 
3666
*/
 
3667
 
 
3668
bool DsMrr_impl::key_uses_partial_cols(uint32_t keyno)
 
3669
{
 
3670
  KEY_PART_INFO *kp= table->key_info[keyno].key_part;
 
3671
  KEY_PART_INFO *kp_end= kp + table->key_info[keyno].key_parts;
 
3672
  for (; kp != kp_end; kp++)
 
3673
  {
 
3674
    if (!kp->field->part_of_key.is_set(keyno))
 
3675
      return true;
 
3676
  }
 
3677
  return false;
 
3678
}
 
3679
 
 
3680
 
 
3681
/**
 
3682
  DS-MRR Internals: Choose between Default MRR implementation and DS-MRR
 
3683
 
 
3684
  Make the choice between using Default MRR implementation and DS-MRR.
 
3685
  This function contains common functionality factored out of dsmrr_info()
 
3686
  and dsmrr_info_const(). The function assumes that the default MRR
 
3687
  implementation's applicability requirements are satisfied.
 
3688
 
 
3689
  @param keyno       Index number
 
3690
  @param rows        E(full rows to be retrieved)
 
3691
  @param flags  IN   MRR flags provided by the MRR user
 
3692
                OUT  If DS-MRR is choosen, flags of DS-MRR implementation
 
3693
                     else the value is not modified
 
3694
  @param bufsz  IN   If DS-MRR is choosen, buffer use of DS-MRR implementation
 
3695
                     else the value is not modified
 
3696
  @param cost   IN   Cost of default MRR implementation
 
3697
                OUT  If DS-MRR is choosen, cost of DS-MRR scan
 
3698
                     else the value is not modified
 
3699
 
 
3700
  @retval true   Default MRR implementation should be used
 
3701
  @retval false  DS-MRR implementation should be used
 
3702
*/
 
3703
 
 
3704
bool DsMrr_impl::choose_mrr_impl(uint32_t keyno, ha_rows rows, uint32_t *flags,
 
3705
                                 uint32_t *bufsz, COST_VECT *cost)
 
3706
{
 
3707
  COST_VECT dsmrr_cost;
 
3708
  bool res;
 
3709
  Session *session= current_session;
 
3710
  if ((session->variables.optimizer_use_mrr == 2) ||
 
3711
      (*flags & HA_MRR_INDEX_ONLY) || (*flags & HA_MRR_SORTED) ||
 
3712
      (keyno == table->s->primary_key &&
 
3713
       h->primary_key_is_clustered()) ||
 
3714
       key_uses_partial_cols(keyno))
 
3715
  {
 
3716
    /* Use the default implementation */
 
3717
    *flags |= HA_MRR_USE_DEFAULT_IMPL;
 
3718
    return true;
 
3719
  }
 
3720
 
 
3721
  uint32_t add_len= table->key_info[keyno].key_length + h->ref_length;
 
3722
  *bufsz -= add_len;
 
3723
  if (get_disk_sweep_mrr_cost(keyno, rows, *flags, bufsz, &dsmrr_cost))
 
3724
    return true;
 
3725
  *bufsz += add_len;
 
3726
 
 
3727
  bool force_dsmrr;
 
3728
  /*
 
3729
    If @@optimizer_use_mrr==force, then set cost of DS-MRR to be minimum of
 
3730
    DS-MRR and Default implementations cost. This allows one to force use of
 
3731
    DS-MRR whenever it is applicable without affecting other cost-based
 
3732
    choices.
 
3733
  */
 
3734
  if ((force_dsmrr= (session->variables.optimizer_use_mrr == 1)) &&
 
3735
      dsmrr_cost.total_cost() > cost->total_cost())
 
3736
    dsmrr_cost= *cost;
 
3737
 
 
3738
  if (force_dsmrr || dsmrr_cost.total_cost() <= cost->total_cost())
 
3739
  {
 
3740
    *flags &= ~HA_MRR_USE_DEFAULT_IMPL;  /* Use the DS-MRR implementation */
 
3741
    *flags &= ~HA_MRR_SORTED;          /* We will return unordered output */
 
3742
    *cost= dsmrr_cost;
 
3743
    res= false;
 
3744
  }
 
3745
  else
 
3746
  {
 
3747
    /* Use the default MRR implementation */
 
3748
    res= true;
 
3749
  }
 
3750
  return res;
 
3751
}
 
3752
 
 
3753
 
 
3754
static void get_sort_and_sweep_cost(Table *table, ha_rows nrows, COST_VECT *cost);
 
3755
 
 
3756
 
 
3757
/**
 
3758
  Get cost of DS-MRR scan
 
3759
 
 
3760
  @param keynr              Index to be used
 
3761
  @param rows               E(Number of rows to be scanned)
 
3762
  @param flags              Scan parameters (HA_MRR_* flags)
 
3763
  @param buffer_size INOUT  Buffer size
 
3764
  @param cost        OUT    The cost
 
3765
 
 
3766
  @retval false  OK
 
3767
  @retval true   Error, DS-MRR cannot be used (the buffer is too small
 
3768
                 for even 1 rowid)
 
3769
*/
 
3770
 
 
3771
bool DsMrr_impl::get_disk_sweep_mrr_cost(uint32_t keynr, ha_rows rows, uint32_t flags,
 
3772
                                         uint32_t *buffer_size, COST_VECT *cost)
 
3773
{
 
3774
  uint32_t max_buff_entries, elem_size;
 
3775
  ha_rows rows_in_full_step, rows_in_last_step;
 
3776
  uint32_t n_full_steps;
 
3777
  double index_read_cost;
 
3778
 
 
3779
  elem_size= h->ref_length + sizeof(void*) * (!test(flags & HA_MRR_NO_ASSOCIATION));
 
3780
  max_buff_entries = *buffer_size / elem_size;
 
3781
 
 
3782
  if (!max_buff_entries)
 
3783
    return true; /* Buffer has not enough space for even 1 rowid */
 
3784
 
 
3785
  /* Number of iterations we'll make with full buffer */
 
3786
  n_full_steps= (uint)floor(rows2double(rows) / max_buff_entries);
 
3787
 
 
3788
  /*
 
3789
    Get numbers of rows we'll be processing in
 
3790
     - non-last sweep, with full buffer
 
3791
     - last iteration, with non-full buffer
 
3792
  */
 
3793
  rows_in_full_step= max_buff_entries;
 
3794
  rows_in_last_step= rows % max_buff_entries;
 
3795
 
 
3796
  /* Adjust buffer size if we expect to use only part of the buffer */
 
3797
  if (n_full_steps)
 
3798
  {
 
3799
    get_sort_and_sweep_cost(table, rows, cost);
 
3800
    cost->multiply(n_full_steps);
 
3801
  }
 
3802
  else
 
3803
  {
 
3804
    cost->zero();
 
3805
    *buffer_size= cmax((ulong)*buffer_size,
 
3806
                      (size_t)(1.2*rows_in_last_step) * elem_size +
 
3807
                      h->ref_length + table->key_info[keynr].key_length);
 
3808
  }
 
3809
 
 
3810
  COST_VECT last_step_cost;
 
3811
  get_sort_and_sweep_cost(table, rows_in_last_step, &last_step_cost);
 
3812
  cost->add(&last_step_cost);
 
3813
 
 
3814
  if (n_full_steps != 0)
 
3815
    cost->mem_cost= *buffer_size;
 
3816
  else
 
3817
    cost->mem_cost= (double)rows_in_last_step * elem_size;
 
3818
 
 
3819
  /* Total cost of all index accesses */
 
3820
  index_read_cost= h->index_only_read_time(keynr, (double)rows);
 
3821
  cost->add_io(index_read_cost, 1 /* Random seeks */);
 
3822
  return false;
 
3823
}
 
3824
 
 
3825
 
 
3826
/*
 
3827
  Get cost of one sort-and-sweep step
 
3828
 
 
3829
  SYNOPSIS
 
3830
    get_sort_and_sweep_cost()
 
3831
      table       Table being accessed
 
3832
      nrows       Number of rows to be sorted and retrieved
 
3833
      cost   OUT  The cost
 
3834
 
 
3835
  DESCRIPTION
 
3836
    Get cost of these operations:
 
3837
     - sort an array of #nrows ROWIDs using qsort
 
3838
     - read #nrows records from table in a sweep.
 
3839
*/
 
3840
 
 
3841
static
 
3842
void get_sort_and_sweep_cost(Table *table, ha_rows nrows, COST_VECT *cost)
 
3843
{
 
3844
  if (nrows)
 
3845
  {
 
3846
    get_sweep_read_cost(table, nrows, false, cost);
 
3847
    /* Add cost of qsort call: n * log2(n) * cost(rowid_comparison) */
 
3848
    double cmp_op= rows2double(nrows) * (1.0 / TIME_FOR_COMPARE_ROWID);
 
3849
    if (cmp_op < 3)
 
3850
      cmp_op= 3;
 
3851
    cost->cpu_cost += cmp_op * log2(cmp_op);
 
3852
  }
 
3853
  else
 
3854
    cost->zero();
 
3855
}
 
3856
 
 
3857
 
 
3858
/**
 
3859
  Get cost of reading nrows table records in a "disk sweep"
 
3860
 
 
3861
  A disk sweep read is a sequence of handler->rnd_pos(rowid) calls that made
 
3862
  for an ordered sequence of rowids.
 
3863
 
 
3864
  We assume hard disk IO. The read is performed as follows:
 
3865
 
 
3866
   1. The disk head is moved to the needed cylinder
 
3867
   2. The controller waits for the plate to rotate
 
3868
   3. The data is transferred
 
3869
 
 
3870
  Time to do #3 is insignificant compared to #2+#1.
 
3871
 
 
3872
  Time to move the disk head is proportional to head travel distance.
 
3873
 
 
3874
  Time to wait for the plate to rotate depends on whether the disk head
 
3875
  was moved or not.
 
3876
 
 
3877
  If disk head wasn't moved, the wait time is proportional to distance
 
3878
  between the previous block and the block we're reading.
 
3879
 
 
3880
  If the head was moved, we don't know how much we'll need to wait for the
 
3881
  plate to rotate. We assume the wait time to be a variate with a mean of
 
3882
  0.5 of full rotation time.
 
3883
 
 
3884
  Our cost units are "random disk seeks". The cost of random disk seek is
 
3885
  actually not a constant, it depends one range of cylinders we're going
 
3886
  to access. We make it constant by introducing a fuzzy concept of "typical
 
3887
  datafile length" (it's fuzzy as it's hard to tell whether it should
 
3888
  include index file, temp.tables etc). Then random seek cost is:
 
3889
 
 
3890
    1 = half_rotation_cost + move_cost * 1/3 * typical_data_file_length
 
3891
 
 
3892
  We define half_rotation_cost as DISK_SEEK_BASE_COST=0.9.
 
3893
 
 
3894
  @param table             Table to be accessed
 
3895
  @param nrows             Number of rows to retrieve
 
3896
  @param interrupted       true <=> Assume that the disk sweep will be
 
3897
                           interrupted by other disk IO. false - otherwise.
 
3898
  @param cost         OUT  The cost.
 
3899
*/
 
3900
 
 
3901
void get_sweep_read_cost(Table *table, ha_rows nrows, bool interrupted,
 
3902
                         COST_VECT *cost)
 
3903
{
 
3904
  cost->zero();
 
3905
  if (table->file->primary_key_is_clustered())
 
3906
  {
 
3907
    cost->io_count= table->file->read_time(table->s->primary_key,
 
3908
                                           (uint) nrows, nrows);
 
3909
  }
 
3910
  else
 
3911
  {
 
3912
    double n_blocks=
 
3913
      ceil(uint64_t2double(table->file->stats.data_file_length) / IO_SIZE);
 
3914
    double busy_blocks=
 
3915
      n_blocks * (1.0 - pow(1.0 - 1.0/n_blocks, rows2double(nrows)));
 
3916
    if (busy_blocks < 1.0)
 
3917
      busy_blocks= 1.0;
 
3918
 
 
3919
    cost->io_count= busy_blocks;
 
3920
 
 
3921
    if (!interrupted)
 
3922
    {
 
3923
      /* Assume reading is done in one 'sweep' */
 
3924
      cost->avg_io_cost= (DISK_SEEK_BASE_COST +
 
3925
                          DISK_SEEK_PROP_COST*n_blocks/busy_blocks);
 
3926
    }
 
3927
  }
 
3928
  return;
1153
3929
}
1154
3930
 
1155
3931
 
1166
3942
  @param sorted         Set to 1 if result should be sorted per key
1167
3943
 
1168
3944
  @note
1169
 
    Record is read into table->getInsertRecord()
 
3945
    Record is read into table->record[0]
1170
3946
 
1171
3947
  @retval
1172
3948
    0                   Found row
1175
3951
  @retval
1176
3952
    \#                  Error code
1177
3953
*/
1178
 
int Cursor::read_range_first(const key_range *start_key,
1179
 
                             const key_range *end_key,
1180
 
                             bool eq_range_arg,
1181
 
                             bool )
 
3954
int handler::read_range_first(const key_range *start_key,
 
3955
                              const key_range *end_key,
 
3956
                              bool eq_range_arg,
 
3957
                              bool sorted  __attribute__((unused)))
1182
3958
{
1183
3959
  int result;
1184
3960
 
1191
3967
    key_compare_result_on_equal= ((end_key->flag == HA_READ_BEFORE_KEY) ? 1 :
1192
3968
                                  (end_key->flag == HA_READ_AFTER_KEY) ? -1 : 0);
1193
3969
  }
1194
 
  range_key_part= getTable()->key_info[active_index].key_part;
 
3970
  range_key_part= table->key_info[active_index].key_part;
1195
3971
 
1196
3972
  if (!start_key)                       // Read first record
1197
 
    result= index_first(getTable()->getInsertRecord());
 
3973
    result= index_first(table->record[0]);
1198
3974
  else
1199
 
    result= index_read_map(getTable()->getInsertRecord(),
 
3975
    result= index_read_map(table->record[0],
1200
3976
                           start_key->key,
1201
3977
                           start_key->keypart_map,
1202
3978
                           start_key->flag);
1213
3989
  Read next row between two endpoints.
1214
3990
 
1215
3991
  @note
1216
 
    Record is read into table->getInsertRecord()
 
3992
    Record is read into table->record[0]
1217
3993
 
1218
3994
  @retval
1219
3995
    0                   Found row
1222
3998
  @retval
1223
3999
    \#                  Error code
1224
4000
*/
1225
 
int Cursor::read_range_next()
 
4001
int handler::read_range_next()
1226
4002
{
1227
4003
  int result;
1228
4004
 
1229
4005
  if (eq_range)
1230
4006
  {
1231
4007
    /* We trust that index_next_same always gives a row in range */
1232
 
    return(index_next_same(getTable()->getInsertRecord(),
 
4008
    return(index_next_same(table->record[0],
1233
4009
                                end_range->key,
1234
4010
                                end_range->length));
1235
4011
  }
1236
 
  result= index_next(getTable()->getInsertRecord());
 
4012
  result= index_next(table->record[0]);
1237
4013
  if (result)
1238
 
    return result;
 
4014
    return(result);
1239
4015
  return(compare_key(end_range) <= 0 ? 0 : HA_ERR_END_OF_FILE);
1240
4016
}
1241
4017
 
1255
4031
    - -1  : Key is less than range
1256
4032
    - 1   : Key is larger than range
1257
4033
*/
1258
 
int Cursor::compare_key(key_range *range)
 
4034
int handler::compare_key(key_range *range)
1259
4035
{
1260
4036
  int cmp;
1261
 
  if (not range)
 
4037
  if (!range || in_range_check_pushed_down)
1262
4038
    return 0;                                   // No max range
1263
4039
  cmp= key_cmp(range_key_part, range->key, range->length);
1264
4040
  if (!cmp)
1266
4042
  return cmp;
1267
4043
}
1268
4044
 
1269
 
int Cursor::index_read_idx_map(unsigned char * buf, uint32_t index,
 
4045
 
 
4046
/*
 
4047
  Same as compare_key() but doesn't check have in_range_check_pushed_down.
 
4048
  This is used by index condition pushdown implementation.
 
4049
*/
 
4050
 
 
4051
int handler::compare_key2(key_range *range)
 
4052
{
 
4053
  int cmp;
 
4054
  if (!range)
 
4055
    return 0;                                   // no max range
 
4056
  cmp= key_cmp(range_key_part, range->key, range->length);
 
4057
  if (!cmp)
 
4058
    cmp= key_compare_result_on_equal;
 
4059
  return cmp;
 
4060
}
 
4061
 
 
4062
int handler::index_read_idx_map(unsigned char * buf, uint32_t index,
1270
4063
                                const unsigned char * key,
1271
4064
                                key_part_map keypart_map,
1272
4065
                                enum ha_rkey_function find_flag)
1273
4066
{
1274
4067
  int error, error1;
1275
 
  error= doStartIndexScan(index, 0);
 
4068
  error= index_init(index, 0);
1276
4069
  if (!error)
1277
4070
  {
1278
4071
    error= index_read_map(buf, key, keypart_map, find_flag);
1279
 
    error1= doEndIndexScan();
 
4072
    error1= index_end();
1280
4073
  }
1281
4074
  return error ?  error : error1;
1282
4075
}
1283
4076
 
 
4077
 
 
4078
/**
 
4079
  Returns a list of all known extensions.
 
4080
 
 
4081
    No mutexes, worst case race is a minor surplus memory allocation
 
4082
    We have to recreate the extension map if mysqld is restarted (for example
 
4083
    within libmysqld)
 
4084
 
 
4085
  @retval
 
4086
    pointer             pointer to TYPELIB structure
 
4087
*/
 
4088
static bool exts_handlerton(Session *unused __attribute__((unused)),
 
4089
                            plugin_ref plugin,
 
4090
                            void *arg)
 
4091
{
 
4092
  List<char> *found_exts= (List<char> *) arg;
 
4093
  handlerton *hton= plugin_data(plugin, handlerton *);
 
4094
  handler *file;
 
4095
  if (hton->state == SHOW_OPTION_YES && hton->create &&
 
4096
      (file= hton->create(hton, (TABLE_SHARE*) 0, current_session->mem_root)))
 
4097
  {
 
4098
    List_iterator_fast<char> it(*found_exts);
 
4099
    const char **ext, *old_ext;
 
4100
 
 
4101
    for (ext= file->bas_ext(); *ext; ext++)
 
4102
    {
 
4103
      while ((old_ext= it++))
 
4104
      {
 
4105
        if (!strcmp(old_ext, *ext))
 
4106
          break;
 
4107
      }
 
4108
      if (!old_ext)
 
4109
        found_exts->push_back((char *) *ext);
 
4110
 
 
4111
      it.rewind();
 
4112
    }
 
4113
    delete file;
 
4114
  }
 
4115
  return false;
 
4116
}
 
4117
 
 
4118
TYPELIB *ha_known_exts(void)
 
4119
{
 
4120
  if (!known_extensions.type_names || mysys_usage_id != known_extensions_id)
 
4121
  {
 
4122
    List<char> found_exts;
 
4123
    const char **ext, *old_ext;
 
4124
 
 
4125
    known_extensions_id= mysys_usage_id;
 
4126
 
 
4127
    plugin_foreach(NULL, exts_handlerton,
 
4128
                   DRIZZLE_STORAGE_ENGINE_PLUGIN, &found_exts);
 
4129
 
 
4130
    ext= (const char **) malloc(sizeof(char *)*
 
4131
                                (found_exts.elements+1));
 
4132
                              
 
4133
 
 
4134
    assert(ext != 0);
 
4135
    known_extensions.count= found_exts.elements;
 
4136
    known_extensions.type_names= ext;
 
4137
 
 
4138
    List_iterator_fast<char> it(found_exts);
 
4139
    while ((old_ext= it++))
 
4140
      *ext++= old_ext;
 
4141
    *ext= 0;
 
4142
  }
 
4143
  return &known_extensions;
 
4144
}
 
4145
 
 
4146
 
 
4147
static bool stat_print(Session *session, const char *type, uint32_t type_len,
 
4148
                       const char *file, uint32_t file_len,
 
4149
                       const char *status, uint32_t status_len)
 
4150
{
 
4151
  Protocol *protocol= session->protocol;
 
4152
  protocol->prepare_for_resend();
 
4153
  protocol->store(type, type_len, system_charset_info);
 
4154
  protocol->store(file, file_len, system_charset_info);
 
4155
  protocol->store(status, status_len, system_charset_info);
 
4156
  if (protocol->write())
 
4157
    return true;
 
4158
  return false;
 
4159
}
 
4160
 
 
4161
bool ha_show_status(Session *session, handlerton *db_type, enum ha_stat_type stat)
 
4162
{
 
4163
  List<Item> field_list;
 
4164
  Protocol *protocol= session->protocol;
 
4165
  bool result;
 
4166
 
 
4167
  field_list.push_back(new Item_empty_string("Type",10));
 
4168
  field_list.push_back(new Item_empty_string("Name",FN_REFLEN));
 
4169
  field_list.push_back(new Item_empty_string("Status",10));
 
4170
 
 
4171
  if (protocol->send_fields(&field_list,
 
4172
                            Protocol::SEND_NUM_ROWS | Protocol::SEND_EOF))
 
4173
    return true;
 
4174
 
 
4175
  result= db_type->show_status &&
 
4176
    db_type->show_status(db_type, session, stat_print, stat) ? 1 : 0;
 
4177
 
 
4178
  if (!result)
 
4179
    my_eof(session);
 
4180
  return result;
 
4181
}
 
4182
 
 
4183
 
1284
4184
/**
1285
4185
  Check if the conditions for row-based binlogging is correct for the table.
1286
4186
 
1287
4187
  A row in the given table should be replicated if:
 
4188
  - Row-based replication is enabled in the current thread
 
4189
  - The binlog is enabled
1288
4190
  - It is not a temporary table
 
4191
  - The binary log is open
 
4192
  - The database the table resides in shall be binlogged (binlog_*_db rules)
 
4193
  - table is not mysql.event
1289
4194
*/
1290
4195
 
1291
 
static bool log_row_for_replication(Table* table,
1292
 
                                    const unsigned char *before_record,
1293
 
                                    const unsigned char *after_record)
 
4196
static bool binlog_log_row(Table* table,
 
4197
                           const unsigned char *before_record,
 
4198
                           const unsigned char *after_record)
1294
4199
{
1295
 
  TransactionServices &transaction_services= TransactionServices::singleton();
 
4200
  bool error= false;
1296
4201
  Session *const session= table->in_use;
1297
4202
 
1298
 
  if (table->getShare()->getType() || not transaction_services.shouldConstructMessages())
 
4203
  if (table->no_replicate == false)
1299
4204
    return false;
1300
4205
 
1301
 
  bool result= false;
 
4206
  error= replicator_session_init(session);
1302
4207
 
1303
 
  switch (session->getLex()->sql_command)
 
4208
  switch (session->lex->sql_command)
1304
4209
  {
1305
 
  case SQLCOM_CREATE_TABLE:
1306
 
    /*
1307
 
     * We are in a CREATE TABLE ... SELECT statement
1308
 
     * and the kernel has already created the table
1309
 
     * and put a CreateTableStatement in the active
1310
 
     * Transaction message.  Here, we add a new InsertRecord
1311
 
     * to a new Transaction message (because the above
1312
 
     * CREATE TABLE will commit the transaction containing
1313
 
     * it).
1314
 
     */
1315
 
    result= transaction_services.insertRecord(*session, *table);
1316
 
    break;
1317
4210
  case SQLCOM_REPLACE:
 
4211
  case SQLCOM_INSERT:
1318
4212
  case SQLCOM_REPLACE_SELECT:
1319
 
    /*
1320
 
     * This is a total hack because of the code that is
1321
 
     * in write_record() in sql_insert.cc. During
1322
 
     * a REPLACE statement, a call to insertRecord() is
1323
 
     * called.  If it fails, then a call to deleteRecord()
1324
 
     * is called, followed by a repeat of the original
1325
 
     * call to insertRecord().  So, log_row_for_replication
1326
 
     * could be called multiple times for a REPLACE
1327
 
     * statement.  The below looks at the values of before_record
1328
 
     * and after_record to determine which call to this
1329
 
     * function is for the delete or the insert, since NULL
1330
 
     * is passed for after_record for the delete and NULL is
1331
 
     * passed for before_record for the insert...
1332
 
     *
1333
 
     * In addition, there is an optimization that allows an
1334
 
     * engine to convert the above delete + insert into an
1335
 
     * update, so we must also check for this case below...
1336
 
     */
1337
 
    if (after_record == NULL)
1338
 
    {
1339
 
      /*
1340
 
       * The storage engine is passed the record in table->record[1]
1341
 
       * as the row to delete (this is the conflicting row), so
1342
 
       * we need to notify TransactionService to use that row.
1343
 
       */
1344
 
      transaction_services.deleteRecord(*session, *table, true);
1345
 
      /* 
1346
 
       * We set the "current" statement message to NULL.  This triggers
1347
 
       * the replication services component to generate a new statement
1348
 
       * message for the inserted record which will come next.
1349
 
       */
1350
 
      transaction_services.finalizeStatementMessage(*session->getStatementMessage(), *session);
1351
 
    }
1352
 
    else
1353
 
    {
1354
 
      if (before_record == NULL)
1355
 
        result= transaction_services.insertRecord(*session, *table);
1356
 
      else
1357
 
        transaction_services.updateRecord(*session, *table, before_record, after_record);
1358
 
    }
1359
 
    break;
1360
 
  case SQLCOM_INSERT:
1361
4213
  case SQLCOM_INSERT_SELECT:
1362
 
  case SQLCOM_LOAD:
1363
 
    /*
1364
 
     * The else block below represents an 
1365
 
     * INSERT ... ON DUPLICATE KEY UPDATE that
1366
 
     * has hit a key conflict and actually done
1367
 
     * an update.
1368
 
     */
1369
 
    if (before_record == NULL)
1370
 
      result= transaction_services.insertRecord(*session, *table);
1371
 
    else
1372
 
      transaction_services.updateRecord(*session, *table, before_record, after_record);
 
4214
  case SQLCOM_CREATE_TABLE:
 
4215
    error= replicator_write_row(session, table);
1373
4216
    break;
1374
4217
 
1375
4218
  case SQLCOM_UPDATE:
1376
 
    transaction_services.updateRecord(*session, *table, before_record, after_record);
 
4219
  case SQLCOM_UPDATE_MULTI:
 
4220
    error= replicator_update_row(session, table, before_record, after_record);
1377
4221
    break;
1378
4222
 
1379
4223
  case SQLCOM_DELETE:
1380
 
    transaction_services.deleteRecord(*session, *table);
 
4224
  case SQLCOM_DELETE_MULTI:
 
4225
    error= replicator_delete_row(session, table);
1381
4226
    break;
 
4227
 
 
4228
    /*
 
4229
      For everything else we ignore the event (since it just involves a temp table)
 
4230
    */
1382
4231
  default:
1383
4232
    break;
1384
4233
  }
1385
4234
 
1386
 
  return result;
 
4235
  return error;
1387
4236
}
1388
4237
 
1389
 
int Cursor::ha_external_lock(Session *session, int lock_type)
 
4238
int handler::ha_external_lock(Session *session, int lock_type)
1390
4239
{
1391
4240
  /*
1392
4241
    Whether this is lock or unlock, this should be true, and is to verify that
1395
4244
  */
1396
4245
  assert(next_insert_id == 0);
1397
4246
 
1398
 
  if (DRIZZLE_CURSOR_RDLOCK_START_ENABLED() ||
1399
 
      DRIZZLE_CURSOR_WRLOCK_START_ENABLED() ||
1400
 
      DRIZZLE_CURSOR_UNLOCK_START_ENABLED())
1401
 
  {
1402
 
    if (lock_type == F_RDLCK)
1403
 
    {
1404
 
      DRIZZLE_CURSOR_RDLOCK_START(getTable()->getShare()->getSchemaName(),
1405
 
                                  getTable()->getShare()->getTableName());
1406
 
    }
1407
 
    else if (lock_type == F_WRLCK)
1408
 
    {
1409
 
      DRIZZLE_CURSOR_WRLOCK_START(getTable()->getShare()->getSchemaName(),
1410
 
                                  getTable()->getShare()->getTableName());
1411
 
    }
1412
 
    else if (lock_type == F_UNLCK)
1413
 
    {
1414
 
      DRIZZLE_CURSOR_UNLOCK_START(getTable()->getShare()->getSchemaName(),
1415
 
                                  getTable()->getShare()->getTableName());
1416
 
    }
1417
 
  }
1418
 
 
1419
4247
  /*
1420
4248
    We cache the table flags if the locking succeeded. Otherwise, we
1421
4249
    keep them as they were when they were fetched in ha_open().
1422
4250
  */
 
4251
  DRIZZLE_EXTERNAL_LOCK(lock_type);
1423
4252
 
1424
4253
  int error= external_lock(session, lock_type);
1425
 
 
1426
 
  if (DRIZZLE_CURSOR_RDLOCK_DONE_ENABLED() ||
1427
 
      DRIZZLE_CURSOR_WRLOCK_DONE_ENABLED() ||
1428
 
      DRIZZLE_CURSOR_UNLOCK_DONE_ENABLED())
1429
 
  {
1430
 
    if (lock_type == F_RDLCK)
1431
 
    {
1432
 
      DRIZZLE_CURSOR_RDLOCK_DONE(error);
1433
 
    }
1434
 
    else if (lock_type == F_WRLCK)
1435
 
    {
1436
 
      DRIZZLE_CURSOR_WRLOCK_DONE(error);
1437
 
    }
1438
 
    else if (lock_type == F_UNLCK)
1439
 
    {
1440
 
      DRIZZLE_CURSOR_UNLOCK_DONE(error);
1441
 
    }
1442
 
  }
1443
 
 
1444
 
  return error;
 
4254
  if (error == 0)
 
4255
    cached_table_flags= table_flags();
 
4256
  return(error);
1445
4257
}
1446
4258
 
1447
4259
 
1448
4260
/**
1449
 
  Check Cursor usage and reset state of file to after 'open'
 
4261
  Check handler usage and reset state of file to after 'open'
1450
4262
*/
1451
 
int Cursor::ha_reset()
 
4263
int handler::ha_reset()
1452
4264
{
1453
4265
  /* Check that we have called all proper deallocation functions */
1454
 
  assert(! getTable()->getShare()->all_set.none());
1455
 
  assert(getTable()->key_read == 0);
1456
 
  /* ensure that ha_index_end / endTableScan has been called */
 
4266
  assert((unsigned char*) table->def_read_set.bitmap +
 
4267
              table->s->column_bitmap_size ==
 
4268
              (unsigned char*) table->def_write_set.bitmap);
 
4269
  assert(bitmap_is_set_all(&table->s->all_set));
 
4270
  assert(table->key_read == 0);
 
4271
  /* ensure that ha_index_end / ha_rnd_end has been called */
1457
4272
  assert(inited == NONE);
1458
4273
  /* Free cache used by filesort */
1459
 
  getTable()->free_io_cache();
 
4274
  free_io_cache(table);
1460
4275
  /* reset the bitmaps to point to defaults */
1461
 
  getTable()->default_column_bitmaps();
 
4276
  table->default_column_bitmaps();
1462
4277
  return(reset());
1463
4278
}
1464
4279
 
1465
4280
 
1466
 
int Cursor::insertRecord(unsigned char *buf)
1467
 
{
1468
 
  int error;
1469
 
 
1470
 
  /*
1471
 
   * If we have a timestamp column, update it to the current time
1472
 
   *
1473
 
   * @TODO Technically, the below two lines can be take even further out of the
1474
 
   * Cursor interface and into the fill_record() method.
1475
 
   */
1476
 
  if (getTable()->timestamp_field_type & TIMESTAMP_AUTO_SET_ON_INSERT)
1477
 
  {
1478
 
    getTable()->timestamp_field->set_time();
1479
 
  }
1480
 
 
1481
 
  DRIZZLE_INSERT_ROW_START(getTable()->getShare()->getSchemaName(), getTable()->getShare()->getTableName());
1482
 
  setTransactionReadWrite();
1483
 
  
1484
 
  if (unlikely(plugin::EventObserver::beforeInsertRecord(*getTable(), buf)))
1485
 
  {
1486
 
    error= ER_EVENT_OBSERVER_PLUGIN;
1487
 
  }
1488
 
  else
1489
 
  {
1490
 
    error= doInsertRecord(buf);
1491
 
    if (unlikely(plugin::EventObserver::afterInsertRecord(*getTable(), buf, error))) 
1492
 
    {
1493
 
      error= ER_EVENT_OBSERVER_PLUGIN;
1494
 
    }
1495
 
  }
1496
 
 
1497
 
  ha_statistic_increment(&system_status_var::ha_write_count);
1498
 
 
1499
 
  DRIZZLE_INSERT_ROW_DONE(error);
1500
 
 
1501
 
  if (unlikely(error))
1502
 
  {
1503
 
    return error;
1504
 
  }
1505
 
 
1506
 
  if (unlikely(log_row_for_replication(getTable(), NULL, buf)))
1507
 
    return HA_ERR_RBR_LOGGING_FAILED;
1508
 
 
1509
 
  return 0;
1510
 
}
1511
 
 
1512
 
 
1513
 
int Cursor::updateRecord(const unsigned char *old_data, unsigned char *new_data)
1514
 
{
1515
 
  int error;
1516
 
 
1517
 
  /*
1518
 
    Some storage engines require that the new record is in getInsertRecord()
1519
 
    (and the old record is in getUpdateRecord()).
1520
 
   */
1521
 
  assert(new_data == getTable()->getInsertRecord());
1522
 
 
1523
 
  DRIZZLE_UPDATE_ROW_START(getTable()->getShare()->getSchemaName(), getTable()->getShare()->getTableName());
1524
 
  setTransactionReadWrite();
1525
 
  if (unlikely(plugin::EventObserver::beforeUpdateRecord(*getTable(), old_data, new_data)))
1526
 
  {
1527
 
    error= ER_EVENT_OBSERVER_PLUGIN;
1528
 
  }
1529
 
  else
1530
 
  {
1531
 
    if (getTable()->timestamp_field_type & TIMESTAMP_AUTO_SET_ON_UPDATE)
1532
 
    {
1533
 
      getTable()->timestamp_field->set_time();
1534
 
    }
1535
 
 
1536
 
    error= doUpdateRecord(old_data, new_data);
1537
 
    if (unlikely(plugin::EventObserver::afterUpdateRecord(*getTable(), old_data, new_data, error)))
1538
 
    {
1539
 
      error= ER_EVENT_OBSERVER_PLUGIN;
1540
 
    }
1541
 
  }
1542
 
 
1543
 
  ha_statistic_increment(&system_status_var::ha_update_count);
1544
 
 
1545
 
  DRIZZLE_UPDATE_ROW_DONE(error);
1546
 
 
1547
 
  if (unlikely(error))
1548
 
  {
1549
 
    return error;
1550
 
  }
1551
 
 
1552
 
  if (unlikely(log_row_for_replication(getTable(), old_data, new_data)))
1553
 
    return HA_ERR_RBR_LOGGING_FAILED;
1554
 
 
1555
 
  return 0;
1556
 
}
1557
 
TableShare *Cursor::getShare()
1558
 
{
1559
 
  return getTable()->getMutableShare();
1560
 
}
1561
 
 
1562
 
int Cursor::deleteRecord(const unsigned char *buf)
1563
 
{
1564
 
  int error;
1565
 
 
1566
 
  DRIZZLE_DELETE_ROW_START(getTable()->getShare()->getSchemaName(), getTable()->getShare()->getTableName());
1567
 
  setTransactionReadWrite();
1568
 
  if (unlikely(plugin::EventObserver::beforeDeleteRecord(*getTable(), buf)))
1569
 
  {
1570
 
    error= ER_EVENT_OBSERVER_PLUGIN;
1571
 
  }
1572
 
  else
1573
 
  {
1574
 
    error= doDeleteRecord(buf);
1575
 
    if (unlikely(plugin::EventObserver::afterDeleteRecord(*getTable(), buf, error)))
1576
 
    {
1577
 
      error= ER_EVENT_OBSERVER_PLUGIN;
1578
 
    }
1579
 
  }
1580
 
 
1581
 
  ha_statistic_increment(&system_status_var::ha_delete_count);
1582
 
 
1583
 
  DRIZZLE_DELETE_ROW_DONE(error);
1584
 
 
1585
 
  if (unlikely(error))
1586
 
    return error;
1587
 
 
1588
 
  if (unlikely(log_row_for_replication(getTable(), buf, NULL)))
1589
 
    return HA_ERR_RBR_LOGGING_FAILED;
1590
 
 
1591
 
  return 0;
1592
 
}
1593
 
 
1594
 
} /* namespace drizzled */
 
4281
int handler::ha_write_row(unsigned char *buf)
 
4282
{
 
4283
  int error;
 
4284
  DRIZZLE_INSERT_ROW_START();
 
4285
 
 
4286
  mark_trx_read_write();
 
4287
 
 
4288
  if (unlikely(error= write_row(buf)))
 
4289
    return(error);
 
4290
 
 
4291
  if (unlikely(binlog_log_row(table, 0, buf)))
 
4292
    return HA_ERR_RBR_LOGGING_FAILED; /* purecov: inspected */
 
4293
 
 
4294
  DRIZZLE_INSERT_ROW_END();
 
4295
  return(0);
 
4296
}
 
4297
 
 
4298
 
 
4299
int handler::ha_update_row(const unsigned char *old_data, unsigned char *new_data)
 
4300
{
 
4301
  int error;
 
4302
 
 
4303
  /*
 
4304
    Some storage engines require that the new record is in record[0]
 
4305
    (and the old record is in record[1]).
 
4306
   */
 
4307
  assert(new_data == table->record[0]);
 
4308
 
 
4309
  mark_trx_read_write();
 
4310
 
 
4311
  if (unlikely(error= update_row(old_data, new_data)))
 
4312
    return error;
 
4313
 
 
4314
  if (unlikely(binlog_log_row(table, old_data, new_data)))
 
4315
    return HA_ERR_RBR_LOGGING_FAILED;
 
4316
 
 
4317
  return 0;
 
4318
}
 
4319
 
 
4320
int handler::ha_delete_row(const unsigned char *buf)
 
4321
{
 
4322
  int error;
 
4323
 
 
4324
  mark_trx_read_write();
 
4325
 
 
4326
  if (unlikely(error= delete_row(buf)))
 
4327
    return error;
 
4328
 
 
4329
  if (unlikely(binlog_log_row(table, buf, 0)))
 
4330
    return HA_ERR_RBR_LOGGING_FAILED;
 
4331
 
 
4332
  return 0;
 
4333
}
 
4334
 
 
4335
 
 
4336
 
 
4337
/**
 
4338
  @details
 
4339
  use_hidden_primary_key() is called in case of an update/delete when
 
4340
  (table_flags() and HA_PRIMARY_KEY_REQUIRED_FOR_DELETE) is defined
 
4341
  but we don't have a primary key
 
4342
*/
 
4343
void handler::use_hidden_primary_key()
 
4344
{
 
4345
  /* fallback to use all columns in the table to identify row */
 
4346
  table->use_all_columns();
 
4347
}
 
4348
 
 
4349
void table_case_convert(char * name, uint32_t length)
 
4350
{
 
4351
  if (lower_case_table_names)
 
4352
    files_charset_info->cset->casedn(files_charset_info,
 
4353
                                     name, length, name, length);
 
4354
}
 
4355
 
 
4356
const char *table_case_name(HA_CREATE_INFO *info, const char *name)
 
4357
{
 
4358
  return ((lower_case_table_names == 2 && info->alias) ? info->alias : name);
 
4359
}