~drizzle-trunk/drizzle/development

« back to all changes in this revision

Viewing changes to drizzled/handler.cc

Moved the last of the libdrizzleclient calls into Protocol.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
/* Copyright (C) 2000-2006 MySQL AB
2
 
 
3
 
   This program is free software; you can redistribute it and/or modify
4
 
   it under the terms of the GNU General Public License as published by
5
 
   the Free Software Foundation; version 2 of the License.
6
 
 
7
 
   This program is distributed in the hope that it will be useful,
8
 
   but WITHOUT ANY WARRANTY; without even the implied warranty of
9
 
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
10
 
   GNU General Public License for more details.
11
 
 
12
 
   You should have received a copy of the GNU General Public License
13
 
   along with this program; if not, write to the Free Software
14
 
   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA */
 
1
/* -*- mode: c++; c-basic-offset: 2; indent-tabs-mode: nil; -*-
 
2
 *  vim:expandtab:shiftwidth=2:tabstop=2:smarttab:
 
3
 *
 
4
 *  Copyright (C) 2008 Sun Microsystems
 
5
 *
 
6
 *  This program is free software; you can redistribute it and/or modify
 
7
 *  it under the terms of the GNU General Public License as published by
 
8
 *  the Free Software Foundation; version 2 of the License.
 
9
 *
 
10
 *  This program is distributed in the hope that it will be useful,
 
11
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 
12
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
13
 *  GNU General Public License for more details.
 
14
 *
 
15
 *  You should have received a copy of the GNU General Public License
 
16
 *  along with this program; if not, write to the Free Software
 
17
 *  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 
18
 */
15
19
 
16
20
/**
17
21
  @file handler.cc
19
23
  Handler-calling-functions
20
24
*/
21
25
 
22
 
#ifdef USE_PRAGMA_IMPLEMENTATION
23
 
#pragma implementation                          // gcc: Class implementation
24
 
#endif
25
 
 
26
 
#include <drizzled/server_includes.h>
27
 
#include "rpl_filter.h"
28
 
#include <drizzled/drizzled_error_messages.h>
29
 
 
30
 
/*
31
 
  While we have legacy_db_type, we have this array to
32
 
  check for dups and to find handlerton from legacy_db_type.
33
 
  Remove when legacy_db_type is finally gone
34
 
*/
35
 
st_plugin_int *hton2plugin[MAX_HA];
36
 
 
37
 
static handlerton *installed_htons[128];
38
 
 
39
 
#define BITMAP_STACKBUF_SIZE (128/8)
 
26
#include "drizzled/server_includes.h"
 
27
#include "mysys/hash.h"
 
28
#include "drizzled/error.h"
 
29
#include "drizzled/gettext.h"
 
30
#include "drizzled/data_home.h"
 
31
#include "drizzled/probes.h"
 
32
#include "drizzled/sql_parse.h"
 
33
#include "drizzled/cost_vect.h"
 
34
#include "drizzled/session.h"
 
35
#include "drizzled/sql_base.h"
 
36
#include "drizzled/replicator.h"
 
37
#include "drizzled/lock.h"
 
38
#include "drizzled/item/int.h"
 
39
#include "drizzled/item/empty_string.h"
 
40
#include "drizzled/unireg.h" // for mysql_frm_type
 
41
#include "drizzled/field/timestamp.h"
 
42
#include "drizzled/serialize/table.pb.h"
 
43
 
 
44
using namespace std;
40
45
 
41
46
KEY_CREATE_INFO default_key_create_info= { HA_KEY_ALG_UNDEF, 0, {NULL,0}, {NULL,0} };
42
47
 
43
 
/* number of entries in handlertons[] */
 
48
/* number of entries in storage_engines[] */
44
49
uint32_t total_ha= 0;
45
 
/* number of storage engines (from handlertons[]) that support 2pc */
 
50
/* number of storage engines (from storage_engines[]) that support 2pc */
46
51
uint32_t total_ha_2pc= 0;
47
52
/* size of savepoint storage area (see ha_init) */
48
53
uint32_t savepoint_alloc_size= 0;
49
54
 
50
 
static const LEX_STRING sys_table_aliases[]=
51
 
{
52
 
  { C_STRING_WITH_LEN("INNOBASE") },  { C_STRING_WITH_LEN("INNODB") },
53
 
  { C_STRING_WITH_LEN("HEAP") },      { C_STRING_WITH_LEN("MEMORY") },
54
 
  {NULL, 0}
55
 
};
56
 
 
57
55
const char *ha_row_type[] = {
58
56
  "", "FIXED", "DYNAMIC", "COMPRESSED", "REDUNDANT", "COMPACT", "PAGE", "?","?","?"
59
57
};
61
59
const char *tx_isolation_names[] =
62
60
{ "READ-UNCOMMITTED", "READ-COMMITTED", "REPEATABLE-READ", "SERIALIZABLE",
63
61
  NULL};
 
62
 
64
63
TYPELIB tx_isolation_typelib= {array_elements(tx_isolation_names)-1,"",
65
 
                               tx_isolation_names, NULL};
 
64
                               tx_isolation_names, NULL};
66
65
 
67
66
static TYPELIB known_extensions= {0,"known_exts", NULL, NULL};
68
67
uint32_t known_extensions_id= 0;
69
68
 
70
69
 
71
 
 
72
 
static plugin_ref ha_default_plugin(THD *thd)
73
 
{
74
 
  if (thd->variables.table_plugin)
75
 
    return thd->variables.table_plugin;
76
 
  return my_plugin_lock(thd, &global_system_variables.table_plugin);
77
 
}
78
 
 
79
 
 
80
 
/**
81
 
  Return the default storage engine handlerton for thread
82
 
 
83
 
  @param ha_default_handlerton(thd)
84
 
  @param thd         current thread
85
 
 
86
 
  @return
87
 
    pointer to handlerton
88
 
*/
89
 
handlerton *ha_default_handlerton(THD *thd)
90
 
{
91
 
  plugin_ref plugin= ha_default_plugin(thd);
92
 
  assert(plugin);
93
 
  handlerton *hton= plugin_data(plugin, handlerton*);
94
 
  assert(hton);
95
 
  return hton;
96
 
}
97
 
 
98
 
 
99
 
/**
100
 
  Return the storage engine handlerton for the supplied name
101
 
  
102
 
  @param thd         current thread
103
 
  @param name        name of storage engine
104
 
  
105
 
  @return
106
 
    pointer to storage engine plugin handle
107
 
*/
108
 
plugin_ref ha_resolve_by_name(THD *thd, const LEX_STRING *name)
109
 
{
110
 
  const LEX_STRING *table_alias;
111
 
  plugin_ref plugin;
112
 
 
113
 
redo:
114
 
  /* my_strnncoll is a macro and gcc doesn't do early expansion of macro */
115
 
  if (thd && !my_charset_utf8_general_ci.coll->strnncoll(&my_charset_utf8_general_ci,
116
 
                           (const unsigned char *)name->str, name->length,
117
 
                           (const unsigned char *)STRING_WITH_LEN("DEFAULT"), 0))
118
 
    return ha_default_plugin(thd);
119
 
 
120
 
  if ((plugin= my_plugin_lock_by_name(thd, name, DRIZZLE_STORAGE_ENGINE_PLUGIN)))
121
 
  {
122
 
    handlerton *hton= plugin_data(plugin, handlerton *);
123
 
    if (!(hton->flags & HTON_NOT_USER_SELECTABLE))
124
 
      return plugin;
125
 
      
126
 
    /*
127
 
      unlocking plugin immediately after locking is relatively low cost.
128
 
    */
129
 
    plugin_unlock(thd, plugin);
130
 
  }
131
 
 
132
 
  /*
133
 
    We check for the historical aliases.
134
 
  */
135
 
  for (table_alias= sys_table_aliases; table_alias->str; table_alias+= 2)
136
 
  {
137
 
    if (!my_strnncoll(&my_charset_utf8_general_ci,
138
 
                      (const unsigned char *)name->str, name->length,
139
 
                      (const unsigned char *)table_alias->str, table_alias->length))
140
 
    {
141
 
      name= table_alias + 1;
142
 
      goto redo;
143
 
    }
144
 
  }
145
 
 
146
 
  return NULL;
147
 
}
148
 
 
149
 
 
150
 
plugin_ref ha_lock_engine(THD *thd, handlerton *hton)
151
 
{
152
 
  if (hton)
153
 
  {
154
 
    st_plugin_int **plugin= hton2plugin + hton->slot;
155
 
    
156
 
    return my_plugin_lock(thd, &plugin);
157
 
  }
158
 
  return NULL;
159
 
}
160
 
 
161
 
 
162
 
handlerton *ha_resolve_by_legacy_type(THD *thd, enum legacy_db_type db_type)
163
 
{
164
 
  plugin_ref plugin;
165
 
  switch (db_type) {
166
 
  case DB_TYPE_DEFAULT:
167
 
    return ha_default_handlerton(thd);
168
 
  default:
169
 
    if (db_type > DB_TYPE_UNKNOWN && db_type < DB_TYPE_DEFAULT &&
170
 
        (plugin= ha_lock_engine(thd, installed_htons[db_type])))
171
 
      return plugin_data(plugin, handlerton*);
172
 
    /* fall through */
173
 
  case DB_TYPE_UNKNOWN:
174
 
    return NULL;
175
 
  }
176
 
}
177
 
 
178
 
 
179
 
/**
180
 
  Use other database handler if databasehandler is not compiled in.
181
 
*/
182
 
handlerton *ha_checktype(THD *thd, enum legacy_db_type database_type,
183
 
                          bool no_substitute, bool report_error)
184
 
{
185
 
  handlerton *hton= ha_resolve_by_legacy_type(thd, database_type);
186
 
  if (ha_storage_engine_is_enabled(hton))
187
 
    return hton;
188
 
 
189
 
  if (no_substitute)
190
 
  {
191
 
    if (report_error)
192
 
    {
193
 
      const char *engine_name= ha_resolve_storage_engine_name(hton);
194
 
      my_error(ER_FEATURE_DISABLED,MYF(0),engine_name,engine_name);
195
 
    }
196
 
    return NULL;
197
 
  }
198
 
 
199
 
  return ha_default_handlerton(thd);
200
 
} /* ha_checktype */
201
 
 
202
 
 
203
 
handler *get_new_handler(TABLE_SHARE *share, MEM_ROOT *alloc,
204
 
                         handlerton *db_type)
205
 
{
206
 
  handler *file;
207
 
 
208
 
  if (db_type && db_type->state == SHOW_OPTION_YES && db_type->create)
209
 
  {
210
 
    if ((file= db_type->create(db_type, share, alloc)))
211
 
      file->init();
212
 
    return(file);
213
 
  }
214
 
  /*
215
 
    Try the default table type
216
 
    Here the call to current_thd() is ok as we call this function a lot of
217
 
    times but we enter this branch very seldom.
218
 
  */
219
 
  return(get_new_handler(share, alloc, ha_default_handlerton(current_thd)));
220
 
}
221
 
 
222
 
 
223
70
/**
224
71
  Register handler error messages for use with my_error().
225
72
 
236
83
 
237
84
  /* Allocate a pointer array for the error message strings. */
238
85
  /* Zerofill it to avoid uninitialized gaps. */
239
 
  if (! (errmsgs= (const char**) my_malloc(HA_ERR_ERRORS * sizeof(char*),
240
 
                                           MYF(MY_WME | MY_ZEROFILL))))
 
86
  if (! (errmsgs= (const char**) malloc(HA_ERR_ERRORS * sizeof(char*))))
241
87
    return 1;
 
88
  memset(errmsgs, 0, HA_ERR_ERRORS * sizeof(char *));
242
89
 
243
90
  /* Set the dedicated error messages. */
244
91
  SETMSG(HA_ERR_KEY_NOT_FOUND,          ER(ER_KEY_NOT_FOUND));
307
154
  return 0;
308
155
}
309
156
 
310
 
 
311
 
int ha_finalize_handlerton(st_plugin_int *plugin)
312
 
{
313
 
  handlerton *hton= (handlerton *)plugin->data;
314
 
 
315
 
  switch (hton->state)
316
 
  {
317
 
  case SHOW_OPTION_NO:
318
 
  case SHOW_OPTION_DISABLED:
319
 
    break;
320
 
  case SHOW_OPTION_YES:
321
 
    if (installed_htons[hton->db_type] == hton)
322
 
      installed_htons[hton->db_type]= NULL;
323
 
    break;
324
 
  };
325
 
 
326
 
  if (hton && plugin->plugin->deinit)
327
 
    (void)plugin->plugin->deinit(hton);
328
 
 
329
 
  free((unsigned char*)hton);
330
 
 
331
 
  return(0);
332
 
}
333
 
 
334
 
 
335
 
int ha_initialize_handlerton(st_plugin_int *plugin)
336
 
{
337
 
  handlerton *hton;
338
 
 
339
 
  hton= (handlerton *)my_malloc(sizeof(handlerton),
340
 
                                MYF(MY_WME | MY_ZEROFILL));
341
 
  /* 
342
 
    FIXME: the MY_ZEROFILL flag above doesn't zero all the bytes.
343
 
    
344
 
    This was detected after adding get_backup_engine member to handlerton
345
 
    structure. Apparently get_backup_engine was not NULL even though it was
346
 
    not initialized.
347
 
   */
348
 
  memset(hton, 0, sizeof(hton));
349
 
  /* Historical Requirement */
350
 
  plugin->data= hton; // shortcut for the future
351
 
  if (plugin->plugin->init)
352
 
  {
353
 
    if (plugin->plugin->init(hton))
354
 
    {
355
 
      sql_print_error(_("Plugin '%s' init function returned error."),
356
 
                      plugin->name.str);
357
 
      goto err;
358
 
    }
359
 
  }
360
 
 
361
 
  /*
362
 
    the switch below and hton->state should be removed when
363
 
    command-line options for plugins will be implemented
364
 
  */
365
 
  switch (hton->state) {
366
 
  case SHOW_OPTION_NO:
367
 
    break;
368
 
  case SHOW_OPTION_YES:
369
 
    {
370
 
      uint32_t tmp;
371
 
      /* now check the db_type for conflict */
372
 
      if (hton->db_type <= DB_TYPE_UNKNOWN ||
373
 
          hton->db_type >= DB_TYPE_DEFAULT ||
374
 
          installed_htons[hton->db_type])
375
 
      {
376
 
        int idx= (int) DB_TYPE_FIRST_DYNAMIC;
377
 
 
378
 
        while (idx < (int) DB_TYPE_DEFAULT && installed_htons[idx])
379
 
          idx++;
380
 
 
381
 
        if (idx == (int) DB_TYPE_DEFAULT)
382
 
        {
383
 
          sql_print_warning(_("Too many storage engines!"));
384
 
          return(1);
385
 
        }
386
 
        if (hton->db_type != DB_TYPE_UNKNOWN)
387
 
          sql_print_warning(_("Storage engine '%s' has conflicting typecode. "
388
 
                            "Assigning value %d."), plugin->plugin->name, idx);
389
 
        hton->db_type= (enum legacy_db_type) idx;
390
 
      }
391
 
      installed_htons[hton->db_type]= hton;
392
 
      tmp= hton->savepoint_offset;
393
 
      hton->savepoint_offset= savepoint_alloc_size;
394
 
      savepoint_alloc_size+= tmp;
395
 
      hton->slot= total_ha++;
396
 
      hton2plugin[hton->slot]=plugin;
397
 
      if (hton->prepare)
398
 
        total_ha_2pc++;
399
 
      break;
400
 
    }
401
 
    /* fall through */
402
 
  default:
403
 
    hton->state= SHOW_OPTION_DISABLED;
404
 
    break;
405
 
  }
406
 
  
407
 
  /* 
408
 
    This is entirely for legacy. We will create a new "disk based" hton and a 
409
 
    "memory" hton which will be configurable longterm. We should be able to 
410
 
    remove partition and myisammrg.
411
 
  */
412
 
  if (strcmp(plugin->plugin->name, "MEMORY") == 0)
413
 
    heap_hton= hton;
414
 
 
415
 
  if (strcmp(plugin->plugin->name, "MyISAM") == 0)
416
 
    myisam_hton= hton;
417
 
 
418
 
  return(0);
419
 
err:
420
 
  return(1);
421
 
}
422
 
 
423
157
int ha_init()
424
158
{
425
159
  int error= 0;
430
164
    binary log (which is considered a transaction-capable storage engine in
431
165
    counting total_ha)
432
166
  */
433
 
  opt_using_transactions= total_ha>(uint32_t)opt_bin_log;
434
167
  savepoint_alloc_size+= sizeof(SAVEPOINT);
435
168
  return(error);
436
169
}
439
172
{
440
173
  int error= 0;
441
174
 
442
 
  /* 
 
175
  /*
443
176
    This should be eventualy based  on the graceful shutdown flag.
444
177
    So if flag is equal to HA_PANIC_CLOSE, the deallocate
445
178
    the errors.
450
183
  return(error);
451
184
}
452
185
 
453
 
static bool dropdb_handlerton(THD *unused1 __attribute__((unused)),
454
 
                              plugin_ref plugin,
455
 
                              void *path)
 
186
static bool dropdb_storage_engine(Session *,
 
187
                                  plugin_ref plugin,
 
188
                                  void *path)
456
189
{
457
 
  handlerton *hton= plugin_data(plugin, handlerton *);
458
 
  if (hton->state == SHOW_OPTION_YES && hton->drop_database)
459
 
    hton->drop_database(hton, (char *)path);
 
190
  StorageEngine *engine= plugin_data(plugin, StorageEngine *);
 
191
  if (engine->is_enabled())
 
192
    engine->drop_database((char *)path);
460
193
  return false;
461
194
}
462
195
 
463
196
 
464
197
void ha_drop_database(char* path)
465
198
{
466
 
  plugin_foreach(NULL, dropdb_handlerton, DRIZZLE_STORAGE_ENGINE_PLUGIN, path);
 
199
  plugin_foreach(NULL, dropdb_storage_engine, DRIZZLE_STORAGE_ENGINE_PLUGIN, path);
467
200
}
468
201
 
469
202
 
470
 
static bool closecon_handlerton(THD *thd, plugin_ref plugin,
471
 
                                void *unused __attribute__((unused)))
 
203
static bool closecon_storage_engine(Session *session, plugin_ref plugin,
 
204
                                void *)
472
205
{
473
 
  handlerton *hton= plugin_data(plugin, handlerton *);
 
206
  StorageEngine *engine= plugin_data(plugin, StorageEngine *);
474
207
  /*
475
208
    there's no need to rollback here as all transactions must
476
209
    be rolled back already
477
210
  */
478
 
  if (hton->state == SHOW_OPTION_YES && hton->close_connection &&
479
 
      thd_get_ha_data(thd, hton))
480
 
    hton->close_connection(hton, thd);
 
211
  if (engine->is_enabled() && 
 
212
      session_get_ha_data(session, engine))
 
213
    engine->close_connection(session);
481
214
  return false;
482
215
}
483
216
 
