~drizzle-trunk/drizzle/development

« back to all changes in this revision

Viewing changes to drizzled/handler.cc

  • Committer: Monty Taylor
  • Date: 2009-03-25 21:06:47 UTC
  • mto: This revision was merged to the branch mainline in revision 964.
  • Revision ID: mordred@inaugust.com-20090325210647-7j1tm98gvct3jxsu
Removed legacy_db_type.

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