486
219
  @note
487
220
    don't bother to rollback here, it's done already
488
221
*/
489
 
void ha_close_connection(THD* thd)
 
222
void ha_close_connection(Session* session)
490
223
{
491
 
  plugin_foreach(thd, closecon_handlerton, DRIZZLE_STORAGE_ENGINE_PLUGIN, 0);
 
224
  plugin_foreach(session, closecon_storage_engine, DRIZZLE_STORAGE_ENGINE_PLUGIN, 0);
492
225
}
493
226
 
494
227
/* ========================================================================
593
326
  -----------
594
327
 
595
328
  The server stores its transaction-related data in
596
 
  thd->transaction. This structure has two members of type
597
 
  THD_TRANS. These members correspond to the statement and
 
329
  session->transaction. This structure has two members of type
 
330
  Session_TRANS. These members correspond to the statement and
598
331
  normal transactions respectively:
599
332
 
600
 
  - thd->transaction.stmt contains a list of engines
 
333
  - session->transaction.stmt contains a list of engines
601
334
  that are participating in the given statement
602
 
  - thd->transaction.all contains a list of engines that
 
335
  - session->transaction.all contains a list of engines that
603
336
  have participated in any of the statement transactions started
604
337
  within the context of the normal transaction.
605
338
  Each element of the list contains a pointer to the storage
606
339
  engine, engine-specific transactional data, and engine-specific
607
340
  transaction flags.
608
341
 
609
 
  In autocommit mode thd->transaction.all is empty.
610
 
  Instead, data of thd->transaction.stmt is
 
342
  In autocommit mode session->transaction.all is empty.
 
343
  Instead, data of session->transaction.stmt is
611
344
  used to commit/rollback the normal transaction.
612
345
 
613
346
  The list of registered engines has a few important properties:
618
351
  Transaction life cycle
619
352
  ----------------------
620
353
 
621
 
  When a new connection is established, thd->transaction
 
354
  When a new connection is established, session->transaction
622
355
  members are initialized to an empty state.
623
356
  If a statement uses any tables, all affected engines
624
357
  are registered in the statement engine list. In
634
367
  and emptied again at the next statement's end.
635
368
 
636
369
  The normal transaction is committed in a similar way
637
 
  (by going over all engines in thd->transaction.all list)
 
370
  (by going over all engines in session->transaction.all list)
638
371
  but at different times:
639
372
  - upon COMMIT SQL statement is issued by the user
640
373
  - implicitly, by the server, at the beginning of a DDL statement
644
377
  - if the user has requested so, by issuing ROLLBACK SQL
645
378
  statement
646
379
  - if one of the storage engines requested a rollback
647
 
  by setting thd->transaction_rollback_request. This may
 
380
  by setting session->transaction_rollback_request. This may
648
381
  happen in case, e.g., when the transaction in the engine was
649
382
  chosen a victim of the internal deadlock resolution algorithm
650
383
  and rolled back internally. When such a situation happens, there
671
404
  in each engine independently. The two-phase commit protocol
672
405
  is used only if:
673
406
  - all participating engines support two-phase commit (provide
674
 
    handlerton::prepare PSEA API call) and
 
407
    StorageEngine::prepare PSEA API call) and
675
408
  - transactions in at least two engines modify data (i.e. are
676
409
  not read-only).
677
410
 
686
419
  transactions of other participants.
687
420
 
688
421
  After the normal transaction has been committed,
689
 
  thd->transaction.all list is cleared.
 
422
  session->transaction.all list is cleared.
690
423
 
691
424
  When a connection is closed, the current normal transaction, if
692
425
  any, is rolled back.
735
468
 
736
469
  At the end of a statement, server call
737
470
  ha_autocommit_or_rollback() is invoked. This call in turn
738
 
  invokes handlerton::prepare() for every involved engine.
739
 
  Prepare is followed by a call to handlerton::commit_one_phase()
740
 
  If a one-phase commit will suffice, handlerton::prepare() is not
741
 
  invoked and the server only calls handlerton::commit_one_phase().
 
471
  invokes StorageEngine::prepare() for every involved engine.
 
472
  Prepare is followed by a call to StorageEngine::commit_one_phase()
 
473
  If a one-phase commit will suffice, StorageEngine::prepare() is not
 
474
  invoked and the server only calls StorageEngine::commit_one_phase().
742
475
  At statement commit, the statement-related read-write engine
743
476
  flag is propagated to the corresponding flag in the normal
744
477
  transaction.  When the commit is complete, the list of registered
750
483
  ---------------------------------------------------
751
484
 
752
485
  DDLs and operations with non-transactional engines
753
 
  do not "register" in thd->transaction lists, and thus do not
 
486
  do not "register" in session->transaction lists, and thus do not
754
487
  modify the transaction state. Besides, each DDL in
755
488
  MySQL is prefixed with an implicit normal transaction commit
756
 
  (a call to end_active_trans()), and thus leaves nothing
 
489
  (a call to Session::endActiveTransaction()), and thus leaves nothing
757
490
  to modify.
758
491
  However, as it has been pointed out with CREATE TABLE .. SELECT,
759
492
  some DDL statements can start a *new* transaction.
797
530
    times per transaction.
798
531
 
799
532
*/
800
 
void trans_register_ha(THD *thd, bool all, handlerton *ht_arg)
 
533
void trans_register_ha(Session *session, bool all, StorageEngine *engine)
801
534
{
802
 
  THD_TRANS *trans;
 
535
  Session_TRANS *trans;
803
536
  Ha_trx_info *ha_info;
804
537
 
805
538
  if (all)
806
539
  {
807
 
    trans= &thd->transaction.all;
808
 
    thd->server_status|= SERVER_STATUS_IN_TRANS;
 
540
    trans= &session->transaction.all;
 
541
    session->server_status|= SERVER_STATUS_IN_TRANS;
809
542
  }
810
543
  else
811
 
    trans= &thd->transaction.stmt;
 
544
    trans= &session->transaction.stmt;
812
545
 
813
 
  ha_info= thd->ha_data[ht_arg->slot].ha_info + static_cast<unsigned>(all);
 
546
  ha_info= session->ha_data[engine->slot].ha_info + static_cast<unsigned>(all);
814
547
 
815
548
  if (ha_info->is_started())
816
549
    return; /* already registered, return */
817
550
 
818
 
  ha_info->register_ha(trans, ht_arg);
 
551
  ha_info->register_ha(trans, engine);
819
552
 
820
 
  trans->no_2pc|=(ht_arg->prepare==0);
821
 
  if (thd->transaction.xid_state.xid.is_null())
822
 
    thd->transaction.xid_state.xid.set(thd->query_id);
 
553
  trans->no_2pc|= not engine->has_2pc();
 
554
  if (session->transaction.xid_state.xid.is_null())
 
555
    session->transaction.xid_state.xid.set(session->query_id);
823
556
 
824
557
  return;
825
558
}
830
563
  @retval
831
564
    1   error, transaction was rolled back
832
565
*/
833
 
int ha_prepare(THD *thd)
 
566
int ha_prepare(Session *session)
834
567
{
835
568
  int error=0, all=1;
836
 
  THD_TRANS *trans=all ? &thd->transaction.all : &thd->transaction.stmt;
 
569
  Session_TRANS *trans=all ? &session->transaction.all : &session->transaction.stmt;
837
570
  Ha_trx_info *ha_info= trans->ha_list;
838
571
  if (ha_info)
839
572
  {
840
573
    for (; ha_info; ha_info= ha_info->next())
841
574
    {
842
575
      int err;
843
 
      handlerton *ht= ha_info->ht();
844
 
      status_var_increment(thd->status_var.ha_prepare_count);
845
 
      if (ht->prepare)
 
576
      StorageEngine *engine= ha_info->engine();
 
577
      status_var_increment(session->status_var.ha_prepare_count);
 
578
      if ((err= engine->prepare(session, all)))
846
579
      {
847
 
        if ((err= ht->prepare(ht, thd, all)))
848
 
        {
849
 
          my_error(ER_ERROR_DURING_COMMIT, MYF(0), err);
850
 
          ha_rollback_trans(thd, all);
851
 
          error=1;
852
 
          break;
853
 
        }
 
580
        my_error(ER_ERROR_DURING_COMMIT, MYF(0), err);
 
581
        ha_rollback_trans(session, all);
 
582
        error=1;
 
583
        break;
854
584
      }
855
585
      else
856
586
      {
857
 
        push_warning_printf(thd, DRIZZLE_ERROR::WARN_LEVEL_WARN,
 
587
        push_warning_printf(session, DRIZZLE_ERROR::WARN_LEVEL_WARN,
858
588
                            ER_ILLEGAL_HA, ER(ER_ILLEGAL_HA),
859
 
                            ha_resolve_storage_engine_name(ht));
 
589
                            ha_resolve_storage_engine_name(engine));
860
590
      }
861
591
    }
862
592
  }
879
609
 
880
610
static
881
611
bool
882
 
ha_check_and_coalesce_trx_read_only(THD *thd, Ha_trx_info *ha_list,
 
612
ha_check_and_coalesce_trx_read_only(Session *session, Ha_trx_info *ha_list,
883
613
                                    bool all)
884
614
{
885
615
  /* The number of storage engines that have actual changes. */
893
623
 
894
624
    if (! all)
895
625
    {
896
 
      Ha_trx_info *ha_info_all= &thd->ha_data[ha_info->ht()->slot].ha_info[1];
 
626
      Ha_trx_info *ha_info_all= &session->ha_data[ha_info->engine()->slot].ha_info[1];
897
627
      assert(ha_info != ha_info_all);
898
628
      /*
899
629
        Merge read-only/read-write information about statement
900
630
        transaction to its enclosing normal transaction. Do this
901
631
        only if in a real transaction -- that is, if we know
902
 
        that ha_info_all is registered in thd->transaction.all.
 
632
        that ha_info_all is registered in session->transaction.all.
903
633
        Since otherwise we only clutter the normal transaction flags.
904
634
      */
905
635
      if (ha_info_all->is_started()) /* false if autocommit. */
933
663
    stored functions or triggers. So we simply do nothing now.
934
664
    TODO: This should be fixed in later ( >= 5.1) releases.
935
665
*/
936
 
int ha_commit_trans(THD *thd, bool all)
 
666
int ha_commit_trans(Session *session, bool all)
937
667
{
938
668
  int error= 0, cookie= 0;
939
669
  /*
940
670
    'all' means that this is either an explicit commit issued by
941
671
    user, or an implicit commit issued by a DDL.
942
672
  */
943
 
  THD_TRANS *trans= all ? &thd->transaction.all : &thd->transaction.stmt;
944
 
  bool is_real_trans= all || thd->transaction.all.ha_list == 0;
 
673
  Session_TRANS *trans= all ? &session->transaction.all : &session->transaction.stmt;
 
674
  bool is_real_trans= all || session->transaction.all.ha_list == 0;
945
675
  Ha_trx_info *ha_info= trans->ha_list;
946
 
  my_xid xid= thd->transaction.xid_state.xid.get_my_xid();
947
676
 
948
677
  /*
949
678
    We must not commit the normal transaction if a statement
951
680
    flags will not get propagated to its normal transaction's
952
681
    counterpart.
953
682
  */
954
 
  assert(thd->transaction.stmt.ha_list == NULL ||
955
 
              trans == &thd->transaction.stmt);
 
683
  assert(session->transaction.stmt.ha_list == NULL ||
 
684
              trans == &session->transaction.stmt);
956
685
 
957
 
  if (thd->in_sub_stmt)
958
 
  {
959
 
    /*
960
 
      Since we don't support nested statement transactions in 5.0,
961
 
      we can't commit or rollback stmt transactions while we are inside
962
 
      stored functions or triggers. So we simply do nothing now.
963
 
      TODO: This should be fixed in later ( >= 5.1) releases.
964
 
    */
965
 
    if (!all)
966
 
      return(0);
967
 
    /*
968
 
      We assume that all statements which commit or rollback main transaction
969
 
      are prohibited inside of stored functions or triggers. So they should
970
 
      bail out with error even before ha_commit_trans() call. To be 100% safe
971
 
      let us throw error in non-debug builds.
972
 
    */
973
 
    assert(0);
974
 
    my_error(ER_COMMIT_NOT_ALLOWED_IN_SF_OR_TRG, MYF(0));
975
 
    return(2);
976
 
  }
977
686
  if (ha_info)
978
687
  {
979
688
    bool must_2pc;
980
689
 
981
 
    if (is_real_trans && wait_if_global_read_lock(thd, 0, 0))
 
690
    if (is_real_trans && wait_if_global_read_lock(session, 0, 0))
982
691
    {
983
 
      ha_rollback_trans(thd, all);
 
692
      ha_rollback_trans(session, all);
984
693
      return(1);
985
694
    }
986
695
 
987
 
    if (   is_real_trans
988
 
        && opt_readonly
989
 
        && ! thd->slave_thread
990
 
       )
991
 
    {
992
 
      my_error(ER_OPTION_PREVENTS_STATEMENT, MYF(0), "--read-only");
993
 
      ha_rollback_trans(thd, all);
994
 
      error= 1;
995
 
      goto end;
996
 
    }
997
 
 
998
 
    must_2pc= ha_check_and_coalesce_trx_read_only(thd, ha_info, all);
 
696
    must_2pc= ha_check_and_coalesce_trx_read_only(session, ha_info, all);
999
697
 
1000
698
    if (!trans->no_2pc && must_2pc)
1001
699
    {
1002
700
      for (; ha_info && !error; ha_info= ha_info->next())
1003
701
      {
1004
702
        int err;
1005
 
        handlerton *ht= ha_info->ht();
 
703
        StorageEngine *engine= ha_info->engine();
1006
704
        /*
1007
705
          Do not call two-phase commit if this particular
1008
706
          transaction is read-only. This allows for simpler
1014
712
          Sic: we know that prepare() is not NULL since otherwise
1015
713
          trans->no_2pc would have been set.
1016
714
        */
1017
 
        if ((err= ht->prepare(ht, thd, all)))
 
715
        if ((err= engine->prepare(session, all)))
1018
716
        {
1019
717
          my_error(ER_ERROR_DURING_COMMIT, MYF(0), err);
1020
718
          error= 1;
1021
719
        }
1022
 
        status_var_increment(thd->status_var.ha_prepare_count);
 
720
        status_var_increment(session->status_var.ha_prepare_count);
1023
721
      }
1024
 
      if (error || (is_real_trans && xid &&
1025
 
                    (error= !(cookie= tc_log->log_xid(thd, xid)))))
 
722
      if (error)
1026
723
      {
1027
 
        ha_rollback_trans(thd, all);
 
724
        ha_rollback_trans(session, all);
1028
725
        error= 1;
1029
726
        goto end;
1030
727
      }
1031
728
    }
1032
 
    error=ha_commit_one_phase(thd, all) ? (cookie ? 2 : 1) : 0;
1033
 
    if (cookie)
1034
 
      tc_log->unlog(cookie, xid);
 
729
    error=ha_commit_one_phase(session, all) ? (cookie ? 2 : 1) : 0;
1035
730
end:
1036
731
    if (is_real_trans)
1037
 
      start_waiting_global_read_lock(thd);
 
732
      start_waiting_global_read_lock(session);
1038
733
  }
1039
734
  return(error);
1040
735
}
1043
738
  @note
1044
739
  This function does not care about global read lock. A caller should.
1045
740
*/
1046
 
int ha_commit_one_phase(THD *thd, bool all)
 
741
int ha_commit_one_phase(Session *session, bool all)
1047
742
{
1048
743
  int error=0;
1049
 
  THD_TRANS *trans=all ? &thd->transaction.all : &thd->transaction.stmt;
1050
 
  bool is_real_trans=all || thd->transaction.all.ha_list == 0;
 
744
  Session_TRANS *trans=all ? &session->transaction.all : &session->transaction.stmt;
 
745
  bool is_real_trans=all || session->transaction.all.ha_list == 0;
1051
746
  Ha_trx_info *ha_info= trans->ha_list, *ha_info_next;
1052
747
  if (ha_info)
1053
748
  {
1054
749
    for (; ha_info; ha_info= ha_info_next)
1055
750
    {
1056
751
      int err;
1057
 
      handlerton *ht= ha_info->ht();
1058
 
      if ((err= ht->commit(ht, thd, all)))
 
752
      StorageEngine *engine= ha_info->engine();
 
753
      if ((err= engine->commit(session, all)))
1059
754
      {
1060
755
        my_error(ER_ERROR_DURING_COMMIT, MYF(0), err);
1061
756
        error=1;
1062
757
      }
1063
 
      status_var_increment(thd->status_var.ha_commit_count);
 
758
      status_var_increment(session->status_var.ha_commit_count);
1064
759
      ha_info_next= ha_info->next();
1065
760
      ha_info->reset(); /* keep it conveniently zero-filled */
1066
761
    }
1067
762
    trans->ha_list= 0;
1068
763
    trans->no_2pc=0;
1069
764
    if (is_real_trans)
1070
 
      thd->transaction.xid_state.xid.null();
 
765
      session->transaction.xid_state.xid.null();
1071
766
    if (all)
1072
767
    {
1073
 
      thd->variables.tx_isolation=thd->session_tx_isolation;
1074
 
      thd->transaction.cleanup();
 
768
      session->variables.tx_isolation=session->session_tx_isolation;
 
769
      session->transaction.cleanup();
1075
770
    }
1076
771
  }
1077
772
  return(error);
1078
773
}
1079
774
 
1080
775
 
1081
 
int ha_rollback_trans(THD *thd, bool all)
 
776
int ha_rollback_trans(Session *session, bool all)
1082
777
{
1083
778
  int error=0;
1084
 
  THD_TRANS *trans=all ? &thd->transaction.all : &thd->transaction.stmt;
 
779
  Session_TRANS *trans=all ? &session->transaction.all : &session->transaction.stmt;
1085
780
  Ha_trx_info *ha_info= trans->ha_list, *ha_info_next;
1086
 
  bool is_real_trans=all || thd->transaction.all.ha_list == 0;
 
781
  bool is_real_trans=all || session->transaction.all.ha_list == 0;
1087
782
 
1088
783
  /*
1089
784
    We must not rollback the normal transaction if a statement
1090
785
    transaction is pending.
1091
786
  */
1092
 
  assert(thd->transaction.stmt.ha_list == NULL ||
1093
 
              trans == &thd->transaction.stmt);
 
787
  assert(session->transaction.stmt.ha_list == NULL ||
 
788
              trans == &session->transaction.stmt);
1094
789
 
1095
 
  if (thd->in_sub_stmt)
1096
 
  {
1097
 
    /*
1098
 
      If we are inside stored function or trigger we should not commit or
1099
 
      rollback current statement transaction. See comment in ha_commit_trans()
1100
 
      call for more information.
1101
 
    */
1102
 
    if (!all)
1103
 
      return(0);
1104
 
    assert(0);
1105
 
    my_error(ER_COMMIT_NOT_ALLOWED_IN_SF_OR_TRG, MYF(0));
1106
 
    return(1);
1107
 
  }
1108
790
  if (ha_info)
1109
791
  {
1110
792
    for (; ha_info; ha_info= ha_info_next)
1111
793
    {
1112
794
      int err;
1113
 
      handlerton *ht= ha_info->ht();
1114
 
      if ((err= ht->rollback(ht, thd, all)))
 
795
      StorageEngine *engine= ha_info->engine();
 
796
      if ((err= engine->rollback(session, all)))
1115
797
      { // cannot happen
1116
798
        my_error(ER_ERROR_DURING_ROLLBACK, MYF(0), err);
1117
799
        error=1;
1118
800
      }
1119
 
      status_var_increment(thd->status_var.ha_rollback_count);
 
801
      status_var_increment(session->status_var.ha_rollback_count);
1120
802
      ha_info_next= ha_info->next();
1121
803
      ha_info->reset(); /* keep it conveniently zero-filled */
1122
804
    }
1123
805
    trans->ha_list= 0;
1124
806
    trans->no_2pc=0;
1125
807
    if (is_real_trans)
1126
 
      thd->transaction.xid_state.xid.null();
 
808
      session->transaction.xid_state.xid.null();
1127
809
    if (all)
1128
810
    {
1129
 
      thd->variables.tx_isolation=thd->session_tx_isolation;
1130
 
      thd->transaction.cleanup();
 
811
      session->variables.tx_isolation=session->session_tx_isolation;
 
812
      session->transaction.cleanup();
1131
813
    }
1132
814
  }
1133
815
  if (all)
1134
 
    thd->transaction_rollback_request= false;
 
816
    session->transaction_rollback_request= false;
1135
817
 
1136
818
  /*
1137
819
    If a non-transactional table was updated, warn; don't warn if this is a
1142
824
    the error log; but we don't want users to wonder why they have this
1143
825
    message in the error log, so we don't send it.
1144
826
  */
1145
 
  if (is_real_trans && thd->transaction.all.modified_non_trans_table &&
1146
 
      !thd->slave_thread && thd->killed != THD::KILL_CONNECTION)
1147
 
    push_warning(thd, DRIZZLE_ERROR::WARN_LEVEL_WARN,
 
827
  if (is_real_trans && session->transaction.all.modified_non_trans_table && session->killed != Session::KILL_CONNECTION)
 
828
    push_warning(session, DRIZZLE_ERROR::WARN_LEVEL_WARN,
1148
829
                 ER_WARNING_NOT_COMPLETE_ROLLBACK,
1149
830
                 ER(ER_WARNING_NOT_COMPLETE_ROLLBACK));
1150
831
  return(error);
1161
842
    the user has used LOCK TABLES then that mechanism does not know to do the
1162
843
    commit.
1163
844
*/
1164
 
int ha_autocommit_or_rollback(THD *thd, int error)
 
845
int ha_autocommit_or_rollback(Session *session, int error)
1165
846
{
1166
 
  if (thd->transaction.stmt.ha_list)
 
847
  if (session->transaction.stmt.ha_list)
1167
848
  {
1168
849
    if (!error)
1169
850
    {
1170
 
      if (ha_commit_trans(thd, 0))
1171
 
        error=1;
 
851
      if (ha_commit_trans(session, 0))
 
852
        error=1;
1172
853
    }
1173
 
    else 
 
854
    else
1174
855
    {
1175
 
      (void) ha_rollback_trans(thd, 0);
1176
 
      if (thd->transaction_rollback_request && !thd->in_sub_stmt)
1177
 
        (void) ha_rollback(thd);
 
856
      (void) ha_rollback_trans(session, 0);
 
857
      if (session->transaction_rollback_request)
 
858
        (void) ha_rollback(session);
1178
859
    }
1179
860
 
1180
 
    thd->variables.tx_isolation=thd->session_tx_isolation;
 
861
    session->variables.tx_isolation=session->session_tx_isolation;
1181
862
  }
1182
863
  return(error);
1183
864
}
1184
865
 
1185
866
 
1186
 
struct xahton_st {
 
867
struct xaengine_st {
1187
868
  XID *xid;
1188
869
  int result;
1189
870
};
1190
871
 
1191
 
static bool xacommit_handlerton(THD *unused1 __attribute__((unused)),
1192
 
                                plugin_ref plugin,
1193
 
                                void *arg)
 
872
static bool xacommit_storage_engine(Session *,
 
873
                                    plugin_ref plugin,
 
874
                                    void *arg)
1194
875
{
1195
 
  handlerton *hton= plugin_data(plugin, handlerton *);
1196
 
  if (hton->state == SHOW_OPTION_YES && hton->recover)
 
876
  StorageEngine *engine= plugin_data(plugin, StorageEngine *);
 
877
  if (engine->is_enabled())
1197
878
  {
1198
 
    hton->commit_by_xid(hton, ((struct xahton_st *)arg)->xid);
1199
 
    ((struct xahton_st *)arg)->result= 0;
 
879
    engine->commit_by_xid(((struct xaengine_st *)arg)->xid);
 
880
    ((struct xaengine_st *)arg)->result= 0;
1200
881
  }
1201
882
  return false;
1202
883
}
1203
884
 
1204
 
static bool xarollback_handlerton(THD *unused1 __attribute__((unused)),
 
885
static bool xarollback_storage_engine(Session *,
1205
886
                                  plugin_ref plugin,
1206
887
                                  void *arg)
1207
888
{
1208
 
  handlerton *hton= plugin_data(plugin, handlerton *);
1209
 
  if (hton->state == SHOW_OPTION_YES && hton->recover)
 
889
  StorageEngine *engine= plugin_data(plugin, StorageEngine *);
 
890
  if (engine->is_enabled())
1210
891
  {
1211
 
    hton->rollback_by_xid(hton, ((struct xahton_st *)arg)->xid);
1212
 
    ((struct xahton_st *)arg)->result= 0;
 
892
    engine->rollback_by_xid(((struct xaengine_st *)arg)->xid);
 
893
    ((struct xaengine_st *)arg)->result= 0;
1213
894
  }
1214
895
  return false;
1215
896
}
1217
898
 
1218
899
int ha_commit_or_rollback_by_xid(XID *xid, bool commit)
1219
900
{
1220
 
  struct xahton_st xaop;
 
901
  struct xaengine_st xaop;
1221
902
  xaop.xid= xid;
1222
903
  xaop.result= 1;
1223
904
 
1224
 
  plugin_foreach(NULL, commit ? xacommit_handlerton : xarollback_handlerton,
 
905
  plugin_foreach(NULL, commit ? xacommit_storage_engine : xarollback_storage_engine,
1225
906
                 DRIZZLE_STORAGE_ENGINE_PLUGIN, &xaop);
1226
907
 
1227
908
  return xaop.result;
1251
932
  bool dry_run;
1252
933
};
1253
934
 
1254
 
static bool xarecover_handlerton(THD *unused __attribute__((unused)),
1255
 
                                 plugin_ref plugin,
1256
 
                                 void *arg)
 
935
static bool xarecover_storage_engine(Session *,
 
936
                                     plugin_ref plugin,
 
937
                                     void *arg)
1257
938
{
1258
 
  handlerton *hton= plugin_data(plugin, handlerton *);
 
939
  StorageEngine *engine= plugin_data(plugin, StorageEngine *);
1259
940
  struct xarecover_st *info= (struct xarecover_st *) arg;
1260
941
  int got;
1261
942
 
1262
 
  if (hton->state == SHOW_OPTION_YES && hton->recover)
 
943
  if (engine->is_enabled())
1263
944
  {
1264
 
    while ((got= hton->recover(hton, info->list, info->len)) > 0 )
 
945
    while ((got= engine->recover(info->list, info->len)) > 0 )
1265
946
    {
1266
 
      sql_print_information(_("Found %d prepared transaction(s) in %s"),
1267
 
                            got, ha_resolve_storage_engine_name(hton));
 
947
      errmsg_printf(ERRMSG_LVL_INFO, _("Found %d prepared transaction(s) in %s"),
 
948
                            got, ha_resolve_storage_engine_name(engine));
1268
949
      for (int i=0; i < got; i ++)
1269
950
      {
1270
951
        my_xid x=info->list[i].get_my_xid();
1284
965
            hash_search(info->commit_list, (unsigned char *)&x, sizeof(x)) != 0 :
1285
966
            tc_heuristic_recover == TC_HEURISTIC_RECOVER_COMMIT)
1286
967
        {
1287
 
          hton->commit_by_xid(hton, info->list+i);
 
968
          engine->commit_by_xid(info->list+i);
1288
969
        }
1289
970
        else
1290
971
        {
1291
 
          hton->rollback_by_xid(hton, info->list+i);
 
972
          engine->rollback_by_xid(info->list+i);
1292
973
        }
1293
974
      }
1294
975
      if (got < info->len)
1309
990
  /* commit_list and tc_heuristic_recover cannot be set both */
1310
991
  assert(info.commit_list==0 || tc_heuristic_recover==0);
1311
992
  /* if either is set, total_ha_2pc must be set too */
1312
 
  assert(info.dry_run || total_ha_2pc>(uint32_t)opt_bin_log);
 
993
  assert(info.dry_run);
1313
994
 
1314
 
  if (total_ha_2pc <= (uint32_t)opt_bin_log)
1315
 
    return(0);
 
995
  if (total_ha_2pc <= 1)
 
996
    return 0;
1316
997
 
1317
998
  if (info.commit_list)
1318
 
    sql_print_information(_("Starting crash recovery..."));
 
999
    errmsg_printf(ERRMSG_LVL_INFO, _("Starting crash recovery..."));
1319
1000
 
1320
1001
 
1321
1002
#ifndef WILL_BE_DELETED_LATER
1325
1006
    rollback all pending transactions, without risking inconsistent data
1326
1007
  */
1327
1008
 
1328
 
  assert(total_ha_2pc == (uint32_t) opt_bin_log+1); // only InnoDB and binlog
 
1009
  assert(total_ha_2pc == 2); // only InnoDB and binlog
1329
1010
  tc_heuristic_recover= TC_HEURISTIC_RECOVER_ROLLBACK; // forcing ROLLBACK
1330
1011
  info.dry_run=false;
1331
1012
#endif
1332
1013
 
1333
1014
 
1334
 
  for (info.len= MAX_XID_LIST_SIZE ; 
 
1015
  for (info.len= MAX_XID_LIST_SIZE ;
1335
1016
       info.list==0 && info.len > MIN_XID_LIST_SIZE; info.len/=2)
1336
1017
  {
1337
 
    info.list=(XID *)my_malloc(info.len*sizeof(XID), MYF(0));
 
1018
    info.list=(XID *)malloc(info.len*sizeof(XID));
1338
1019
  }
1339
1020
  if (!info.list)
1340
1021
  {
1341
 
    sql_print_error(ER(ER_OUTOFMEMORY), info.len*sizeof(XID));
 
1022
    errmsg_printf(ERRMSG_LVL_ERROR, ER(ER_OUTOFMEMORY), info.len*sizeof(XID));
1342
1023
    return(1);
1343
1024
  }
1344
1025
 
1345
 
  plugin_foreach(NULL, xarecover_handlerton, 
 
1026
  plugin_foreach(NULL, xarecover_storage_engine,
1346
1027
                 DRIZZLE_STORAGE_ENGINE_PLUGIN, &info);
1347
1028
 
1348
1029
  free((unsigned char*)info.list);
1349
1030
  if (info.found_foreign_xids)
1350
 
    sql_print_warning(_("Found %d prepared XA transactions"), 
1351
 
                      info.found_foreign_xids);
 
1031
    errmsg_printf(ERRMSG_LVL_WARN, _("Found %d prepared XA transactions"),
 
1032
                  info.found_foreign_xids);
1352
1033
  if (info.dry_run && info.found_my_xids)
1353
1034
  {
1354
 
    sql_print_error(_("Found %d prepared transactions! It means that drizzled "
 
1035
    errmsg_printf(ERRMSG_LVL_ERROR,
 
1036
                  _("Found %d prepared transactions! It means that drizzled "
1355
1037
                    "was not shut down properly last time and critical "
1356
1038
                    "recovery information (last binlog or %s file) was "
1357
1039
                    "manually deleted after a crash. You have to start "
1361
1043
    return(1);
1362
1044
  }
1363
1045
  if (info.commit_list)
1364
 
    sql_print_information(_("Crash recovery finished."));
 
1046
    errmsg_printf(ERRMSG_LVL_INFO, _("Crash recovery finished."));
1365
1047
  return(0);
1366
1048
}
1367
1049
 
1373
1055
    so mysql_xa_recover does not filter XID's to ensure uniqueness.
1374
1056
    It can be easily fixed later, if necessary.
1375
1057
*/
1376
 
bool mysql_xa_recover(THD *thd)
 
1058
bool mysql_xa_recover(Session *session)
1377
1059
{
1378
1060
  List<Item> field_list;
1379
 
  Protocol *protocol= thd->protocol;
 
1061
  Protocol *protocol= session->protocol;
1380
1062
  int i=0;
1381
1063
  XID_STATE *xs;
1382
1064
 
1409
1091
  }
1410
1092
 
1411
1093
  pthread_mutex_unlock(&LOCK_xid_cache);
1412
 
  my_eof(thd);
 
1094
  session->my_eof();
1413
1095
  return(0);
1414
1096
}
1415
1097
 
1417
1099
  @details
1418
1100
  This function should be called when MySQL sends rows of a SELECT result set
1419
1101
  or the EOF mark to the client. It releases a possible adaptive hash index
1420
 
  S-latch held by thd in InnoDB and also releases a possible InnoDB query
1421
 
  FIFO ticket to enter InnoDB. To save CPU time, InnoDB allows a thd to
 
1102
  S-latch held by session in InnoDB and also releases a possible InnoDB query
 
1103
  FIFO ticket to enter InnoDB. To save CPU time, InnoDB allows a session to
1422
1104
  keep them over several calls of the InnoDB handler interface when a join
1423
1105
  is executed. But when we let the control to pass to the client they have
1424
1106
  to be released because if the application program uses mysql_use_result(),
1426
1108
  performs another SQL query. In MySQL-4.1 this is even more important because
1427
1109
  there a connection can have several SELECT queries open at the same time.
1428
1110
 
1429
 
  @param thd           the thread handle of the current connection
 
1111
  @param session           the thread handle of the current connection
1430
1112
 
1431
1113
  @return
1432
1114
    always 0
1433
1115
*/
1434
 
static bool release_temporary_latches(THD *thd, plugin_ref plugin,
1435
 
                                      void *unused __attribute__((unused)))
 
1116
static bool release_temporary_latches(Session *session, plugin_ref plugin,
 
1117
                                      void *)
1436
1118
{
1437
 
  handlerton *hton= plugin_data(plugin, handlerton *);
 
1119
  StorageEngine *engine= plugin_data(plugin, StorageEngine *);
1438
1120
 
1439
 
  if (hton->state == SHOW_OPTION_YES && hton->release_temporary_latches)
1440
 
    hton->release_temporary_latches(hton, thd);
 
1121
  if (engine->is_enabled())
 
1122
    engine->release_temporary_latches(session);
1441
1123
 
1442
1124
  return false;
1443
1125
}
1444
1126
 
1445
1127
 
1446
 
int ha_release_temporary_latches(THD *thd)
 
1128
int ha_release_temporary_latches(Session *session)
1447
1129
{
1448
 
  plugin_foreach(thd, release_temporary_latches, DRIZZLE_STORAGE_ENGINE_PLUGIN, 
 
1130
  plugin_foreach(session, release_temporary_latches, DRIZZLE_STORAGE_ENGINE_PLUGIN,
1449
1131
                 NULL);
1450
1132
 
1451
1133
  return 0;
1452
1134
}
1453
1135
 
1454
 
int ha_rollback_to_savepoint(THD *thd, SAVEPOINT *sv)
 
1136
int ha_rollback_to_savepoint(Session *session, SAVEPOINT *sv)
1455
1137
{
1456
1138
  int error=0;
1457
 
  THD_TRANS *trans= (thd->in_sub_stmt ? &thd->transaction.stmt :
1458
 
                                        &thd->transaction.all);
 
1139
  Session_TRANS *trans= &session->transaction.all;
1459
1140
  Ha_trx_info *ha_info, *ha_info_next;
1460
1141
 
1461
1142
  trans->no_2pc=0;
1466
1147
  for (ha_info= sv->ha_list; ha_info; ha_info= ha_info->next())
1467
1148
  {
1468
1149
    int err;
1469
 
    handlerton *ht= ha_info->ht();
1470
 
    assert(ht);
1471
 
    assert(ht->savepoint_set != 0);
1472
 
    if ((err= ht->savepoint_rollback(ht, thd,
1473
 
                                     (unsigned char *)(sv+1)+ht->savepoint_offset)))
 
1150
    StorageEngine *engine= ha_info->engine();
 
1151
    assert(engine);
 
1152
    if ((err= engine->savepoint_rollback(session,
 
1153
                                         (void *)(sv+1))))
1474
1154
    { // cannot happen
1475
1155
      my_error(ER_ERROR_DURING_ROLLBACK, MYF(0), err);
1476
1156
      error=1;
1477
1157
    }
1478
 
    status_var_increment(thd->status_var.ha_savepoint_rollback_count);
1479
 
    trans->no_2pc|= ht->prepare == 0;
 
1158
    status_var_increment(session->status_var.ha_savepoint_rollback_count);
 
1159
    trans->no_2pc|= not engine->has_2pc();
1480
1160
  }
1481
1161
  /*
1482
1162
    rolling back the transaction in all storage engines that were not part of
1486
1166
       ha_info= ha_info_next)
1487
1167
  {
1488
1168
    int err;
1489
 
    handlerton *ht= ha_info->ht();
1490
 
    if ((err= ht->rollback(ht, thd, !thd->in_sub_stmt)))
 
1169
    StorageEngine *engine= ha_info->engine();
 
1170
    if ((err= engine->rollback(session, !(0))))
1491
1171
    { // cannot happen
1492
1172
      my_error(ER_ERROR_DURING_ROLLBACK, MYF(0), err);
1493
1173
      error=1;
1494
1174
    }
1495
 
    status_var_increment(thd->status_var.ha_rollback_count);
 
1175
    status_var_increment(session->status_var.ha_rollback_count);
1496
1176
    ha_info_next= ha_info->next();
1497
1177
    ha_info->reset(); /* keep it conveniently zero-filled */
1498
1178
  }
1506
1186
  section "4.33.4 SQL-statements and transaction states",
1507
1187
  SAVEPOINT is *not* transaction-initiating SQL-statement
1508
1188
*/
1509
 
int ha_savepoint(THD *thd, SAVEPOINT *sv)
 
1189
int ha_savepoint(Session *session, SAVEPOINT *sv)
1510
1190
{
1511
1191
  int error=0;
1512
 
  THD_TRANS *trans= (thd->in_sub_stmt ? &thd->transaction.stmt :
1513
 
                                        &thd->transaction.all);
 
1192
  Session_TRANS *trans= &session->transaction.all;
1514
1193
  Ha_trx_info *ha_info= trans->ha_list;
1515
1194
  for (; ha_info; ha_info= ha_info->next())
1516
1195
  {
1517
1196
    int err;
1518
 
    handlerton *ht= ha_info->ht();
1519
 
    assert(ht);
1520
 
    if (! ht->savepoint_set)
 
1197
    StorageEngine *engine= ha_info->engine();
 
1198
    assert(engine);
 
1199
/*    if (! engine->savepoint_set)
1521
1200
    {
1522
1201
      my_error(ER_CHECK_NOT_IMPLEMENTED, MYF(0), "SAVEPOINT");
1523
1202
      error=1;
1524
1203
      break;
1525
 
    }
1526
 
    if ((err= ht->savepoint_set(ht, thd, (unsigned char *)(sv+1)+ht->savepoint_offset)))
 
1204
    } */
 
1205
    if ((err= engine->savepoint_set(session, (void *)(sv+1))))
1527
1206
    { // cannot happen
1528
1207
      my_error(ER_GET_ERRNO, MYF(0), err);
1529
1208
      error=1;
1530
1209
    }
1531
 
    status_var_increment(thd->status_var.ha_savepoint_count);
 
1210
    status_var_increment(session->status_var.ha_savepoint_count);
1532
1211
  }
1533
1212
  /*
1534
1213
    Remember the list of registered storage engines. All new
1538
1217
  return(error);
1539
1218
}
1540
1219
 
1541
 
int ha_release_savepoint(THD *thd, SAVEPOINT *sv)
 
1220
int ha_release_savepoint(Session *session, SAVEPOINT *sv)
1542
1221
{
1543
1222
  int error=0;
1544
1223
  Ha_trx_info *ha_info= sv->ha_list;
1546
1225
  for (; ha_info; ha_info= ha_info->next())
1547
1226
  {
1548
1227
    int err;
1549
 
    handlerton *ht= ha_info->ht();
 
1228
    StorageEngine *engine= ha_info->engine();
1550
1229
    /* Savepoint life time is enclosed into transaction life time. */
1551
 
    assert(ht);
1552
 
    if (!ht->savepoint_release)
1553
 
      continue;
1554
 
    if ((err= ht->savepoint_release(ht, thd,
1555
 
                                    (unsigned char *)(sv+1) + ht->savepoint_offset)))
 
1230
    assert(engine);
 
1231
    if ((err= engine->savepoint_release(session,
 
1232
                                        (void *)(sv+1))))
1556
1233
    { // cannot happen
1557
1234
      my_error(ER_GET_ERRNO, MYF(0), err);
1558
1235
      error=1;
1562
1239
}
1563
1240
 
1564
1241
 
1565
 
static bool snapshot_handlerton(THD *thd, plugin_ref plugin, void *arg)
 
1242
static bool snapshot_storage_engine(Session *session, plugin_ref plugin, void *arg)
1566
1243
{
1567
 
  handlerton *hton= plugin_data(plugin, handlerton *);
1568
 
  if (hton->state == SHOW_OPTION_YES &&
1569
 
      hton->start_consistent_snapshot)
 
1244
  StorageEngine *engine= plugin_data(plugin, StorageEngine *);
 
1245
  if (engine->is_enabled())
1570
1246
  {
1571
 
    hton->start_consistent_snapshot(hton, thd);
 
1247
    engine->start_consistent_snapshot(session);
1572
1248
    *((bool *)arg)= false;
1573
1249
  }
1574
1250
  return false;
1575
1251
}
1576
1252
 
1577
 
int ha_start_consistent_snapshot(THD *thd)
 
1253
int ha_start_consistent_snapshot(Session *session)
1578
1254
{
1579
1255
  bool warn= true;
1580
1256
 
1581
 
  plugin_foreach(thd, snapshot_handlerton, DRIZZLE_STORAGE_ENGINE_PLUGIN, &warn);
 
1257
  plugin_foreach(session, snapshot_storage_engine, DRIZZLE_STORAGE_ENGINE_PLUGIN, &warn);
1582
1258
 
1583
1259
  /*
1584
1260
    Same idea as when one wants to CREATE TABLE in one engine which does not
1585
1261
    exist:
1586
1262
  */
1587
1263
  if (warn)
1588
 
    push_warning(thd, DRIZZLE_ERROR::WARN_LEVEL_WARN, ER_UNKNOWN_ERROR,
1589
 
                 "This MySQL server does not support any "
 
1264
    push_warning(session, DRIZZLE_ERROR::WARN_LEVEL_WARN, ER_UNKNOWN_ERROR,
 
1265
                 "This Drizzle server does not support any "
1590
1266
                 "consistent-read capable storage engine");
1591
1267
  return 0;
1592
1268
}
1593
1269
 
1594
1270
 
1595
 
static bool flush_handlerton(THD *thd __attribute__((unused)),
 
1271
static bool flush_storage_engine(Session *,
1596
1272
                             plugin_ref plugin,
1597
 
                             void *arg __attribute__((unused)))
 
1273
                             void *)
1598
1274
{
1599
 
  handlerton *hton= plugin_data(plugin, handlerton *);
1600
 
  if (hton->state == SHOW_OPTION_YES && hton->flush_logs && 
1601
 
      hton->flush_logs(hton))
 
1275
  StorageEngine *engine= plugin_data(plugin, StorageEngine *);
 
1276
  if (engine->is_enabled() &&
 
1277
      engine->flush_logs())
1602
1278
    return true;
1603
1279
  return false;
1604
1280
}
1605
1281
 
1606
1282
 
1607
 
bool ha_flush_logs(handlerton *db_type)
 
1283
bool ha_flush_logs(StorageEngine *engine)
1608
1284
{
1609
 
  if (db_type == NULL)
 
1285
  if (engine == NULL)
1610
1286
  {
1611
 
    if (plugin_foreach(NULL, flush_handlerton,
 
1287
    if (plugin_foreach(NULL, flush_storage_engine,
1612
1288
                          DRIZZLE_STORAGE_ENGINE_PLUGIN, 0))
1613
1289
      return true;
1614
1290
  }
1615
1291
  else
1616
1292
  {
1617
 
    if (db_type->state != SHOW_OPTION_YES ||
1618
 
        (db_type->flush_logs && db_type->flush_logs(db_type)))
 
1293
    if ((!engine->is_enabled()) ||
 
1294
        (engine->flush_logs()))
1619
1295
      return true;
1620
1296
  }
1621
1297
  return false;
1629
1305
 
1630
1306
  /* Ensure that table handler get path in lower case */
1631
1307
  if (tmp_path != path)
1632
 
    my_stpcpy(tmp_path, path);
 
1308
    strcpy(tmp_path, path);
1633
1309
 
1634
1310
  /*
1635
1311
    we only should turn into lowercase database/table part
1636
1312
    so start the process after homedirectory
1637
1313
  */
1638
 
  my_casedn_str(files_charset_info, tmp_path + mysql_data_home_len);
 
1314
  my_casedn_str(files_charset_info, tmp_path + drizzle_data_home_len);
1639
1315
  return tmp_path;
1640
1316
}
1641
1317
 
1649
1325
struct Ha_delete_table_error_handler: public Internal_error_handler
1650
1326
{
1651
1327
public:
 
1328
  Ha_delete_table_error_handler() : Internal_error_handler() {}
1652
1329
  virtual bool handle_error(uint32_t sql_errno,
1653
1330
                            const char *message,
1654
1331
                            DRIZZLE_ERROR::enum_warning_level level,
1655
 
                            THD *thd);
 
1332
                            Session *session);
1656
1333
  char buff[DRIZZLE_ERRMSG_SIZE];
1657
1334
};
1658
1335
 
1659
1336
 
1660
1337
bool
1661
1338
Ha_delete_table_error_handler::
1662
 
handle_error(uint32_t sql_errno  __attribute__((unused)),
 
1339
handle_error(uint32_t ,
1663
1340
             const char *message,
1664
 
             DRIZZLE_ERROR::enum_warning_level level __attribute__((unused)),
1665
 
             THD *thd __attribute__((unused)))
 
1341
             DRIZZLE_ERROR::enum_warning_level ,
 
1342
             Session *)
1666
1343
{
1667
1344
  /* Grab the error message */
1668
 
  strmake(buff, message, sizeof(buff)-1);
 
1345
  strncpy(buff, message, sizeof(buff)-1);
1669
1346
  return true;
1670
1347
}
1671
1348
 
1672
1349
 
 
1350
struct storage_engine_delete_table_args {
 
1351
  Session *session;
 
1352
  const char *path;
 
1353
  handler *file;
 
1354
  int error;
 
1355
};
 
1356
 
 
1357
static bool deletetable_storage_engine(Session *,
 
1358
                                       plugin_ref plugin,
 
1359
                                       void *args)
 
1360
{
 
1361
  struct storage_engine_delete_table_args *dtargs= (struct storage_engine_delete_table_args *) args;
 
1362
 
 
1363
  Session *session= dtargs->session;
 
1364
  const char *path= dtargs->path;
 
1365
 
 
1366
  handler *file;
 
1367
  char tmp_path[FN_REFLEN];
 
1368
 
 
1369
  if(dtargs->error!=ENOENT) /* already deleted table */
 
1370
    return false;
 
1371
 
 
1372
  StorageEngine *engine= plugin_data(plugin, StorageEngine *);
 
1373
 
 
1374
  if (!engine)
 
1375
    return false;
 
1376
 
 
1377
  if (!engine->is_enabled())
 
1378
    return false;
 
1379
 
 
1380
  if ((file= engine->create(NULL, session->mem_root)))
 
1381
    file->init();
 
1382
  else
 
1383
    return false;
 
1384
 
 
1385
  path= check_lowercase_names(file, path, tmp_path);
 
1386
  int error= file->ha_delete_table(path);
 
1387
 
 
1388
  if(error!=ENOENT)
 
1389
  {
 
1390
    dtargs->error= error;
 
1391
    if(dtargs->file)
 
1392
      delete dtargs->file;
 
1393
    dtargs->file= file;
 
1394
    return true;
 
1395
  }
 
1396
  else
 
1397
    delete file;
 
1398
 
 
1399
  return false;
 
1400
}
 
1401
 
1673
1402
/**
1674
1403
  This should return ENOENT if the file doesn't exists.
1675
1404
  The .frm file will be deleted only if we return 0 or ENOENT
1676
1405
*/
1677
 
int ha_delete_table(THD *thd, handlerton *table_type, const char *path,
 
1406
int ha_delete_table(Session *session, const char *path,
1678
1407
                    const char *db, const char *alias, bool generate_warning)
1679
1408
{
1680
 
  handler *file;
1681
 
  char tmp_path[FN_REFLEN];
1682
 
  int error;
 
1409
  TABLE_SHARE dummy_share;
1683
1410
  Table dummy_table;
1684
 
  TABLE_SHARE dummy_share;
 
1411
 
 
1412
  struct storage_engine_delete_table_args dtargs;
 
1413
  dtargs.error= ENOENT;
 
1414
  dtargs.session= session;
 
1415
  dtargs.path= path;
 
1416
  dtargs.file= NULL;
 
1417
 
 
1418
  plugin_foreach(NULL, deletetable_storage_engine, DRIZZLE_STORAGE_ENGINE_PLUGIN,
 
1419
                 &dtargs);
1685
1420
 
1686
1421
  memset(&dummy_table, 0, sizeof(dummy_table));
1687
1422
  memset(&dummy_share, 0, sizeof(dummy_share));
1688
1423
  dummy_table.s= &dummy_share;
1689
1424
 
1690
 
  /* DB_TYPE_UNKNOWN is used in ALTER Table when renaming only .frm files */
1691
 
  if (table_type == NULL ||
1692
 
      ! (file=get_new_handler((TABLE_SHARE*)0, thd->mem_root, table_type)))
1693
 
    return(ENOENT);
1694
 
 
1695
 
  path= check_lowercase_names(file, path, tmp_path);
1696
 
  if ((error= file->ha_delete_table(path)) && generate_warning)
 
1425
  if (dtargs.error && generate_warning)
1697
1426
  {
1698
1427
    /*
1699
1428
      Because file->print_error() use my_error() to generate the error message
1712
1441
    dummy_share.table_name.length= strlen(alias);
1713
1442
    dummy_table.alias= alias;
1714
1443
 
1715
 
    file->change_table_ptr(&dummy_table, &dummy_share);
1716
 
 
1717
 
    thd->push_internal_handler(&ha_delete_table_error_handler);
1718
 
    file->print_error(error, 0);
1719
 
 
1720
 
    thd->pop_internal_handler();
 
1444
    if(dtargs.file)
 
1445
    {
 
1446
      handler *file= dtargs.file;
 
1447
      file->change_table_ptr(&dummy_table, &dummy_share);
 
1448
 
 
1449
      session->push_internal_handler(&ha_delete_table_error_handler);
 
1450
      file->print_error(dtargs.error, 0);
 
1451
 
 
1452
      session->pop_internal_handler();
 
1453
    }
 
1454
    else
 
1455
      dtargs.error= -1; /* General form of fail. maybe bad FRM */
1721
1456
 
1722
1457
    /*
1723
1458
      XXX: should we convert *all* errors to warnings here?
1724
1459
      What if the error is fatal?
1725
1460
    */
1726
 
    push_warning(thd, DRIZZLE_ERROR::WARN_LEVEL_ERROR, error,
 
1461
    push_warning(session, DRIZZLE_ERROR::WARN_LEVEL_ERROR, dtargs.error,
1727
1462
                ha_delete_table_error_handler.buff);
1728
1463
  }
1729
 
  delete file;
1730
 
  return(error);
 
1464
 
 
1465
  if(dtargs.file)
 
1466
    delete dtargs.file;
 
1467
 
 
1468
  return dtargs.error;
1731
1469
}
1732
1470
 
1733
1471
/****************************************************************************
1738
1476
  handler *new_handler= get_new_handler(table->s, mem_root, table->s->db_type());
1739
1477
  /*
1740
1478
    Allocate handler->ref here because otherwise ha_open will allocate it
1741
 
    on this->table->mem_root and we will not be able to reclaim that memory 
 
1479
    on this->table->mem_root and we will not be able to reclaim that memory
1742
1480
    when the clone handler object is destroyed.
1743
1481
  */
1744
1482
  if (!(new_handler->ref= (unsigned char*) alloc_root(mem_root, ALIGN_SIZE(ref_length)*2)))
1751
1489
  return NULL;
1752
1490
}
1753
1491
 
1754
 
 
 
1492
int handler::ha_index_init(uint32_t idx, bool sorted)
 
1493
{
 
1494
  int result;
 
1495
  assert(inited==NONE);
 
1496
  if (!(result= index_init(idx, sorted)))
 
1497
    inited=INDEX;
 
1498
  end_range= NULL;
 
1499
  return(result);
 
1500
}
 
1501
 
 
1502
int handler::ha_index_end()
 
1503
{
 
1504
  assert(inited==INDEX);
 
1505
  inited=NONE;
 
1506
  end_range= NULL;
 
1507
  return(index_end());
 
1508
}
 
1509
 
 
1510
int handler::ha_rnd_init(bool scan)
 
1511
{
 
1512
  int result;
 
1513
  assert(inited==NONE || (inited==RND && scan));
 
1514
  inited= (result= rnd_init(scan)) ? NONE: RND;
 
1515
  return(result);
 
1516
}
 
1517
 
 
1518
int handler::ha_rnd_end()
 
1519
{
 
1520
  assert(inited==RND);
 
1521
  inited=NONE;
 
1522
  return(rnd_end());
 
1523
}
 
1524
 
 
1525
int handler::ha_index_or_rnd_end()
 
1526
{
 
1527
  return inited == INDEX ? ha_index_end() : inited == RND ? ha_rnd_end() : 0;
 
1528
}
 
1529
 
 
1530
handler::Table_flags handler::ha_table_flags() const
 
1531
{
 
1532
  return cached_table_flags;
 
1533
}
 
1534
 
 
1535
void handler::ha_start_bulk_insert(ha_rows rows)
 
1536
{
 
1537
  estimation_rows_to_insert= rows;
 
1538
  start_bulk_insert(rows);
 
1539
}
 
1540
 
 
1541
int handler::ha_end_bulk_insert()
 
1542
{
 
1543
  estimation_rows_to_insert= 0;
 
1544
  return end_bulk_insert();
 
1545
}
 
1546
 
 
1547
void handler::change_table_ptr(Table *table_arg, TABLE_SHARE *share)
 
1548
{
 
1549
  table= table_arg;
 
1550
  table_share= share;
 
1551
}
 
1552
 
 
1553
const key_map *handler::keys_to_use_for_scanning()
 
1554
{
 
1555
  return &key_map_empty;
 
1556
}
 
1557
 
 
1558
bool handler::has_transactions()
 
1559
{
 
1560
  return (ha_table_flags() & HA_NO_TRANSACTIONS) == 0;
 
1561
}
1755
1562
 
1756
1563
void handler::ha_statistic_increment(ulong SSV::*offset) const
1757
1564
{
1758
1565
  status_var_increment(table->in_use->status_var.*offset);
1759
1566
}
1760
1567
 
1761
 
void **handler::ha_data(THD *thd) const
1762
 
{
1763
 
  return thd_ha_data(thd, ht);
1764
 
}
1765
 
 
1766
 
THD *handler::ha_thd(void) const
1767
 
{
1768
 
  assert(!table || !table->in_use || table->in_use == current_thd);
1769
 
  return (table && table->in_use) ? table->in_use : current_thd;
1770
 
}
 
1568
void **handler::ha_data(Session *session) const
 
1569
{
 
1570
  return session_ha_data(session, engine);
 
1571
}
 
1572
 
 
1573
Session *handler::ha_session(void) const
 
1574
{
 
1575
  assert(!table || !table->in_use || table->in_use == current_session);
 
1576
  return (table && table->in_use) ? table->in_use : current_session;
 
1577
}
 
1578
 
 
1579
 
 
1580
bool handler::is_fatal_error(int error, uint32_t flags)
 
1581
{
 
1582
  if (!error ||
 
1583
      ((flags & HA_CHECK_DUP_KEY) &&
 
1584
       (error == HA_ERR_FOUND_DUPP_KEY ||
 
1585
        error == HA_ERR_FOUND_DUPP_UNIQUE)))
 
1586
    return false;
 
1587
  return true;
 
1588
}
 
1589
 
 
1590
 
 
1591
ha_rows handler::records() { return stats.records; }
1771
1592
 
1772
1593
/**
1773
1594
  Open database-handler.
1804
1625
    (void) extra(HA_EXTRA_NO_READCHECK);        // Not needed in SQL
1805
1626
 
1806
1627
    /* ref is already allocated for us if we're called from handler::clone() */
1807
 
    if (!ref && !(ref= (unsigned char*) alloc_root(&table->mem_root, 
 
1628
    if (!ref && !(ref= (unsigned char*) alloc_root(&table->mem_root,
1808
1629
                                          ALIGN_SIZE(ref_length)*2)))
1809
1630
    {
1810
1631
      close();
1898
1719
void handler::adjust_next_insert_id_after_explicit_value(uint64_t nr)
1899
1720
{
1900
1721
  /*
1901
 
    If we have set THD::next_insert_id previously and plan to insert an
 
1722
    If we have set Session::next_insert_id previously and plan to insert an
1902
1723
    explicitely-specified value larger than this, we need to increase
1903
 
    THD::next_insert_id to be greater than the explicit value.
 
1724
    Session::next_insert_id to be greater than the explicit value.
1904
1725
  */
1905
1726
  if ((next_insert_id > 0) && (nr >= next_insert_id))
1906
1727
    set_next_insert_id(compute_next_insert_id(nr, &table->in_use->variables));
1976
1797
    again to reserve a new interval.
1977
1798
 
1978
1799
  - In both cases, the reserved intervals are remembered in
1979
 
    thd->auto_inc_intervals_in_cur_stmt_for_binlog if statement-based
 
1800
    session->auto_inc_intervals_in_cur_stmt_for_binlog if statement-based
1980
1801
    binlogging; the last reserved interval is remembered in
1981
1802
    auto_inc_interval_for_cur_row.
1982
1803
 
1990
1811
    start counting from the inserted value.
1991
1812
 
1992
1813
    This function's "outputs" are: the table's auto_increment field is filled
1993
 
    with a value, thd->next_insert_id is filled with the value to use for the
 
1814
    with a value, session->next_insert_id is filled with the value to use for the
1994
1815
    next row, if a value was autogenerated for the current row it is stored in
1995
 
    thd->insert_id_for_cur_row, if get_auto_increment() was called
1996
 
    thd->auto_inc_interval_for_cur_row is modified, if that interval is not
1997
 
    present in thd->auto_inc_intervals_in_cur_stmt_for_binlog it is added to
 
1816
    session->insert_id_for_cur_row, if get_auto_increment() was called
 
1817
    session->auto_inc_interval_for_cur_row is modified, if that interval is not
 
1818
    present in session->auto_inc_intervals_in_cur_stmt_for_binlog it is added to
1998
1819
    this list.
1999
1820
 
2000
1821
  @todo
2021
1842
{
2022
1843
  uint64_t nr, nb_reserved_values;
2023
1844
  bool append= false;
2024
 
  THD *thd= table->in_use;
2025
 
  struct system_variables *variables= &thd->variables;
 
1845
  Session *session= table->in_use;
 
1846
  struct system_variables *variables= &session->variables;
2026
1847
 
2027
1848
  /*
2028
1849
    next_insert_id is a "cursor" into the reserved interval, it may go greater
2047
1868
  {
2048
1869
    /* next_insert_id is beyond what is reserved, so we reserve more. */
2049
1870
    const Discrete_interval *forced=
2050
 
      thd->auto_inc_intervals_forced.get_next();
 
1871
      session->auto_inc_intervals_forced.get_next();
2051
1872
    if (forced != NULL)
2052
1873
    {
2053
1874
      nr= forced->minimum();
2060
1881
        handler::ha_start_bulk_insert(); if 0 it means "unknown".
2061
1882
      */
2062
1883
      uint32_t nb_already_reserved_intervals=
2063
 
        thd->auto_inc_intervals_in_cur_stmt_for_binlog.nb_elements();
 
1884
        session->auto_inc_intervals_in_cur_stmt_for_binlog.nb_elements();
2064
1885
      uint64_t nb_desired_values;
2065
1886
      /*
2066
1887
        If an estimation was given to the engine:
2081
1902
        /* avoid overflow in formula, with this if() */
2082
1903
        if (nb_already_reserved_intervals <= AUTO_INC_DEFAULT_NB_MAX_BITS)
2083
1904
        {
2084
 
          nb_desired_values= AUTO_INC_DEFAULT_NB_ROWS * 
 
1905
          nb_desired_values= AUTO_INC_DEFAULT_NB_ROWS *
2085
1906
            (1 << nb_already_reserved_intervals);
2086
 
          set_if_smaller(nb_desired_values, AUTO_INC_DEFAULT_NB_MAX);
 
1907
          set_if_smaller(nb_desired_values, (uint64_t)AUTO_INC_DEFAULT_NB_MAX);
2087
1908
        }
2088
1909
        else
2089
1910
          nb_desired_values= AUTO_INC_DEFAULT_NB_MAX;
2095
1916
                         &nb_reserved_values);
2096
1917
      if (nr == ~(uint64_t) 0)
2097
1918
        return(HA_ERR_AUTOINC_READ_FAILED);  // Mark failure
2098
 
      
 
1919
 
2099
1920
      /*
2100
1921
        That rounding below should not be needed when all engines actually
2101
1922
        respect offset and increment in get_auto_increment(). But they don't
2106
1927
      */
2107
1928
      nr= compute_next_insert_id(nr-1, variables);
2108
1929
    }
2109
 
    
 
1930
 
2110
1931
    if (table->s->next_number_keypart == 0)
2111
1932
    {
2112
1933
      /* We must defer the appending until "nr" has been possibly truncated */
2119
1940
    /*
2120
1941
      first test if the query was aborted due to strict mode constraints
2121
1942
    */
2122
 
    if (thd->killed == THD::KILL_BAD_DATA)
 
1943
    if (session->killed == Session::KILL_BAD_DATA)
2123
1944
      return(HA_ERR_AUTOINC_ERANGE);
2124
1945
 
2125
1946
    /*
2138
1959
  {
2139
1960
    auto_inc_interval_for_cur_row.replace(nr, nb_reserved_values,
2140
1961
                                          variables->auto_increment_increment);
2141
 
    /* Row-based replication does not need to store intervals in binlog */
2142
 
    if (!thd->current_stmt_binlog_row_based)
2143
 
        thd->auto_inc_intervals_in_cur_stmt_for_binlog.append(auto_inc_interval_for_cur_row.minimum(),
2144
 
                                                              auto_inc_interval_for_cur_row.values(),
2145
 
                                                              variables->auto_increment_increment);
2146
1962
  }
2147
1963
 
2148
1964
  /*
2196
2012
  @param first_value         (OUT) the first value reserved by the handler
2197
2013
  @param nb_reserved_values  (OUT) how many values the handler reserved
2198
2014
*/
2199
 
void handler::get_auto_increment(uint64_t offset __attribute__((unused)),
2200
 
                                 uint64_t increment __attribute__((unused)),
2201
 
                                 uint64_t nb_desired_values __attribute__((unused)),
 
2015
void handler::get_auto_increment(uint64_t ,
 
2016
                                 uint64_t ,
 
2017
                                 uint64_t ,
2202
2018
                                 uint64_t *first_value,
2203
2019
                                 uint64_t *nb_reserved_values)
2204
2020
{
2281
2097
  else
2282
2098
  {
2283
2099
    /* Table is opened and defined at this point */
2284
 
    key_unpack(&str,table,(uint) key_nr);
2285
 
    uint32_t max_length=DRIZZLE_ERRMSG_SIZE-(uint) strlen(msg);
 
2100
    key_unpack(&str,table,(uint32_t) key_nr);
 
2101
    uint32_t max_length=DRIZZLE_ERRMSG_SIZE-(uint32_t) strlen(msg);
2286
2102
    if (str.length() >= max_length)
2287
2103
    {
2288
2104
      str.length(max_length-4);
2345
2161
      char key[MAX_KEY_LENGTH];
2346
2162
      String str(key,sizeof(key),system_charset_info);
2347
2163
      /* Table is opened and defined at this point */
2348
 
      key_unpack(&str,table,(uint) key_nr);
 
2164
      key_unpack(&str,table,(uint32_t) key_nr);
2349
2165
      max_length= (DRIZZLE_ERRMSG_SIZE-
2350
 
                   (uint) strlen(ER(ER_FOREIGN_DUPLICATE_KEY)));
 
2166
                   (uint32_t) strlen(ER(ER_FOREIGN_DUPLICATE_KEY)));
2351
2167
      if (str.length() >= max_length)
2352
2168
      {
2353
2169
        str.length(max_length-4);
2461
2277
    my_message(ER_LOCK_OR_ACTIVE_TRANSACTION,
2462
2278
               ER(ER_LOCK_OR_ACTIVE_TRANSACTION), MYF(0));
2463
2279
    return;
2464
 
    break;
2465
2280
  default:
2466
2281
    {
2467
2282
      /* The error was "unknown" to this function.
2471
2286
      temporary= get_error_message(error, &str);
2472
2287
      if (!str.is_empty())
2473
2288
      {
2474
 
        const char* engine= table_type();
2475
 
        if (temporary)
2476
 
          my_error(ER_GET_TEMPORARY_ERRMSG, MYF(0), error, str.ptr(), engine);
2477
 
        else
2478
 
          my_error(ER_GET_ERRMSG, MYF(0), error, str.ptr(), engine);
 
2289
              const char* engine_name= table_type();
 
2290
              if (temporary)
 
2291
                my_error(ER_GET_TEMPORARY_ERRMSG, MYF(0), error, str.ptr(),
 
2292
                   engine_name);
 
2293
              else
 
2294
                my_error(ER_GET_ERRMSG, MYF(0), error, str.ptr(), engine_name);
2479
2295
      }
2480
2296
      else
2481
 
        my_error(ER_GET_ERRNO,errflag,error);
 
2297
      {
 
2298
              my_error(ER_GET_ERRNO,errflag,error);
 
2299
      }
2482
2300
      return;
2483
2301
    }
2484
2302
  }
2496
2314
  @return
2497
2315
    Returns true if this is a temporary error
2498
2316
*/
2499
 
bool handler::get_error_message(int error __attribute__((unused)),
2500
 
                                String* buf __attribute__((unused)))
 
2317
bool handler::get_error_message(int ,
 
2318
                                String* )
2501
2319
{
2502
2320
  return false;
2503
2321
}
2524
2342
        Field *field= table->field[keypart->fieldnr-1];
2525
2343
        if (field->type() == DRIZZLE_TYPE_BLOB)
2526
2344
        {
2527
 
          if (check_opt->sql_flags & TT_FOR_UPGRADE)
2528
 
            check_opt->flags= T_MEDIUM;
2529
2345
          return HA_ADMIN_NEEDS_CHECK;
2530
2346
        }
2531
2347
      }
2541
2357
  return 0;
2542
2358
}
2543
2359
 
2544
 
 
2545
 
static bool update_frm_version(Table *table)
2546
 
{
2547
 
  char path[FN_REFLEN];
2548
 
  File file;
2549
 
  bool result= true;
2550
 
 
2551
 
  /*
2552
 
    No need to update frm version in case table was created or checked
2553
 
    by server with the same version. This also ensures that we do not
2554
 
    update frm version for temporary tables as this code doesn't support
2555
 
    temporary tables.
2556
 
  */
2557
 
  if (table->s->mysql_version == DRIZZLE_VERSION_ID)
2558
 
    return(0);
2559
 
 
2560
 
  strxmov(path, table->s->normalized_path.str, reg_ext, NULL);
2561
 
 
2562
 
  if ((file= my_open(path, O_RDWR|O_BINARY, MYF(MY_WME))) >= 0)
2563
 
  {
2564
 
    unsigned char version[4];
2565
 
    char *key= table->s->table_cache_key.str;
2566
 
    uint32_t key_length= table->s->table_cache_key.length;
2567
 
    Table *entry;
2568
 
    HASH_SEARCH_STATE state;
2569
 
 
2570
 
    int4store(version, DRIZZLE_VERSION_ID);
2571
 
 
2572
 
    if (pwrite(file, (unsigned char*)version, 4, 51L) == 0)
2573
 
    {
2574
 
      result= false;
2575
 
      goto err;
2576
 
    }
2577
 
 
2578
 
    for (entry=(Table*) hash_first(&open_cache,(unsigned char*) key,key_length, &state);
2579
 
         entry;
2580
 
         entry= (Table*) hash_next(&open_cache,(unsigned char*) key,key_length, &state))
2581
 
      entry->s->mysql_version= DRIZZLE_VERSION_ID;
2582
 
  }
2583
 
err:
2584
 
  if (file >= 0)
2585
 
    my_close(file,MYF(MY_WME));
2586
 
  return(result);
2587
 
}
2588
 
 
2589
 
 
2590
 
 
2591
2360
/**
2592
2361
  @return
2593
2362
    key if error because of duplicated keys
2594
2363
*/
2595
2364
uint32_t handler::get_dup_key(int error)
2596
2365
{
2597
 
  table->file->errkey  = (uint) -1;
 
2366
  table->file->errkey  = (uint32_t) -1;
2598
2367
  if (error == HA_ERR_FOUND_DUPP_KEY || error == HA_ERR_FOREIGN_DUPLICATE_KEY ||
2599
2368
      error == HA_ERR_FOUND_DUPP_UNIQUE ||
2600
2369
      error == HA_ERR_DROP_INDEX_FK)
2666
2435
/**
2667
2436
  Performs checks upon the table.
2668
2437
 
2669
 
  @param thd                thread doing CHECK Table operation
 
2438
  @param session                thread doing CHECK Table operation
2670
2439
  @param check_opt          options from the parser
2671
2440
 
2672
2441
  @retval
2678
2447
  @retval
2679
2448
    HA_ADMIN_NOT_IMPLEMENTED
2680
2449
*/
2681
 
int handler::ha_check(THD *thd, HA_CHECK_OPT *check_opt)
 
2450
int handler::ha_check(Session *session, HA_CHECK_OPT *check_opt)
2682
2451
{
2683
2452
  int error;
2684
2453
 
2685
 
  if ((table->s->mysql_version >= DRIZZLE_VERSION_ID) &&
2686
 
      (check_opt->sql_flags & TT_FOR_UPGRADE))
2687
 
    return 0;
2688
 
 
2689
2454
  if (table->s->mysql_version < DRIZZLE_VERSION_ID)
2690
2455
  {
2691
2456
    if ((error= check_old_types()))
2693
2458
    error= ha_check_for_upgrade(check_opt);
2694
2459
    if (error && (error != HA_ADMIN_NEEDS_CHECK))
2695
2460
      return error;
2696
 
    if (!error && (check_opt->sql_flags & TT_FOR_UPGRADE))
2697
 
      return 0;
2698
2461
  }
2699
 
  if ((error= check(thd, check_opt)))
 
2462
  if ((error= check(session, check_opt)))
2700
2463
    return error;
2701
 
  return update_frm_version(table);
 
2464
  return HA_ADMIN_OK;
2702
2465
}
2703
2466
 
2704
2467
/**
2710
2473
void
2711
2474
handler::mark_trx_read_write()
2712
2475
{
2713
 
  Ha_trx_info *ha_info= &ha_thd()->ha_data[ht->slot].ha_info[0];
 
2476
  Ha_trx_info *ha_info= &ha_session()->ha_data[engine->slot].ha_info[0];
2714
2477
  /*
2715
2478
    When a storage engine method is called, the transaction must
2716
2479
    have been started, unless it's a DDL call, for which the
2721
2484
  */
2722
2485
  if (ha_info->is_started())
2723
2486
  {
2724
 
    assert(has_transactions());
2725
2487
    /*
2726
2488
      table_share can be NULL in ha_delete_table(). See implementation
2727
2489
      of standalone function ha_delete_table() in sql_base.cc.
2738
2500
  @sa handler::repair()
2739
2501
*/
2740
2502
 
2741
 
int handler::ha_repair(THD* thd, HA_CHECK_OPT* check_opt)
 
2503
int handler::ha_repair(Session* session, HA_CHECK_OPT* check_opt)
2742
2504
{
2743
2505
  int result;
2744
2506
 
2745
2507
  mark_trx_read_write();
2746
2508
 
2747
 
  if ((result= repair(thd, check_opt)))
 
2509
  if ((result= repair(session, check_opt)))
2748
2510
    return result;
2749
 
  return update_frm_version(table);
 
2511
  return HA_ADMIN_OK;
2750
2512
}
2751
2513
 
2752
2514
 
2803
2565
*/
2804
2566
 
2805
2567
int
2806
 
handler::ha_optimize(THD* thd, HA_CHECK_OPT* check_opt)
 
2568
handler::ha_optimize(Session* session, HA_CHECK_OPT* check_opt)
2807
2569
{
2808
2570
  mark_trx_read_write();
2809
2571
 
2810
 
  return optimize(thd, check_opt);
 
2572
  return optimize(session, check_opt);
2811
2573
}
2812
2574
 
2813
2575
 
2818
2580
*/
2819
2581
 
2820
2582
int
2821
 
handler::ha_analyze(THD* thd, HA_CHECK_OPT* check_opt)
 
2583
handler::ha_analyze(Session* session, HA_CHECK_OPT* check_opt)
2822
2584
{
2823
2585
  mark_trx_read_write();
2824
2586
 
2825
 
  return analyze(thd, check_opt);
 
2587
  return analyze(session, check_opt);
2826
2588
}
2827
2589
 
2828
2590
 
2833
2595
*/
2834
2596
 
2835
2597
bool
2836
 
handler::ha_check_and_repair(THD *thd)
 
2598
handler::ha_check_and_repair(Session *session)
2837
2599
{
2838
2600
  mark_trx_read_write();
2839
2601
 
2840
 
  return check_and_repair(thd);
 
2602
  return check_and_repair(session);
2841
2603
}
2842
2604
 
2843
2605
 
2955
2717
*/
2956
2718
 
2957
2719
int
2958
 
handler::ha_create(const char *name, Table *form, HA_CREATE_INFO *info)
 
2720
handler::ha_create(const char *name, Table *form, HA_CREATE_INFO *create_info)
2959
2721
{
2960
2722
  mark_trx_read_write();
2961
2723
 
2962
 
  return create(name, form, info);
 
2724
  return create(name, form, create_info);
2963
2725
}
2964
2726
 
2965
2727
 
2971
2733
 
2972
2734
int
2973
2735
handler::ha_create_handler_files(const char *name, const char *old_name,
2974
 
                        int action_flag, HA_CREATE_INFO *info)
 
2736
                                 int action_flag, HA_CREATE_INFO *create_info)
2975
2737
{
2976
2738
  mark_trx_read_write();
2977
2739
 
2978
 
  return create_handler_files(name, old_name, action_flag, info);
 
2740
  return create_handler_files(name, old_name, action_flag, create_info);
2979
2741
}
2980
2742
 
2981
2743
 
2987
2749
  starts to commit every now and then automatically.
2988
2750
  This hint can be safely ignored.
2989
2751
*/
2990
 
int ha_enable_transaction(THD *thd, bool on)
 
2752
int ha_enable_transaction(Session *session, bool on)
2991
2753
{
2992
2754
  int error=0;
2993
2755
 
2994
 
  if ((thd->transaction.on= on))
 
2756
  if ((session->transaction.on= on))
2995
2757
  {
2996
2758
    /*
2997
2759
      Now all storage engines should have transaction handling enabled.
2999
2761
      is an optimization hint that storage engine is free to ignore.
3000
2762
      So, let's commit an open transaction (if any) now.
3001
2763
    */
3002
 
    if (!(error= ha_commit_trans(thd, 0)))
3003
 
      error= end_trans(thd, COMMIT);
 
2764
    if (!(error= ha_commit_trans(session, 0)))
 
2765
      if (! session->endTransaction(COMMIT))
 
2766
        error= 1;
 
2767
 
3004
2768
  }
3005
2769
  return(error);
3006
2770
}
3068
2832
  @retval
3069
2833
   1  error
3070
2834
*/
3071
 
int ha_create_table(THD *thd, const char *path,
 
2835
int ha_create_table(Session *session, const char *path,
3072
2836
                    const char *db, const char *table_name,
3073
2837
                    HA_CREATE_INFO *create_info,
3074
2838
                    bool update_create_info)
3078
2842
  char name_buff[FN_REFLEN];
3079
2843
  const char *name;
3080
2844
  TABLE_SHARE share;
3081
 
  
3082
 
  init_tmp_table_share(thd, &share, db, 0, table_name, path);
3083
 
  if (open_table_def(thd, &share, 0) ||
3084
 
      open_table_from_share(thd, &share, "", 0, (uint) READ_ALL, 0, &table,
 
2845
 
 
2846
  init_tmp_table_share(session, &share, db, 0, table_name, path);
 
2847
  if (open_table_def(session, &share, 0) ||
 
2848
      open_table_from_share(session, &share, "", 0, (uint32_t) READ_ALL, 0, &table,
3085
2849
                            OTM_CREATE))
3086
2850
    goto err;
3087
2851
 
3091
2855
  name= check_lowercase_names(table.file, share.path.str, name_buff);
3092
2856
 
3093
2857
  error= table.file->ha_create(name, &table, create_info);
3094
 
  closefrm(&table, 0);
 
2858
  table.closefrm(false);
3095
2859
  if (error)
3096
2860
  {
3097
 
    strxmov(name_buff, db, ".", table_name, NULL);
 
2861
    sprintf(name_buff,"%s.%s",db,table_name);
3098
2862
    my_error(ER_CANT_CREATE_TABLE, MYF(ME_BELL+ME_WAITTANG), name_buff, error);
3099
2863
  }
3100
2864
err:
3102
2866
  return(error != 0);
3103
2867
}
3104
2868
 
3105
 
/**
3106
 
  Try to discover table from engine.
3107
 
 
3108
 
  @note
3109
 
    If found, write the frm file to disk.
3110
 
 
3111
 
  @retval
3112
 
  -1    Table did not exists
3113
 
  @retval
3114
 
   0    Table created ok
3115
 
  @retval
3116
 
   > 0  Error, table existed but could not be created
3117
 
*/
3118
 
int ha_create_table_from_engine(THD* thd, const char *db, const char *name)
3119
 
{
3120
 
  int error;
3121
 
  unsigned char *frmblob;
3122
 
  size_t frmlen;
3123
 
  char path[FN_REFLEN];
3124
 
  HA_CREATE_INFO create_info;
3125
 
  Table table;
3126
 
  TABLE_SHARE share;
3127
 
 
3128
 
  memset(&create_info, 0, sizeof(create_info));
3129
 
  if ((error= ha_discover(thd, db, name, &frmblob, &frmlen)))
3130
 
  {
3131
 
    /* Table could not be discovered and thus not created */
3132
 
    return(error);
3133
 
  }
3134
 
 
3135
 
  /*
3136
 
    Table exists in handler and could be discovered
3137
 
    frmblob and frmlen are set, write the frm to disk
3138
 
  */
3139
 
 
3140
 
  build_table_filename(path, FN_REFLEN-1, db, name, "", 0);
3141
 
  // Save the frm file
3142
 
  error= writefrm(path, frmblob, frmlen);
3143
 
  free(frmblob);
3144
 
  if (error)
3145
 
    return(2);
3146
 
 
3147
 
  init_tmp_table_share(thd, &share, db, 0, name, path);
3148
 
  if (open_table_def(thd, &share, 0))
3149
 
  {
3150
 
    return(3);
3151
 
  }
3152
 
  if (open_table_from_share(thd, &share, "" ,0, 0, 0, &table, OTM_OPEN))
3153
 
  {
3154
 
    free_table_share(&share);
3155
 
    return(3);
3156
 
  }
3157
 
 
3158
 
  table.updateCreateInfo(&create_info);
3159
 
  create_info.table_options|= HA_OPTION_CREATE_FROM_ENGINE;
3160
 
 
3161
 
  check_lowercase_names(table.file, path, path);
3162
 
  error=table.file->ha_create(path, &table, &create_info);
3163
 
  closefrm(&table, 1);
3164
 
 
3165
 
  return(error != 0);
3166
 
}
3167
 
 
3168
2869
void st_ha_check_opt::init()
3169
2870
{
3170
 
  flags= sql_flags= 0;
3171
 
  sort_buffer_size = current_thd->variables.myisam_sort_buff_size;
 
2871
  flags= 0; 
 
2872
  use_frm= false;
3172
2873
}
3173
2874
 
3174
2875
 
3185
2886
/**
3186
2887
  Init a key cache if it has not been initied before.
3187
2888
*/
3188
 
int ha_init_key_cache(const char *name __attribute__((unused)),
 
2889
int ha_init_key_cache(const char *,
3189
2890
                      KEY_CACHE *key_cache)
3190
2891
{
3191
2892
  if (!key_cache->key_cache_inited)
3192
2893
  {
3193
2894
    pthread_mutex_lock(&LOCK_global_system_variables);
3194
2895
    uint32_t tmp_buff_size= (uint32_t) key_cache->param_buff_size;
3195
 
    uint32_t tmp_block_size= (uint) key_cache->param_block_size;
 
2896
    uint32_t tmp_block_size= (uint32_t) key_cache->param_block_size;
3196
2897
    uint32_t division_limit= key_cache->param_division_limit;
3197
2898
    uint32_t age_threshold=  key_cache->param_age_threshold;
3198
2899
    pthread_mutex_unlock(&LOCK_global_system_variables);
3261
2962
  return 0;
3262
2963
}
3263
2964
 
3264
 
 
3265
 
/**
3266
 
  Try to discover one table from handler(s).
3267
 
 
3268
 
  @retval
3269
 
    -1   Table did not exists
3270
 
  @retval
3271
 
    0   OK. In this case *frmblob and *frmlen are set
3272
 
  @retval
3273
 
    >0   error.  frmblob and frmlen may not be set
3274
 
*/
3275
 
struct st_discover_args
3276
 
{
3277
 
  const char *db;
3278
 
  const char *name;
3279
 
  unsigned char **frmblob; 
3280
 
  size_t *frmlen;
3281
 
};
3282
 
 
3283
 
static bool discover_handlerton(THD *thd, plugin_ref plugin,
3284
 
                                void *arg)
3285
 
{
3286
 
  st_discover_args *vargs= (st_discover_args *)arg;
3287
 
  handlerton *hton= plugin_data(plugin, handlerton *);
3288
 
  if (hton->state == SHOW_OPTION_YES && hton->discover &&
3289
 
      (!(hton->discover(hton, thd, vargs->db, vargs->name, 
3290
 
                        vargs->frmblob, 
3291
 
                        vargs->frmlen))))
3292
 
    return true;
3293
 
 
3294
 
  return false;
3295
 
}
3296
 
 
3297
 
int ha_discover(THD *thd, const char *db, const char *name,
3298
 
                unsigned char **frmblob, size_t *frmlen)
3299
 
{
3300
 
  int error= -1; // Table does not exist in any handler
3301
 
  st_discover_args args= {db, name, frmblob, frmlen};
3302
 
 
3303
 
  if (is_prefix(name,tmp_file_prefix)) /* skip temporary tables */
3304
 
    return(error);
3305
 
 
3306
 
  if (plugin_foreach(thd, discover_handlerton,
3307
 
                 DRIZZLE_STORAGE_ENGINE_PLUGIN, &args))
3308
 
    error= 0;
3309
 
 
3310
 
  if (!error)
3311
 
    status_var_increment(thd->status_var.ha_discover_count);
3312
 
  return(error);
3313
 
}
3314
 
 
3315
 
 
3316
2965
/**
3317
2966
  Call this function in order to give the handler the possiblity
3318
2967
  to ask engine if there are any new tables that should be written to disk
3336
2985
  @retval
3337
2986
    \#                  Error code
3338
2987
*/
3339
 
struct st_table_exists_in_engine_args
 
2988
struct st_table_exists_in_storage_engine_args
3340
2989
{
3341
2990
  const char *db;
3342
2991
  const char *name;
3343
2992
  int err;
 
2993
  StorageEngine* engine;
3344
2994
};
3345
2995
 
3346
 
static bool table_exists_in_engine_handlerton(THD *thd, plugin_ref plugin,
 
2996
static bool table_exists_in_storage_engine(Session *session, plugin_ref plugin,
3347
2997
                                              void *arg)
3348
2998
{
3349
 
  st_table_exists_in_engine_args *vargs= (st_table_exists_in_engine_args *)arg;
3350
 
  handlerton *hton= plugin_data(plugin, handlerton *);
 
2999
  st_table_exists_in_storage_engine_args *vargs= (st_table_exists_in_storage_engine_args *)arg;
 
3000
  StorageEngine *engine= plugin_data(plugin, StorageEngine *);
3351
3001
 
3352
3002
  int err= HA_ERR_NO_SUCH_TABLE;
3353
3003
 
3354
 
  if (hton->state == SHOW_OPTION_YES && hton->table_exists_in_engine)
3355
 
    err = hton->table_exists_in_engine(hton, thd, vargs->db, vargs->name);
 
3004
  if (engine->is_enabled())
 
3005
    err = engine->table_exists_in_engine(session, vargs->db, vargs->name);
3356
3006
 
3357
3007
  vargs->err = err;
3358
3008
  if (vargs->err == HA_ERR_TABLE_EXIST)
 
3009
  {
 
3010
    vargs->engine= engine;
3359
3011
    return true;
 
3012
  }
3360
3013
 
3361
3014
  return false;
3362
3015
}
3363
3016
 
3364
 
int ha_table_exists_in_engine(THD* thd, const char* db, const char* name)
 
3017
int ha_table_exists_in_engine(Session* session,
 
3018
                              const char* db, const char* name,
 
3019
                              StorageEngine **engine)
3365
3020
{
3366
 
  st_table_exists_in_engine_args args= {db, name, HA_ERR_NO_SUCH_TABLE};
3367
 
  plugin_foreach(thd, table_exists_in_engine_handlerton,
 
3021
  st_table_exists_in_storage_engine_args args= {db, name, HA_ERR_NO_SUCH_TABLE, NULL};
 
3022
  plugin_foreach(session, table_exists_in_storage_engine,
3368
3023
                 DRIZZLE_STORAGE_ENGINE_PLUGIN, &args);
 
3024
 
 
3025
  if(args.err==HA_ERR_NO_SUCH_TABLE)
 
3026
  {
 
3027
    /* Default way of knowing if a table exists. (checking .frm exists) */
 
3028
 
 
3029
    char path[FN_REFLEN];
 
3030
    build_table_filename(path, sizeof(path),
 
3031
                         db, name, "", 0);
 
3032
    if (table_proto_exists(path)==EEXIST)
 
3033
      args.err= HA_ERR_TABLE_EXIST;
 
3034
    else
 
3035
      args.err= HA_ERR_NO_SUCH_TABLE;
 
3036
 
 
3037
    if(args.err==HA_ERR_TABLE_EXIST)
 
3038
    {
 
3039
      drizzle::Table table;
 
3040
      build_table_filename(path, sizeof(path),
 
3041
                           db, name, ".dfe", 0);
 
3042
      if(drizzle_read_table_proto(path, &table)==0)
 
3043
      {
 
3044
        LEX_STRING engine_name= { (char*)table.engine().name().c_str(),
 
3045
                                 strlen(table.engine().name().c_str()) };
 
3046
        plugin_ref plugin= ha_resolve_by_name(session, &engine_name);
 
3047
        if(plugin)
 
3048
          args.engine= plugin_data(plugin,StorageEngine *);
 
3049
      }
 
3050
    }
 
3051
  }
 
3052
 
 
3053
  if(engine)
 
3054
    *engine= args.engine;
 
3055
 
3369
3056
  return(args.err);
3370
3057
}
3371
3058
 
3390
3077
    Estimated cost of 'index only' scan
3391
3078
*/
3392
3079
 
3393
 
double handler::index_only_read_time(uint32_t keynr, double records)
 
3080
double handler::index_only_read_time(uint32_t keynr, double key_records)
3394
3081
{
3395
 
  double read_time;
3396
3082
  uint32_t keys_per_block= (stats.block_size/2/
3397
3083
                        (table->key_info[keynr].key_length + ref_length) + 1);
3398
 
  read_time=((double) (records + keys_per_block-1) /
3399
 
             (double) keys_per_block);
3400
 
  return read_time;
 
3084
  return ((double) (key_records + keys_per_block-1) /
 
3085
          (double) keys_per_block);
3401
3086
}
3402
3087
 
3403
3088
 
3424
3109
 
3425
3110
  @note
3426
3111
    This method (or an overriding one in a derived class) must check for
3427
 
    thd->killed and return HA_POS_ERROR if it is not zero. This is required
 
3112
    session->killed and return HA_POS_ERROR if it is not zero. This is required
3428
3113
    for a user to be able to interrupt the calculation by killing the
3429
3114
    connection/query.
3430
3115
 
3439
3124
ha_rows
3440
3125
handler::multi_range_read_info_const(uint32_t keyno, RANGE_SEQ_IF *seq,
3441
3126
                                     void *seq_init_param,
3442
 
                                     uint32_t n_ranges_arg __attribute__((unused)),
 
3127
                                     uint32_t ,
3443
3128
                                     uint32_t *bufsz, uint32_t *flags, COST_VECT *cost)
3444
3129
{
3445
3130
  KEY_MULTI_RANGE range;
3446
3131
  range_seq_t seq_it;
3447
3132
  ha_rows rows, total_rows= 0;
3448
3133
  uint32_t n_ranges=0;
3449
 
  THD *thd= current_thd;
3450
 
  
 
3134
  Session *session= current_session;
 
3135
 
3451
3136
  /* Default MRR implementation doesn't need buffer */
3452
3137
  *bufsz= 0;
3453
3138
 
3454
3139
  seq_it= seq->init(seq_init_param, n_ranges, *flags);
3455
3140
  while (!seq->next(seq_it, &range))
3456
3141
  {
3457
 
    if (unlikely(thd->killed != 0))
 
3142
    if (unlikely(session->killed != 0))
3458
3143
      return HA_POS_ERROR;
3459
 
    
 
3144
 
3460
3145
    n_ranges++;
3461
3146
    key_range *min_endp, *max_endp;
3462
3147
    {
3467
3152
      rows= 1; /* there can be at most one row */
3468
3153
    else
3469
3154
    {
3470
 
      if (HA_POS_ERROR == (rows= this->records_in_range(keyno, min_endp, 
 
3155
      if (HA_POS_ERROR == (rows= this->records_in_range(keyno, min_endp,
3471
3156
                                                        max_endp)))
3472
3157
      {
3473
3158
        /* Can't scan one range => can't do MRR scan at all */
3477
3162
    }
3478
3163
    total_rows += rows;
3479
3164
  }
3480
 
  
 
3165
 
3481
3166
  if (total_rows != HA_POS_ERROR)
3482
3167
  {
3483
3168
    /* The following calculation is the same as in multi_range_read_info(): */
3485
3170
    cost->zero();
3486
3171
    cost->avg_io_cost= 1; /* assume random seeks */
3487
3172
    if ((*flags & HA_MRR_INDEX_ONLY) && total_rows > 2)
3488
 
      cost->io_count= index_only_read_time(keyno, (uint)total_rows);
 
3173
      cost->io_count= index_only_read_time(keyno, (uint32_t)total_rows);
3489
3174
    else
3490
3175
      cost->io_count= read_time(keyno, n_ranges, total_rows);
3491
3176
    cost->cpu_cost= (double) total_rows / TIME_FOR_COMPARE + 0.01;
3550
3235
/**
3551
3236
  Initialize the MRR scan
3552
3237
 
3553
 
  Initialize the MRR scan. This function may do heavyweight scan 
 
3238
  Initialize the MRR scan. This function may do heavyweight scan
3554
3239
  initialization like row prefetching/sorting/etc (NOTE: but better not do
3555
3240
  it here as we may not need it, e.g. if we never satisfy WHERE clause on
3556
3241
  previous tables. For many implementations it would be natural to do such
3557
3242
  initializations in the first multi_read_range_next() call)
3558
3243
 
3559
3244
  mode is a combination of the following flags: HA_MRR_SORTED,
3560
 
  HA_MRR_INDEX_ONLY, HA_MRR_NO_ASSOCIATION 
 
3245
  HA_MRR_INDEX_ONLY, HA_MRR_NO_ASSOCIATION
3561
3246
 
3562
3247
  @param seq             Range sequence to be traversed
3563
3248
  @param seq_init_param  First parameter for seq->init()
3569
3254
    One must have called index_init() before calling this function. Several
3570
3255
    multi_range_read_init() calls may be made in course of one query.
3571
3256
 
3572
 
    Until WL#2623 is done (see its text, section 3.2), the following will 
 
3257
    Until WL#2623 is done (see its text, section 3.2), the following will
3573
3258
    also hold:
3574
3259
    The caller will guarantee that if "seq->init == mrr_ranges_array_init"
3575
3260
    then seq_init_param is an array of n_ranges KEY_MULTI_RANGE structures.
3576
3261
    This property will only be used by NDB handler until WL#2623 is done.
3577
 
     
 
3262
 
3578
3263
    Buffer memory management is done according to the following scenario:
3579
3264
    The caller allocates the buffer and provides it to the callee by filling
3580
3265
    the members of HANDLER_BUFFER structure.
3591
3276
int
3592
3277
handler::multi_range_read_init(RANGE_SEQ_IF *seq_funcs, void *seq_init_param,
3593
3278
                               uint32_t n_ranges, uint32_t mode,
3594
 
                               HANDLER_BUFFER *buf __attribute__((unused)))
 
3279
                               HANDLER_BUFFER *)
3595
3280
{
3596
3281
  mrr_iter= seq_funcs->init(seq_init_param, n_ranges, mode);
3597
3282
  mrr_funcs= *seq_funcs;
3669
3354
 
3670
3355
 
3671
3356
/* **************************************************************************
3672
 
 * DS-MRR implementation 
 
3357
 * DS-MRR implementation
3673
3358
 ***************************************************************************/
3674
3359
 
3675
3360
/**
3690
3375
  @retval other Error
3691
3376
*/
3692
3377
 
3693
 
int DsMrr_impl::dsmrr_init(handler *h, KEY *key,
 
3378
int DsMrr_impl::dsmrr_init(handler *h_in, KEY *key,
3694
3379
                           RANGE_SEQ_IF *seq_funcs, void *seq_init_param,
3695
3380
                           uint32_t n_ranges, uint32_t mode, HANDLER_BUFFER *buf)
3696
3381
{
3698
3383
  uint32_t keyno;
3699
3384
  Item *pushed_cond= NULL;
3700
3385
  handler *new_h2;
3701
 
  keyno= h->active_index;
 
3386
  keyno= h_in->active_index;
3702
3387
  assert(h2 == NULL);
3703
3388
  if (mode & HA_MRR_USE_DEFAULT_IMPL || mode & HA_MRR_SORTED)
3704
3389
  {
3705
3390
    use_default_impl= true;
3706
 
    return(h->handler::multi_range_read_init(seq_funcs, seq_init_param,
 
3391
    return(h_in->handler::multi_range_read_init(seq_funcs, seq_init_param,
3707
3392
                                                  n_ranges, mode, buf));
3708
3393
  }
3709
3394
  rowids_buf= buf->buffer;
3710
3395
  //psergey-todo: don't add key_length as it is not needed anymore
3711
 
  rowids_buf += key->key_length + h->ref_length;
 
3396
  rowids_buf += key->key_length + h_in->ref_length;
3712
3397
 
3713
3398
  is_mrr_assoc= !test(mode & HA_MRR_NO_ASSOCIATION);
3714
3399
  rowids_buf_end= buf->buffer_end;
3715
 
  
3716
 
  elem_size= h->ref_length + (int)is_mrr_assoc * sizeof(void*);
3717
 
  rowids_buf_last= rowids_buf + 
 
3400
 
 
3401
  elem_size= h_in->ref_length + (int)is_mrr_assoc * sizeof(void*);
 
3402
  rowids_buf_last= rowids_buf +
3718
3403
                      ((rowids_buf_end - rowids_buf)/ elem_size)*
3719
3404
                      elem_size;
3720
3405
  rowids_buf_end= rowids_buf_last;
3721
3406
 
3722
3407
  /* Create a separate handler object to do rndpos() calls. */
3723
 
  THD *thd= current_thd;
3724
 
  if (!(new_h2= h->clone(thd->mem_root)) || 
3725
 
      new_h2->ha_external_lock(thd, F_RDLCK))
 
3408
  Session *session= current_session;
 
3409
  if (!(new_h2= h_in->clone(session->mem_root)) ||
 
3410
      new_h2->ha_external_lock(session, F_RDLCK))
3726
3411
  {
3727
3412
    delete new_h2;
3728
3413
    return(1);
3729
3414
  }
3730
3415
 
3731
 
  if (keyno == h->pushed_idx_cond_keyno)
3732
 
    pushed_cond= h->pushed_idx_cond;
3733
 
  if (h->ha_index_end())
 
3416
  if (keyno == h_in->pushed_idx_cond_keyno)
 
3417
    pushed_cond= h_in->pushed_idx_cond;
 
3418
  if (h_in->ha_index_end())
3734
3419
  {
3735
3420
    new_h2= h2;
3736
3421
    goto error;
3740
3425
  table->prepare_for_position();
3741
3426
  new_h2->extra(HA_EXTRA_KEYREAD);
3742
3427
 
3743
 
  if (h2->ha_index_init(keyno, false) || 
 
3428
  if (h2->ha_index_init(keyno, false) ||
3744
3429
      h2->handler::multi_range_read_init(seq_funcs, seq_init_param, n_ranges,
3745
3430
                                         mode, buf))
3746
3431
    goto error;
3747
3432
  use_default_impl= false;
3748
 
  
 
3433
 
3749
3434
  if (pushed_cond)
3750
3435
    h2->idx_cond_push(keyno, pushed_cond);
3751
3436
  if (dsmrr_fill_buffer(new_h2))
3755
3440
    If the above call has scanned through all intervals in *seq, then
3756
3441
    adjust *buf to indicate that the remaining buffer space will not be used.
3757
3442
  */
3758
 
  if (dsmrr_eof) 
 
3443
  if (dsmrr_eof)
3759
3444
    buf->end_of_used_area= rowids_buf_last;
3760
3445
 
3761
 
  if (h->ha_rnd_init(false))
 
3446
  if (h_in->ha_rnd_init(false))
3762
3447
    goto error;
3763
 
  
 
3448
 
3764
3449
  return(0);
3765
3450
error:
3766
3451
  h2->ha_index_or_rnd_end();
3767
 
  h2->ha_external_lock(thd, F_UNLCK);
 
3452
  h2->ha_external_lock(session, F_UNLCK);
3768
3453
  h2->close();
3769
3454
  delete h2;
3770
3455
  return(1);
3775
3460
{
3776
3461
  if (h2)
3777
3462
  {
3778
 
    h2->ha_external_lock(current_thd, F_UNLCK);
 
3463
    h2->ha_external_lock(current_session, F_UNLCK);
3779
3464
    h2->close();
3780
3465
    delete h2;
3781
3466
    h2= NULL;
3795
3480
  DS-MRR: Fill the buffer with rowids and sort it by rowid
3796
3481
 
3797
3482
  {This is an internal function of DiskSweep MRR implementation}
3798
 
  Scan the MRR ranges and collect ROWIDs (or {ROWID, range_id} pairs) into 
3799
 
  buffer. When the buffer is full or scan is completed, sort the buffer by 
 
3483
  Scan the MRR ranges and collect ROWIDs (or {ROWID, range_id} pairs) into
 
3484
  buffer. When the buffer is full or scan is completed, sort the buffer by
3800
3485
  rowid and return.
3801
 
  
3802
 
  The function assumes that rowids buffer is empty when it is invoked. 
3803
 
  
 
3486
 
 
3487
  The function assumes that rowids buffer is empty when it is invoked.
 
3488
 
3804
3489
  @param h  Table handler
3805
3490
 
3806
3491
  @retval 0      OK, the next portion of rowids is in the buffer,
3808
3493
  @retval other  Error
3809
3494
*/
3810
3495
 
3811
 
int DsMrr_impl::dsmrr_fill_buffer(handler *unused __attribute__((unused)))
 
3496
int DsMrr_impl::dsmrr_fill_buffer(handler *)
3812
3497
{
3813
3498
  char *range_info;
3814
3499
  int res = 0;
3815
3500
 
3816
3501
  rowids_buf_cur= rowids_buf;
3817
 
  while ((rowids_buf_cur < rowids_buf_end) && 
 
3502
  while ((rowids_buf_cur < rowids_buf_end) &&
3818
3503
         !(res= h2->handler::multi_range_read_next(&range_info)))
3819
3504
  {
3820
3505
    /* Put rowid, or {rowid, range_id} pair into the buffer */
3830
3515
  }
3831
3516
 
3832
3517
  if (res && res != HA_ERR_END_OF_FILE)
3833
 
    return(res); 
 
3518
    return(res);
3834
3519
  dsmrr_eof= test(res == HA_ERR_END_OF_FILE);
3835
3520
 
3836
3521
  /* Sort the buffer contents by rowid */
3837
3522
  uint32_t elem_size= h->ref_length + (int)is_mrr_assoc * sizeof(void*);
3838
3523
  uint32_t n_rowids= (rowids_buf_cur - rowids_buf) / elem_size;
3839
 
  
 
3524
 
3840
3525
  my_qsort2(rowids_buf, n_rowids, elem_size, (qsort2_cmp)rowid_cmp,
3841
3526
            (void*)h);
3842
3527
  rowids_buf_last= rowids_buf_cur;
3849
3534
  DS-MRR implementation: multi_range_read_next() function
3850
3535
*/
3851
3536
 
3852
 
int DsMrr_impl::dsmrr_next(handler *h, char **range_info)
 
3537
int DsMrr_impl::dsmrr_next(handler *h_in, char **range_info)
3853
3538
{
3854
3539
  int res;
3855
 
  
 
3540
 
3856
3541
  if (use_default_impl)
3857
 
    return h->handler::multi_range_read_next(range_info);
3858
 
    
 
3542
    return h_in->handler::multi_range_read_next(range_info);
 
3543
 
3859
3544
  if (rowids_buf_cur == rowids_buf_last)
3860
3545
  {
3861
3546
    if (dsmrr_eof)
3867
3552
    if (res)
3868
3553
      goto end;
3869
3554
  }
3870
 
  
 
3555
 
3871
3556
  /* Return EOF if there are no rowids in the buffer after re-fill attempt */
3872
3557
  if (rowids_buf_cur == rowids_buf_last)
3873
3558
  {
3875
3560
    goto end;
3876
3561
  }
3877
3562
 
3878
 
  res= h->rnd_pos(table->record[0], rowids_buf_cur);
3879
 
  rowids_buf_cur += h->ref_length;
 
3563
  res= h_in->rnd_pos(table->record[0], rowids_buf_cur);
 
3564
  rowids_buf_cur += h_in->ref_length;
3880
3565
  if (is_mrr_assoc)
3881
3566
  {
3882
3567
    memcpy(range_info, rowids_buf_cur, sizeof(void*));
3895
3580
*/
3896
3581
int DsMrr_impl::dsmrr_info(uint32_t keyno, uint32_t n_ranges, uint32_t rows, uint32_t *bufsz,
3897
3582
                           uint32_t *flags, COST_VECT *cost)
3898
 
{  
 
3583
{
3899
3584
  int res;
3900
3585
  uint32_t def_flags= *flags;
3901
3586
  uint32_t def_bufsz= *bufsz;
3905
3590
                                         &def_flags, cost);
3906
3591
  assert(!res);
3907
3592
 
3908
 
  if ((*flags & HA_MRR_USE_DEFAULT_IMPL) || 
 
3593
  if ((*flags & HA_MRR_USE_DEFAULT_IMPL) ||
3909
3594
      choose_mrr_impl(keyno, rows, &def_flags, &def_bufsz, cost))
3910
3595
  {
3911
3596
    /* Default implementation is choosen */
3921
3606
*/
3922
3607
 
3923
3608
ha_rows DsMrr_impl::dsmrr_info_const(uint32_t keyno, RANGE_SEQ_IF *seq,
3924
 
                                 void *seq_init_param, uint32_t n_ranges, 
 
3609
                                 void *seq_init_param, uint32_t n_ranges,
3925
3610
                                 uint32_t *bufsz, uint32_t *flags, COST_VECT *cost)
3926
3611
{
3927
3612
  ha_rows rows;
3929
3614
  uint32_t def_bufsz= *bufsz;
3930
3615
  /* Get cost/flags/mem_usage of default MRR implementation */
3931
3616
  rows= h->handler::multi_range_read_info_const(keyno, seq, seq_init_param,
3932
 
                                                n_ranges, &def_bufsz, 
 
3617
                                                n_ranges, &def_bufsz,
3933
3618
                                                &def_flags, cost);
3934
3619
  if (rows == HA_POS_ERROR)
3935
3620
  {
4015
3700
{
4016
3701
  COST_VECT dsmrr_cost;
4017
3702
  bool res;
4018
 
  THD *thd= current_thd;
4019
 
  if ((thd->variables.optimizer_use_mrr == 2) || 
 
3703
  Session *session= current_session;
 
3704
  if ((session->variables.optimizer_use_mrr == 2) ||
4020
3705
      (*flags & HA_MRR_INDEX_ONLY) || (*flags & HA_MRR_SORTED) ||
4021
 
      (keyno == table->s->primary_key && 
4022
 
       h->primary_key_is_clustered()) || 
 
3706
      (keyno == table->s->primary_key &&
 
3707
       h->primary_key_is_clustered()) ||
4023
3708
       key_uses_partial_cols(keyno))
4024
3709
  {
4025
3710
    /* Use the default implementation */
4026
3711
    *flags |= HA_MRR_USE_DEFAULT_IMPL;
4027
3712
    return true;
4028
3713
  }
4029
 
  
4030
 
  uint32_t add_len= table->key_info[keyno].key_length + h->ref_length; 
 
3714
 
 
3715
  uint32_t add_len= table->key_info[keyno].key_length + h->ref_length;
4031
3716
  *bufsz -= add_len;
4032
3717
  if (get_disk_sweep_mrr_cost(keyno, rows, *flags, bufsz, &dsmrr_cost))
4033
3718
    return true;
4034
3719
  *bufsz += add_len;
4035
 
  
 
3720
 
4036
3721
  bool force_dsmrr;
4037
 
  /* 
 
3722
  /*
4038
3723
    If @@optimizer_use_mrr==force, then set cost of DS-MRR to be minimum of
4039
3724
    DS-MRR and Default implementations cost. This allows one to force use of
4040
3725
    DS-MRR whenever it is applicable without affecting other cost-based
4041
3726
    choices.
4042
3727
  */
4043
 
  if ((force_dsmrr= (thd->variables.optimizer_use_mrr == 1)) &&
 
3728
  if ((force_dsmrr= (session->variables.optimizer_use_mrr == 1)) &&
4044
3729
      dsmrr_cost.total_cost() > cost->total_cost())
4045
3730
    dsmrr_cost= *cost;
4046
3731
 
4092
3777
    return true; /* Buffer has not enough space for even 1 rowid */
4093
3778
 
4094
3779
  /* Number of iterations we'll make with full buffer */
4095
 
  n_full_steps= (uint)floor(rows2double(rows) / max_buff_entries);
4096
 
  
4097
 
  /* 
4098
 
    Get numbers of rows we'll be processing in 
4099
 
     - non-last sweep, with full buffer 
 
3780
  n_full_steps= (uint32_t)floor(rows2double(rows) / max_buff_entries);
 
3781
 
 
3782
  /*
 
3783
    Get numbers of rows we'll be processing in
 
3784
     - non-last sweep, with full buffer
4100
3785
     - last iteration, with non-full buffer
4101
3786
  */
4102
3787
  rows_in_full_step= max_buff_entries;
4103
3788
  rows_in_last_step= rows % max_buff_entries;
4104
 
  
 
3789
 
4105
3790
  /* Adjust buffer size if we expect to use only part of the buffer */
4106
3791
  if (n_full_steps)
4107
3792
  {
4111
3796
  else
4112
3797
  {
4113
3798
    cost->zero();
4114
 
    *buffer_size= cmax((ulong)*buffer_size, 
4115
 
                      (size_t)(1.2*rows_in_last_step) * elem_size + 
 
3799
    *buffer_size= cmax((ulong)*buffer_size,
 
3800
                      (size_t)(1.2*rows_in_last_step) * elem_size +
4116
3801
                      h->ref_length + table->key_info[keynr].key_length);
4117
3802
  }
4118
 
  
 
3803
 
4119
3804
  COST_VECT last_step_cost;
4120
3805
  get_sort_and_sweep_cost(table, rows_in_last_step, &last_step_cost);
4121
3806
  cost->add(&last_step_cost);
4122
 
 
 
3807
 
4123
3808
  if (n_full_steps != 0)
4124
3809
    cost->mem_cost= *buffer_size;
4125
3810
  else
4126
3811
    cost->mem_cost= (double)rows_in_last_step * elem_size;
4127
 
  
 
3812
 
4128
3813
  /* Total cost of all index accesses */
4129
3814
  index_read_cost= h->index_only_read_time(keynr, (double)rows);
4130
3815
  cost->add_io(index_read_cost, 1 /* Random seeks */);
4132
3817
}
4133
3818
 
4134
3819
 
4135
 
/* 
 
3820
/*
4136
3821
  Get cost of one sort-and-sweep step
4137
3822
 
4138
3823
  SYNOPSIS
4147
3832
     - read #nrows records from table in a sweep.
4148
3833
*/
4149
3834
 
4150
 
static 
 
3835
static
4151
3836
void get_sort_and_sweep_cost(Table *table, ha_rows nrows, COST_VECT *cost)
4152
3837
{
4153
3838
  if (nrows)
4181
3866
  Time to move the disk head is proportional to head travel distance.
4182
3867
 
4183
3868
  Time to wait for the plate to rotate depends on whether the disk head
4184
 
  was moved or not. 
 
3869
  was moved or not.
4185
3870
 
4186
3871
  If disk head wasn't moved, the wait time is proportional to distance
4187
3872
  between the previous block and the block we're reading.
4192
3877
 
4193
3878
  Our cost units are "random disk seeks". The cost of random disk seek is
4194
3879
  actually not a constant, it depends one range of cylinders we're going
4195
 
  to access. We make it constant by introducing a fuzzy concept of "typical 
 
3880
  to access. We make it constant by introducing a fuzzy concept of "typical
4196
3881
  datafile length" (it's fuzzy as it's hard to tell whether it should
4197
3882
  include index file, temp.tables etc). Then random seek cost is:
4198
3883
 
4207
3892
  @param cost         OUT  The cost.
4208
3893
*/
4209
3894
 
4210
 
void get_sweep_read_cost(Table *table, ha_rows nrows, bool interrupted, 
 
3895
void get_sweep_read_cost(Table *table, ha_rows nrows, bool interrupted,
4211
3896
                         COST_VECT *cost)
4212
3897
{
4213
3898
  cost->zero();
4214
3899
  if (table->file->primary_key_is_clustered())
4215
3900
  {
4216
3901
    cost->io_count= table->file->read_time(table->s->primary_key,
4217
 
                                           (uint) nrows, nrows);
 
3902
                                           (uint32_t) nrows, nrows);
4218
3903
  }
4219
3904
  else
4220
3905
  {
4263
3948
int handler::read_range_first(const key_range *start_key,
4264
3949
                              const key_range *end_key,
4265
3950
                              bool eq_range_arg,
4266
 
                              bool sorted  __attribute__((unused)))
 
3951
                              bool )
4267
3952
{
4268
3953
  int result;
4269
3954
 
4286
3971
                           start_key->keypart_map,
4287
3972
                           start_key->flag);
4288
3973
  if (result)
4289
 
    return((result == HA_ERR_KEY_NOT_FOUND) 
 
3974
    return((result == HA_ERR_KEY_NOT_FOUND)
4290
3975
                ? HA_ERR_END_OF_FILE
4291
3976
                : result);
4292
3977
 
4368
4053
  return cmp;
4369
4054
}
4370
4055
 
4371
 
int handler::index_read_idx_map(unsigned char * buf, uint32_t index, const unsigned char * key,
 
4056
int handler::index_read_idx_map(unsigned char * buf, uint32_t index,
 
4057
                                const unsigned char * key,
4372
4058
                                key_part_map keypart_map,
4373
4059
                                enum ha_rkey_function find_flag)
4374
4060
{
4393
4079
  @retval
4394
4080
    pointer             pointer to TYPELIB structure
4395
4081
*/
4396
 
static bool exts_handlerton(THD *unused __attribute__((unused)),
 
4082
static bool exts_handlerton(Session *,
4397
4083
                            plugin_ref plugin,
4398
4084
                            void *arg)
4399
4085
{
4400
4086
  List<char> *found_exts= (List<char> *) arg;
4401
 
  handlerton *hton= plugin_data(plugin, handlerton *);
 
4087
  StorageEngine *engine= plugin_data(plugin, StorageEngine *);
4402
4088
  handler *file;
4403
 
  if (hton->state == SHOW_OPTION_YES && hton->create &&
4404
 
      (file= hton->create(hton, (TABLE_SHARE*) 0, current_thd->mem_root)))
 
4089
  if (engine->is_enabled() &&
 
4090
      (file= engine->create((TABLE_SHARE*) 0, current_session->mem_root)))
4405
4091
  {
4406
4092
    List_iterator_fast<char> it(*found_exts);
4407
4093
    const char **ext, *old_ext;
4435
4121
    plugin_foreach(NULL, exts_handlerton,
4436
4122
                   DRIZZLE_STORAGE_ENGINE_PLUGIN, &found_exts);
4437
4123
 
4438
 
    ext= (const char **) my_once_alloc(sizeof(char *)*
4439
 
                                       (found_exts.elements+1),
4440
 
                                       MYF(MY_WME | MY_FAE));
 
4124
    ext= (const char **) malloc(sizeof(char *)*
 
4125
                                (found_exts.elements+1));
 
4126
                              
4441
4127
 
4442
4128
    assert(ext != 0);
4443
4129
    known_extensions.count= found_exts.elements;
4452
4138
}
4453
4139
 
4454
4140
 
4455
 
static bool stat_print(THD *thd, const char *type, uint32_t type_len,
 
4141
static bool stat_print(Session *session, const char *type, uint32_t type_len,
4456
4142
                       const char *file, uint32_t file_len,
4457
4143
                       const char *status, uint32_t status_len)
4458
4144
{
4459
 
  Protocol *protocol= thd->protocol;
 
4145
  Protocol *protocol= session->protocol;
4460
4146
  protocol->prepare_for_resend();
4461
4147
  protocol->store(type, type_len, system_charset_info);
4462
4148
  protocol->store(file, file_len, system_charset_info);
4466
4152
  return false;
4467
4153
}
4468
4154
 
4469
 
bool ha_show_status(THD *thd, handlerton *db_type, enum ha_stat_type stat)
 
4155
bool ha_show_status(Session *session, StorageEngine *engine, enum ha_stat_type stat)
4470
4156
{
4471
4157
  List<Item> field_list;
4472
 
  Protocol *protocol= thd->protocol;
 
4158
  Protocol *protocol= session->protocol;
4473
4159
  bool result;
4474
4160
 
4475
4161
  field_list.push_back(new Item_empty_string("Type",10));
4480
4166
                            Protocol::SEND_NUM_ROWS | Protocol::SEND_EOF))
4481
4167
    return true;
4482
4168
 
4483
 
  result= db_type->show_status &&
4484
 
    db_type->show_status(db_type, thd, stat_print, stat) ? 1 : 0;
 
4169
  result= engine->show_status(session, stat_print, stat) ? 1 : 0;
4485
4170
 
4486
4171
  if (!result)
4487
 
    my_eof(thd);
 
4172
    session->my_eof();
4488
4173
  return result;
4489
4174
}
4490
4175
 
4501
4186
  - table is not mysql.event
4502
4187
*/
4503
4188
 
4504
 
static bool check_table_binlog_row_based(THD *thd, Table *table)
4505
 
{
4506
 
  if (table->s->cached_row_logging_check == -1)
4507
 
  {
4508
 
    int const check(table->s->tmp_table == NO_TMP_TABLE &&
4509
 
                    binlog_filter->db_ok(table->s->db.str));
4510
 
    table->s->cached_row_logging_check= check;
4511
 
  }
4512
 
 
4513
 
  assert(table->s->cached_row_logging_check == 0 ||
4514
 
              table->s->cached_row_logging_check == 1);
4515
 
 
4516
 
  return (thd->current_stmt_binlog_row_based &&
4517
 
          table->s->cached_row_logging_check &&
4518
 
          (thd->options & OPTION_BIN_LOG) &&
4519
 
          mysql_bin_log.is_open());
4520
 
}
4521
 
 
4522
 
 
4523
 
/**
4524
 
   Write table maps for all (manually or automatically) locked tables
4525
 
   to the binary log.
4526
 
 
4527
 
   This function will generate and write table maps for all tables
4528
 
   that are locked by the thread 'thd'.  Either manually locked
4529
 
   (stored in THD::locked_tables) and automatically locked (stored
4530
 
   in THD::lock) are considered.
4531
 
 
4532
 
   @param thd     Pointer to THD structure
4533
 
 
4534
 
   @retval 0   All OK
4535
 
   @retval 1   Failed to write all table maps
4536
 
 
4537
 
   @sa
4538
 
       THD::lock
4539
 
       THD::locked_tables
4540
 
*/
4541
 
 
4542
 
static int write_locked_table_maps(THD *thd)
4543
 
{
4544
 
  if (thd->get_binlog_table_maps() == 0)
4545
 
  {
4546
 
    DRIZZLE_LOCK *locks[3];
4547
 
    locks[0]= thd->extra_lock;
4548
 
    locks[1]= thd->lock;
4549
 
    locks[2]= thd->locked_tables;
4550
 
    for (uint32_t i= 0 ; i < sizeof(locks)/sizeof(*locks) ; ++i )
4551
 
    {
4552
 
      DRIZZLE_LOCK const *const lock= locks[i];
4553
 
      if (lock == NULL)
4554
 
        continue;
4555
 
 
4556
 
      Table **const end_ptr= lock->table + lock->table_count;
4557
 
      for (Table **table_ptr= lock->table ; 
4558
 
           table_ptr != end_ptr ;
4559
 
           ++table_ptr)
4560
 
      {
4561
 
        Table *const table= *table_ptr;
4562
 
        if (table->current_lock == F_WRLCK &&
4563
 
            check_table_binlog_row_based(thd, table))
4564
 
        {
4565
 
          int const has_trans= table->file->has_transactions();
4566
 
          int const error= thd->binlog_write_table_map(table, has_trans);
4567
 
          /*
4568
 
            If an error occurs, it is the responsibility of the caller to
4569
 
            roll back the transaction.
4570
 
          */
4571
 
          if (unlikely(error))
4572
 
            return(1);
4573
 
        }
4574
 
      }
4575
 
    }
4576
 
  }
4577
 
  return(0);
4578
 
}
4579
 
 
4580
 
 
4581
 
typedef bool Log_func(THD*, Table*, bool, const unsigned char*, const unsigned char*);
4582
 
 
4583
 
static int binlog_log_row(Table* table,
4584
 
                          const unsigned char *before_record,
4585
 
                          const unsigned char *after_record,
4586
 
                          Log_func *log_func)
4587
 
{
4588
 
  if (table->no_replicate)
4589
 
    return 0;
4590
 
  bool error= 0;
4591
 
  THD *const thd= table->in_use;
4592
 
 
4593
 
  if (check_table_binlog_row_based(thd, table))
4594
 
  {
 
4189
static bool binlog_log_row(Table* table,
 
4190
                           const unsigned char *before_record,
 
4191
                           const unsigned char *after_record)
 
4192
{
 
4193
  bool error= false;
 
4194
  Session *const session= table->in_use;
 
4195
 
 
4196
  if (table->no_replicate == false)
 
4197
    return false;
 
4198
 
 
4199
  error= replicator_session_init(session);
 
4200
 
 
4201
  switch (session->lex->sql_command)
 
4202
  {
 
4203
  case SQLCOM_REPLACE:
 
4204
  case SQLCOM_INSERT:
 
4205
  case SQLCOM_REPLACE_SELECT:
 
4206
  case SQLCOM_INSERT_SELECT:
 
4207
  case SQLCOM_CREATE_TABLE:
 
4208
    error= replicator_write_row(session, table);
 
4209
    break;
 
4210
 
 
4211
  case SQLCOM_UPDATE:
 
4212
  case SQLCOM_UPDATE_MULTI:
 
4213
    error= replicator_update_row(session, table, before_record, after_record);
 
4214
    break;
 
4215
 
 
4216
  case SQLCOM_DELETE:
 
4217
  case SQLCOM_DELETE_MULTI:
 
4218
    error= replicator_delete_row(session, table);
 
4219
    break;
 
4220
 
4595
4221
    /*
4596
 
      If there are no table maps written to the binary log, this is
4597
 
      the first row handled in this statement. In that case, we need
4598
 
      to write table maps for all locked tables to the binary log.
 
4222
      For everything else we ignore the event (since it just involves a temp table)
4599
4223
    */
4600
 
    if (likely(!(error= write_locked_table_maps(thd))))
4601
 
    {
4602
 
      bool const has_trans= table->file->has_transactions();
4603
 
      error= (*log_func)(thd, table, has_trans, before_record, after_record);
4604
 
    }
 
4224
  default:
 
4225
    break;
4605
4226
  }
4606
 
  return error ? HA_ERR_RBR_LOGGING_FAILED : 0;
 
4227
 
 
4228
  return error;
4607
4229
}
4608
4230
 
4609
 
int handler::ha_external_lock(THD *thd, int lock_type)
 
4231
int handler::ha_external_lock(Session *session, int lock_type)
4610
4232
{
4611
4233
  /*
4612
4234
    Whether this is lock or unlock, this should be true, and is to verify that
4621
4243
  */
4622
4244
  DRIZZLE_EXTERNAL_LOCK(lock_type);
4623
4245
 
4624
 
  int error= external_lock(thd, lock_type);
 
4246
  int error= external_lock(session, lock_type);
4625
4247
  if (error == 0)
4626
4248
    cached_table_flags= table_flags();
4627
4249
  return(error);
4652
4274
int handler::ha_write_row(unsigned char *buf)
4653
4275
{
4654
4276
  int error;
4655
 
  Log_func *log_func= Write_rows_log_event::binlog_row_logging_function;
4656
4277
  DRIZZLE_INSERT_ROW_START();
4657
4278
 
 
4279
  /* 
 
4280
   * If we have a timestamp column, update it to the current time 
 
4281
   * 
 
4282
   * @TODO Technically, the below two lines can be take even further out of the
 
4283
   * handler interface and into the fill_record() method.
 
4284
   */
 
4285
  if (table->timestamp_field_type & TIMESTAMP_AUTO_SET_ON_INSERT)
 
4286
    table->timestamp_field->set_time();
 
4287
 
4658
4288
  mark_trx_read_write();
4659
4289
 
4660
4290
  if (unlikely(error= write_row(buf)))
4661
4291
    return(error);
4662
 
  if (unlikely(error= binlog_log_row(table, 0, buf, log_func)))
4663
 
    return(error); /* purecov: inspected */
 
4292
 
 
4293
  if (unlikely(binlog_log_row(table, 0, buf)))
 
4294
    return HA_ERR_RBR_LOGGING_FAILED; /* purecov: inspected */
 
4295
 
4664
4296
  DRIZZLE_INSERT_ROW_END();
4665
4297
  return(0);
4666
4298
}
4669
4301
int handler::ha_update_row(const unsigned char *old_data, unsigned char *new_data)
4670
4302
{
4671
4303
  int error;
4672
 
  Log_func *log_func= Update_rows_log_event::binlog_row_logging_function;
4673
4304
 
4674
4305
  /*
4675
4306
    Some storage engines require that the new record is in record[0]
4681
4312
 
4682
4313
  if (unlikely(error= update_row(old_data, new_data)))
4683
4314
    return error;
4684
 
  if (unlikely(error= binlog_log_row(table, old_data, new_data, log_func)))
4685
 
    return error;
 
4315
 
 
4316
  if (unlikely(binlog_log_row(table, old_data, new_data)))
 
4317
    return HA_ERR_RBR_LOGGING_FAILED;
 
4318
 
4686
4319
  return 0;
4687
4320
}
4688
4321
 
4689
4322
int handler::ha_delete_row(const unsigned char *buf)
4690
4323
{
4691
4324
  int error;
4692
 
  Log_func *log_func= Delete_rows_log_event::binlog_row_logging_function;
4693
4325
 
4694
4326
  mark_trx_read_write();
4695
4327
 
4696
4328
  if (unlikely(error= delete_row(buf)))
4697
4329
    return error;
4698
 
  if (unlikely(error= binlog_log_row(table, buf, 0, log_func)))
4699
 
    return error;
 
4330
 
 
4331
  if (unlikely(binlog_log_row(table, buf, 0)))
 
4332
    return HA_ERR_RBR_LOGGING_FAILED;
 
4333
 
4700
4334
  return 0;
4701
4335
}
4702
4336
 
4713
4347
  /* fallback to use all columns in the table to identify row */
4714
4348
  table->use_all_columns();
4715
4349
}
 
4350
 
 
4351
void table_case_convert(char * name, uint32_t length)
 
4352
{
 
4353
  if (lower_case_table_names)
 
4354
    files_charset_info->cset->casedn(files_charset_info,
 
4355
                                     name, length, name, length);
 
4356
}
 
4357
 
 
4358
const char *table_case_name(HA_CREATE_INFO *info, const char *name)
 
4359
{
 
4360
  return ((lower_case_table_names == 2 && info->alias) ? info->alias : name);
 
4361
}