~drizzle-trunk/drizzle/development

« back to all changes in this revision

Viewing changes to drizzled/sql_base.cc

  • Committer: Brian Aker
  • Date: 2009-06-03 19:30:45 UTC
  • mfrom: (1046.1.6 merge)
  • Revision ID: brian@gaz-20090603193045-4xgeczyfixh07beg
MergeĀ forĀ Brian

Show diffs side-by-side

added added

removed removed

Lines of Context:
11
11
 
12
12
  You should have received a copy of the GNU General Public License
13
13
  along with this program; if not, write to the Free Software
14
 
  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA */
 
14
  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA */
15
15
 
16
16
 
17
17
/* Basic functions needed by many modules */
18
 
#include "config.h"
 
18
#include <drizzled/server_includes.h>
 
19
#include <drizzled/field/timestamp.h>
 
20
#include <drizzled/field/null.h>
19
21
#include <assert.h>
20
22
 
21
23
#include <signal.h>
30
32
#  include <time.h>
31
33
# endif
32
34
#endif
33
 
#include "drizzled/internal/my_pthread.h"
34
 
#include "drizzled/internal/thread_var.h"
 
35
#include <mysys/my_pthread.h>
35
36
 
36
37
#include <drizzled/sql_select.h>
 
38
#include <mysys/my_dir.h>
37
39
#include <drizzled/error.h>
38
40
#include <drizzled/gettext.h>
39
41
#include <drizzled/nested_join.h>
40
42
#include <drizzled/sql_base.h>
41
43
#include <drizzled/show.h>
42
44
#include <drizzled/item/cmpfunc.h>
43
 
#include <drizzled/replication_services.h>
 
45
#include <drizzled/transaction_services.h>
44
46
#include <drizzled/check_stack_overrun.h>
45
47
#include <drizzled/lock.h>
46
 
#include <drizzled/plugin/listen.h>
47
 
#include "drizzled/cached_directory.h"
48
 
#include <drizzled/field/timestamp.h>
49
 
#include <drizzled/field/null.h>
50
 
#include "drizzled/sql_table.h"
51
 
#include "drizzled/global_charset_info.h"
52
 
#include "drizzled/pthread_globals.h"
53
 
#include "drizzled/internal/iocache.h"
54
 
#include "drizzled/drizzled.h"
55
 
#include "drizzled/plugin/authorization.h"
56
 
#include "drizzled/table/temporary.h"
57
 
#include "drizzled/table/placeholder.h"
58
 
#include "drizzled/table/unused.h"
59
 
 
60
 
using namespace std;
61
 
 
62
 
namespace drizzled
 
48
 
 
49
extern drizzled::TransactionServices transaction_services;
 
50
 
 
51
/**
 
52
  @defgroup Data_Dictionary Data Dictionary
 
53
  @{
 
54
*/
 
55
Table *unused_tables;                           /* Used by mysql_test */
 
56
HASH open_cache;                                /* Used by mysql_test */
 
57
static HASH table_def_cache;
 
58
static pthread_mutex_t LOCK_table_share;
 
59
static bool table_def_inited= 0;
 
60
 
 
61
static int open_unireg_entry(Session *session, Table *entry, TableList *table_list,
 
62
                             const char *alias,
 
63
                             char *cache_key, uint32_t cache_key_length);
 
64
extern "C" void free_cache_entry(void *entry);
 
65
static void close_old_data_files(Session *session, Table *table, bool morph_locks,
 
66
                                 bool send_refresh);
 
67
 
 
68
 
 
69
extern "C" unsigned char *table_cache_key(const unsigned char *record, size_t *length,
 
70
                                          bool )
63
71
{
 
72
  Table *entry=(Table*) record;
 
73
  *length= entry->s->table_cache_key.length;
 
74
  return (unsigned char*) entry->s->table_cache_key.str;
 
75
}
64
76
 
65
 
extern bool volatile shutdown_in_progress;
66
77
 
67
78
bool table_cache_init(void)
68
79
{
69
 
  return false;
 
80
  return hash_init(&open_cache, &my_charset_bin,
 
81
                   (size_t) table_cache_size+16,
 
82
                   0, 0, table_cache_key,
 
83
                   free_cache_entry, 0);
 
84
}
 
85
 
 
86
void table_cache_free(void)
 
87
{
 
88
  if (table_def_inited)
 
89
  {
 
90
    close_cached_tables(NULL, NULL, false, false, false);
 
91
    if (!open_cache.records)                    // Safety first
 
92
      hash_free(&open_cache);
 
93
  }
70
94
}
71
95
 
72
96
uint32_t cached_open_tables(void)
73
97
{
74
 
  return table::getCache().size();
75
 
}
76
 
 
77
 
void table_cache_free(void)
78
 
{
79
 
  refresh_version++;                            // Force close of open tables
80
 
 
81
 
  table::getUnused().clear();
82
 
  table::getCache().clear();
83
 
}
84
 
 
85
 
/*
86
 
  Close cursor handle, but leave the table in the table cache
 
98
  return open_cache.records;
 
99
}
 
100
 
 
101
/*
 
102
  Create a table cache key
 
103
 
 
104
  SYNOPSIS
 
105
  create_table_def_key()
 
106
  key                   Create key here (must be of size MAX_DBKEY_LENGTH)
 
107
  table_list            Table definition
 
108
 
 
109
  IMPLEMENTATION
 
110
  The table cache_key is created from:
 
111
  db_name + \0
 
112
  table_name + \0
 
113
 
 
114
  if the table is a tmp table, we add the following to make each tmp table
 
115
  unique on the slave:
 
116
 
 
117
  4 bytes for master thread id
 
118
  4 bytes pseudo thread id
 
119
 
 
120
  RETURN
 
121
  Length of key
 
122
*/
 
123
 
 
124
uint32_t create_table_def_key(char *key, TableList *table_list)
 
125
{
 
126
  uint32_t key_length;
 
127
  char *key_pos= key;
 
128
  key_pos= strcpy(key_pos, table_list->db) + strlen(table_list->db);
 
129
  key_pos= strcpy(key_pos+1, table_list->table_name) +
 
130
    strlen(table_list->table_name);
 
131
  key_length= (uint32_t)(key_pos-key)+1;
 
132
 
 
133
  return key_length;
 
134
}
 
135
 
 
136
 
 
137
 
 
138
/*****************************************************************************
 
139
  Functions to handle table definition cach (TableShare)
 
140
 *****************************************************************************/
 
141
 
 
142
extern "C" unsigned char *table_def_key(const unsigned char *record, size_t *length,
 
143
                                        bool )
 
144
{
 
145
  TableShare *entry=(TableShare*) record;
 
146
  *length= entry->table_cache_key.length;
 
147
  return (unsigned char*) entry->table_cache_key.str;
 
148
}
 
149
 
 
150
 
 
151
static void table_def_free_entry(TableShare *share)
 
152
{
 
153
  share->free_table_share();
 
154
}
 
155
 
 
156
 
 
157
bool table_def_init(void)
 
158
{
 
159
  table_def_inited= 1;
 
160
  pthread_mutex_init(&LOCK_table_share, MY_MUTEX_INIT_FAST);
 
161
 
 
162
  return hash_init(&table_def_cache, &my_charset_bin, (size_t)table_def_size,
 
163
                   0, 0, table_def_key,
 
164
                   (hash_free_key) table_def_free_entry, 0);
 
165
}
 
166
 
 
167
 
 
168
void table_def_free(void)
 
169
{
 
170
  if (table_def_inited)
 
171
  {
 
172
    table_def_inited= 0;
 
173
    pthread_mutex_destroy(&LOCK_table_share);
 
174
    hash_free(&table_def_cache);
 
175
  }
 
176
}
 
177
 
 
178
 
 
179
uint32_t cached_table_definitions(void)
 
180
{
 
181
  return table_def_cache.records;
 
182
}
 
183
 
 
184
 
 
185
/*
 
186
  Get TableShare for a table.
 
187
 
 
188
  get_table_share()
 
189
  session                       Thread handle
 
190
  table_list            Table that should be opened
 
191
  key                   Table cache key
 
192
  key_length            Length of key
 
193
  error                 out: Error code from open_table_def()
 
194
 
 
195
  IMPLEMENTATION
 
196
  Get a table definition from the table definition cache.
 
197
  If it doesn't exist, create a new from the table definition file.
 
198
 
 
199
  NOTES
 
200
  We must have wrlock on LOCK_open when we come here
 
201
  (To be changed later)
 
202
 
 
203
  RETURN
 
204
  0  Error
 
205
#  Share for table
 
206
*/
 
207
 
 
208
TableShare *get_table_share(Session *session, TableList *table_list, char *key,
 
209
                            uint32_t key_length, uint32_t, int *error)
 
210
{
 
211
  TableShare *share;
 
212
 
 
213
  *error= 0;
 
214
 
 
215
  /* Read table definition from cache */
 
216
  if ((share= (TableShare*) hash_search(&table_def_cache,(unsigned char*) key,
 
217
                                        key_length)))
 
218
    goto found;
 
219
 
 
220
  if (!(share= alloc_table_share(table_list, key, key_length)))
 
221
  {
 
222
    return(0);
 
223
  }
 
224
 
 
225
  /*
 
226
    Lock mutex to be able to read table definition from file without
 
227
    conflicts
 
228
  */
 
229
  (void) pthread_mutex_lock(&share->mutex);
 
230
 
 
231
  if (my_hash_insert(&table_def_cache, (unsigned char*) share))
 
232
  {
 
233
    share->free_table_share();
 
234
    return(0);                          // return error
 
235
  }
 
236
  if (open_table_def(session, share))
 
237
  {
 
238
    *error= share->error;
 
239
    (void) hash_delete(&table_def_cache, (unsigned char*) share);
 
240
    return(0);
 
241
  }
 
242
  share->ref_count++;                           // Mark in use
 
243
  (void) pthread_mutex_unlock(&share->mutex);
 
244
  return(share);
 
245
 
 
246
found:
 
247
  /*
 
248
    We found an existing table definition. Return it if we didn't get
 
249
    an error when reading the table definition from file.
 
250
  */
 
251
 
 
252
  /* We must do a lock to ensure that the structure is initialized */
 
253
  (void) pthread_mutex_lock(&share->mutex);
 
254
  if (share->error)
 
255
  {
 
256
    /* Table definition contained an error */
 
257
    share->open_table_error(share->error, share->open_errno, share->errarg);
 
258
    (void) pthread_mutex_unlock(&share->mutex);
 
259
 
 
260
    return 0;
 
261
  }
 
262
 
 
263
  share->ref_count++;
 
264
  (void) pthread_mutex_unlock(&share->mutex);
 
265
 
 
266
  return(share);
 
267
}
 
268
 
 
269
 
 
270
/*
 
271
  Get a table share. If it didn't exist, try creating it from engine
 
272
 
 
273
  For arguments and return values, see get_table_from_share()
 
274
*/
 
275
 
 
276
static TableShare
 
277
*get_table_share_with_create(Session *session, TableList *table_list,
 
278
                             char *key, uint32_t key_length,
 
279
                             uint32_t db_flags, int *error)
 
280
{
 
281
  TableShare *share;
 
282
 
 
283
  share= get_table_share(session, table_list, key, key_length, db_flags, error);
 
284
  /*
 
285
    If share is not NULL, we found an existing share.
 
286
 
 
287
    If share is NULL, and there is no error, we're inside
 
288
    pre-locking, which silences 'ER_NO_SUCH_TABLE' errors
 
289
    with the intention to silently drop non-existing tables
 
290
    from the pre-locking list. In this case we still need to try
 
291
    auto-discover before returning a NULL share.
 
292
 
 
293
    If share is NULL and the error is ER_NO_SUCH_TABLE, this is
 
294
    the same as above, only that the error was not silenced by
 
295
    pre-locking. Once again, we need to try to auto-discover
 
296
    the share.
 
297
 
 
298
    Finally, if share is still NULL, it's a real error and we need
 
299
    to abort.
 
300
 
 
301
    @todo Rework alternative ways to deal with ER_NO_SUCH Table.
 
302
  */
 
303
  if (share || (session->is_error() && (session->main_da.sql_errno() != ER_NO_SUCH_TABLE)))
 
304
 
 
305
    return(share);
 
306
 
 
307
  return 0;
 
308
}
 
309
 
 
310
 
 
311
/*
 
312
  Mark that we are not using table share anymore.
 
313
 
 
314
  SYNOPSIS
 
315
  release_table_share()
 
316
  share         Table share
 
317
 
 
318
  IMPLEMENTATION
 
319
  If ref_count goes to zero and (we have done a refresh or if we have
 
320
  already too many open table shares) then delete the definition.
 
321
 
 
322
  If type == RELEASE_WAIT_FOR_DROP then don't return until we get a signal
 
323
  that the table is deleted or the thread is killed.
 
324
*/
 
325
 
 
326
void release_table_share(TableShare *share)
 
327
{
 
328
  bool to_be_deleted= false;
 
329
 
 
330
  safe_mutex_assert_owner(&LOCK_open);
 
331
 
 
332
  pthread_mutex_lock(&share->mutex);
 
333
  if (!--share->ref_count)
 
334
    to_be_deleted= true;
 
335
 
 
336
  if (to_be_deleted)
 
337
  {
 
338
    hash_delete(&table_def_cache, (unsigned char*) share);
 
339
    return;
 
340
  }
 
341
  pthread_mutex_unlock(&share->mutex);
 
342
}
 
343
 
 
344
 
 
345
/*
 
346
  Check if table definition exits in cache
 
347
 
 
348
  SYNOPSIS
 
349
  get_cached_table_share()
 
350
  db                    Database name
 
351
  table_name            Table name
 
352
 
 
353
  RETURN
 
354
  0  Not cached
 
355
#  TableShare for table
 
356
*/
 
357
 
 
358
TableShare *get_cached_table_share(const char *db, const char *table_name)
 
359
{
 
360
  char key[NAME_LEN*2+2];
 
361
  TableList table_list;
 
362
  uint32_t key_length;
 
363
  safe_mutex_assert_owner(&LOCK_open);
 
364
 
 
365
  table_list.db= (char*) db;
 
366
  table_list.table_name= (char*) table_name;
 
367
  key_length= create_table_def_key(key, &table_list);
 
368
  return (TableShare*) hash_search(&table_def_cache,(unsigned char*) key, key_length);
 
369
}
 
370
 
 
371
 
 
372
/*
 
373
  Close file handle, but leave the table in the table cache
87
374
 
88
375
  SYNOPSIS
89
376
  close_handle_and_leave_table_as_lock()
90
 
  table         Table Cursor
 
377
  table         Table handler
91
378
 
92
379
  NOTES
93
380
  By leaving the table in the table cache, it disallows any other thread
94
381
  to open the table
95
382
 
96
 
  session->getKilled() will be set if we run out of memory
 
383
  session->killed will be set if we run out of memory
97
384
 
98
385
  If closing a MERGE child, the calling function has to take care for
99
386
  closing the parent too, if necessary.
102
389
 
103
390
void close_handle_and_leave_table_as_lock(Table *table)
104
391
{
 
392
  TableShare *share, *old_share= table->s;
 
393
  char *key_buff;
 
394
  MEM_ROOT *mem_root= &table->mem_root;
 
395
 
105
396
  assert(table->db_stat);
106
 
  assert(table->getShare()->getType() == message::Table::STANDARD);
107
397
 
108
398
  /*
109
399
    Make a local copy of the table share and free the current one.
110
400
    This has to be done to ensure that the table share is removed from
111
401
    the table defintion cache as soon as the last instance is removed
112
402
  */
113
 
  TableIdentifier identifier(table->getShare()->getSchemaName(), table->getShare()->getTableName(), message::Table::INTERNAL);
114
 
  const TableIdentifier::Key &key(identifier.getKey());
115
 
  TableShare *share= new TableShare(identifier.getType(),
116
 
                                    identifier,
117
 
                                    const_cast<char *>(key.vector()),  static_cast<uint32_t>(table->getShare()->getCacheKeySize()));
118
 
 
119
 
  table->cursor->close();
120
 
  table->db_stat= 0;                            // Mark cursor closed
121
 
  TableShare::release(table->getMutableShare());
122
 
  table->setShare(share);
123
 
}
124
 
 
 
403
  if (multi_alloc_root(mem_root,
 
404
                       &share, sizeof(*share),
 
405
                       &key_buff, old_share->table_cache_key.length,
 
406
                       NULL))
 
407
  {
 
408
    memset(share, 0, sizeof(*share));
 
409
    share->set_table_cache_key(key_buff, old_share->table_cache_key.str,
 
410
                               old_share->table_cache_key.length);
 
411
    share->tmp_table= INTERNAL_TMP_TABLE;       // for intern_close_table()
 
412
  }
 
413
 
 
414
  table->file->close();
 
415
  table->db_stat= 0;                            // Mark file closed
 
416
  release_table_share(table->s);
 
417
  table->s= share;
 
418
  table->file->change_table_ptr(table, table->s);
 
419
}
 
420
 
 
421
 
 
422
 
 
423
/*
 
424
  Create a list for all open tables matching SQL expression
 
425
 
 
426
  SYNOPSIS
 
427
  list_open_tables()
 
428
  wild          SQL like expression
 
429
 
 
430
  NOTES
 
431
  One gets only a list of tables for which one has any kind of privilege.
 
432
  db and table names are allocated in result struct, so one doesn't need
 
433
  a lock on LOCK_open when traversing the return list.
 
434
 
 
435
  RETURN VALUES
 
436
  NULL  Error (Probably OOM)
 
437
#               Pointer to list of names of open tables.
 
438
*/
 
439
 
 
440
OPEN_TableList *list_open_tables(const char *db, const char *wild)
 
441
{
 
442
  int result = 0;
 
443
  OPEN_TableList **start_list, *open_list;
 
444
  TableList table_list;
 
445
 
 
446
  pthread_mutex_lock(&LOCK_open); /* List all open tables */
 
447
  memset(&table_list, 0, sizeof(table_list));
 
448
  start_list= &open_list;
 
449
  open_list=0;
 
450
 
 
451
  for (uint32_t idx=0 ; result == 0 && idx < open_cache.records; idx++)
 
452
  {
 
453
    OPEN_TableList *table;
 
454
    Table *entry=(Table*) hash_element(&open_cache,idx);
 
455
    TableShare *share= entry->s;
 
456
 
 
457
    if (db && my_strcasecmp(system_charset_info, db, share->db.str))
 
458
      continue;
 
459
    if (wild && wild_compare(share->table_name.str, wild, 0))
 
460
      continue;
 
461
 
 
462
    /* Check if user has SELECT privilege for any column in the table */
 
463
    table_list.db=         share->db.str;
 
464
    table_list.table_name= share->table_name.str;
 
465
 
 
466
    /* need to check if we haven't already listed it */
 
467
    for (table= open_list  ; table ; table=table->next)
 
468
    {
 
469
      if (!strcmp(table->table, share->table_name.str) &&
 
470
          !strcmp(table->db,    share->db.str))
 
471
      {
 
472
        if (entry->in_use)
 
473
          table->in_use++;
 
474
        if (entry->locked_by_name)
 
475
          table->locked++;
 
476
        break;
 
477
      }
 
478
    }
 
479
    if (table)
 
480
      continue;
 
481
    if (!(*start_list = (OPEN_TableList *)
 
482
          sql_alloc(sizeof(**start_list)+share->table_cache_key.length)))
 
483
    {
 
484
      open_list=0;                              // Out of memory
 
485
      break;
 
486
    }
 
487
    strcpy((*start_list)->table=
 
488
           strcpy(((*start_list)->db= (char*) ((*start_list)+1)),
 
489
                  share->db.str)+share->db.length+1,
 
490
           share->table_name.str);
 
491
    (*start_list)->in_use= entry->in_use ? 1 : 0;
 
492
    (*start_list)->locked= entry->locked_by_name ? 1 : 0;
 
493
    start_list= &(*start_list)->next;
 
494
    *start_list=0;
 
495
  }
 
496
  pthread_mutex_unlock(&LOCK_open);
 
497
  return(open_list);
 
498
}
125
499
 
126
500
/*****************************************************************************
127
501
 *       Functions to free open table cache
128
502
 ****************************************************************************/
129
503
 
130
504
 
131
 
void Table::intern_close_table()
 
505
void intern_close_table(Table *table)
132
506
{                                               // Free all structures
133
 
  free_io_cache();
134
 
  if (cursor)                              // Not true if name lock
 
507
  free_io_cache(table);
 
508
  if (table->file)                              // Not true if name lock
 
509
    table->closefrm(true);                      // close file
 
510
}
 
511
 
 
512
/*
 
513
  Remove table from the open table cache
 
514
 
 
515
  SYNOPSIS
 
516
  free_cache_entry()
 
517
  entry         Table to remove
 
518
 
 
519
  NOTE
 
520
  We need to have a lock on LOCK_open when calling this
 
521
*/
 
522
 
 
523
void free_cache_entry(void *entry)
 
524
{
 
525
  Table *table= static_cast<Table *>(entry);
 
526
  intern_close_table(table);
 
527
  if (!table->in_use)
135
528
  {
136
 
    delete_table(true);                 // close cursor
 
529
    table->next->prev=table->prev;              /* remove from used chain */
 
530
    table->prev->next=table->next;
 
531
    if (table == unused_tables)
 
532
    {
 
533
      unused_tables=unused_tables->next;
 
534
      if (table == unused_tables)
 
535
        unused_tables= NULL;
 
536
    }
137
537
  }
 
538
 
 
539
  free(table);
138
540
}
139
541
 
140
542
/* Free resources allocated by filesort() and read_record() */
141
543
 
142
 
void Table::free_io_cache()
 
544
void free_io_cache(Table *table)
143
545
{
144
 
  if (sort.io_cache)
 
546
  if (table->sort.io_cache)
145
547
  {
146
 
    sort.io_cache->close_cached_file();
147
 
    delete sort.io_cache;
148
 
    sort.io_cache= 0;
 
548
    close_cached_file(table->sort.io_cache);
 
549
    delete table->sort.io_cache;
 
550
    table->sort.io_cache= 0;
149
551
  }
150
552
}
151
553
 
153
555
/*
154
556
  Close all tables which aren't in use by any thread
155
557
 
156
 
  @param session Thread context (may be NULL)
 
558
  @param session Thread context
157
559
  @param tables List of tables to remove from the cache
158
 
  @param have_lock If table::Cache::singleton().mutex() is locked
 
560
  @param have_lock If LOCK_open is locked
159
561
  @param wait_for_refresh Wait for a impending flush
160
562
  @param wait_for_placeholders Wait for tables being reopened so that the GRL
161
563
  won't proceed while write-locked tables are being reopened by other
165
567
  and tables must be NULL.
166
568
*/
167
569
 
168
 
bool Session::close_cached_tables(TableList *tables, bool wait_for_refresh, bool wait_for_placeholders)
 
570
bool close_cached_tables(Session *session, TableList *tables, bool have_lock,
 
571
                         bool wait_for_refresh, bool wait_for_placeholders)
169
572
{
170
 
  bool result= false;
171
 
  Session *session= this;
 
573
  bool result=0;
 
574
  assert(session || (!wait_for_refresh && !tables));
172
575
 
 
576
  if (!have_lock)
 
577
    pthread_mutex_lock(&LOCK_open); /* Optionally lock for remove tables from open_cahe if not in use */
 
578
  if (!tables)
173
579
  {
174
 
    table::Cache::singleton().mutex().lock(); /* Optionally lock for remove tables from open_cahe if not in use */
175
 
 
176
 
    if (tables == NULL)
177
 
    {
178
 
      refresh_version++;                                // Force close of open tables
179
 
 
180
 
      table::getUnused().clear();
181
 
 
182
 
      if (wait_for_refresh)
183
 
      {
184
 
        /*
185
 
          Other threads could wait in a loop in open_and_lock_tables(),
186
 
          trying to lock one or more of our tables.
187
 
 
188
 
          If they wait for the locks in thr_multi_lock(), their lock
189
 
          request is aborted. They loop in open_and_lock_tables() and
190
 
          enter open_table(). Here they notice the table is refreshed and
191
 
          wait for COND_refresh. Then they loop again in
192
 
          openTablesLock() and this time open_table() succeeds. At
193
 
          this moment, if we (the FLUSH TABLES thread) are scheduled and
194
 
          on another FLUSH TABLES enter close_cached_tables(), they could
195
 
          awake while we sleep below, waiting for others threads (us) to
196
 
          close their open tables. If this happens, the other threads
197
 
          would find the tables unlocked. They would get the locks, one
198
 
          after the other, and could do their destructive work. This is an
199
 
          issue if we have LOCK TABLES in effect.
200
 
 
201
 
          The problem is that the other threads passed all checks in
202
 
          open_table() before we refresh the table.
203
 
 
204
 
          The fix for this problem is to set some_tables_deleted for all
205
 
          threads with open tables. These threads can still get their
206
 
          locks, but will immediately release them again after checking
207
 
          this variable. They will then loop in openTablesLock()
208
 
          again. There they will wait until we update all tables version
209
 
          below.
210
 
 
211
 
          Setting some_tables_deleted is done by table::Cache::singleton().removeTable()
212
 
          in the other branch.
213
 
 
214
 
          In other words (reviewer suggestion): You need this setting of
215
 
          some_tables_deleted for the case when table was opened and all
216
 
          related checks were passed before incrementing refresh_version
217
 
          (which you already have) but attempt to lock the table happened
218
 
          after the call to Session::close_old_data_files() i.e. after removal of
219
 
          current thread locks.
220
 
        */
221
 
        for (table::CacheMap::const_iterator iter= table::getCache().begin();
222
 
             iter != table::getCache().end();
223
 
             iter++)
224
 
        {
225
 
          Table *table= (*iter).second;
226
 
          if (table->in_use)
227
 
            table->in_use->some_tables_deleted= false;
228
 
        }
229
 
      }
230
 
    }
231
 
    else
232
 
    {
233
 
      bool found= false;
234
 
      for (TableList *table= tables; table; table= table->next_local)
235
 
      {
236
 
        TableIdentifier identifier(table->getSchemaName(), table->getTableName());
237
 
        if (table::Cache::singleton().removeTable(session, identifier,
238
 
                                    RTFC_OWNED_BY_Session_FLAG))
239
 
        {
240
 
          found= true;
241
 
        }
242
 
      }
243
 
      if (!found)
244
 
        wait_for_refresh= false;                        // Nothing to wait for
245
 
    }
246
 
 
 
580
    refresh_version++;                          // Force close of open tables
 
581
    while (unused_tables)
 
582
    {
 
583
#ifdef EXTRA_DEBUG
 
584
      if (hash_delete(&open_cache,(unsigned char*) unused_tables))
 
585
        printf("Warning: Couldn't delete open table from hash\n");
 
586
#else
 
587
      hash_delete(&open_cache,(unsigned char*) unused_tables);
 
588
#endif
 
589
    }
247
590
    if (wait_for_refresh)
248
591
    {
249
592
      /*
250
 
        If there is any table that has a lower refresh_version, wait until
251
 
        this is closed (or this thread is killed) before returning
 
593
        Other threads could wait in a loop in open_and_lock_tables(),
 
594
        trying to lock one or more of our tables.
 
595
 
 
596
        If they wait for the locks in thr_multi_lock(), their lock
 
597
        request is aborted. They loop in open_and_lock_tables() and
 
598
        enter open_table(). Here they notice the table is refreshed and
 
599
        wait for COND_refresh. Then they loop again in
 
600
        open_and_lock_tables() and this time open_table() succeeds. At
 
601
        this moment, if we (the FLUSH TABLES thread) are scheduled and
 
602
        on another FLUSH TABLES enter close_cached_tables(), they could
 
603
        awake while we sleep below, waiting for others threads (us) to
 
604
        close their open tables. If this happens, the other threads
 
605
        would find the tables unlocked. They would get the locks, one
 
606
        after the other, and could do their destructive work. This is an
 
607
        issue if we have LOCK TABLES in effect.
 
608
 
 
609
        The problem is that the other threads passed all checks in
 
610
        open_table() before we refresh the table.
 
611
 
 
612
        The fix for this problem is to set some_tables_deleted for all
 
613
        threads with open tables. These threads can still get their
 
614
        locks, but will immediately release them again after checking
 
615
        this variable. They will then loop in open_and_lock_tables()
 
616
        again. There they will wait until we update all tables version
 
617
        below.
 
618
 
 
619
        Setting some_tables_deleted is done by remove_table_from_cache()
 
620
        in the other branch.
 
621
 
 
622
        In other words (reviewer suggestion): You need this setting of
 
623
        some_tables_deleted for the case when table was opened and all
 
624
        related checks were passed before incrementing refresh_version
 
625
        (which you already have) but attempt to lock the table happened
 
626
        after the call to close_old_data_files() i.e. after removal of
 
627
        current thread locks.
252
628
      */
253
 
      session->mysys_var->current_mutex= &table::Cache::singleton().mutex();
254
 
      session->mysys_var->current_cond= &COND_refresh;
255
 
      session->set_proc_info("Flushing tables");
256
 
 
257
 
      session->close_old_data_files();
258
 
 
259
 
      bool found= true;
260
 
      /* Wait until all threads has closed all the tables we had locked */
261
 
      while (found && ! session->getKilled())
262
 
      {
263
 
        found= false;
264
 
        for (table::CacheMap::const_iterator iter= table::getCache().begin();
265
 
             iter != table::getCache().end();
266
 
             iter++)
 
629
      for (uint32_t idx=0 ; idx < open_cache.records ; idx++)
 
630
      {
 
631
        Table *table=(Table*) hash_element(&open_cache,idx);
 
632
        if (table->in_use)
 
633
          table->in_use->some_tables_deleted= 1;
 
634
      }
 
635
    }
 
636
  }
 
637
  else
 
638
  {
 
639
    bool found=0;
 
640
    for (TableList *table= tables; table; table= table->next_local)
 
641
    {
 
642
      if (remove_table_from_cache(session, table->db, table->table_name,
 
643
                                  RTFC_OWNED_BY_Session_FLAG))
 
644
        found=1;
 
645
    }
 
646
    if (!found)
 
647
      wait_for_refresh=0;                       // Nothing to wait for
 
648
  }
 
649
 
 
650
  if (wait_for_refresh)
 
651
  {
 
652
    /*
 
653
      If there is any table that has a lower refresh_version, wait until
 
654
      this is closed (or this thread is killed) before returning
 
655
    */
 
656
    session->mysys_var->current_mutex= &LOCK_open;
 
657
    session->mysys_var->current_cond= &COND_refresh;
 
658
    session->set_proc_info("Flushing tables");
 
659
 
 
660
    close_old_data_files(session,session->open_tables,1,1);
 
661
 
 
662
    bool found=1;
 
663
    /* Wait until all threads has closed all the tables we had locked */
 
664
    while (found && ! session->killed)
 
665
    {
 
666
      found=0;
 
667
      for (uint32_t idx=0 ; idx < open_cache.records ; idx++)
 
668
      {
 
669
        Table *table=(Table*) hash_element(&open_cache,idx);
 
670
        /* Avoid a self-deadlock. */
 
671
        if (table->in_use == session)
 
672
          continue;
 
673
        /*
 
674
          Note that we wait here only for tables which are actually open, and
 
675
          not for placeholders with Table::open_placeholder set. Waiting for
 
676
          latter will cause deadlock in the following scenario, for example:
 
677
 
 
678
conn1: lock table t1 write;
 
679
conn2: lock table t2 write;
 
680
conn1: flush tables;
 
681
conn2: flush tables;
 
682
 
 
683
It also does not make sense to wait for those of placeholders that
 
684
are employed by CREATE TABLE as in this case table simply does not
 
685
exist yet.
 
686
        */
 
687
        if (table->needs_reopen_or_name_lock() && (table->db_stat ||
 
688
                                                   (table->open_placeholder && wait_for_placeholders)))
267
689
        {
268
 
          Table *table= (*iter).second;
269
 
          /* Avoid a self-deadlock. */
270
 
          if (table->in_use == session)
271
 
            continue;
272
 
          /*
273
 
            Note that we wait here only for tables which are actually open, and
274
 
            not for placeholders with Table::open_placeholder set. Waiting for
275
 
            latter will cause deadlock in the following scenario, for example:
276
 
 
277
 
            conn1-> lock table t1 write;
278
 
            conn2-> lock table t2 write;
279
 
            conn1-> flush tables;
280
 
            conn2-> flush tables;
281
 
 
282
 
            It also does not make sense to wait for those of placeholders that
283
 
            are employed by CREATE TABLE as in this case table simply does not
284
 
            exist yet.
285
 
          */
286
 
          if (table->needs_reopen_or_name_lock() && (table->db_stat ||
287
 
                                                     (table->open_placeholder && wait_for_placeholders)))
288
 
          {
289
 
            found= true;
290
 
            boost_unique_lock_t scoped(table::Cache::singleton().mutex(), boost::adopt_lock_t());
291
 
            COND_refresh.wait(scoped);
292
 
            scoped.release();
293
 
            break;
294
 
          }
 
690
          found=1;
 
691
          pthread_cond_wait(&COND_refresh,&LOCK_open);
 
692
          break;
295
693
        }
296
694
      }
 
695
    }
 
696
    /*
 
697
      No other thread has the locked tables open; reopen them and get the
 
698
      old locks. This should always succeed (unless some external process
 
699
      has removed the tables)
 
700
    */
 
701
    session->in_lock_tables=1;
 
702
    result=reopen_tables(session,1,1);
 
703
    session->in_lock_tables=0;
 
704
    /* Set version for table */
 
705
    for (Table *table=session->open_tables; table ; table= table->next)
 
706
    {
297
707
      /*
298
 
        No other thread has the locked tables open; reopen them and get the
299
 
        old locks. This should always succeed (unless some external process
300
 
        has removed the tables)
 
708
        Preserve the version (0) of write locked tables so that a impending
 
709
        global read lock won't sneak in.
301
710
      */
302
 
      result= session->reopen_tables(true, true);
303
 
 
304
 
      /* Set version for table */
305
 
      for (Table *table= session->open_tables; table ; table= table->getNext())
306
 
      {
307
 
        /*
308
 
          Preserve the version (0) of write locked tables so that a impending
309
 
          global read lock won't sneak in.
310
 
        */
311
 
        if (table->reginfo.lock_type < TL_WRITE_ALLOW_WRITE)
312
 
          table->getMutableShare()->refreshVersion();
313
 
      }
 
711
      if (table->reginfo.lock_type < TL_WRITE_ALLOW_WRITE)
 
712
        table->s->version= refresh_version;
314
713
    }
315
 
 
316
 
    table::Cache::singleton().mutex().unlock();
317
714
  }
318
 
 
 
715
  if (!have_lock)
 
716
    pthread_mutex_unlock(&LOCK_open);
319
717
  if (wait_for_refresh)
320
718
  {
321
 
    boost_unique_lock_t scopedLock(session->mysys_var->mutex);
 
719
    pthread_mutex_lock(&session->mysys_var->mutex);
322
720
    session->mysys_var->current_mutex= 0;
323
721
    session->mysys_var->current_cond= 0;
324
722
    session->set_proc_info(0);
 
723
    pthread_mutex_unlock(&session->mysys_var->mutex);
325
724
  }
326
 
 
327
 
  return result;
 
725
  return(result);
328
726
}
329
727
 
330
728
 
332
730
  move one table to free list 
333
731
*/
334
732
 
335
 
bool Session::free_cached_table()
 
733
static bool free_cached_table(Session *session, Table **table_ptr)
336
734
{
337
 
  bool found_old_table= false;
338
 
  table::Concurrent *table= static_cast<table::Concurrent *>(open_tables);
 
735
  bool found_old_table= 0;
 
736
  Table *table= *table_ptr;
339
737
 
340
 
  safe_mutex_assert_owner(table::Cache::singleton().mutex().native_handle());
 
738
  safe_mutex_assert_owner(&LOCK_open);
341
739
  assert(table->key_read == 0);
342
 
  assert(!table->cursor || table->cursor->inited == Cursor::NONE);
 
740
  assert(!table->file || table->file->inited == handler::NONE);
343
741
 
344
 
  open_tables= table->getNext();
 
742
  *table_ptr= table->next;
345
743
 
346
744
  if (table->needs_reopen_or_name_lock() ||
347
 
      version != refresh_version || !table->db_stat)
 
745
      session->version != refresh_version || !table->db_stat)
348
746
  {
349
 
    table::remove_table(table);
 
747
    hash_delete(&open_cache,(unsigned char*) table);
350
748
    found_old_table= true;
351
749
  }
352
750
  else
355
753
      Open placeholders have Table::db_stat set to 0, so they should be
356
754
      handled by the first alternative.
357
755
    */
358
 
    assert(not table->open_placeholder);
 
756
    assert(!table->open_placeholder);
359
757
 
360
758
    /* Free memory and reset for next loop */
361
 
    table->cursor->ha_reset();
362
 
    table->in_use= NULL;
363
 
 
364
 
    table::getUnused().link(table);
 
759
    table->file->ha_reset();
 
760
    table->in_use= false;
 
761
    if (unused_tables)
 
762
    {
 
763
      table->next=unused_tables;                /* Link in last */
 
764
      table->prev=unused_tables->prev;
 
765
      unused_tables->prev=table;
 
766
      table->prev->next=table;
 
767
    }
 
768
    else
 
769
      unused_tables=table->next=table->prev=table;
365
770
  }
366
771
 
367
772
  return found_old_table;
380
785
{
381
786
  bool found_old_table= false;
382
787
 
383
 
  safe_mutex_assert_not_owner(table::Cache::singleton().mutex().native_handle());
 
788
  safe_mutex_assert_not_owner(&LOCK_open);
384
789
 
385
 
  boost_unique_lock_t scoped_lock(table::Cache::singleton().mutex()); /* Close all open tables on Session */
 
790
  pthread_mutex_lock(&LOCK_open); /* Close all open tables on Session */
386
791
 
387
792
  while (open_tables)
388
 
  {
389
 
    found_old_table|= free_cached_table();
390
 
  }
 
793
    found_old_table|= free_cached_table(this, &open_tables);
391
794
  some_tables_deleted= false;
392
795
 
393
796
  if (found_old_table)
394
797
  {
395
798
    /* Tell threads waiting for refresh that something has happened */
396
 
    locking::broadcast_refresh();
 
799
    broadcast_refresh();
397
800
  }
 
801
 
 
802
  pthread_mutex_unlock(&LOCK_open);
398
803
}
399
804
 
400
805
/*
408
813
  table_name            Table name
409
814
 
410
815
NOTES:
411
 
This is called by find_table_in_global_list().
 
816
This is called by find_table_in_local_list() and
 
817
find_table_in_global_list().
412
818
 
413
819
RETURN VALUES
414
820
NULL    Table not found
422
828
{
423
829
  for (; table; table= table->*link )
424
830
  {
425
 
    if ((table->table == 0 || table->table->getShare()->getType() == message::Table::STANDARD) &&
426
 
        strcasecmp(table->getSchemaName(), db_name) == 0 &&
427
 
        strcasecmp(table->getTableName(), table_name) == 0)
 
831
    if ((table->table == 0 || table->table->s->tmp_table == NO_TMP_TABLE) &&
 
832
        strcmp(table->db, db_name) == 0 &&
 
833
        strcmp(table->table_name, table_name) == 0)
428
834
      break;
429
835
  }
430
836
  return table;
467
873
0 if table is unique
468
874
*/
469
875
 
470
 
TableList* unique_table(TableList *table, TableList *table_list,
 
876
TableList* unique_table(Session *session, TableList *table, TableList *table_list,
471
877
                        bool check_alias)
472
878
{
473
879
  TableList *res;
486
892
  if (table->table)
487
893
  {
488
894
    /* temporary table is always unique */
489
 
    if (table->table && table->table->getShare()->getType() != message::Table::STANDARD)
490
 
      return 0;
 
895
    if (table->table && table->table->s->tmp_table != NO_TMP_TABLE)
 
896
      return(0);
491
897
    table= table->find_underlying_table(table->table);
492
898
    /*
493
899
      as far as we have table->table we have to find real TableList of
495
901
    */
496
902
    assert(table);
497
903
  }
498
 
  d_name= table->getSchemaName();
499
 
  t_name= table->getTableName();
 
904
  d_name= table->db;
 
905
  t_name= table->table_name;
500
906
  t_alias= table->alias;
501
907
 
502
908
  for (;;)
503
909
  {
504
 
    if ((! (res= find_table_in_global_list(table_list, d_name, t_name))) ||
 
910
    if (((! (res= find_table_in_global_list(table_list, d_name, t_name))) &&
 
911
         (! (res= mysql_lock_have_duplicate(session, table, table_list)))) ||
505
912
        ((!res->table || res->table != table->table) &&
506
913
         (!check_alias || !(my_strcasecmp(files_charset_info, t_alias, res->alias))) &&
507
914
         res->select_lex && !res->select_lex->exclude_from_table_unique_test))
517
924
}
518
925
 
519
926
 
520
 
void Open_tables_state::doGetTableNames(const SchemaIdentifier &schema_identifier,
521
 
                                        std::set<std::string>& set_of_names)
522
 
{
523
 
  for (Table *table= getTemporaryTables() ; table ; table= table->getNext())
524
 
  {
525
 
    if (schema_identifier.compare(table->getShare()->getSchemaName()))
526
 
    {
527
 
      set_of_names.insert(table->getShare()->getTableName());
528
 
    }
529
 
  }
530
 
}
531
 
 
532
 
void Open_tables_state::doGetTableNames(CachedDirectory &,
533
 
                                        const SchemaIdentifier &schema_identifier,
534
 
                                        std::set<std::string> &set_of_names)
535
 
{
536
 
  doGetTableNames(schema_identifier, set_of_names);
537
 
}
538
 
 
539
 
void Open_tables_state::doGetTableIdentifiers(const SchemaIdentifier &schema_identifier,
540
 
                                              TableIdentifier::vector &set_of_identifiers)
541
 
{
542
 
  for (Table *table= getTemporaryTables() ; table ; table= table->getNext())
543
 
  {
544
 
    if (schema_identifier.compare(table->getShare()->getSchemaName()))
545
 
    {
546
 
      set_of_identifiers.push_back(TableIdentifier(table->getShare()->getSchemaName(),
547
 
                                                   table->getShare()->getTableName(),
548
 
                                                   table->getShare()->getPath()));
549
 
    }
550
 
  }
551
 
}
552
 
 
553
 
void Open_tables_state::doGetTableIdentifiers(CachedDirectory &,
554
 
                                              const SchemaIdentifier &schema_identifier,
555
 
                                              TableIdentifier::vector &set_of_identifiers)
556
 
{
557
 
  doGetTableIdentifiers(schema_identifier, set_of_identifiers);
558
 
}
559
 
 
560
 
bool Open_tables_state::doDoesTableExist(const TableIdentifier &identifier)
561
 
{
562
 
  for (Table *table= getTemporaryTables() ; table ; table= table->getNext())
563
 
  {
564
 
    if (table->getShare()->getType() == message::Table::TEMPORARY)
565
 
    {
566
 
      if (identifier.getKey() == table->getShare()->getCacheKey())
567
 
      {
568
 
        return true;
569
 
      }
570
 
    }
571
 
  }
572
 
 
573
 
  return false;
574
 
}
575
 
 
576
 
int Open_tables_state::doGetTableDefinition(const TableIdentifier &identifier,
577
 
                                  message::Table &table_proto)
578
 
{
579
 
  for (Table *table= getTemporaryTables() ; table ; table= table->getNext())
580
 
  {
581
 
    if (table->getShare()->getType() == message::Table::TEMPORARY)
582
 
    {
583
 
      if (identifier.getKey() == table->getShare()->getCacheKey())
584
 
      {
585
 
        table_proto.CopyFrom(*(table->getShare()->getTableProto()));
586
 
 
587
 
        return EEXIST;
588
 
      }
589
 
    }
590
 
  }
591
 
 
592
 
  return ENOENT;
593
 
}
594
 
 
595
 
Table *Open_tables_state::find_temporary_table(const TableIdentifier &identifier)
596
 
{
597
 
  for (Table *table= temporary_tables ; table ; table= table->getNext())
598
 
  {
599
 
    if (identifier.getKey() == table->getShare()->getCacheKey())
600
 
      return table;
601
 
  }
602
 
 
603
 
  return NULL;                               // Not a temporary table
 
927
/*
 
928
  Issue correct error message in case we found 2 duplicate tables which
 
929
  prevent some update operation
 
930
 
 
931
  SYNOPSIS
 
932
  update_non_unique_table_error()
 
933
  update      table which we try to update
 
934
  operation   name of update operation
 
935
  duplicate   duplicate table which we found
 
936
 
 
937
NOTE:
 
938
here we hide view underlying tables if we have them
 
939
*/
 
940
 
 
941
void update_non_unique_table_error(TableList *update,
 
942
                                   const char *,
 
943
                                   TableList *)
 
944
{
 
945
  my_error(ER_UPDATE_TABLE_USED, MYF(0), update->alias);
 
946
}
 
947
 
 
948
 
 
949
Table *find_temporary_table(Session *session, const char *db, const char *table_name)
 
950
{
 
951
  TableList table_list;
 
952
 
 
953
  table_list.db= (char*) db;
 
954
  table_list.table_name= (char*) table_name;
 
955
  return find_temporary_table(session, &table_list);
 
956
}
 
957
 
 
958
 
 
959
Table *find_temporary_table(Session *session, TableList *table_list)
 
960
{
 
961
  char  key[MAX_DBKEY_LENGTH];
 
962
  uint  key_length;
 
963
  Table *table;
 
964
 
 
965
  key_length= create_table_def_key(key, table_list);
 
966
  for (table=session->temporary_tables ; table ; table= table->next)
 
967
  {
 
968
    if (table->s->table_cache_key.length == key_length &&
 
969
        !memcmp(table->s->table_cache_key.str, key, key_length))
 
970
      return(table);
 
971
  }
 
972
  return(0);                               // Not a temporary table
604
973
}
605
974
 
606
975
 
630
999
  @retval -1  the table is in use by a outer query
631
1000
*/
632
1001
 
633
 
int Open_tables_state::drop_temporary_table(const drizzled::TableIdentifier &identifier)
 
1002
int drop_temporary_table(Session *session, TableList *table_list)
634
1003
{
635
1004
  Table *table;
636
1005
 
637
 
  if (not (table= find_temporary_table(identifier)))
638
 
    return 1;
 
1006
  if (!(table= find_temporary_table(session, table_list)))
 
1007
    return(1);
639
1008
 
640
1009
  /* Table might be in use by some outer statement. */
641
 
  if (table->query_id && table->query_id != getQueryId())
642
 
  {
643
 
    my_error(ER_CANT_REOPEN_TABLE, MYF(0), table->getAlias());
644
 
    return -1;
645
 
  }
646
 
 
647
 
  close_temporary_table(table);
648
 
 
649
 
  return 0;
 
1010
  if (table->query_id && table->query_id != session->query_id)
 
1011
  {
 
1012
    my_error(ER_CANT_REOPEN_TABLE, MYF(0), table->alias);
 
1013
    return(-1);
 
1014
  }
 
1015
 
 
1016
  /*
 
1017
    If LOCK TABLES list is not empty and contains this table,
 
1018
    unlock the table and remove the table from this list.
 
1019
  */
 
1020
  mysql_lock_remove(session, session->locked_tables, table, false);
 
1021
  close_temporary_table(session, table, 1, 1);
 
1022
  return(0);
 
1023
}
 
1024
 
 
1025
/*
 
1026
  unlink from session->temporary tables and close temporary table
 
1027
*/
 
1028
 
 
1029
void close_temporary_table(Session *session, Table *table,
 
1030
                           bool free_share, bool delete_table)
 
1031
{
 
1032
  if (table->prev)
 
1033
  {
 
1034
    table->prev->next= table->next;
 
1035
    if (table->prev->next)
 
1036
      table->next->prev= table->prev;
 
1037
  }
 
1038
  else
 
1039
  {
 
1040
    /* removing the item from the list */
 
1041
    assert(table == session->temporary_tables);
 
1042
    /*
 
1043
      slave must reset its temporary list pointer to zero to exclude
 
1044
      passing non-zero value to end_slave via rli->save_temporary_tables
 
1045
      when no temp tables opened, see an invariant below.
 
1046
    */
 
1047
    session->temporary_tables= table->next;
 
1048
    if (session->temporary_tables)
 
1049
      table->next->prev= 0;
 
1050
  }
 
1051
  close_temporary(table, free_share, delete_table);
 
1052
}
 
1053
 
 
1054
 
 
1055
/*
 
1056
  Close and delete a temporary table
 
1057
 
 
1058
  NOTE
 
1059
  This dosn't unlink table from session->temporary
 
1060
  If this is needed, use close_temporary_table()
 
1061
*/
 
1062
 
 
1063
void close_temporary(Table *table, bool free_share, bool delete_table)
 
1064
{
 
1065
  StorageEngine *table_type= table->s->db_type();
 
1066
 
 
1067
  free_io_cache(table);
 
1068
  table->closefrm(false);
 
1069
 
 
1070
  if (delete_table)
 
1071
    rm_temporary_table(table_type, table->s->path.str);
 
1072
 
 
1073
  if (free_share)
 
1074
  {
 
1075
    table->s->free_table_share();
 
1076
    free((char*) table);
 
1077
  }
 
1078
}
 
1079
 
 
1080
 
 
1081
/*
 
1082
  Used by ALTER Table when the table is a temporary one. It changes something
 
1083
  only if the ALTER contained a RENAME clause (otherwise, table_name is the old
 
1084
  name).
 
1085
  Prepares a table cache key, which is the concatenation of db, table_name and
 
1086
  session->slave_proxy_id, separated by '\0'.
 
1087
*/
 
1088
 
 
1089
bool rename_temporary_table(Table *table, const char *db, const char *table_name)
 
1090
{
 
1091
  char *key;
 
1092
  uint32_t key_length;
 
1093
  TableShare *share= table->s;
 
1094
  TableList table_list;
 
1095
 
 
1096
  if (!(key=(char*) alloc_root(&share->mem_root, MAX_DBKEY_LENGTH)))
 
1097
    return true;                                /* purecov: inspected */
 
1098
 
 
1099
  table_list.db= (char*) db;
 
1100
  table_list.table_name= (char*) table_name;
 
1101
  key_length= create_table_def_key(key, &table_list);
 
1102
  share->set_table_cache_key(key, key_length);
 
1103
 
 
1104
  return false;
 
1105
}
 
1106
 
 
1107
 
 
1108
/* move table first in unused links */
 
1109
 
 
1110
static void relink_unused(Table *table)
 
1111
{
 
1112
  if (table != unused_tables)
 
1113
  {
 
1114
    table->prev->next=table->next;              /* Remove from unused list */
 
1115
    table->next->prev=table->prev;
 
1116
    table->next=unused_tables;                  /* Link in unused tables */
 
1117
    table->prev=unused_tables->prev;
 
1118
    unused_tables->prev->next=table;
 
1119
    unused_tables->prev=table;
 
1120
    unused_tables=table;
 
1121
  }
650
1122
}
651
1123
 
652
1124
 
656
1128
 
657
1129
  @param  session     Thread context
658
1130
  @param  find    Table to remove
 
1131
  @param  unlock  true  - free all locks on tables removed that are
 
1132
  done with LOCK TABLES
 
1133
  false - otherwise
659
1134
 
660
 
  @note because we risk the chance of deleting the share, we can't assume that it will exist past, this should be modified once we can use a TableShare::shared_ptr here.
 
1135
  @note When unlock parameter is false or current thread doesn't have
 
1136
  any tables locked with LOCK TABLES, tables are assumed to be
 
1137
  not locked (for example already unlocked).
661
1138
*/
662
1139
 
663
 
void Session::unlink_open_table(Table *find)
 
1140
void unlink_open_table(Session *session, Table *find, bool unlock)
664
1141
{
665
 
  const TableIdentifier::Key find_key(find->getShare()->getCacheKey());
666
 
  Table **prev;
667
 
  safe_mutex_assert_owner(table::Cache::singleton().mutex().native_handle());
668
 
 
 
1142
  char key[MAX_DBKEY_LENGTH];
 
1143
  uint32_t key_length= find->s->table_cache_key.length;
 
1144
  Table *list, **prev;
 
1145
 
 
1146
  safe_mutex_assert_owner(&LOCK_open);
 
1147
 
 
1148
  memcpy(key, find->s->table_cache_key.str, key_length);
669
1149
  /*
670
 
    Note that we need to hold table::Cache::singleton().mutex() while changing the
 
1150
    Note that we need to hold LOCK_open while changing the
671
1151
    open_tables list. Another thread may work on it.
672
 
    (See: table::Cache::singleton().removeTable(), mysql_wait_completed_table())
 
1152
    (See: remove_table_from_cache(), mysql_wait_completed_table())
673
1153
    Closing a MERGE child before the parent would be fatal if the
674
1154
    other thread tries to abort the MERGE lock in between.
675
1155
  */
676
 
  for (prev= &open_tables; *prev; )
 
1156
  for (prev= &session->open_tables; *prev; )
677
1157
  {
678
 
    Table *list= *prev;
 
1158
    list= *prev;
679
1159
 
680
 
    if (list->getShare()->getCacheKey() == find_key)
 
1160
    if (list->s->table_cache_key.length == key_length &&
 
1161
        !memcmp(list->s->table_cache_key.str, key, key_length))
681
1162
    {
 
1163
      if (unlock && session->locked_tables)
 
1164
        mysql_lock_remove(session, session->locked_tables, list, true);
 
1165
 
682
1166
      /* Remove table from open_tables list. */
683
 
      *prev= list->getNext();
684
 
 
 
1167
      *prev= list->next;
685
1168
      /* Close table. */
686
 
      table::remove_table(static_cast<table::Concurrent *>(list));
 
1169
      hash_delete(&open_cache,(unsigned char*) list); // Close table
687
1170
    }
688
1171
    else
689
1172
    {
690
1173
      /* Step to next entry in open_tables list. */
691
 
      prev= list->getNextPtr();
 
1174
      prev= &list->next;
692
1175
    }
693
1176
  }
694
1177
 
695
1178
  // Notify any 'refresh' threads
696
 
  locking::broadcast_refresh();
 
1179
  broadcast_refresh();
697
1180
}
698
1181
 
699
1182
 
716
1199
  table that was locked with LOCK TABLES.
717
1200
*/
718
1201
 
719
 
void Session::drop_open_table(Table *table, const TableIdentifier &identifier)
 
1202
void drop_open_table(Session *session, Table *table, const char *db_name,
 
1203
                     const char *table_name)
720
1204
{
721
 
  if (table->getShare()->getType())
722
 
  {
723
 
    close_temporary_table(table);
724
 
  }
 
1205
  if (table->s->tmp_table)
 
1206
    close_temporary_table(session, table, 1, 1);
725
1207
  else
726
1208
  {
727
 
    boost_unique_lock_t scoped_lock(table::Cache::singleton().mutex()); /* Close and drop a table (AUX routine) */
 
1209
    StorageEngine *table_type= table->s->db_type();
 
1210
    pthread_mutex_lock(&LOCK_open); /* Close and drop a table (AUX routine) */
728
1211
    /*
729
1212
      unlink_open_table() also tells threads waiting for refresh or close
730
1213
      that something has happened.
731
1214
    */
732
 
    unlink_open_table(table);
733
 
    plugin::StorageEngine::dropTable(*this, identifier);
 
1215
    unlink_open_table(session, table, false);
 
1216
    quick_rm_table(table_type, db_name, table_name, false);
 
1217
    pthread_mutex_unlock(&LOCK_open);
734
1218
  }
735
1219
}
736
1220
 
740
1224
 
741
1225
  SYNOPSIS
742
1226
  wait_for_condition()
743
 
  session       Thread Cursor
 
1227
  session       Thread handler
744
1228
  mutex mutex that is currently hold that is associated with condition
745
1229
  Will be unlocked on return
746
1230
  cond  Condition to wait for
747
1231
*/
748
1232
 
749
 
void Session::wait_for_condition(boost::mutex &mutex, boost::condition_variable_any &cond)
 
1233
void wait_for_condition(Session *session, pthread_mutex_t *mutex, pthread_cond_t *cond)
750
1234
{
751
1235
  /* Wait until the current table is up to date */
752
 
  const char *saved_proc_info;
753
 
  mysys_var->current_mutex= &mutex;
754
 
  mysys_var->current_cond= &cond;
755
 
  saved_proc_info= get_proc_info();
756
 
  set_proc_info("Waiting for table");
757
 
  {
758
 
    /*
759
 
      We must unlock mutex first to avoid deadlock becasue conditions are
760
 
      sent to this thread by doing locks in the following order:
761
 
      lock(mysys_var->mutex)
762
 
      lock(mysys_var->current_mutex)
763
 
 
764
 
      One by effect of this that one can only use wait_for_condition with
765
 
      condition variables that are guranteed to not disapper (freed) even if this
766
 
      mutex is unlocked
767
 
    */
768
 
    boost_unique_lock_t scopedLock(mutex, boost::adopt_lock_t());
769
 
    if (not getKilled())
770
 
    {
771
 
      cond.wait(scopedLock);
772
 
    }
773
 
  }
774
 
  boost_unique_lock_t mysys_scopedLock(mysys_var->mutex);
775
 
  mysys_var->current_mutex= 0;
776
 
  mysys_var->current_cond= 0;
777
 
  set_proc_info(saved_proc_info);
 
1236
  const char *proc_info;
 
1237
  session->mysys_var->current_mutex= mutex;
 
1238
  session->mysys_var->current_cond= cond;
 
1239
  proc_info=session->get_proc_info();
 
1240
  session->set_proc_info("Waiting for table");
 
1241
  if (!session->killed)
 
1242
    (void) pthread_cond_wait(cond, mutex);
 
1243
 
 
1244
  /*
 
1245
    We must unlock mutex first to avoid deadlock becasue conditions are
 
1246
    sent to this thread by doing locks in the following order:
 
1247
    lock(mysys_var->mutex)
 
1248
    lock(mysys_var->current_mutex)
 
1249
 
 
1250
    One by effect of this that one can only use wait_for_condition with
 
1251
    condition variables that are guranteed to not disapper (freed) even if this
 
1252
    mutex is unlocked
 
1253
  */
 
1254
 
 
1255
  pthread_mutex_unlock(mutex);
 
1256
  pthread_mutex_lock(&session->mysys_var->mutex);
 
1257
  session->mysys_var->current_mutex= 0;
 
1258
  session->mysys_var->current_cond= 0;
 
1259
  session->set_proc_info(proc_info);
 
1260
  pthread_mutex_unlock(&session->mysys_var->mutex);
 
1261
}
 
1262
 
 
1263
 
 
1264
/**
 
1265
  Exclusively name-lock a table that is already write-locked by the
 
1266
  current thread.
 
1267
 
 
1268
  @param session current thread context
 
1269
  @param tables table list containing one table to open.
 
1270
 
 
1271
  @return false on success, true otherwise.
 
1272
*/
 
1273
 
 
1274
bool name_lock_locked_table(Session *session, TableList *tables)
 
1275
{
 
1276
  /* Under LOCK TABLES we must only accept write locked tables. */
 
1277
  tables->table= find_locked_table(session, tables->db, tables->table_name);
 
1278
 
 
1279
  if (!tables->table)
 
1280
    my_error(ER_TABLE_NOT_LOCKED, MYF(0), tables->alias);
 
1281
  else if (tables->table->reginfo.lock_type <= TL_WRITE_DEFAULT)
 
1282
    my_error(ER_TABLE_NOT_LOCKED_FOR_WRITE, MYF(0), tables->alias);
 
1283
  else
 
1284
  {
 
1285
    /*
 
1286
      Ensures that table is opened only by this thread and that no
 
1287
      other statement will open this table.
 
1288
    */
 
1289
    wait_while_table_is_used(session, tables->table, HA_EXTRA_FORCE_REOPEN);
 
1290
    return(false);
 
1291
  }
 
1292
 
 
1293
  return(true);
 
1294
}
 
1295
 
 
1296
 
 
1297
/*
 
1298
  Open table which is already name-locked by this thread.
 
1299
 
 
1300
  SYNOPSIS
 
1301
  reopen_name_locked_table()
 
1302
  session         Thread handle
 
1303
  table_list  TableList object for table to be open, TableList::table
 
1304
  member should point to Table object which was used for
 
1305
  name-locking.
 
1306
  link_in     true  - if Table object for table to be opened should be
 
1307
  linked into Session::open_tables list.
 
1308
  false - placeholder used for name-locking is already in
 
1309
  this list so we only need to preserve Table::next
 
1310
  pointer.
 
1311
 
 
1312
  NOTE
 
1313
  This function assumes that its caller already acquired LOCK_open mutex.
 
1314
 
 
1315
  RETURN VALUE
 
1316
  false - Success
 
1317
  true  - Error
 
1318
*/
 
1319
 
 
1320
bool reopen_name_locked_table(Session* session, TableList* table_list, bool link_in)
 
1321
{
 
1322
  Table *table= table_list->table;
 
1323
  TableShare *share;
 
1324
  char *table_name= table_list->table_name;
 
1325
  Table orig_table;
 
1326
 
 
1327
  safe_mutex_assert_owner(&LOCK_open);
 
1328
 
 
1329
  if (session->killed || !table)
 
1330
    return true;
 
1331
 
 
1332
  orig_table= *table;
 
1333
 
 
1334
  if (open_unireg_entry(session, table, table_list, table_name,
 
1335
                        table->s->table_cache_key.str,
 
1336
                        table->s->table_cache_key.length))
 
1337
  {
 
1338
    intern_close_table(table);
 
1339
    /*
 
1340
      If there was an error during opening of table (for example if it
 
1341
      does not exist) '*table' object can be wiped out. To be able
 
1342
      properly release name-lock in this case we should restore this
 
1343
      object to its original state.
 
1344
    */
 
1345
    *table= orig_table;
 
1346
    return(true);
 
1347
  }
 
1348
 
 
1349
  share= table->s;
 
1350
  /*
 
1351
    We want to prevent other connections from opening this table until end
 
1352
    of statement as it is likely that modifications of table's metadata are
 
1353
    not yet finished (for example CREATE TRIGGER have to change .TRG file,
 
1354
    or we might want to drop table if CREATE TABLE ... SELECT fails).
 
1355
    This also allows us to assume that no other connection will sneak in
 
1356
    before we will get table-level lock on this table.
 
1357
  */
 
1358
  share->version=0;
 
1359
  table->in_use = session;
 
1360
 
 
1361
  if (link_in)
 
1362
  {
 
1363
    table->next= session->open_tables;
 
1364
    session->open_tables= table;
 
1365
  }
 
1366
  else
 
1367
  {
 
1368
    /*
 
1369
      Table object should be already in Session::open_tables list so we just
 
1370
      need to set Table::next correctly.
 
1371
    */
 
1372
    table->next= orig_table.next;
 
1373
  }
 
1374
 
 
1375
  table->tablenr=session->current_tablenr++;
 
1376
  table->used_fields=0;
 
1377
  table->const_table=0;
 
1378
  table->null_row= false;
 
1379
  table->maybe_null= false;
 
1380
  table->force_index= false;
 
1381
  table->status=STATUS_NO_RECORD;
 
1382
 
 
1383
  return false;
778
1384
}
779
1385
 
780
1386
 
791
1397
  case of failure.
792
1398
*/
793
1399
 
794
 
table::Placeholder *Session::table_cache_insert_placeholder(const drizzled::TableIdentifier &arg)
 
1400
Table *table_cache_insert_placeholder(Session *session, const char *key,
 
1401
                                      uint32_t key_length)
795
1402
{
796
 
  safe_mutex_assert_owner(table::Cache::singleton().mutex().native_handle());
 
1403
  Table *table;
 
1404
  TableShare *share;
 
1405
  char *key_buff;
 
1406
 
 
1407
  safe_mutex_assert_owner(&LOCK_open);
797
1408
 
798
1409
  /*
799
1410
    Create a table entry with the right key and with an old refresh version
 
1411
    Note that we must use my_multi_malloc() here as this is freed by the
 
1412
    table cache
800
1413
  */
801
 
  TableIdentifier identifier(arg.getSchemaName(), arg.getTableName(), message::Table::INTERNAL);
802
 
  table::Placeholder *table= new table::Placeholder(this, identifier);
803
 
 
804
 
  if (not table::Cache::singleton().insert(table))
 
1414
  if (!my_multi_malloc(MYF(MY_WME | MY_ZEROFILL),
 
1415
                       &table, sizeof(*table),
 
1416
                       &share, sizeof(*share),
 
1417
                       &key_buff, key_length,
 
1418
                       NULL))
 
1419
    return NULL;
 
1420
 
 
1421
  table->s= share;
 
1422
  share->set_table_cache_key(key_buff, key, key_length);
 
1423
  share->tmp_table= INTERNAL_TMP_TABLE;  // for intern_close_table
 
1424
  table->in_use= session;
 
1425
  table->locked_by_name=1;
 
1426
 
 
1427
  if (my_hash_insert(&open_cache, (unsigned char*)table))
805
1428
  {
806
 
    delete table;
807
 
 
 
1429
    free((unsigned char*) table);
808
1430
    return NULL;
809
1431
  }
810
1432
 
833
1455
  @retval  true   Error occured (OOM)
834
1456
  @retval  false  Success. 'table' parameter set according to above rules.
835
1457
*/
836
 
bool Session::lock_table_name_if_not_cached(const TableIdentifier &identifier, Table **table)
 
1458
 
 
1459
bool lock_table_name_if_not_cached(Session *session, const char *db,
 
1460
                                   const char *table_name, Table **table)
837
1461
{
838
 
  const TableIdentifier::Key &key(identifier.getKey());
839
 
 
840
 
  boost_unique_lock_t scope_lock(table::Cache::singleton().mutex()); /* Obtain a name lock even though table is not in cache (like for create table)  */
841
 
 
842
 
  table::CacheMap::iterator iter;
843
 
 
844
 
  iter= table::getCache().find(key);
845
 
 
846
 
  if (iter != table::getCache().end())
 
1462
  char key[MAX_DBKEY_LENGTH];
 
1463
  char *key_pos= key;
 
1464
  uint32_t key_length;
 
1465
 
 
1466
  key_pos= strcpy(key_pos, db) + strlen(db);
 
1467
  key_pos= strcpy(key_pos+1, table_name) + strlen(table_name);
 
1468
  key_length= (uint32_t) (key_pos-key)+1;
 
1469
 
 
1470
  pthread_mutex_lock(&LOCK_open); /* Obtain a name lock even though table is not in cache (like for create table)  */
 
1471
 
 
1472
  if (hash_search(&open_cache, (unsigned char *)key, key_length))
847
1473
  {
 
1474
    pthread_mutex_unlock(&LOCK_open);
848
1475
    *table= 0;
849
 
    return false;
 
1476
    return(false);
850
1477
  }
851
 
 
852
 
  if (not (*table= table_cache_insert_placeholder(identifier)))
 
1478
  if (!(*table= table_cache_insert_placeholder(session, key, key_length)))
853
1479
  {
854
 
    return true;
 
1480
    pthread_mutex_unlock(&LOCK_open);
 
1481
    return(true);
855
1482
  }
856
 
  (*table)->open_placeholder= true;
857
 
  (*table)->setNext(open_tables);
858
 
  open_tables= *table;
859
 
 
860
 
  return false;
 
1483
  (*table)->open_placeholder= 1;
 
1484
  (*table)->next= session->open_tables;
 
1485
  session->open_tables= *table;
 
1486
  pthread_mutex_unlock(&LOCK_open);
 
1487
  return(false);
861
1488
}
862
1489
 
863
1490
/*
893
1520
*/
894
1521
 
895
1522
 
896
 
Table *Session::openTable(TableList *table_list, bool *refresh, uint32_t flags)
 
1523
Table *open_table(Session *session, TableList *table_list, bool *refresh, uint32_t flags)
897
1524
{
898
 
  Table *table;
 
1525
  register Table *table;
 
1526
  char key[MAX_DBKEY_LENGTH];
 
1527
  unsigned int key_length;
899
1528
  const char *alias= table_list->alias;
 
1529
  HASH_SEARCH_STATE state;
900
1530
 
901
1531
  /* Parsing of partitioning information from .frm needs session->lex set up. */
902
 
  assert(lex->is_lex_started);
 
1532
  assert(session->lex->is_lex_started);
903
1533
 
904
1534
  /* find a unused table in the open table cache */
905
1535
  if (refresh)
906
1536
    *refresh= false;
907
1537
 
908
1538
  /* an open table operation needs a lot of the stack space */
909
 
  if (check_stack_overrun(this, STACK_MIN_SIZE_FOR_OPEN, (unsigned char *)&alias))
910
 
    return NULL;
911
 
 
912
 
  if (getKilled())
913
 
    return NULL;
914
 
 
915
 
  TableIdentifier identifier(table_list->getSchemaName(), table_list->getTableName());
916
 
  const TableIdentifier::Key &key(identifier.getKey());
917
 
  table::CacheRange ppp;
 
1539
  if (check_stack_overrun(session, STACK_MIN_SIZE_FOR_OPEN, (unsigned char *)&alias))
 
1540
    return NULL;
 
1541
 
 
1542
  if (session->killed)
 
1543
    return NULL;
 
1544
 
 
1545
  key_length= create_table_def_key(key, table_list);
918
1546
 
919
1547
  /*
920
1548
    Unless requested otherwise, try to resolve this table in the list
923
1551
    same name. This block implements the behaviour.
924
1552
    TODO -> move this block into a separate function.
925
1553
  */
926
 
  bool reset= false;
927
 
  for (table= getTemporaryTables(); table ; table=table->getNext())
 
1554
  for (table= session->temporary_tables; table ; table=table->next)
928
1555
  {
929
 
    if (table->getShare()->getCacheKey() == key)
 
1556
    if (table->s->table_cache_key.length == key_length && !memcmp(table->s->table_cache_key.str, key, key_length))
930
1557
    {
931
1558
      /*
932
1559
        We're trying to use the same temporary table twice in a query.
936
1563
      */
937
1564
      if (table->query_id)
938
1565
      {
939
 
        my_error(ER_CANT_REOPEN_TABLE, MYF(0), table->getAlias());
 
1566
        my_error(ER_CANT_REOPEN_TABLE, MYF(0), table->alias);
940
1567
        return NULL;
941
1568
      }
942
 
      table->query_id= getQueryId();
943
 
      reset= true;
944
 
      break;
 
1569
      table->query_id= session->query_id;
 
1570
      goto reset;
945
1571
    }
946
1572
  }
947
1573
 
948
 
  if (not reset)
 
1574
  if (flags & DRIZZLE_OPEN_TEMPORARY_ONLY)
949
1575
  {
950
 
    if (flags & DRIZZLE_OPEN_TEMPORARY_ONLY)
951
 
    {
952
 
      my_error(ER_NO_SUCH_TABLE, MYF(0), table_list->getSchemaName(), table_list->getTableName());
953
 
      return NULL;
954
 
    }
955
 
 
956
 
    /*
957
 
      If it's the first table from a list of tables used in a query,
958
 
      remember refresh_version (the version of open_cache state).
959
 
      If the version changes while we're opening the remaining tables,
960
 
      we will have to back off, close all the tables opened-so-far,
961
 
      and try to reopen them.
962
 
 
963
 
      Note-> refresh_version is currently changed only during FLUSH TABLES.
964
 
    */
965
 
    if (!open_tables)
966
 
    {
967
 
      version= refresh_version;
968
 
    }
969
 
    else if ((version != refresh_version) &&
970
 
             ! (flags & DRIZZLE_LOCK_IGNORE_FLUSH))
971
 
    {
972
 
      /* Someone did a refresh while thread was opening tables */
973
 
      if (refresh)
974
 
        *refresh= true;
975
 
 
976
 
      return NULL;
977
 
    }
978
 
 
979
 
    /*
980
 
      Before we test the global cache, we test our local session cache.
981
 
    */
982
 
    if (cached_table)
983
 
    {
984
 
      assert(false); /* Not implemented yet */
985
 
    }
986
 
 
987
 
    /*
988
 
      Non pre-locked/LOCK TABLES mode, and the table is not temporary:
989
 
      this is the normal use case.
990
 
      Now we should:
991
 
      - try to find the table in the table cache.
992
 
      - if one of the discovered Table instances is name-locked
993
 
      (table->getShare()->version == 0) back off -- we have to wait
994
 
      until no one holds a name lock on the table.
995
 
      - if there is no such Table in the name cache, read the table definition
996
 
      and insert it into the cache.
997
 
      We perform all of the above under table::Cache::singleton().mutex() which currently protects
998
 
      the open cache (also known as table cache) and table definitions stored
999
 
      on disk.
1000
 
    */
1001
 
 
1002
 
    {
1003
 
      table::Cache::singleton().mutex().lock(); /* Lock for FLUSH TABLES for open table */
1004
 
 
1005
 
      /*
1006
 
        Actually try to find the table in the open_cache.
1007
 
        The cache may contain several "Table" instances for the same
1008
 
        physical table. The instances that are currently "in use" by
1009
 
        some thread have their "in_use" member != NULL.
1010
 
        There is no good reason for having more than one entry in the
1011
 
        hash for the same physical table, except that we use this as
1012
 
        an implicit "pending locks queue" - see
1013
 
        wait_for_locked_table_names for details.
1014
 
      */
1015
 
      ppp= table::getCache().equal_range(key);
1016
 
 
1017
 
      table= NULL;
1018
 
      for (table::CacheMap::const_iterator iter= ppp.first;
1019
 
           iter != ppp.second; ++iter, table= NULL)
 
1576
    my_error(ER_NO_SUCH_TABLE, MYF(0), table_list->db, table_list->table_name);
 
1577
    return NULL;
 
1578
  }
 
1579
 
 
1580
  /*
 
1581
    The table is not temporary - if we're in pre-locked or LOCK TABLES
 
1582
    mode, let's try to find the requested table in the list of pre-opened
 
1583
    and locked tables. If the table is not there, return an error - we can't
 
1584
    open not pre-opened tables in pre-locked/LOCK TABLES mode.
 
1585
TODO: move this block into a separate function.
 
1586
  */
 
1587
  if (session->locked_tables)
 
1588
  { // Using table locks
 
1589
    Table *best_table= 0;
 
1590
    int best_distance= INT_MIN;
 
1591
    bool check_if_used= false;
 
1592
    for (table=session->open_tables; table ; table=table->next)
 
1593
    {
 
1594
      if (table->s->table_cache_key.length == key_length &&
 
1595
          !memcmp(table->s->table_cache_key.str, key, key_length))
1020
1596
      {
1021
 
        table= (*iter).second;
1022
 
 
1023
 
        if (not table->in_use)
1024
 
          break;
 
1597
        if (check_if_used && table->query_id &&
 
1598
            table->query_id != session->query_id)
 
1599
        {
 
1600
          /*
 
1601
            If we are in stored function or trigger we should ensure that
 
1602
            we won't change table that is already used by calling statement.
 
1603
            So if we are opening table for writing, we should check that it
 
1604
            is not already open by some calling stamement.
 
1605
          */
 
1606
          my_error(ER_CANT_UPDATE_USED_TABLE_IN_SF_OR_TRG, MYF(0),
 
1607
                   table->s->table_name.str);
 
1608
          return NULL;
 
1609
        }
1025
1610
        /*
1026
 
          Here we flush tables marked for flush.
1027
 
          Normally, table->getShare()->version contains the value of
1028
 
          refresh_version from the moment when this table was
1029
 
          (re-)opened and added to the cache.
1030
 
          If since then we did (or just started) FLUSH TABLES
1031
 
          statement, refresh_version has been increased.
1032
 
          For "name-locked" Table instances, table->getShare()->version is set
1033
 
          to 0 (see lock_table_name for details).
1034
 
          In case there is a pending FLUSH TABLES or a name lock, we
1035
 
          need to back off and re-start opening tables.
1036
 
          If we do not back off now, we may dead lock in case of lock
1037
 
          order mismatch with some other thread:
1038
 
          c1-> name lock t1; -- sort of exclusive lock
1039
 
          c2-> open t2;      -- sort of shared lock
1040
 
          c1-> name lock t2; -- blocks
1041
 
          c2-> open t1; -- blocks
 
1611
          When looking for a usable Table, ignore MERGE children, as they
 
1612
          belong to their parent and cannot be used explicitly.
1042
1613
        */
1043
 
        if (table->needs_reopen_or_name_lock())
1044
 
        {
1045
 
          if (flags & DRIZZLE_LOCK_IGNORE_FLUSH)
1046
 
          {
1047
 
            /* Force close at once after usage */
1048
 
            version= table->getShare()->getVersion();
1049
 
            continue;
1050
 
          }
1051
 
 
1052
 
          /* Avoid self-deadlocks by detecting self-dependencies. */
1053
 
          if (table->open_placeholder && table->in_use == this)
1054
 
          {
1055
 
            table::Cache::singleton().mutex().unlock();
1056
 
            my_error(ER_UPDATE_TABLE_USED, MYF(0), table->getShare()->getTableName());
1057
 
            return NULL;
1058
 
          }
1059
 
 
1060
 
          /*
1061
 
            Back off, part 1: mark the table as "unused" for the
1062
 
            purpose of name-locking by setting table->db_stat to 0. Do
1063
 
            that only for the tables in this thread that have an old
1064
 
            table->getShare()->version (this is an optimization (?)).
1065
 
            table->db_stat == 0 signals wait_for_locked_table_names
1066
 
            that the tables in question are not used any more. See
1067
 
            table_is_used call for details.
1068
 
          */
1069
 
          close_old_data_files(false, false);
1070
 
 
1071
 
          /*
1072
 
            Back-off part 2: try to avoid "busy waiting" on the table:
1073
 
            if the table is in use by some other thread, we suspend
1074
 
            and wait till the operation is complete: when any
1075
 
            operation that juggles with table->getShare()->version completes,
1076
 
            it broadcasts COND_refresh condition variable.
1077
 
            If 'old' table we met is in use by current thread we return
1078
 
            without waiting since in this situation it's this thread
1079
 
            which is responsible for broadcasting on COND_refresh
1080
 
            (and this was done already in Session::close_old_data_files()).
1081
 
            Good example of such situation is when we have statement
1082
 
            that needs two instances of table and FLUSH TABLES comes
1083
 
            after we open first instance but before we open second
1084
 
            instance.
1085
 
          */
1086
 
          if (table->in_use != this)
1087
 
          {
1088
 
            /* wait_for_conditionwill unlock table::Cache::singleton().mutex() for us */
1089
 
            wait_for_condition(table::Cache::singleton().mutex(), COND_refresh);
1090
 
          }
1091
 
          else
1092
 
          {
1093
 
            table::Cache::singleton().mutex().unlock();
1094
 
          }
1095
 
          /*
1096
 
            There is a refresh in progress for this table.
1097
 
            Signal the caller that it has to try again.
1098
 
          */
1099
 
          if (refresh)
1100
 
            *refresh= true;
1101
 
          return NULL;
1102
 
        }
1103
 
      }
1104
 
      if (table)
1105
 
      {
1106
 
        table::getUnused().unlink(static_cast<table::Concurrent *>(table));
1107
 
        table->in_use= this;
1108
 
      }
1109
 
      else
1110
 
      {
1111
 
        /* Insert a new Table instance into the open cache */
1112
 
        int error;
1113
 
        /* Free cache if too big */
1114
 
        table::getUnused().cull();
1115
 
 
1116
 
        if (table_list->isCreate())
1117
 
        {
1118
 
          TableIdentifier  lock_table_identifier(table_list->getSchemaName(), table_list->getTableName(), message::Table::STANDARD);
1119
 
 
1120
 
          if (not plugin::StorageEngine::doesTableExist(*this, lock_table_identifier))
1121
 
          {
1122
 
            /*
1123
 
              Table to be created, so we need to create placeholder in table-cache.
1124
 
            */
1125
 
            if (!(table= table_cache_insert_placeholder(lock_table_identifier)))
 
1614
        if (!my_strcasecmp(system_charset_info, table->alias, alias) &&
 
1615
            table->query_id != session->query_id)  /* skip tables already used */
 
1616
        {
 
1617
          int distance= ((int) table->reginfo.lock_type -
 
1618
                         (int) table_list->lock_type);
 
1619
          /*
 
1620
            Find a table that either has the exact lock type requested,
 
1621
            or has the best suitable lock. In case there is no locked
 
1622
            table that has an equal or higher lock than requested,
 
1623
            we us the closest matching lock to be able to produce an error
 
1624
            message about wrong lock mode on the table. The best_table
 
1625
            is changed if bd < 0 <= d or bd < d < 0 or 0 <= d < bd.
 
1626
 
 
1627
            distance <  0 - No suitable lock found
 
1628
            distance >  0 - we have lock mode higher then we require
 
1629
            distance == 0 - we have lock mode exactly which we need
 
1630
          */
 
1631
          if ((best_distance < 0 && distance > best_distance) || (distance >= 0 && distance < best_distance))
 
1632
          {
 
1633
            best_distance= distance;
 
1634
            best_table= table;
 
1635
            if (best_distance == 0 && !check_if_used)
1126
1636
            {
1127
 
              table::Cache::singleton().mutex().unlock();
1128
 
              return NULL;
 
1637
              /*
 
1638
                If we have found perfect match and we don't need to check that
 
1639
                table is not used by one of calling statements (assuming that
 
1640
                we are inside of function or trigger) we can finish iterating
 
1641
                through open tables list.
 
1642
              */
 
1643
              break;
1129
1644
            }
1130
 
            /*
1131
 
              Link placeholder to the open tables list so it will be automatically
1132
 
              removed once tables are closed. Also mark it so it won't be ignored
1133
 
              by other trying to take name-lock.
1134
 
            */
1135
 
            table->open_placeholder= true;
1136
 
            table->setNext(open_tables);
1137
 
            open_tables= table;
1138
 
            table::Cache::singleton().mutex().unlock();
1139
 
 
1140
 
            return table ;
1141
 
          }
1142
 
          /* Table exists. Let us try to open it. */
1143
 
        }
1144
 
 
1145
 
        /* make a new table */
1146
 
        {
1147
 
          table::Concurrent *new_table= new table::Concurrent;
1148
 
          table= new_table;
1149
 
          if (new_table == NULL)
1150
 
          {
1151
 
            table::Cache::singleton().mutex().unlock();
1152
 
            return NULL;
1153
 
          }
1154
 
 
1155
 
          error= new_table->open_unireg_entry(this, alias, identifier);
1156
 
          if (error != 0)
1157
 
          {
1158
 
            delete new_table;
1159
 
            table::Cache::singleton().mutex().unlock();
1160
 
            return NULL;
1161
 
          }
1162
 
          (void)table::Cache::singleton().insert(new_table);
 
1645
          }
1163
1646
        }
1164
1647
      }
1165
 
 
1166
 
      table::Cache::singleton().mutex().unlock();
1167
 
    }
 
1648
    }
 
1649
    if (best_table)
 
1650
    {
 
1651
      table= best_table;
 
1652
      table->query_id= session->query_id;
 
1653
      goto reset;
 
1654
    }
 
1655
    /*
 
1656
      No table in the locked tables list. In case of explicit LOCK TABLES
 
1657
      this can happen if a user did not include the able into the list.
 
1658
      In case of pre-locked mode locked tables list is generated automatically,
 
1659
      so we may only end up here if the table did not exist when
 
1660
      locked tables list was created.
 
1661
    */
 
1662
    my_error(ER_TABLE_NOT_LOCKED, MYF(0), alias);
 
1663
    return NULL;
 
1664
  }
 
1665
 
 
1666
  /*
 
1667
    If it's the first table from a list of tables used in a query,
 
1668
    remember refresh_version (the version of open_cache state).
 
1669
    If the version changes while we're opening the remaining tables,
 
1670
    we will have to back off, close all the tables opened-so-far,
 
1671
    and try to reopen them.
 
1672
 
 
1673
    Note-> refresh_version is currently changed only during FLUSH TABLES.
 
1674
  */
 
1675
  if (!session->open_tables)
 
1676
    session->version=refresh_version;
 
1677
  else if ((session->version != refresh_version) &&
 
1678
           ! (flags & DRIZZLE_LOCK_IGNORE_FLUSH))
 
1679
  {
 
1680
    /* Someone did a refresh while thread was opening tables */
1168
1681
    if (refresh)
1169
 
    {
1170
 
      table->setNext(open_tables); /* Link into simple list */
1171
 
      open_tables= table;
1172
 
    }
1173
 
    table->reginfo.lock_type= TL_READ; /* Assume read */
1174
 
 
1175
 
  }
1176
 
  assert(table->getShare()->getTableCount() > 0 || table->getShare()->getType() != message::Table::STANDARD);
1177
 
 
 
1682
      *refresh= true;
 
1683
    pthread_mutex_unlock(&LOCK_open);
 
1684
 
 
1685
    return NULL;
 
1686
  }
 
1687
 
 
1688
  /*
 
1689
    Before we test the global cache, we test our local session cache.
 
1690
  */
 
1691
  if (session->cached_table)
 
1692
  {
 
1693
    assert(false); /* Not implemented yet */
 
1694
  }
 
1695
 
 
1696
  /*
 
1697
    Non pre-locked/LOCK TABLES mode, and the table is not temporary:
 
1698
    this is the normal use case.
 
1699
    Now we should:
 
1700
    - try to find the table in the table cache.
 
1701
    - if one of the discovered Table instances is name-locked
 
1702
    (table->s->version == 0) back off -- we have to wait
 
1703
    until no one holds a name lock on the table.
 
1704
    - if there is no such Table in the name cache, read the table definition
 
1705
    and insert it into the cache.
 
1706
    We perform all of the above under LOCK_open which currently protects
 
1707
    the open cache (also known as table cache) and table definitions stored
 
1708
    on disk.
 
1709
  */
 
1710
 
 
1711
  pthread_mutex_lock(&LOCK_open); /* Lock for FLUSH TABLES for open table */
 
1712
 
 
1713
  /*
 
1714
    Actually try to find the table in the open_cache.
 
1715
    The cache may contain several "Table" instances for the same
 
1716
    physical table. The instances that are currently "in use" by
 
1717
    some thread have their "in_use" member != NULL.
 
1718
    There is no good reason for having more than one entry in the
 
1719
    hash for the same physical table, except that we use this as
 
1720
    an implicit "pending locks queue" - see
 
1721
    wait_for_locked_table_names for details.
 
1722
  */
 
1723
  for (table= (Table*) hash_first(&open_cache, (unsigned char*) key, key_length,
 
1724
                                  &state);
 
1725
       table && table->in_use ;
 
1726
       table= (Table*) hash_next(&open_cache, (unsigned char*) key, key_length,
 
1727
                                 &state))
 
1728
  {
 
1729
    /*
 
1730
      Here we flush tables marked for flush.
 
1731
      Normally, table->s->version contains the value of
 
1732
      refresh_version from the moment when this table was
 
1733
      (re-)opened and added to the cache.
 
1734
      If since then we did (or just started) FLUSH TABLES
 
1735
      statement, refresh_version has been increased.
 
1736
      For "name-locked" Table instances, table->s->version is set
 
1737
      to 0 (see lock_table_name for details).
 
1738
      In case there is a pending FLUSH TABLES or a name lock, we
 
1739
      need to back off and re-start opening tables.
 
1740
      If we do not back off now, we may dead lock in case of lock
 
1741
      order mismatch with some other thread:
 
1742
c1: name lock t1; -- sort of exclusive lock
 
1743
c2: open t2;      -- sort of shared lock
 
1744
c1: name lock t2; -- blocks
 
1745
c2: open t1; -- blocks
 
1746
    */
 
1747
    if (table->needs_reopen_or_name_lock())
 
1748
    {
 
1749
      if (flags & DRIZZLE_LOCK_IGNORE_FLUSH)
 
1750
      {
 
1751
        /* Force close at once after usage */
 
1752
        session->version= table->s->version;
 
1753
        continue;
 
1754
      }
 
1755
 
 
1756
      /* Avoid self-deadlocks by detecting self-dependencies. */
 
1757
      if (table->open_placeholder && table->in_use == session)
 
1758
      {
 
1759
        pthread_mutex_unlock(&LOCK_open);
 
1760
        my_error(ER_UPDATE_TABLE_USED, MYF(0), table->s->table_name.str);
 
1761
        return NULL;
 
1762
      }
 
1763
 
 
1764
      /*
 
1765
        Back off, part 1: mark the table as "unused" for the
 
1766
        purpose of name-locking by setting table->db_stat to 0. Do
 
1767
        that only for the tables in this thread that have an old
 
1768
        table->s->version (this is an optimization (?)).
 
1769
        table->db_stat == 0 signals wait_for_locked_table_names
 
1770
        that the tables in question are not used any more. See
 
1771
        table_is_used call for details.
 
1772
 
 
1773
        Notice that HANDLER tables were already taken care of by
 
1774
        the earlier call to mysql_ha_flush() in this same critical
 
1775
        section.
 
1776
      */
 
1777
      close_old_data_files(session,session->open_tables,0,0);
 
1778
      /*
 
1779
        Back-off part 2: try to avoid "busy waiting" on the table:
 
1780
        if the table is in use by some other thread, we suspend
 
1781
        and wait till the operation is complete: when any
 
1782
        operation that juggles with table->s->version completes,
 
1783
        it broadcasts COND_refresh condition variable.
 
1784
        If 'old' table we met is in use by current thread we return
 
1785
        without waiting since in this situation it's this thread
 
1786
        which is responsible for broadcasting on COND_refresh
 
1787
        (and this was done already in close_old_data_files()).
 
1788
        Good example of such situation is when we have statement
 
1789
        that needs two instances of table and FLUSH TABLES comes
 
1790
        after we open first instance but before we open second
 
1791
        instance.
 
1792
      */
 
1793
      if (table->in_use != session)
 
1794
      {
 
1795
        /* wait_for_conditionwill unlock LOCK_open for us */
 
1796
        wait_for_condition(session, &LOCK_open, &COND_refresh);
 
1797
      }
 
1798
      else
 
1799
      {
 
1800
        pthread_mutex_unlock(&LOCK_open);
 
1801
      }
 
1802
      /*
 
1803
        There is a refresh in progress for this table.
 
1804
        Signal the caller that it has to try again.
 
1805
      */
 
1806
      if (refresh)
 
1807
        *refresh= true;
 
1808
      return NULL;
 
1809
    }
 
1810
  }
 
1811
  if (table)
 
1812
  {
 
1813
    /* Unlink the table from "unused_tables" list. */
 
1814
    if (table == unused_tables)
 
1815
    {  // First unused
 
1816
      unused_tables=unused_tables->next; // Remove from link
 
1817
      if (table == unused_tables)
 
1818
        unused_tables= NULL;
 
1819
    }
 
1820
    table->prev->next=table->next; /* Remove from unused list */
 
1821
    table->next->prev=table->prev;
 
1822
    table->in_use= session;
 
1823
  }
 
1824
  else
 
1825
  {
 
1826
    /* Insert a new Table instance into the open cache */
 
1827
    int error;
 
1828
    /* Free cache if too big */
 
1829
    while (open_cache.records > table_cache_size && unused_tables)
 
1830
      hash_delete(&open_cache,(unsigned char*) unused_tables); /* purecov: tested */
 
1831
 
 
1832
    if (table_list->create)
 
1833
    {
 
1834
      if (ha_table_exists_in_engine(session, table_list->db,
 
1835
                                    table_list->table_name)
 
1836
          != HA_ERR_TABLE_EXIST)
 
1837
      {
 
1838
        /*
 
1839
          Table to be created, so we need to create placeholder in table-cache.
 
1840
        */
 
1841
        if (!(table= table_cache_insert_placeholder(session, key, key_length)))
 
1842
        {
 
1843
          pthread_mutex_unlock(&LOCK_open);
 
1844
          return NULL;
 
1845
        }
 
1846
        /*
 
1847
          Link placeholder to the open tables list so it will be automatically
 
1848
          removed once tables are closed. Also mark it so it won't be ignored
 
1849
          by other trying to take name-lock.
 
1850
        */
 
1851
        table->open_placeholder= true;
 
1852
        table->next= session->open_tables;
 
1853
        session->open_tables= table;
 
1854
        pthread_mutex_unlock(&LOCK_open);
 
1855
        return table ;
 
1856
      }
 
1857
      /* Table exists. Let us try to open it. */
 
1858
    }
 
1859
 
 
1860
    /* make a new table */
 
1861
    table= new Table;
 
1862
    if (table == NULL)
 
1863
    {
 
1864
      pthread_mutex_unlock(&LOCK_open);
 
1865
      return NULL;
 
1866
    }
 
1867
 
 
1868
    error= open_unireg_entry(session, table, table_list, alias, key, key_length);
 
1869
    if (error != 0)
 
1870
    {
 
1871
      free(table);
 
1872
      pthread_mutex_unlock(&LOCK_open);
 
1873
      return NULL;
 
1874
    }
 
1875
    my_hash_insert(&open_cache, (unsigned char*) table);
 
1876
  }
 
1877
 
 
1878
  pthread_mutex_unlock(&LOCK_open);
 
1879
  if (refresh)
 
1880
  {
 
1881
    table->next=session->open_tables; /* Link into simple list */
 
1882
    session->open_tables=table;
 
1883
  }
 
1884
  table->reginfo.lock_type= TL_READ; /* Assume read */
 
1885
 
 
1886
reset:
 
1887
  assert(table->s->ref_count > 0 || table->s->tmp_table != NO_TMP_TABLE);
 
1888
 
 
1889
  if (session->lex->need_correct_ident())
 
1890
    table->alias_name_used= my_strcasecmp(table_alias_charset,
 
1891
                                          table->s->table_name.str, alias);
1178
1892
  /* Fix alias if table name changes */
1179
 
  if (strcmp(table->getAlias(), alias))
 
1893
  if (strcmp(table->alias, alias))
1180
1894
  {
1181
 
    table->setAlias(alias);
 
1895
    uint32_t length=(uint32_t) strlen(alias)+1;
 
1896
    table->alias= (char*) realloc((char*) table->alias, length);
 
1897
    memcpy((void*) table->alias, alias, length);
1182
1898
  }
1183
1899
 
1184
1900
  /* These variables are also set in reopen_table() */
1185
 
  table->tablenr= current_tablenr++;
 
1901
  table->tablenr=session->current_tablenr++;
1186
1902
  table->used_fields= 0;
1187
1903
  table->const_table= 0;
1188
1904
  table->null_row= false;
1189
1905
  table->maybe_null= false;
1190
1906
  table->force_index= false;
1191
1907
  table->status=STATUS_NO_RECORD;
1192
 
  table->insert_values.clear();
 
1908
  table->insert_values= 0;
1193
1909
  /* Catch wrong handling of the auto_increment_field_not_null. */
1194
1910
  assert(!table->auto_increment_field_not_null);
1195
1911
  table->auto_increment_field_not_null= false;
1196
1912
  if (table->timestamp_field)
1197
 
  {
1198
1913
    table->timestamp_field_type= table->timestamp_field->get_auto_set_type();
1199
 
  }
1200
1914
  table->pos_in_table_list= table_list;
1201
1915
  table->clear_column_bitmaps();
1202
1916
  assert(table->key_read == 0);
1205
1919
}
1206
1920
 
1207
1921
 
 
1922
Table *find_locked_table(Session *session, const char *db,const char *table_name)
 
1923
{
 
1924
  char key[MAX_DBKEY_LENGTH];
 
1925
  char *key_pos= key;
 
1926
  uint32_t key_length;
 
1927
 
 
1928
  key_pos= strcpy(key_pos, db) + strlen(db);
 
1929
  key_pos= strcpy(key_pos+1, table_name) + strlen(table_name);
 
1930
  key_length= (uint32_t)(key_pos-key)+1;
 
1931
 
 
1932
  for (Table *table=session->open_tables; table ; table=table->next)
 
1933
  {
 
1934
    if (table->s->table_cache_key.length == key_length &&
 
1935
        !memcmp(table->s->table_cache_key.str, key, key_length))
 
1936
      return table;
 
1937
  }
 
1938
  return(0);
 
1939
}
 
1940
 
 
1941
 
 
1942
/*
 
1943
  Reopen an table because the definition has changed.
 
1944
 
 
1945
  SYNOPSIS
 
1946
  reopen_table()
 
1947
  table Table object
 
1948
 
 
1949
  NOTES
 
1950
  The data file for the table is already closed and the share is released
 
1951
  The table has a 'dummy' share that mainly contains database and table name.
 
1952
 
 
1953
  RETURN
 
1954
  0  ok
 
1955
  1  error. The old table object is not changed.
 
1956
*/
 
1957
 
 
1958
bool reopen_table(Table *table)
 
1959
{
 
1960
  Table tmp;
 
1961
  bool error= 1;
 
1962
  Field **field;
 
1963
  uint32_t key,part;
 
1964
  TableList table_list;
 
1965
  Session *session= table->in_use;
 
1966
 
 
1967
  assert(table->s->ref_count == 0);
 
1968
  assert(!table->sort.io_cache);
 
1969
 
 
1970
#ifdef EXTRA_DEBUG
 
1971
  if (table->db_stat)
 
1972
    errmsg_printf(ERRMSG_LVL_ERROR, _("Table %s had a open data handler in reopen_table"),
 
1973
                  table->alias);
 
1974
#endif
 
1975
  table_list.db=         table->s->db.str;
 
1976
  table_list.table_name= table->s->table_name.str;
 
1977
  table_list.table=      table;
 
1978
 
 
1979
  if (wait_for_locked_table_names(session, &table_list))
 
1980
    return(1);                             // Thread was killed
 
1981
 
 
1982
  if (open_unireg_entry(session, &tmp, &table_list,
 
1983
                        table->alias,
 
1984
                        table->s->table_cache_key.str,
 
1985
                        table->s->table_cache_key.length))
 
1986
    goto end;
 
1987
 
 
1988
  /* This list copies variables set by open_table */
 
1989
  tmp.tablenr=          table->tablenr;
 
1990
  tmp.used_fields=      table->used_fields;
 
1991
  tmp.const_table=      table->const_table;
 
1992
  tmp.null_row=         table->null_row;
 
1993
  tmp.maybe_null=       table->maybe_null;
 
1994
  tmp.status=           table->status;
 
1995
 
 
1996
  /* Get state */
 
1997
  tmp.in_use=           session;
 
1998
  tmp.reginfo.lock_type=table->reginfo.lock_type;
 
1999
 
 
2000
  /* Replace table in open list */
 
2001
  tmp.next=             table->next;
 
2002
  tmp.prev=             table->prev;
 
2003
 
 
2004
  if (table->file)
 
2005
    table->closefrm(true);              // close file, free everything
 
2006
 
 
2007
  *table= tmp;
 
2008
  table->default_column_bitmaps();
 
2009
  table->file->change_table_ptr(table, table->s);
 
2010
 
 
2011
  assert(table->alias != 0);
 
2012
  for (field=table->field ; *field ; field++)
 
2013
  {
 
2014
    (*field)->table= (*field)->orig_table= table;
 
2015
    (*field)->table_name= &table->alias;
 
2016
  }
 
2017
  for (key=0 ; key < table->s->keys ; key++)
 
2018
  {
 
2019
    for (part=0 ; part < table->key_info[key].usable_key_parts ; part++)
 
2020
      table->key_info[key].key_part[part].field->table= table;
 
2021
  }
 
2022
  /*
 
2023
    Do not attach MERGE children here. The children might be reopened
 
2024
    after the parent. Attach children after reopening all tables that
 
2025
    require reopen. See for example reopen_tables().
 
2026
  */
 
2027
 
 
2028
  broadcast_refresh();
 
2029
  error=0;
 
2030
 
 
2031
end:
 
2032
  return(error);
 
2033
}
 
2034
 
 
2035
 
1208
2036
/**
1209
2037
  Close all instances of a table open by this thread and replace
1210
2038
  them with exclusive name-locks.
1222
2050
  the strings are used in a loop even after the share may be freed.
1223
2051
*/
1224
2052
 
1225
 
void Session::close_data_files_and_morph_locks(const TableIdentifier &identifier)
 
2053
void close_data_files_and_morph_locks(Session *session, const char *db,
 
2054
                                      const char *table_name)
1226
2055
{
1227
 
  safe_mutex_assert_owner(table::Cache::singleton().mutex().native_handle()); /* Adjust locks at the end of ALTER TABLEL */
1228
 
 
1229
 
  if (lock)
 
2056
  Table *table;
 
2057
 
 
2058
  safe_mutex_assert_owner(&LOCK_open); /* Adjust locks at the end of ALTER TABLEL */
 
2059
 
 
2060
  if (session->lock)
1230
2061
  {
1231
2062
    /*
1232
2063
      If we are not under LOCK TABLES we should have only one table
1233
2064
      open and locked so it makes sense to remove the lock at once.
1234
2065
    */
1235
 
    unlockTables(lock);
1236
 
    lock= 0;
 
2066
    mysql_unlock_tables(session, session->lock);
 
2067
    session->lock= 0;
1237
2068
  }
1238
2069
 
1239
2070
  /*
1241
2072
    for target table name if we process ALTER Table ... RENAME.
1242
2073
    So loop below makes sense even if we are not under LOCK TABLES.
1243
2074
  */
1244
 
  for (Table *table= open_tables; table ; table=table->getNext())
 
2075
  for (table=session->open_tables; table ; table=table->next)
1245
2076
  {
1246
 
    if (table->getShare()->getCacheKey() == identifier.getKey())
 
2077
    if (!strcmp(table->s->table_name.str, table_name) &&
 
2078
        !strcmp(table->s->db.str, db))
1247
2079
    {
1248
 
      table->open_placeholder= true;
 
2080
      if (session->locked_tables)
 
2081
      {
 
2082
        mysql_lock_remove(session, session->locked_tables, table, true);
 
2083
      }
 
2084
      table->open_placeholder= 1;
1249
2085
      close_handle_and_leave_table_as_lock(table);
1250
2086
    }
1251
2087
  }
1265
2101
  situations like FLUSH TABLES or ALTER Table. In general
1266
2102
  case one should just repeat open_tables()/lock_tables()
1267
2103
  combination when one needs tables to be reopened (for
1268
 
  example see openTablesLock()).
 
2104
  example see open_and_lock_tables()).
1269
2105
 
1270
 
  @note One should have lock on table::Cache::singleton().mutex() when calling this.
 
2106
  @note One should have lock on LOCK_open when calling this.
1271
2107
 
1272
2108
  @return false in case of success, true - otherwise.
1273
2109
*/
1274
2110
 
1275
 
bool Session::reopen_tables(bool get_locks, bool)
 
2111
bool reopen_tables(Session *session, bool get_locks, bool mark_share_as_old)
1276
2112
{
1277
2113
  Table *table,*next,**prev;
1278
2114
  Table **tables,**tables_ptr;                  // For locks
1281
2117
    DRIZZLE_LOCK_IGNORE_GLOBAL_READ_LOCK |
1282
2118
    DRIZZLE_LOCK_IGNORE_FLUSH;
1283
2119
 
1284
 
  if (open_tables == NULL)
1285
 
    return false;
 
2120
  if (!session->open_tables)
 
2121
    return(0);
1286
2122
 
1287
 
  safe_mutex_assert_owner(table::Cache::singleton().mutex().native_handle());
 
2123
  safe_mutex_assert_owner(&LOCK_open);
1288
2124
  if (get_locks)
1289
2125
  {
1290
2126
    /*
1291
2127
      The ptr is checked later
1292
2128
      Do not handle locks of MERGE children.
1293
2129
    */
1294
 
    uint32_t opens= 0;
1295
 
 
1296
 
    for (table= open_tables; table ; table=table->getNext())
1297
 
    {
 
2130
    uint32_t opens=0;
 
2131
    for (table= session->open_tables; table ; table=table->next)
1298
2132
      opens++;
1299
 
    }
1300
 
    tables= new Table *[opens];
 
2133
    tables= (Table**) malloc(sizeof(Table*)*opens);
1301
2134
  }
1302
2135
  else
1303
 
  {
1304
 
    tables= &open_tables;
1305
 
  }
 
2136
    tables= &session->open_tables;
1306
2137
  tables_ptr =tables;
1307
2138
 
1308
 
  prev= &open_tables;
1309
 
  for (table= open_tables; table ; table=next)
 
2139
  prev= &session->open_tables;
 
2140
  for (table=session->open_tables; table ; table=next)
1310
2141
  {
1311
 
    next= table->getNext();
1312
 
 
1313
 
    my_error(ER_CANT_REOPEN_TABLE, MYF(0), table->getAlias());
1314
 
    table::remove_table(static_cast<table::Concurrent *>(table));
1315
 
    error= 1;
 
2142
    uint32_t db_stat=table->db_stat;
 
2143
    next=table->next;
 
2144
    if (!tables || (!db_stat && reopen_table(table)))
 
2145
    {
 
2146
      my_error(ER_CANT_REOPEN_TABLE, MYF(0), table->alias);
 
2147
      hash_delete(&open_cache,(unsigned char*) table);
 
2148
      error=1;
 
2149
    }
 
2150
    else
 
2151
    {
 
2152
      *prev= table;
 
2153
      prev= &table->next;
 
2154
      /* Do not handle locks of MERGE children. */
 
2155
      if (get_locks && !db_stat)
 
2156
        *tables_ptr++= table;                   // need new lock on this
 
2157
      if (mark_share_as_old)
 
2158
      {
 
2159
        table->s->version=0;
 
2160
        table->open_placeholder= 0;
 
2161
      }
 
2162
    }
1316
2163
  }
1317
2164
  *prev=0;
1318
2165
  if (tables != tables_ptr)                     // Should we get back old locks
1319
2166
  {
1320
 
    DrizzleLock *local_lock;
 
2167
    DRIZZLE_LOCK *lock;
1321
2168
    /*
1322
2169
      We should always get these locks. Anyway, we must not go into
1323
 
      wait_for_tables() as it tries to acquire table::Cache::singleton().mutex(), which is
 
2170
      wait_for_tables() as it tries to acquire LOCK_open, which is
1324
2171
      already locked.
1325
2172
    */
1326
 
    some_tables_deleted= false;
1327
 
 
1328
 
    if ((local_lock= lockTables(tables, (uint32_t) (tables_ptr - tables),
1329
 
                                       flags, &not_used)))
 
2173
    session->some_tables_deleted=0;
 
2174
    if ((lock= mysql_lock_tables(session, tables, (uint32_t) (tables_ptr - tables),
 
2175
                                 flags, &not_used)))
1330
2176
    {
1331
 
      /* unused */
 
2177
      session->locked_tables=mysql_lock_merge(session->locked_tables,lock);
1332
2178
    }
1333
2179
    else
1334
2180
    {
1341
2187
      error=1;
1342
2188
    }
1343
2189
  }
1344
 
 
1345
2190
  if (get_locks && tables)
1346
 
    delete [] tables;
1347
 
 
1348
 
  locking::broadcast_refresh();
1349
 
 
 
2191
  {
 
2192
    free((unsigned char*) tables);
 
2193
  }
 
2194
  broadcast_refresh();
1350
2195
  return(error);
1351
2196
}
1352
2197
 
1365
2210
  @param send_refresh  Should we awake waiters even if we didn't close any tables?
1366
2211
*/
1367
2212
 
1368
 
void Session::close_old_data_files(bool morph_locks, bool send_refresh)
 
2213
static void close_old_data_files(Session *session, Table *table, bool morph_locks,
 
2214
                                 bool send_refresh)
1369
2215
{
1370
2216
  bool found= send_refresh;
1371
2217
 
1372
 
  Table *table= open_tables;
1373
 
 
1374
 
  for (; table ; table=table->getNext())
 
2218
  for (; table ; table=table->next)
1375
2219
  {
1376
2220
    /*
1377
2221
      Reopen marked for flush.
1392
2236
              lock on it. This will also give them a chance to close their
1393
2237
              instances of this table.
1394
2238
            */
1395
 
            abortLock(ulcktbl);
1396
 
            removeLock(ulcktbl);
 
2239
            mysql_lock_abort(session, ulcktbl, true);
 
2240
            mysql_lock_remove(session, session->locked_tables, ulcktbl, true);
1397
2241
            ulcktbl->lock_count= 0;
1398
2242
          }
1399
2243
          if ((ulcktbl != table) && ulcktbl->db_stat)
1404
2248
              as a placeholder. When this happens, do not clear the
1405
2249
              placeholder flag. See the branch below ("***").
1406
2250
            */
1407
 
            ulcktbl->open_placeholder= true;
 
2251
            ulcktbl->open_placeholder= 1;
1408
2252
            close_handle_and_leave_table_as_lock(ulcktbl);
1409
2253
          }
1410
2254
          /*
1411
2255
            We want to protect the table from concurrent DDL operations
1412
2256
            (like RENAME Table) until we will re-open and re-lock it.
1413
2257
          */
1414
 
          table->open_placeholder= true;
 
2258
          table->open_placeholder= 1;
1415
2259
        }
1416
2260
        close_handle_and_leave_table_as_lock(table);
1417
2261
      }
1428
2272
          flag has been set because of a former close through a child.
1429
2273
          See above the comment that refers to this note.
1430
2274
        */
1431
 
        table->open_placeholder= false;
 
2275
        table->open_placeholder= 0;
1432
2276
      }
1433
2277
    }
1434
2278
  }
1435
2279
  if (found)
1436
 
    locking::broadcast_refresh();
 
2280
    broadcast_refresh();
 
2281
}
 
2282
 
 
2283
 
 
2284
/*
 
2285
  Wait until all threads has closed the tables in the list
 
2286
  We have also to wait if there is thread that has a lock on this table even
 
2287
  if the table is closed
 
2288
*/
 
2289
 
 
2290
bool table_is_used(Table *table, bool wait_for_name_lock)
 
2291
{
 
2292
  do
 
2293
  {
 
2294
    char *key= table->s->table_cache_key.str;
 
2295
    uint32_t key_length= table->s->table_cache_key.length;
 
2296
 
 
2297
    HASH_SEARCH_STATE state;
 
2298
    for (Table *search= (Table*) hash_first(&open_cache, (unsigned char*) key,
 
2299
                                            key_length, &state);
 
2300
         search ;
 
2301
         search= (Table*) hash_next(&open_cache, (unsigned char*) key,
 
2302
                                    key_length, &state))
 
2303
    {
 
2304
      if (search->in_use == table->in_use)
 
2305
        continue;                               // Name locked by this thread
 
2306
      /*
 
2307
        We can't use the table under any of the following conditions:
 
2308
        - There is an name lock on it (Table is to be deleted or altered)
 
2309
        - If we are in flush table and we didn't execute the flush
 
2310
        - If the table engine is open and it's an old version
 
2311
        (We must wait until all engines are shut down to use the table)
 
2312
      */
 
2313
      if ( (search->locked_by_name && wait_for_name_lock) ||
 
2314
           (search->is_name_opened() && search->needs_reopen_or_name_lock()))
 
2315
        return(1);
 
2316
    }
 
2317
  } while ((table=table->next));
 
2318
  return(0);
1437
2319
}
1438
2320
 
1439
2321
 
1444
2326
  bool result;
1445
2327
 
1446
2328
  session->set_proc_info("Waiting for tables");
1447
 
  {
1448
 
    boost_unique_lock_t lock(table::Cache::singleton().mutex());
1449
 
    while (not session->getKilled())
1450
 
    {
1451
 
      session->some_tables_deleted= false;
1452
 
      session->close_old_data_files(false, dropping_tables != 0);
1453
 
      if (not table::Cache::singleton().areTablesUsed(session->open_tables, 1))
1454
 
      {
1455
 
        break;
1456
 
      }
1457
 
      COND_refresh.wait(lock);
1458
 
    }
1459
 
    if (session->getKilled())
1460
 
      result= true;                                     // aborted
1461
 
    else
1462
 
    {
1463
 
      /* Now we can open all tables without any interference */
1464
 
      session->set_proc_info("Reopen tables");
1465
 
      session->version= refresh_version;
1466
 
      result= session->reopen_tables(false, false);
1467
 
    }
1468
 
  }
 
2329
  pthread_mutex_lock(&LOCK_open); /* Lock for all tables to be refreshed */
 
2330
  while (!session->killed)
 
2331
  {
 
2332
    session->some_tables_deleted=0;
 
2333
    close_old_data_files(session,session->open_tables,0,dropping_tables != 0);
 
2334
    if (!table_is_used(session->open_tables,1))
 
2335
      break;
 
2336
    (void) pthread_cond_wait(&COND_refresh,&LOCK_open);
 
2337
  }
 
2338
  if (session->killed)
 
2339
    result= 1;                                  // aborted
 
2340
  else
 
2341
  {
 
2342
    /* Now we can open all tables without any interference */
 
2343
    session->set_proc_info("Reopen tables");
 
2344
    session->version= refresh_version;
 
2345
    result=reopen_tables(session,0,0);
 
2346
  }
 
2347
  pthread_mutex_unlock(&LOCK_open);
1469
2348
  session->set_proc_info(0);
1470
 
 
1471
 
  return result;
 
2349
  return(result);
1472
2350
}
1473
2351
 
1474
2352
 
1496
2374
*/
1497
2375
 
1498
2376
 
1499
 
Table *drop_locked_tables(Session *session, const drizzled::TableIdentifier &identifier)
 
2377
Table *drop_locked_tables(Session *session,const char *db, const char *table_name)
1500
2378
{
1501
2379
  Table *table,*next,**prev, *found= 0;
1502
2380
  prev= &session->open_tables;
1503
2381
 
1504
2382
  /*
1505
 
    Note that we need to hold table::Cache::singleton().mutex() while changing the
 
2383
    Note that we need to hold LOCK_open while changing the
1506
2384
    open_tables list. Another thread may work on it.
1507
 
    (See: table::Cache::singleton().removeTable(), mysql_wait_completed_table())
 
2385
    (See: remove_table_from_cache(), mysql_wait_completed_table())
1508
2386
    Closing a MERGE child before the parent would be fatal if the
1509
2387
    other thread tries to abort the MERGE lock in between.
1510
2388
  */
1511
2389
  for (table= session->open_tables; table ; table=next)
1512
2390
  {
1513
 
    next=table->getNext();
1514
 
    if (table->getShare()->getCacheKey() == identifier.getKey())
 
2391
    next=table->next;
 
2392
    if (!strcmp(table->s->table_name.str, table_name) &&
 
2393
        !strcmp(table->s->db.str, db))
1515
2394
    {
1516
 
      session->removeLock(table);
 
2395
      mysql_lock_remove(session, session->locked_tables, table, true);
1517
2396
 
1518
2397
      if (!found)
1519
2398
      {
1522
2401
        if (table->db_stat)
1523
2402
        {
1524
2403
          table->db_stat= 0;
1525
 
          table->cursor->close();
 
2404
          table->file->close();
1526
2405
        }
1527
2406
      }
1528
2407
      else
1529
2408
      {
1530
2409
        /* We already have a name lock, remove copy */
1531
 
        table::remove_table(static_cast<table::Concurrent *>(table));
 
2410
        hash_delete(&open_cache,(unsigned char*) table);
1532
2411
      }
1533
2412
    }
1534
2413
    else
1535
2414
    {
1536
2415
      *prev=table;
1537
 
      prev= table->getNextPtr();
 
2416
      prev= &table->next;
1538
2417
    }
1539
2418
  }
1540
2419
  *prev=0;
1541
2420
  if (found)
1542
 
    locking::broadcast_refresh();
1543
 
 
 
2421
    broadcast_refresh();
 
2422
  if (session->locked_tables && session->locked_tables->table_count == 0)
 
2423
  {
 
2424
    free((unsigned char*) session->locked_tables);
 
2425
    session->locked_tables=0;
 
2426
  }
1544
2427
  return(found);
1545
2428
}
1546
2429
 
1551
2434
  other threads trying to get the lock.
1552
2435
*/
1553
2436
 
1554
 
void abort_locked_tables(Session *session, const drizzled::TableIdentifier &identifier)
 
2437
void abort_locked_tables(Session *session,const char *db, const char *table_name)
1555
2438
{
1556
2439
  Table *table;
1557
 
  for (table= session->open_tables; table ; table= table->getNext())
 
2440
  for (table= session->open_tables; table ; table= table->next)
1558
2441
  {
1559
 
    if (table->getShare()->getCacheKey() == identifier.getKey())
 
2442
    if (!strcmp(table->s->table_name.str, table_name) &&
 
2443
        !strcmp(table->s->db.str, db))
1560
2444
    {
1561
2445
      /* If MERGE child, forward lock handling to parent. */
1562
 
      session->abortLock(table);
 
2446
      mysql_lock_abort(session, table, true);
1563
2447
      break;
1564
2448
    }
1565
2449
  }
1566
2450
}
1567
2451
 
 
2452
/*
 
2453
  Load a table definition from file and open unireg table
 
2454
 
 
2455
  SYNOPSIS
 
2456
  open_unireg_entry()
 
2457
  session                       Thread handle
 
2458
  entry         Store open table definition here
 
2459
  table_list            TableList with db, table_name
 
2460
  alias         Alias name
 
2461
  cache_key             Key for share_cache
 
2462
  cache_key_length      length of cache_key
 
2463
 
 
2464
  NOTES
 
2465
  Extra argument for open is taken from session->open_options
 
2466
  One must have a lock on LOCK_open when calling this function
 
2467
 
 
2468
  RETURN
 
2469
  0     ok
 
2470
#       Error
 
2471
*/
 
2472
 
 
2473
static int open_unireg_entry(Session *session, Table *entry, TableList *table_list,
 
2474
                             const char *alias,
 
2475
                             char *cache_key, uint32_t cache_key_length)
 
2476
{
 
2477
  int error;
 
2478
  TableShare *share;
 
2479
  uint32_t discover_retry_count= 0;
 
2480
 
 
2481
  safe_mutex_assert_owner(&LOCK_open);
 
2482
retry:
 
2483
  if (!(share= get_table_share_with_create(session, table_list, cache_key,
 
2484
                                           cache_key_length,
 
2485
                                           table_list->i_s_requested_object,
 
2486
                                           &error)))
 
2487
    return(1);
 
2488
 
 
2489
  while ((error= open_table_from_share(session, share, alias,
 
2490
                                       (uint32_t) (HA_OPEN_KEYFILE |
 
2491
                                                   HA_OPEN_RNDFILE |
 
2492
                                                   HA_GET_INDEX |
 
2493
                                                   HA_TRY_READ_ONLY),
 
2494
                                       (EXTRA_RECORD),
 
2495
                                       session->open_options, entry, OTM_OPEN)))
 
2496
  {
 
2497
    if (error == 7)                             // Table def changed
 
2498
    {
 
2499
      share->version= 0;                        // Mark share as old
 
2500
      if (discover_retry_count++)               // Retry once
 
2501
        goto err;
 
2502
 
 
2503
      /*
 
2504
TODO:
 
2505
Here we should wait until all threads has released the table.
 
2506
For now we do one retry. This may cause a deadlock if there
 
2507
is other threads waiting for other tables used by this thread.
 
2508
 
 
2509
Proper fix would be to if the second retry failed:
 
2510
- Mark that table def changed
 
2511
- Return from open table
 
2512
- Close all tables used by this thread
 
2513
- Start waiting that the share is released
 
2514
- Retry by opening all tables again
 
2515
      */
 
2516
 
 
2517
      /*
 
2518
        TO BE FIXED
 
2519
        To avoid deadlock, only wait for release if no one else is
 
2520
        using the share.
 
2521
      */
 
2522
      if (share->ref_count != 1)
 
2523
        goto err;
 
2524
      /* Free share and wait until it's released by all threads */
 
2525
      release_table_share(share);
 
2526
      if (!session->killed)
 
2527
      {
 
2528
        drizzle_reset_errors(session, 1);         // Clear warnings
 
2529
        session->clear_error();                 // Clear error message
 
2530
        goto retry;
 
2531
      }
 
2532
      return(1);
 
2533
    }
 
2534
    if (!entry->s || !entry->s->crashed)
 
2535
      goto err;
 
2536
    // Code below is for repairing a crashed file
 
2537
    if ((error= lock_table_name(session, table_list, true)))
 
2538
    {
 
2539
      if (error < 0)
 
2540
        goto err;
 
2541
      if (wait_for_locked_table_names(session, table_list))
 
2542
      {
 
2543
        unlock_table_name(table_list);
 
2544
        goto err;
 
2545
      }
 
2546
    }
 
2547
    pthread_mutex_unlock(&LOCK_open);
 
2548
    session->clear_error();                             // Clear error message
 
2549
    error= 0;
 
2550
    if (open_table_from_share(session, share, alias,
 
2551
                              (uint32_t) (HA_OPEN_KEYFILE | HA_OPEN_RNDFILE |
 
2552
                                          HA_GET_INDEX |
 
2553
                                          HA_TRY_READ_ONLY),
 
2554
                              EXTRA_RECORD,
 
2555
                              ha_open_options | HA_OPEN_FOR_REPAIR,
 
2556
                              entry, OTM_OPEN) || ! entry->file ||
 
2557
        (entry->file->is_crashed() && entry->file->ha_check_and_repair(session)))
 
2558
    {
 
2559
      /* Give right error message */
 
2560
      session->clear_error();
 
2561
      my_error(ER_NOT_KEYFILE, MYF(0), share->table_name.str, my_errno);
 
2562
      errmsg_printf(ERRMSG_LVL_ERROR, _("Couldn't repair table: %s.%s"), share->db.str,
 
2563
                    share->table_name.str);
 
2564
      if (entry->file)
 
2565
        entry->closefrm(false);
 
2566
      error=1;
 
2567
    }
 
2568
    else
 
2569
      session->clear_error();                   // Clear error message
 
2570
    pthread_mutex_lock(&LOCK_open);
 
2571
    unlock_table_name(table_list);
 
2572
 
 
2573
    if (error)
 
2574
      goto err;
 
2575
    break;
 
2576
  }
 
2577
 
 
2578
  /*
 
2579
    If we are here, there was no fatal error (but error may be still
 
2580
    unitialized).
 
2581
  */
 
2582
  if (unlikely(entry->file->implicit_emptied))
 
2583
  {
 
2584
    entry->file->implicit_emptied= 0;
 
2585
    {
 
2586
      char *query, *end;
 
2587
      uint32_t query_buf_size= 20 + share->db.length + share->table_name.length +1;
 
2588
      if ((query= (char*) malloc(query_buf_size)))
 
2589
      {
 
2590
        /* 
 
2591
          "this DELETE FROM is needed even with row-based binlogging"
 
2592
 
 
2593
          We inherited this from MySQL. TODO: fix it to issue a propper truncate
 
2594
          of the table (though that may not be completely right sematics).
 
2595
        */
 
2596
        end= query;
 
2597
        end+= sprintf(query, "DELETE FROM `%s`.`%s`", share->db.str,
 
2598
                      share->table_name.str);
 
2599
        transaction_services.rawStatement(session, query, (size_t)(end - query)); 
 
2600
        free(query);
 
2601
      }
 
2602
      else
 
2603
      {
 
2604
        errmsg_printf(ERRMSG_LVL_ERROR, _("When opening HEAP table, could not allocate memory "
 
2605
                                          "to write 'DELETE FROM `%s`.`%s`' to replication"),
 
2606
                      table_list->db, table_list->table_name);
 
2607
        my_error(ER_OUTOFMEMORY, MYF(0), query_buf_size);
 
2608
        entry->closefrm(false);
 
2609
        goto err;
 
2610
      }
 
2611
    }
 
2612
  }
 
2613
  return(0);
 
2614
 
 
2615
err:
 
2616
  release_table_share(share);
 
2617
 
 
2618
  return 1;
 
2619
}
 
2620
 
1568
2621
 
1569
2622
/*
1570
2623
  Open all tables in list
1571
2624
 
1572
2625
  SYNOPSIS
1573
2626
  open_tables()
1574
 
  session - thread Cursor
 
2627
  session - thread handler
1575
2628
  start - list of tables in/out
1576
2629
  counter - number of opened tables will be return using this parameter
1577
2630
  flags   - bitmap of flags to modify how the tables will be open:
1594
2647
  -1 - error
1595
2648
*/
1596
2649
 
1597
 
int Session::open_tables_from_list(TableList **start, uint32_t *counter, uint32_t flags)
 
2650
int open_tables(Session *session, TableList **start, uint32_t *counter, uint32_t flags)
1598
2651
{
1599
2652
  TableList *tables= NULL;
1600
2653
  bool refresh;
1601
 
  int result= 0;
 
2654
  int result=0;
 
2655
  MEM_ROOT new_frm_mem;
1602
2656
  /* Also used for indicating that prelocking is need */
1603
2657
  bool safe_to_ignore_table;
1604
2658
 
1605
 
  current_tablenr= 0;
 
2659
  /*
 
2660
    temporary mem_root for new .frm parsing.
 
2661
TODO: variables for size
 
2662
  */
 
2663
  init_sql_alloc(&new_frm_mem, 8024, 8024);
 
2664
 
 
2665
  session->current_tablenr= 0;
1606
2666
restart:
1607
2667
  *counter= 0;
1608
 
  set_proc_info("Opening tables");
 
2668
  session->set_proc_info("Opening tables");
1609
2669
 
1610
2670
  /*
1611
2671
    For every table in the list of tables to open, try to find or open
1625
2685
    {
1626
2686
      continue;
1627
2687
    }
 
2688
    /*
 
2689
      If this TableList object is a placeholder for an information_schema
 
2690
      table, create a temporary table to represent the information_schema
 
2691
      table in the query. Do not fill it yet - will be filled during
 
2692
      execution.
 
2693
    */
 
2694
    if (tables->schema_table)
 
2695
    {
 
2696
      if (mysql_schema_table(session, session->lex, tables) == false)
 
2697
        continue;
 
2698
      return -1;
 
2699
    }
1628
2700
    (*counter)++;
1629
2701
 
1630
2702
    /*
1631
 
     * Is the user authorized to see this table? Do this before we check
1632
 
     * to see if it exists so that an unauthorized user cannot phish for
1633
 
     * table/schema information via error messages
1634
 
     */
1635
 
    TableIdentifier the_table(tables->getSchemaName(), tables->getTableName());
1636
 
    if (not plugin::Authorization::isAuthorized(getSecurityContext(),
1637
 
                                                the_table))
1638
 
    {
1639
 
      result= -1;                               // Fatal error
1640
 
      break;
1641
 
    }
1642
 
 
1643
 
 
1644
 
    /*
1645
2703
      Not a placeholder: must be a base table or a view, and the table is
1646
2704
      not opened yet. Try to open the table.
1647
2705
    */
1648
2706
    if (tables->table == NULL)
1649
 
      tables->table= openTable(tables, &refresh, flags);
 
2707
      tables->table= open_table(session, tables, &refresh, flags);
1650
2708
 
1651
2709
    if (tables->table == NULL)
1652
2710
    {
 
2711
      free_root(&new_frm_mem, MYF(MY_KEEP_PREALLOC));
 
2712
 
1653
2713
      if (refresh)                              // Refresh in progress
1654
2714
      {
1655
2715
        /*
1666
2726
          we pretend that we have finished calculation which we were doing
1667
2727
          currently.
1668
2728
        */
1669
 
        close_tables_for_reopen(start);
 
2729
        close_tables_for_reopen(session, start);
1670
2730
        goto restart;
1671
2731
      }
1672
2732
 
1676
2736
      result= -1;                               // Fatal error
1677
2737
      break;
1678
2738
    }
1679
 
    if (tables->lock_type != TL_UNLOCK)
 
2739
    if (tables->lock_type != TL_UNLOCK && ! session->locked_tables)
1680
2740
    {
1681
2741
      if (tables->lock_type == TL_WRITE_DEFAULT)
1682
 
        tables->table->reginfo.lock_type= update_lock_default;
1683
 
      else if (tables->table->getShare()->getType() == message::Table::STANDARD)
 
2742
        tables->table->reginfo.lock_type= session->update_lock_default;
 
2743
      else if (tables->table->s->tmp_table == NO_TMP_TABLE)
1684
2744
        tables->table->reginfo.lock_type= tables->lock_type;
1685
2745
    }
1686
2746
  }
1687
2747
 
1688
 
  set_proc_info(0);
 
2748
  session->set_proc_info(0);
 
2749
  free_root(&new_frm_mem, MYF(0));              // Free pre-alloced block
1689
2750
 
1690
2751
  if (result && tables)
1691
2752
  {
1695
2756
    */
1696
2757
    tables->table= NULL;
1697
2758
  }
1698
 
 
1699
2759
  return(result);
1700
2760
}
1701
2761
 
1702
2762
 
1703
2763
/*
 
2764
  Check that lock is ok for tables; Call start stmt if ok
 
2765
 
 
2766
  SYNOPSIS
 
2767
  check_lock_and_start_stmt()
 
2768
  session                       Thread handle
 
2769
  table_list            Table to check
 
2770
  lock_type             Lock used for table
 
2771
 
 
2772
  RETURN VALUES
 
2773
  0     ok
 
2774
  1     error
 
2775
*/
 
2776
 
 
2777
static bool check_lock_and_start_stmt(Session *session, Table *table,
 
2778
                                      thr_lock_type lock_type)
 
2779
{
 
2780
  int error;
 
2781
 
 
2782
  if ((int) lock_type >= (int) TL_WRITE_ALLOW_READ &&
 
2783
      (int) table->reginfo.lock_type < (int) TL_WRITE_ALLOW_READ)
 
2784
  {
 
2785
    my_error(ER_TABLE_NOT_LOCKED_FOR_WRITE, MYF(0),table->alias);
 
2786
    return(1);
 
2787
  }
 
2788
  if ((error=table->file->start_stmt(session, lock_type)))
 
2789
  {
 
2790
    table->file->print_error(error,MYF(0));
 
2791
    return(1);
 
2792
  }
 
2793
  return(0);
 
2794
}
 
2795
 
 
2796
 
 
2797
/**
 
2798
  @brief Open and lock one table
 
2799
 
 
2800
  @param[in]    session             thread handle
 
2801
  @param[in]    table_l         table to open is first table in this list
 
2802
  @param[in]    lock_type       lock to use for table
 
2803
 
 
2804
  @return       table
 
2805
  @retval     != NULL         OK, opened table returned
 
2806
  @retval     NULL            Error
 
2807
 
 
2808
  @note
 
2809
  If ok, the following are also set:
 
2810
  table_list->lock_type         lock_type
 
2811
  table_list->table             table
 
2812
 
 
2813
  @note
 
2814
  If table_l is a list, not a single table, the list is temporarily
 
2815
  broken.
 
2816
 
 
2817
  @detail
 
2818
  This function is meant as a replacement for open_ltable() when
 
2819
  MERGE tables can be opened. open_ltable() cannot open MERGE tables.
 
2820
 
 
2821
  There may be more differences between open_n_lock_single_table() and
 
2822
  open_ltable(). One known difference is that open_ltable() does
 
2823
  neither call decide_logging_format() nor handle some other logging
 
2824
  and locking issues because it does not call lock_tables().
 
2825
*/
 
2826
 
 
2827
Table *open_n_lock_single_table(Session *session, TableList *table_l,
 
2828
                                thr_lock_type lock_type)
 
2829
{
 
2830
  TableList *save_next_global;
 
2831
 
 
2832
  /* Remember old 'next' pointer. */
 
2833
  save_next_global= table_l->next_global;
 
2834
  /* Break list. */
 
2835
  table_l->next_global= NULL;
 
2836
 
 
2837
  /* Set requested lock type. */
 
2838
  table_l->lock_type= lock_type;
 
2839
 
 
2840
  /* Open the table. */
 
2841
  if (simple_open_n_lock_tables(session, table_l))
 
2842
    table_l->table= NULL; /* Just to be sure. */
 
2843
 
 
2844
  /* Restore list. */
 
2845
  table_l->next_global= save_next_global;
 
2846
 
 
2847
  return table_l->table;
 
2848
}
 
2849
 
 
2850
 
 
2851
/*
1704
2852
  Open and lock one table
1705
2853
 
1706
2854
  SYNOPSIS
1707
 
  openTableLock()
1708
 
  session                       Thread Cursor
 
2855
  open_ltable()
 
2856
  session                       Thread handler
1709
2857
  table_list            Table to open is first table in this list
1710
2858
  lock_type             Lock to use for open
1711
2859
  lock_flags          Flags passed to mysql_lock_table
1724
2872
  table_list->table             table
1725
2873
*/
1726
2874
 
1727
 
Table *Session::openTableLock(TableList *table_list, thr_lock_type lock_type)
 
2875
Table *open_ltable(Session *session, TableList *table_list, thr_lock_type lock_type,
 
2876
                   uint32_t lock_flags)
1728
2877
{
1729
2878
  Table *table;
1730
2879
  bool refresh;
1731
2880
 
1732
 
  set_proc_info("Opening table");
1733
 
  current_tablenr= 0;
1734
 
  while (!(table= openTable(table_list, &refresh)) &&
 
2881
  session->set_proc_info("Opening table");
 
2882
  session->current_tablenr= 0;
 
2883
  while (!(table= open_table(session, table_list, &refresh, 0)) &&
1735
2884
         refresh)
1736
2885
    ;
1737
2886
 
1739
2888
  {
1740
2889
    table_list->lock_type= lock_type;
1741
2890
    table_list->table=     table;
1742
 
 
1743
 
    assert(lock == 0);  // You must lock everything at once
1744
 
    if ((table->reginfo.lock_type= lock_type) != TL_UNLOCK)
1745
 
      if (! (lock= lockTables(&table_list->table, 1, 0, &refresh)))
 
2891
    if (session->locked_tables)
 
2892
    {
 
2893
      if (check_lock_and_start_stmt(session, table, lock_type))
1746
2894
        table= 0;
1747
 
  }
1748
 
 
1749
 
  set_proc_info(0);
1750
 
 
1751
 
  return table;
 
2895
    }
 
2896
    else
 
2897
    {
 
2898
      assert(session->lock == 0);       // You must lock everything at once
 
2899
      if ((table->reginfo.lock_type= lock_type) != TL_UNLOCK)
 
2900
        if (! (session->lock= mysql_lock_tables(session, &table_list->table, 1,
 
2901
                                                lock_flags, &refresh)))
 
2902
          table= 0;
 
2903
    }
 
2904
  }
 
2905
 
 
2906
  session->set_proc_info(0);
 
2907
  return(table);
 
2908
}
 
2909
 
 
2910
 
 
2911
/*
 
2912
  Open all tables in list, locks them and optionally process derived tables.
 
2913
 
 
2914
  SYNOPSIS
 
2915
  open_and_lock_tables_derived()
 
2916
  session               - thread handler
 
2917
  tables        - list of tables for open&locking
 
2918
  derived     - if to handle derived tables
 
2919
 
 
2920
  RETURN
 
2921
  false - ok
 
2922
  true  - error
 
2923
 
 
2924
  NOTE
 
2925
  The lock will automaticaly be freed by close_thread_tables()
 
2926
 
 
2927
  NOTE
 
2928
  There are two convenience functions:
 
2929
  - simple_open_n_lock_tables(session, tables)  without derived handling
 
2930
  - open_and_lock_tables(session, tables)       with derived handling
 
2931
  Both inline functions call open_and_lock_tables_derived() with
 
2932
  the third argument set appropriately.
 
2933
*/
 
2934
 
 
2935
int open_and_lock_tables_derived(Session *session, TableList *tables, bool derived)
 
2936
{
 
2937
  uint32_t counter;
 
2938
  bool need_reopen;
 
2939
 
 
2940
  for ( ; ; )
 
2941
  {
 
2942
    if (open_tables(session, &tables, &counter, 0))
 
2943
      return(-1);
 
2944
 
 
2945
    if (!lock_tables(session, tables, counter, &need_reopen))
 
2946
      break;
 
2947
    if (!need_reopen)
 
2948
      return(-1);
 
2949
    close_tables_for_reopen(session, &tables);
 
2950
  }
 
2951
  if (derived &&
 
2952
      (mysql_handle_derived(session->lex, &mysql_derived_prepare) ||
 
2953
       (session->fill_derived_tables() &&
 
2954
        mysql_handle_derived(session->lex, &mysql_derived_filling))))
 
2955
    return(true); /* purecov: inspected */
 
2956
  return(0);
 
2957
}
 
2958
 
 
2959
 
 
2960
/*
 
2961
  Open all tables in list and process derived tables
 
2962
 
 
2963
  SYNOPSIS
 
2964
  open_normal_and_derived_tables
 
2965
  session               - thread handler
 
2966
  tables        - list of tables for open
 
2967
  flags       - bitmap of flags to modify how the tables will be open:
 
2968
  DRIZZLE_LOCK_IGNORE_FLUSH - open table even if someone has
 
2969
  done a flush or namelock on it.
 
2970
 
 
2971
  RETURN
 
2972
  false - ok
 
2973
  true  - error
 
2974
 
 
2975
  NOTE
 
2976
  This is to be used on prepare stage when you don't read any
 
2977
  data from the tables.
 
2978
*/
 
2979
 
 
2980
bool open_normal_and_derived_tables(Session *session, TableList *tables, uint32_t flags)
 
2981
{
 
2982
  uint32_t counter;
 
2983
  assert(!session->fill_derived_tables());
 
2984
  if (open_tables(session, &tables, &counter, flags) ||
 
2985
      mysql_handle_derived(session->lex, &mysql_derived_prepare))
 
2986
    return(true); /* purecov: inspected */
 
2987
  return(0);
1752
2988
}
1753
2989
 
1754
2990
/*
1756
2992
 
1757
2993
  SYNOPSIS
1758
2994
  lock_tables()
1759
 
  session                       Thread Cursor
 
2995
  session                       Thread handler
1760
2996
  tables                Tables to lock
1761
2997
  count         Number of opened tables
1762
2998
  need_reopen         Out parameter which if true indicates that some
1779
3015
  -1    Error
1780
3016
*/
1781
3017
 
1782
 
int Session::lock_tables(TableList *tables, uint32_t count, bool *need_reopen)
 
3018
int lock_tables(Session *session, TableList *tables, uint32_t count, bool *need_reopen)
1783
3019
{
1784
3020
  TableList *table;
1785
 
  Session *session= this;
1786
3021
 
1787
3022
  /*
1788
3023
    We can't meet statement requiring prelocking if we already
1793
3028
  if (tables == NULL)
1794
3029
    return 0;
1795
3030
 
1796
 
  assert(session->lock == 0);   // You must lock everything at once
1797
 
  Table **start,**ptr;
1798
 
  uint32_t lock_flag= DRIZZLE_LOCK_NOTIFY_IF_NEED_REOPEN;
1799
 
 
1800
 
  if (!(ptr=start=(Table**) session->alloc(sizeof(Table*)*count)))
1801
 
    return -1;
1802
 
  for (table= tables; table; table= table->next_global)
 
3031
  if (!session->locked_tables)
1803
3032
  {
1804
 
    if (!table->placeholder())
1805
 
      *(ptr++)= table->table;
 
3033
    assert(session->lock == 0); // You must lock everything at once
 
3034
    Table **start,**ptr;
 
3035
    uint32_t lock_flag= DRIZZLE_LOCK_NOTIFY_IF_NEED_REOPEN;
 
3036
 
 
3037
    if (!(ptr=start=(Table**) session->alloc(sizeof(Table*)*count)))
 
3038
      return(-1);
 
3039
    for (table= tables; table; table= table->next_global)
 
3040
    {
 
3041
      if (!table->placeholder())
 
3042
        *(ptr++)= table->table;
 
3043
    }
 
3044
 
 
3045
    if (!(session->lock= mysql_lock_tables(session, start, (uint32_t) (ptr - start),
 
3046
                                           lock_flag, need_reopen)))
 
3047
    {
 
3048
      return(-1);
 
3049
    }
1806
3050
  }
1807
 
 
1808
 
  if (!(session->lock= session->lockTables(start, (uint32_t) (ptr - start), lock_flag, need_reopen)))
 
3051
  else
1809
3052
  {
1810
 
    return -1;
 
3053
    TableList *first_not_own= session->lex->first_not_own_table();
 
3054
    /*
 
3055
      When open_and_lock_tables() is called for a single table out of
 
3056
      a table list, the 'next_global' chain is temporarily broken. We
 
3057
      may not find 'first_not_own' before the end of the "list".
 
3058
      Look for example at those places where open_n_lock_single_table()
 
3059
      is called. That function implements the temporary breaking of
 
3060
      a table list for opening a single table.
 
3061
    */
 
3062
    for (table= tables;
 
3063
         table && table != first_not_own;
 
3064
         table= table->next_global)
 
3065
    {
 
3066
      if (!table->placeholder() &&
 
3067
          check_lock_and_start_stmt(session, table->table, table->lock_type))
 
3068
      {
 
3069
        return(-1);
 
3070
      }
 
3071
    }
1811
3072
  }
1812
3073
 
1813
3074
  return 0;
1815
3076
 
1816
3077
 
1817
3078
/*
 
3079
  Prepare statement for reopening of tables and recalculation of set of
 
3080
  prelocked tables.
 
3081
 
 
3082
  SYNOPSIS
 
3083
  close_tables_for_reopen()
 
3084
  session    in     Thread context
 
3085
  tables in/out List of tables which we were trying to open and lock
 
3086
 
 
3087
*/
 
3088
 
 
3089
void close_tables_for_reopen(Session *session, TableList **tables)
 
3090
{
 
3091
  /*
 
3092
    If table list consists only from tables from prelocking set, table list
 
3093
    for new attempt should be empty, so we have to update list's root pointer.
 
3094
  */
 
3095
  if (session->lex->first_not_own_table() == *tables)
 
3096
    *tables= 0;
 
3097
  session->lex->chop_off_not_own_tables();
 
3098
  for (TableList *tmp= *tables; tmp; tmp= tmp->next_global)
 
3099
    tmp->table= 0;
 
3100
  session->close_thread_tables();
 
3101
}
 
3102
 
 
3103
 
 
3104
/*
1818
3105
  Open a single table without table caching and don't set it in open_list
1819
3106
 
1820
3107
  SYNPOSIS
1834
3121
#  Table object
1835
3122
*/
1836
3123
 
1837
 
Table *Open_tables_state::open_temporary_table(const TableIdentifier &identifier,
1838
 
                                               bool link_in_list)
 
3124
Table *open_temporary_table(Session *session, const char *path, const char *db,
 
3125
                            const char *table_name, bool link_in_list,
 
3126
                            open_table_mode open_mode)
1839
3127
{
1840
 
  assert(identifier.isTmp());
1841
 
 
1842
 
 
1843
 
  table::Temporary *new_tmp_table= new table::Temporary(identifier.getType(),
1844
 
                                                        identifier,
1845
 
                                                        const_cast<char *>(const_cast<TableIdentifier&>(identifier).getPath().c_str()),
1846
 
                                                        static_cast<uint32_t>(identifier.getPath().length()));
1847
 
  if (not new_tmp_table)
 
3128
  Table *tmp_table;
 
3129
  TableShare *share;
 
3130
  char cache_key[MAX_DBKEY_LENGTH], *saved_cache_key, *tmp_path;
 
3131
  uint32_t key_length, path_length;
 
3132
  TableList table_list;
 
3133
 
 
3134
  table_list.db=         (char*) db;
 
3135
  table_list.table_name= (char*) table_name;
 
3136
  /* Create the cache_key for temporary tables */
 
3137
  key_length= create_table_def_key(cache_key, &table_list);
 
3138
  path_length= strlen(path);
 
3139
 
 
3140
  if (!(tmp_table= (Table*) malloc(sizeof(*tmp_table) + sizeof(*share) +
 
3141
                                   path_length + 1 + key_length)))
1848
3142
    return NULL;
1849
3143
 
 
3144
  share= (TableShare*) (tmp_table+1);
 
3145
  tmp_path= (char*) (share+1);
 
3146
  saved_cache_key= strcpy(tmp_path, path)+path_length+1;
 
3147
  memcpy(saved_cache_key, cache_key, key_length);
 
3148
 
 
3149
  share->init(saved_cache_key, key_length, strchr(saved_cache_key, '\0')+1, tmp_path);
 
3150
 
1850
3151
  /*
1851
3152
    First open the share, and then open the table from the share we just opened.
1852
3153
  */
1853
 
  if (new_tmp_table->getMutableShare()->open_table_def(*static_cast<Session *>(this), identifier) ||
1854
 
      new_tmp_table->getMutableShare()->open_table_from_share(static_cast<Session *>(this), identifier, identifier.getTableName().c_str(),
1855
 
                                                              (uint32_t) (HA_OPEN_KEYFILE | HA_OPEN_RNDFILE |
1856
 
                                                                          HA_GET_INDEX),
1857
 
                                                              ha_open_options,
1858
 
                                                              *new_tmp_table))
 
3154
  if (open_table_def(session, share) ||
 
3155
      open_table_from_share(session, share, table_name,
 
3156
                            (open_mode == OTM_ALTER) ? 0 :
 
3157
                            (uint32_t) (HA_OPEN_KEYFILE | HA_OPEN_RNDFILE |
 
3158
                                        HA_GET_INDEX),
 
3159
                            (open_mode == OTM_ALTER) ?
 
3160
                            (EXTRA_RECORD | OPEN_FRM_FILE_ONLY)
 
3161
                            : (EXTRA_RECORD),
 
3162
                            ha_open_options,
 
3163
                            tmp_table, open_mode))
1859
3164
  {
1860
3165
    /* No need to lock share->mutex as this is not needed for tmp tables */
1861
 
    delete new_tmp_table->getMutableShare();
1862
 
    delete new_tmp_table;
1863
 
 
1864
 
    return 0;
1865
 
  }
1866
 
 
1867
 
  new_tmp_table->reginfo.lock_type= TL_WRITE;    // Simulate locked
 
3166
    share->free_table_share();
 
3167
    free((char*) tmp_table);
 
3168
    return(0);
 
3169
  }
 
3170
 
 
3171
  tmp_table->reginfo.lock_type= TL_WRITE;        // Simulate locked
 
3172
  if (open_mode == OTM_ALTER)
 
3173
  {
 
3174
    /*
 
3175
      Temporary table has been created with frm_only
 
3176
      and has not been created in any storage engine
 
3177
    */
 
3178
    share->tmp_table= TMP_TABLE_FRM_FILE_ONLY;
 
3179
  }
 
3180
  else
 
3181
    share->tmp_table= (tmp_table->file->has_transactions() ?
 
3182
                       TRANSACTIONAL_TMP_TABLE : NON_TRANSACTIONAL_TMP_TABLE);
1868
3183
 
1869
3184
  if (link_in_list)
1870
3185
  {
1871
3186
    /* growing temp list at the head */
1872
 
    new_tmp_table->setNext(this->temporary_tables);
1873
 
    if (new_tmp_table->getNext())
1874
 
    {
1875
 
      new_tmp_table->getNext()->setPrev(new_tmp_table);
1876
 
    }
1877
 
    this->temporary_tables= new_tmp_table;
1878
 
    this->temporary_tables->setPrev(0);
1879
 
  }
1880
 
  new_tmp_table->pos_in_table_list= 0;
1881
 
 
1882
 
  return new_tmp_table;
 
3187
    tmp_table->next= session->temporary_tables;
 
3188
    if (tmp_table->next)
 
3189
      tmp_table->next->prev= tmp_table;
 
3190
    session->temporary_tables= tmp_table;
 
3191
    session->temporary_tables->prev= 0;
 
3192
  }
 
3193
  tmp_table->pos_in_table_list= 0;
 
3194
 
 
3195
  return tmp_table;
 
3196
}
 
3197
 
 
3198
 
 
3199
bool rm_temporary_table(StorageEngine *base, char *path)
 
3200
{
 
3201
  bool error=0;
 
3202
  handler *file;
 
3203
 
 
3204
  if(delete_table_proto_file(path))
 
3205
    error=1; /* purecov: inspected */
 
3206
 
 
3207
  file= get_new_handler((TableShare*) 0, current_session->mem_root, base);
 
3208
  if (file && file->ha_delete_table(path))
 
3209
  {
 
3210
    error=1;
 
3211
    errmsg_printf(ERRMSG_LVL_WARN, _("Could not remove temporary table: '%s', error: %d"),
 
3212
                  path, my_errno);
 
3213
  }
 
3214
  delete file;
 
3215
  return(error);
1883
3216
}
1884
3217
 
1885
3218
 
1896
3229
Field *not_found_field= (Field*) 0x1;
1897
3230
Field *view_ref_found= (Field*) 0x2;
1898
3231
 
 
3232
#define WRONG_GRANT (Field*) -1
 
3233
 
1899
3234
static void update_field_dependencies(Session *session, Field *field, Table *table)
1900
3235
{
1901
3236
  if (session->mark_used_columns != MARK_COLUMNS_NONE)
1902
3237
  {
1903
 
    boost::dynamic_bitset<> *current_bitmap= NULL;
 
3238
    MY_BITMAP *current_bitmap, *other_bitmap;
1904
3239
 
1905
3240
    /*
1906
3241
      We always want to register the used keys, as the column bitmap may have
1913
3248
    if (session->mark_used_columns == MARK_COLUMNS_READ)
1914
3249
    {
1915
3250
      current_bitmap= table->read_set;
 
3251
      other_bitmap=   table->write_set;
1916
3252
    }
1917
3253
    else
1918
3254
    {
1919
3255
      current_bitmap= table->write_set;
 
3256
      other_bitmap=   table->read_set;
1920
3257
    }
1921
3258
 
1922
 
    //if (current_bitmap->testAndSet(field->position()))
1923
 
    if (current_bitmap->test(field->position()))
 
3259
    if (bitmap_test_and_set(current_bitmap, field->field_index))
1924
3260
    {
1925
3261
      if (session->mark_used_columns == MARK_COLUMNS_WRITE)
1926
3262
        session->dup_field= field;
1927
3263
      return;
1928
3264
    }
 
3265
    if (table->get_fields_in_item_tree)
 
3266
      field->flags|= GET_FIXED_FIELDS_FLAG;
1929
3267
    table->used_fields++;
1930
3268
  }
 
3269
  else if (table->get_fields_in_item_tree)
 
3270
    field->flags|= GET_FIXED_FIELDS_FLAG;
1931
3271
}
1932
3272
 
1933
3273
 
1936
3276
 
1937
3277
  SYNOPSIS
1938
3278
  find_field_in_natural_join()
1939
 
  session                        [in]  thread Cursor
 
3279
  session                        [in]  thread handler
1940
3280
  table_ref            [in]  table reference to search
1941
3281
  name           [in]  name of field
1942
3282
  length                 [in]  length of name
1956
3296
 
1957
3297
  RETURN
1958
3298
  NULL        if the field was not found
1959
 
  PTR         Pointer to the found Field
 
3299
  WRONG_GRANT if no access rights to the found field
 
3300
#           Pointer to the found Field
1960
3301
*/
1961
3302
 
1962
3303
static Field *
1989
3330
    return NULL;
1990
3331
  {
1991
3332
    /* This is a base table. */
1992
 
    assert(nj_col->table_ref->table == nj_col->table_field->getTable());
 
3333
    assert(nj_col->table_ref->table == nj_col->table_field->table);
1993
3334
    found_field= nj_col->table_field;
1994
3335
    update_field_dependencies(session, found_field, nj_col->table_ref->table);
1995
3336
  }
2005
3346
 
2006
3347
  SYNOPSIS
2007
3348
  find_field_in_table()
2008
 
  session                               thread Cursor
 
3349
  session                               thread handler
2009
3350
  table                 table where to search for the field
2010
3351
  name                  name of field
2011
3352
  length                        length of name
2026
3367
  uint32_t cached_field_index= *cached_field_index_ptr;
2027
3368
 
2028
3369
  /* We assume here that table->field < NO_CACHED_FIELD_INDEX = UINT_MAX */
2029
 
  if (cached_field_index < table->getShare()->sizeFields() &&
 
3370
  if (cached_field_index < table->s->fields &&
2030
3371
      !my_strcasecmp(system_charset_info,
2031
 
                     table->getField(cached_field_index)->field_name, name))
2032
 
  {
2033
 
    field_ptr= table->getFields() + cached_field_index;
2034
 
  }
2035
 
  else if (table->getShare()->getNamedFieldSize())
2036
 
  {
2037
 
    field_ptr= table->getMutableShare()->getNamedField(std::string(name, length));
 
3372
                     table->field[cached_field_index]->field_name, name))
 
3373
    field_ptr= table->field + cached_field_index;
 
3374
  else if (table->s->name_hash.records)
 
3375
  {
 
3376
    field_ptr= (Field**) hash_search(&table->s->name_hash, (unsigned char*) name,
 
3377
                                     length);
2038
3378
    if (field_ptr)
2039
3379
    {
2040
3380
      /*
2041
3381
        field_ptr points to field in TableShare. Convert it to the matching
2042
3382
        field in table
2043
3383
      */
2044
 
      field_ptr= (table->getFields() + table->getShare()->positionFields(field_ptr));
 
3384
      field_ptr= (table->field + (field_ptr - table->s->field));
2045
3385
    }
2046
3386
  }
2047
3387
  else
2048
3388
  {
2049
 
    if (!(field_ptr= table->getFields()))
 
3389
    if (!(field_ptr= table->field))
2050
3390
      return((Field *)0);
2051
3391
    for (; *field_ptr; ++field_ptr)
2052
3392
      if (!my_strcasecmp(system_charset_info, (*field_ptr)->field_name, name))
2055
3395
 
2056
3396
  if (field_ptr && *field_ptr)
2057
3397
  {
2058
 
    *cached_field_index_ptr= field_ptr - table->getFields();
 
3398
    *cached_field_index_ptr= field_ptr - table->field;
2059
3399
    field= *field_ptr;
2060
3400
  }
2061
3401
  else
2062
3402
  {
2063
3403
    if (!allow_rowid ||
2064
3404
        my_strcasecmp(system_charset_info, name, "_rowid") ||
2065
 
        table->getShare()->rowid_field_offset == 0)
 
3405
        table->s->rowid_field_offset == 0)
2066
3406
      return((Field*) 0);
2067
 
    field= table->getField(table->getShare()->rowid_field_offset-1);
 
3407
    field= table->field[table->s->rowid_field_offset-1];
2068
3408
  }
2069
3409
 
2070
3410
  update_field_dependencies(session, field, table);
2071
3411
 
2072
 
  return field;
 
3412
  return(field);
2073
3413
}
2074
3414
 
2075
3415
 
2078
3418
 
2079
3419
  SYNOPSIS
2080
3420
  find_field_in_table_ref()
2081
 
  session                          [in]  thread Cursor
 
3421
  session                          [in]  thread handler
2082
3422
  table_list               [in]  table reference to search
2083
3423
  name             [in]  name of field
2084
3424
  length                   [in]  field length of name
2087
3427
  table_name             [in]  optional table name that qualifies the field
2088
3428
  ref                  [in/out] if 'name' is resolved to a view field, ref
2089
3429
  is set to point to the found view field
 
3430
  check_privileges       [in]  check privileges
2090
3431
  allow_rowid              [in]  do allow finding of "_rowid" field?
2091
3432
  cached_field_index_ptr [in]  cached position in field list (used to
2092
3433
  speedup lookup for fields in prepared tables)
2119
3460
                        const char *name, uint32_t length,
2120
3461
                        const char *item_name, const char *db_name,
2121
3462
                        const char *table_name, Item **ref,
2122
 
                        bool allow_rowid,
 
3463
                        bool check_privileges, bool allow_rowid,
2123
3464
                        uint32_t *cached_field_index_ptr,
2124
3465
                        bool register_tree_change, TableList **actual_table)
2125
3466
{
2143
3484
    inside the view, but we want to search directly in the view columns
2144
3485
    which are represented as a 'field_translation'.
2145
3486
 
2146
 
    TODO-> Ensure that table_name, db_name and tables->db always points to something !
 
3487
TODO: Ensure that table_name, db_name and tables->db always points to
 
3488
something !
2147
3489
  */
2148
3490
  if (/* Exclude nested joins. */
2149
 
      (!table_list->getNestedJoin()) &&
 
3491
      (!table_list->nested_join) &&
2150
3492
      /* Include merge views and information schema tables. */
2151
3493
      /*
2152
3494
        Test if the field qualifiers match the table reference we plan
2154
3496
      */
2155
3497
      table_name && table_name[0] &&
2156
3498
      (my_strcasecmp(table_alias_charset, table_list->alias, table_name) ||
2157
 
       (db_name && db_name[0] && table_list->getSchemaName() && table_list->getSchemaName()[0] &&
2158
 
        strcmp(db_name, table_list->getSchemaName()))))
2159
 
    return 0;
 
3499
       (db_name && db_name[0] && table_list->db && table_list->db[0] &&
 
3500
        strcmp(db_name, table_list->db))))
 
3501
    return(0);
2160
3502
 
2161
3503
  *actual_table= NULL;
2162
3504
 
2163
 
  if (!table_list->getNestedJoin())
 
3505
  if (!table_list->nested_join)
2164
3506
  {
2165
3507
    /* 'table_list' is a stored table. */
2166
3508
    assert(table_list->table);
2180
3522
    */
2181
3523
    if (table_name && table_name[0])
2182
3524
    {
2183
 
      List_iterator<TableList> it(table_list->getNestedJoin()->join_list);
 
3525
      List_iterator<TableList> it(table_list->nested_join->join_list);
2184
3526
      TableList *table;
2185
3527
      while ((table= it++))
2186
3528
      {
2187
3529
        if ((fld= find_field_in_table_ref(session, table, name, length, item_name,
2188
3530
                                          db_name, table_name, ref,
2189
 
                                          allow_rowid,
 
3531
                                          check_privileges, allow_rowid,
2190
3532
                                          cached_field_index_ptr,
2191
3533
                                          register_tree_change, actual_table)))
2192
 
          return fld;
 
3534
          return(fld);
2193
3535
      }
2194
 
      return NULL;
 
3536
      return(0);
2195
3537
    }
2196
3538
    /*
2197
3539
      Non-qualified field, search directly in the result columns of the
2208
3550
    if (session->mark_used_columns != MARK_COLUMNS_NONE)
2209
3551
    {
2210
3552
      /*
2211
 
        Get rw_set correct for this field so that the Cursor
 
3553
        Get rw_set correct for this field so that the handler
2212
3554
        knows that this field is involved in the query and gets
2213
3555
        retrieved/updated
2214
3556
      */
2228
3570
        field_to_set= fld;
2229
3571
      if (field_to_set)
2230
3572
      {
2231
 
        Table *table= field_to_set->getTable();
 
3573
        Table *table= field_to_set->table;
2232
3574
        if (session->mark_used_columns == MARK_COLUMNS_READ)
2233
 
          table->setReadSet(field_to_set->position());
 
3575
          table->setReadSet(field_to_set->field_index);
2234
3576
        else
2235
 
          table->setWriteSet(field_to_set->position());
 
3577
          table->setWriteSet(field_to_set->field_index);
2236
3578
      }
2237
3579
    }
2238
3580
  }
2241
3583
 
2242
3584
 
2243
3585
/*
 
3586
  Find field in table, no side effects, only purpose is to check for field
 
3587
  in table object and get reference to the field if found.
 
3588
 
 
3589
  SYNOPSIS
 
3590
  find_field_in_table_sef()
 
3591
 
 
3592
  table                         table where to find
 
3593
  name                          Name of field searched for
 
3594
 
 
3595
  RETURN
 
3596
  0                   field is not found
 
3597
#                   pointer to field
 
3598
*/
 
3599
 
 
3600
Field *find_field_in_table_sef(Table *table, const char *name)
 
3601
{
 
3602
  Field **field_ptr;
 
3603
  if (table->s->name_hash.records)
 
3604
  {
 
3605
    field_ptr= (Field**)hash_search(&table->s->name_hash,(unsigned char*) name,
 
3606
                                    strlen(name));
 
3607
    if (field_ptr)
 
3608
    {
 
3609
      /*
 
3610
        field_ptr points to field in TableShare. Convert it to the matching
 
3611
        field in table
 
3612
      */
 
3613
      field_ptr= (table->field + (field_ptr - table->s->field));
 
3614
    }
 
3615
  }
 
3616
  else
 
3617
  {
 
3618
    if (!(field_ptr= table->field))
 
3619
      return (Field *)0;
 
3620
    for (; *field_ptr; ++field_ptr)
 
3621
      if (!my_strcasecmp(system_charset_info, (*field_ptr)->field_name, name))
 
3622
        break;
 
3623
  }
 
3624
  if (field_ptr)
 
3625
    return *field_ptr;
 
3626
  else
 
3627
    return (Field *)0;
 
3628
}
 
3629
 
 
3630
 
 
3631
/*
2244
3632
  Find field in table list.
2245
3633
 
2246
3634
  SYNOPSIS
2259
3647
  - REPORT_EXCEPT_NON_UNIQUE report all other errors
2260
3648
  except when non-unique fields were found
2261
3649
  - REPORT_ALL_ERRORS
 
3650
  check_privileges      need to check privileges
2262
3651
  register_tree_change  true if ref is not a stack variable and we
2263
3652
  to need register changes in item tree
2264
3653
 
2277
3666
find_field_in_tables(Session *session, Item_ident *item,
2278
3667
                     TableList *first_table, TableList *last_table,
2279
3668
                     Item **ref, find_item_error_report_type report_error,
2280
 
                     bool register_tree_change)
 
3669
                     bool check_privileges, bool register_tree_change)
2281
3670
{
2282
3671
  Field *found=0;
2283
3672
  const char *db= item->db_name;
2319
3708
                                 true, &(item->cached_field_index));
2320
3709
    else
2321
3710
      found= find_field_in_table_ref(session, table_ref, name, length, item->name,
2322
 
                                     NULL, NULL, ref,
 
3711
                                     NULL, NULL, ref, check_privileges,
2323
3712
                                     true, &(item->cached_field_index),
2324
3713
                                     register_tree_change,
2325
3714
                                     &actual_table);
2326
3715
    if (found)
2327
3716
    {
 
3717
      if (found == WRONG_GRANT)
 
3718
        return (Field*) 0;
 
3719
 
2328
3720
      /*
2329
3721
        Only views fields should be marked as dependent, not an underlying
2330
3722
        fields.
2364
3756
  {
2365
3757
    Field *cur_field= find_field_in_table_ref(session, cur_table, name, length,
2366
3758
                                              item->name, db, table_name, ref,
 
3759
                                              (session->lex->sql_command ==
 
3760
                                               SQLCOM_SHOW_FIELDS)
 
3761
                                              ? false : check_privileges,
2367
3762
                                              allow_rowid,
2368
3763
                                              &(item->cached_field_index),
2369
3764
                                              register_tree_change,
2370
3765
                                              &actual_table);
2371
3766
    if (cur_field)
2372
3767
    {
 
3768
      if (cur_field == WRONG_GRANT)
 
3769
      {
 
3770
        if (session->lex->sql_command != SQLCOM_SHOW_FIELDS)
 
3771
          return (Field*) 0;
 
3772
 
 
3773
        session->clear_error();
 
3774
        cur_field= find_field_in_table_ref(session, cur_table, name, length,
 
3775
                                           item->name, db, table_name, ref,
 
3776
                                           false,
 
3777
                                           allow_rowid,
 
3778
                                           &(item->cached_field_index),
 
3779
                                           register_tree_change,
 
3780
                                           &actual_table);
 
3781
        if (cur_field)
 
3782
        {
 
3783
          Field *nf=new Field_null(NULL,0,Field::NONE,
 
3784
                                   cur_field->field_name,
 
3785
                                   &my_charset_bin);
 
3786
          nf->init(cur_table->table);
 
3787
          cur_field= nf;
 
3788
        }
 
3789
      }
 
3790
 
2373
3791
      /*
2374
3792
        Store the original table of the field, which may be different from
2375
3793
        cur_table in the case of NATURAL/USING join.
2474
3892
 
2475
3893
 
2476
3894
Item **
2477
 
find_item_in_list(Session *session,
2478
 
                  Item *find, List<Item> &items, uint32_t *counter,
 
3895
find_item_in_list(Item *find, List<Item> &items, uint32_t *counter,
2479
3896
                  find_item_error_report_type report_error,
2480
3897
                  enum_resolution_type *resolution)
2481
3898
{
2555
3972
            */
2556
3973
            if (report_error != IGNORE_ERRORS)
2557
3974
              my_error(ER_NON_UNIQ_ERROR, MYF(0),
2558
 
                       find->full_name(), session->where);
 
3975
                       find->full_name(), current_session->where);
2559
3976
            return (Item**) 0;
2560
3977
          }
2561
3978
          found_unaliased= li.ref();
2586
4003
              continue;                           // Same field twice
2587
4004
            if (report_error != IGNORE_ERRORS)
2588
4005
              my_error(ER_NON_UNIQ_ERROR, MYF(0),
2589
 
                       find->full_name(), session->where);
 
4006
                       find->full_name(), current_session->where);
2590
4007
            return (Item**) 0;
2591
4008
          }
2592
4009
          found= li.ref();
2638
4055
    {
2639
4056
      if (report_error != IGNORE_ERRORS)
2640
4057
        my_error(ER_NON_UNIQ_ERROR, MYF(0),
2641
 
                 find->full_name(), session->where);
 
4058
                 find->full_name(), current_session->where);
2642
4059
      return (Item **) 0;
2643
4060
    }
2644
4061
    if (found_unaliased)
2654
4071
  {
2655
4072
    if (report_error == REPORT_ALL_ERRORS)
2656
4073
      my_error(ER_BAD_FIELD_ERROR, MYF(0),
2657
 
               find->full_name(), session->where);
 
4074
               find->full_name(), current_session->where);
2658
4075
    return (Item **) 0;
2659
4076
  }
2660
4077
  else
2772
4189
    Leaf table references to which new natural join columns are added
2773
4190
    if the leaves are != NULL.
2774
4191
  */
2775
 
  TableList *leaf_1= (table_ref_1->getNestedJoin() &&
2776
 
                      ! table_ref_1->is_natural_join) ?
 
4192
  TableList *leaf_1= (table_ref_1->nested_join &&
 
4193
                      !table_ref_1->is_natural_join) ?
2777
4194
    NULL : table_ref_1;
2778
 
  TableList *leaf_2= (table_ref_2->getNestedJoin() &&
2779
 
                      ! table_ref_2->is_natural_join) ?
 
4195
  TableList *leaf_2= (table_ref_2->nested_join &&
 
4196
                      !table_ref_2->is_natural_join) ?
2780
4197
    NULL : table_ref_2;
2781
4198
 
2782
4199
  *found_using_fields= 0;
2788
4205
    /* true if field_name_1 is a member of using_fields */
2789
4206
    bool is_using_column_1;
2790
4207
    if (!(nj_col_1= it_1.get_or_create_column_ref(leaf_1)))
2791
 
      return(result);
 
4208
      goto err;
2792
4209
    field_name_1= nj_col_1->name();
2793
4210
    is_using_column_1= using_fields &&
2794
4211
      test_if_string_in_list(field_name_1, using_fields);
2806
4223
      Natural_join_column *cur_nj_col_2;
2807
4224
      const char *cur_field_name_2;
2808
4225
      if (!(cur_nj_col_2= it_2.get_or_create_column_ref(leaf_2)))
2809
 
        return(result);
 
4226
        goto err;
2810
4227
      cur_field_name_2= cur_nj_col_2->name();
2811
4228
 
2812
4229
      /*
2826
4243
            (found && (!using_fields || is_using_column_1)))
2827
4244
        {
2828
4245
          my_error(ER_NON_UNIQ_ERROR, MYF(0), field_name_1, session->where);
2829
 
          return(result);
 
4246
          goto err;
2830
4247
        }
2831
4248
        nj_col_2= cur_nj_col_2;
2832
4249
        found= true;
2859
4276
      Item_func_eq *eq_cond;
2860
4277
 
2861
4278
      if (!item_1 || !item_2)
2862
 
        return(result); // out of memory
 
4279
        goto err;                               // out of memory
2863
4280
 
2864
4281
      /*
2865
4282
        In the case of no_wrap_view_item == 0, the created items must be
2884
4301
      */
2885
4302
      if (set_new_item_local_context(session, item_ident_1, nj_col_1->table_ref) ||
2886
4303
          set_new_item_local_context(session, item_ident_2, nj_col_2->table_ref))
2887
 
        return(result);
 
4304
        goto err;
2888
4305
 
2889
4306
      if (!(eq_cond= new Item_func_eq(item_ident_1, item_ident_2)))
2890
 
        return(result);                               /* Out of memory. */
 
4307
        goto err;                               /* Out of memory. */
2891
4308
 
2892
4309
      /*
2893
4310
        Add the new equi-join condition to the ON clause. Notice that
2904
4321
      {
2905
4322
        Table *table_1= nj_col_1->table_ref->table;
2906
4323
        /* Mark field_1 used for table cache. */
2907
 
        table_1->setReadSet(field_1->position());
 
4324
        table_1->setReadSet(field_1->field_index);
2908
4325
        table_1->covering_keys&= field_1->part_of_key;
2909
4326
        table_1->merge_keys|= field_1->part_of_key;
2910
4327
      }
2912
4329
      {
2913
4330
        Table *table_2= nj_col_2->table_ref->table;
2914
4331
        /* Mark field_2 used for table cache. */
2915
 
        table_2->setReadSet(field_2->position());
 
4332
        table_2->setReadSet(field_2->field_index);
2916
4333
        table_2->covering_keys&= field_2->part_of_key;
2917
4334
        table_2->merge_keys|= field_2->part_of_key;
2918
4335
      }
2933
4350
  */
2934
4351
  result= false;
2935
4352
 
 
4353
err:
2936
4354
  return(result);
2937
4355
}
2938
4356
 
2974
4392
*/
2975
4393
 
2976
4394
static bool
2977
 
store_natural_using_join_columns(Session *session,
 
4395
store_natural_using_join_columns(Session *,
2978
4396
                                 TableList *natural_using_join,
2979
4397
                                 TableList *table_ref_1,
2980
4398
                                 TableList *table_ref_2,
2990
4408
 
2991
4409
  if (!(non_join_columns= new List<Natural_join_column>) ||
2992
4410
      !(natural_using_join->join_columns= new List<Natural_join_column>))
2993
 
  {
2994
 
    return(result);
2995
 
  }
 
4411
    goto err;
2996
4412
 
2997
4413
  /* Append the columns of the first join operand. */
2998
4414
  for (it_1.set(table_ref_1); !it_1.end_of_fields(); it_1.next())
3030
4446
        if (!(common_field= it++))
3031
4447
        {
3032
4448
          my_error(ER_BAD_FIELD_ERROR, MYF(0), using_field_name_ptr,
3033
 
                   session->where);
3034
 
          return(result);
 
4449
                   current_session->where);
 
4450
          goto err;
3035
4451
        }
3036
4452
        if (!my_strcasecmp(system_charset_info,
3037
4453
                           common_field->name(), using_field_name_ptr))
3059
4475
 
3060
4476
  result= false;
3061
4477
 
 
4478
err:
3062
4479
  return(result);
3063
4480
}
3064
4481
 
3101
4518
  bool result= true;
3102
4519
 
3103
4520
  /* Call the procedure recursively for each nested table reference. */
3104
 
  if (table_ref->getNestedJoin())
 
4521
  if (table_ref->nested_join)
3105
4522
  {
3106
 
    List_iterator_fast<TableList> nested_it(table_ref->getNestedJoin()->join_list);
 
4523
    List_iterator_fast<TableList> nested_it(table_ref->nested_join->join_list);
3107
4524
    TableList *same_level_left_neighbor= nested_it++;
3108
4525
    TableList *same_level_right_neighbor= NULL;
3109
4526
    /* Left/right-most neighbors, possibly at higher levels in the join tree. */
3128
4545
          cur_table_ref->outer_join & JOIN_TYPE_RIGHT)
3129
4546
      {
3130
4547
        /* This can happen only for JOIN ... ON. */
3131
 
        assert(table_ref->getNestedJoin()->join_list.elements == 2);
 
4548
        assert(table_ref->nested_join->join_list.elements == 2);
3132
4549
        std::swap(same_level_left_neighbor, cur_table_ref);
3133
4550
      }
3134
4551
 
3141
4558
      real_right_neighbor= (same_level_right_neighbor) ?
3142
4559
        same_level_right_neighbor : right_neighbor;
3143
4560
 
3144
 
      if (cur_table_ref->getNestedJoin() &&
 
4561
      if (cur_table_ref->nested_join &&
3145
4562
          store_top_level_join_columns(session, cur_table_ref,
3146
4563
                                       real_left_neighbor, real_right_neighbor))
3147
 
        return(result);
 
4564
        goto err;
3148
4565
      same_level_right_neighbor= cur_table_ref;
3149
4566
    }
3150
4567
  }
3155
4572
  */
3156
4573
  if (table_ref->is_natural_join)
3157
4574
  {
3158
 
    assert(table_ref->getNestedJoin() &&
3159
 
           table_ref->getNestedJoin()->join_list.elements == 2);
3160
 
    List_iterator_fast<TableList> operand_it(table_ref->getNestedJoin()->join_list);
 
4575
    assert(table_ref->nested_join &&
 
4576
           table_ref->nested_join->join_list.elements == 2);
 
4577
    List_iterator_fast<TableList> operand_it(table_ref->nested_join->join_list);
3161
4578
    /*
3162
4579
      Notice that the order of join operands depends on whether table_ref
3163
4580
      represents a LEFT or a RIGHT join. In a RIGHT join, the operands are
3176
4593
      std::swap(table_ref_1, table_ref_2);
3177
4594
    if (mark_common_columns(session, table_ref_1, table_ref_2,
3178
4595
                            using_fields, &found_using_fields))
3179
 
      return(result);
 
4596
      goto err;
3180
4597
 
3181
4598
    /*
3182
4599
      Swap the join operands back, so that we pick the columns of the second
3188
4605
    if (store_natural_using_join_columns(session, table_ref, table_ref_1,
3189
4606
                                         table_ref_2, using_fields,
3190
4607
                                         found_using_fields))
3191
 
      return(result);
 
4608
      goto err;
3192
4609
 
3193
4610
    /*
3194
4611
      Change NATURAL JOIN to JOIN ... ON. We do this for both operands
3221
4638
  }
3222
4639
  result= false; /* All is OK. */
3223
4640
 
 
4641
err:
3224
4642
  return(result);
3225
4643
}
3226
4644
 
3336
4754
                             ((Item_field*) item)->table_name, &it,
3337
4755
                             any_privileges))
3338
4756
      {
3339
 
        return -1;
 
4757
        return(-1);
3340
4758
      }
3341
4759
      if (sum_func_list)
3342
4760
      {
3353
4771
      session->lex->current_select->cur_pos_in_select_list++;
3354
4772
  }
3355
4773
  session->lex->current_select->cur_pos_in_select_list= UNDEF_POS;
3356
 
 
3357
 
  return 0;
 
4774
  return(0);
3358
4775
}
3359
4776
 
3360
4777
/****************************************************************************
3401
4818
      session->lex->current_select->is_item_list_lookup= save_is_item_list_lookup;
3402
4819
      session->lex->allow_sum_func= save_allow_sum_func;
3403
4820
      session->mark_used_columns= save_mark_used_columns;
3404
 
      return true;
 
4821
      return(true); /* purecov: inspected */
3405
4822
    }
3406
4823
    if (ref)
3407
4824
      *(ref++)= item;
3431
4848
  RETURN pointer on pointer to next_leaf of last element
3432
4849
*/
3433
4850
 
3434
 
static TableList **make_leaves_list(TableList **list, TableList *tables)
 
4851
TableList **make_leaves_list(TableList **list, TableList *tables)
3435
4852
{
3436
4853
  for (TableList *table= tables; table; table= table->next_local)
3437
4854
  {
3448
4865
 
3449
4866
  SYNOPSIS
3450
4867
  setup_tables()
3451
 
  session                 Thread Cursor
 
4868
  session                 Thread handler
3452
4869
  context       name resolution contest to setup table list there
3453
4870
  from_clause   Top-level list of table references in the FROM clause
3454
4871
  tables          Table list (select_lex->table_list)
3504
4921
    }
3505
4922
    table->setup_table_map(table_list, tablenr);
3506
4923
    if (table_list->process_index_hints(table))
3507
 
      return 1;
 
4924
      return(1);
3508
4925
  }
3509
4926
  if (tablenr > MAX_TABLES)
3510
4927
  {
3511
4928
    my_error(ER_TOO_MANY_TABLES,MYF(0),MAX_TABLES);
3512
 
    return 1;
 
4929
    return(1);
3513
4930
  }
3514
4931
 
3515
4932
  /* Precompute and store the row types of NATURAL/USING joins. */
3516
4933
  if (setup_natural_join_row_types(session, from_clause, context))
3517
 
    return 1;
 
4934
    return(1);
3518
4935
 
3519
 
  return 0;
 
4936
  return(0);
3520
4937
}
3521
4938
 
3522
4939
 
3525
4942
 
3526
4943
  SYNOPSIS
3527
4944
  setup_tables_and_check_view_access()
3528
 
  session                 Thread Cursor
 
4945
  session                 Thread handler
3529
4946
  context       name resolution contest to setup table list there
3530
4947
  from_clause   Top-level list of table references in the FROM clause
3531
4948
  tables          Table list (select_lex->table_list)
3551
4968
                                   bool select_insert)
3552
4969
{
3553
4970
  TableList *leaves_tmp= NULL;
 
4971
  bool first_table= true;
3554
4972
 
3555
4973
  if (setup_tables(session, context, from_clause, tables,
3556
4974
                   &leaves_tmp, select_insert))
3559
4977
  if (leaves)
3560
4978
    *leaves= leaves_tmp;
3561
4979
 
 
4980
  for (; leaves_tmp; leaves_tmp= leaves_tmp->next_leaf)
 
4981
  {
 
4982
    first_table= 0;
 
4983
  }
3562
4984
  return false;
3563
4985
}
3564
4986
 
3565
4987
 
3566
4988
/*
 
4989
  Create a key_map from a list of index names
 
4990
 
 
4991
  SYNOPSIS
 
4992
  get_key_map_from_key_list()
 
4993
  map           key_map to fill in
 
4994
  table         Table
 
4995
  index_list            List of index names
 
4996
 
 
4997
  RETURN
 
4998
  0     ok;  In this case *map will includes the choosed index
 
4999
  1     error
 
5000
*/
 
5001
 
 
5002
bool get_key_map_from_key_list(key_map *map, Table *table,
 
5003
                               List<String> *index_list)
 
5004
{
 
5005
  List_iterator_fast<String> it(*index_list);
 
5006
  String *name;
 
5007
  uint32_t pos;
 
5008
 
 
5009
  map->reset();
 
5010
  while ((name=it++))
 
5011
  {
 
5012
    if (table->s->keynames.type_names == 0 ||
 
5013
        (pos= find_type(&table->s->keynames, name->ptr(),
 
5014
                        name->length(), 1)) <=
 
5015
        0)
 
5016
    {
 
5017
      my_error(ER_KEY_DOES_NOT_EXITS, MYF(0), name->c_ptr(),
 
5018
               table->pos_in_table_list->alias);
 
5019
      map->set();
 
5020
      return 1;
 
5021
    }
 
5022
    map->set(pos-1);
 
5023
  }
 
5024
  return 0;
 
5025
}
 
5026
 
 
5027
 
 
5028
/*
3567
5029
  Drops in all fields instead of current '*' field
3568
5030
 
3569
5031
  SYNOPSIS
3570
5032
  insert_fields()
3571
 
  session                       Thread Cursor
 
5033
  session                       Thread handler
3572
5034
  context             Context for name resolution
3573
5035
  db_name               Database name in case of 'database_name.table_name.*'
3574
5036
  table_name            Table name in case of 'table_name.*'
3622
5084
    assert(tables->is_leaf_for_name_resolution());
3623
5085
 
3624
5086
    if ((table_name && my_strcasecmp(table_alias_charset, table_name, tables->alias)) ||
3625
 
        (db_name && strcasecmp(tables->getSchemaName(),db_name)))
 
5087
        (db_name && strcmp(tables->db,db_name)))
3626
5088
      continue;
3627
5089
 
3628
5090
    /*
3645
5107
      Item *item;
3646
5108
 
3647
5109
      if (!(item= field_iterator.create_item(session)))
3648
 
        return true;
 
5110
        return(true);
3649
5111
 
3650
5112
      if (!found)
3651
5113
      {
3658
5120
      if ((field= field_iterator.field()))
3659
5121
      {
3660
5122
        /* Mark fields as used to allow storage engine to optimze access */
3661
 
        field->getTable()->setReadSet(field->position());
 
5123
        field->table->setReadSet(field->field_index);
3662
5124
        if (table)
3663
5125
        {
3664
5126
          table->covering_keys&= field->part_of_key;
3673
5135
          */
3674
5136
          Natural_join_column *nj_col;
3675
5137
          if (!(nj_col= field_iterator.get_natural_column_ref()))
3676
 
            return true;
 
5138
            return(true);
3677
5139
          assert(nj_col->table_field);
3678
5140
          field_table= nj_col->table_ref->table;
3679
5141
          if (field_table)
3696
5158
      For NATURAL joins, used_tables is updated in the IF above.
3697
5159
    */
3698
5160
    if (table)
3699
 
      table->used_fields= table->getShare()->sizeFields();
 
5161
      table->used_fields= table->s->fields;
3700
5162
  }
3701
5163
  if (found)
3702
 
    return false;
 
5164
    return(false);
3703
5165
 
3704
5166
  /*
3705
 
    @TODO in the case when we skipped all columns because there was a
3706
 
    qualified '*', and all columns were coalesced, we have to give a more
3707
 
    meaningful message than ER_BAD_TABLE_ERROR.
 
5167
TODO: in the case when we skipped all columns because there was a
 
5168
qualified '*', and all columns were coalesced, we have to give a more
 
5169
meaningful message than ER_BAD_TABLE_ERROR.
3708
5170
  */
3709
5171
  if (!table_name)
3710
5172
    my_message(ER_NO_TABLES_USED, ER(ER_NO_TABLES_USED), MYF(0));
3711
5173
  else
3712
5174
    my_error(ER_BAD_TABLE_ERROR, MYF(0), table_name);
3713
5175
 
3714
 
  return true;
 
5176
  return(true);
3715
5177
}
3716
5178
 
3717
5179
 
3720
5182
 
3721
5183
  SYNOPSIS
3722
5184
  setup_conds()
3723
 
  session     thread Cursor
 
5185
  session     thread handler
3724
5186
  tables  list of tables for name resolving (select_lex->table_list)
3725
5187
  leaves  list of leaves of join table tree (select_lex->leaf_tables)
3726
5188
  conds   WHERE clause
3733
5195
  false if all is OK
3734
5196
*/
3735
5197
 
3736
 
int Session::setup_conds(TableList *leaves, COND **conds)
 
5198
int setup_conds(Session *session, TableList *leaves, COND **conds)
3737
5199
{
3738
 
  Session *session= this;
3739
5200
  Select_Lex *select_lex= session->lex->current_select;
3740
5201
  TableList *table= NULL;       // For HP compilers
3741
5202
  void *save_session_marker= session->session_marker;
3743
5204
    it_is_update set to true when tables of primary Select_Lex (Select_Lex
3744
5205
    which belong to LEX, i.e. most up SELECT) will be updated by
3745
5206
    INSERT/UPDATE/LOAD
3746
 
    NOTE-> using this condition helps to prevent call of prepare_check_option()
3747
 
    from subquery of VIEW, because tables of subquery belongs to VIEW
3748
 
    (see condition before prepare_check_option() call)
 
5207
NOTE: using this condition helps to prevent call of prepare_check_option()
 
5208
from subquery of VIEW, because tables of subquery belongs to VIEW
 
5209
(see condition before prepare_check_option() call)
3749
5210
  */
3750
5211
  bool save_is_item_list_lookup= select_lex->is_item_list_lookup;
3751
5212
  select_lex->is_item_list_lookup= 0;
3786
5247
          goto err_no_arena;
3787
5248
        select_lex->cond_count++;
3788
5249
      }
3789
 
      embedding= embedded->getEmbedding();
 
5250
      embedding= embedded->embedding;
3790
5251
    }
3791
5252
    while (embedding &&
3792
 
           embedding->getNestedJoin()->join_list.head() == embedded);
 
5253
           embedding->nested_join->join_list.head() == embedded);
3793
5254
 
3794
5255
  }
3795
5256
  session->session_marker= save_session_marker;
3799
5260
 
3800
5261
err_no_arena:
3801
5262
  select_lex->is_item_list_lookup= save_is_item_list_lookup;
3802
 
 
3803
 
  return 1;
 
5263
  return(1);
3804
5264
}
3805
5265
 
3806
5266
 
3815
5275
 
3816
5276
  SYNOPSIS
3817
5277
  fill_record()
 
5278
  session           thread handler
3818
5279
  fields        Item_fields list to be filled
3819
5280
  values        values to fill with
3820
5281
  ignore_errors true if we should ignore errors
3830
5291
*/
3831
5292
 
3832
5293
bool
3833
 
fill_record(Session *session, List<Item> &fields, List<Item> &values, bool ignore_errors)
 
5294
fill_record(Session * session, List<Item> &fields, List<Item> &values, bool ignore_errors)
3834
5295
{
3835
5296
  List_iterator_fast<Item> f(fields),v(values);
3836
 
  Item *value;
 
5297
  Item *value, *fld;
3837
5298
  Item_field *field;
3838
 
  Table *table;
 
5299
  Table *table= 0;
 
5300
  List<Table> tbl_list;
 
5301
  bool abort_on_warning_saved= session->abort_on_warning;
 
5302
  tbl_list.empty();
3839
5303
 
3840
5304
  /*
3841
5305
    Reset the table->auto_increment_field_not_null as it is valid for
3847
5311
      On INSERT or UPDATE fields are checked to be from the same table,
3848
5312
      thus we safely can take table from the first field.
3849
5313
    */
3850
 
    field= static_cast<Item_field *>(f++);
3851
 
    table= field->field->getTable();
 
5314
    fld= (Item_field*)f++;
 
5315
    if (!(field= fld->filed_for_view_update()))
 
5316
    {
 
5317
      my_error(ER_NONUPDATEABLE_COLUMN, MYF(0), fld->name);
 
5318
      goto err;
 
5319
    }
 
5320
    table= field->field->table;
3852
5321
    table->auto_increment_field_not_null= false;
3853
5322
    f.rewind();
3854
5323
  }
3855
 
 
3856
 
  while ((field= static_cast<Item_field *>(f++)))
 
5324
  while ((fld= f++))
3857
5325
  {
3858
 
    value= v++;
3859
 
 
 
5326
    if (!(field= fld->filed_for_view_update()))
 
5327
    {
 
5328
      my_error(ER_NONUPDATEABLE_COLUMN, MYF(0), fld->name);
 
5329
      goto err;
 
5330
    }
 
5331
    value=v++;
3860
5332
    Field *rfield= field->field;
3861
 
    table= rfield->getTable();
3862
 
 
 
5333
    table= rfield->table;
3863
5334
    if (rfield == table->next_number_field)
3864
5335
      table->auto_increment_field_not_null= true;
3865
5336
    if ((value->save_in_field(rfield, 0) < 0) && !ignore_errors)
3866
5337
    {
3867
5338
      my_message(ER_UNKNOWN_ERROR, ER(ER_UNKNOWN_ERROR), MYF(0));
3868
 
      if (table)
3869
 
        table->auto_increment_field_not_null= false;
3870
 
 
3871
 
      return true;
3872
 
    }
3873
 
  }
3874
 
 
3875
 
  return session->is_error();
 
5339
      goto err;
 
5340
    }
 
5341
    tbl_list.push_back(table);
 
5342
  }
 
5343
  /* Update virtual fields*/
 
5344
  session->abort_on_warning= false;
 
5345
  if (tbl_list.head())
 
5346
  {
 
5347
    List_iterator_fast<Table> t(tbl_list);
 
5348
    Table *prev_table= 0;
 
5349
    while ((table= t++))
 
5350
    {
 
5351
      /*
 
5352
        Do simple optimization to prevent unnecessary re-generating
 
5353
        values for virtual fields
 
5354
      */
 
5355
      if (table != prev_table)
 
5356
        prev_table= table;
 
5357
    }
 
5358
  }
 
5359
  session->abort_on_warning= abort_on_warning_saved;
 
5360
  return(session->is_error());
 
5361
err:
 
5362
  session->abort_on_warning= abort_on_warning_saved;
 
5363
  if (table)
 
5364
    table->auto_increment_field_not_null= false;
 
5365
  return(true);
3876
5366
}
3877
5367
 
3878
5368
 
3881
5371
 
3882
5372
  SYNOPSIS
3883
5373
  fill_record()
 
5374
  session           thread handler
3884
5375
  ptr           pointer on pointer to record
3885
5376
  values        list of fields
3886
5377
  ignore_errors true if we should ignore errors
3895
5386
  true    error occured
3896
5387
*/
3897
5388
 
3898
 
bool fill_record(Session *session, Field **ptr, List<Item> &values, bool)
 
5389
bool
 
5390
fill_record(Session *session, Field **ptr, List<Item> &values,
 
5391
            bool )
3899
5392
{
3900
5393
  List_iterator_fast<Item> v(values);
3901
5394
  Item *value;
3902
5395
  Table *table= 0;
3903
5396
  Field *field;
 
5397
  List<Table> tbl_list;
 
5398
  bool abort_on_warning_saved= session->abort_on_warning;
3904
5399
 
 
5400
  tbl_list.empty();
3905
5401
  /*
3906
5402
    Reset the table->auto_increment_field_not_null as it is valid for
3907
5403
    only one row.
3912
5408
      On INSERT or UPDATE fields are checked to be from the same table,
3913
5409
      thus we safely can take table from the first field.
3914
5410
    */
3915
 
    table= (*ptr)->getTable();
 
5411
    table= (*ptr)->table;
3916
5412
    table->auto_increment_field_not_null= false;
3917
5413
  }
3918
5414
  while ((field = *ptr++) && ! session->is_error())
3919
5415
  {
3920
5416
    value=v++;
3921
 
    table= field->getTable();
 
5417
    table= field->table;
3922
5418
    if (field == table->next_number_field)
3923
5419
      table->auto_increment_field_not_null= true;
3924
5420
    if (value->save_in_field(field, 0) < 0)
 
5421
      goto err;
 
5422
    tbl_list.push_back(table);
 
5423
  }
 
5424
  /* Update virtual fields*/
 
5425
  session->abort_on_warning= false;
 
5426
  if (tbl_list.head())
 
5427
  {
 
5428
    List_iterator_fast<Table> t(tbl_list);
 
5429
    Table *prev_table= 0;
 
5430
    while ((table= t++))
3925
5431
    {
3926
 
      if (table)
3927
 
        table->auto_increment_field_not_null= false;
3928
 
 
3929
 
      return true;
 
5432
      /*
 
5433
        Do simple optimization to prevent unnecessary re-generating
 
5434
        values for virtual fields
 
5435
      */
 
5436
      if (table != prev_table)
 
5437
      {
 
5438
        prev_table= table;
 
5439
      }
3930
5440
    }
3931
5441
  }
3932
 
 
 
5442
  session->abort_on_warning= abort_on_warning_saved;
3933
5443
  return(session->is_error());
 
5444
 
 
5445
err:
 
5446
  session->abort_on_warning= abort_on_warning_saved;
 
5447
  if (table)
 
5448
    table->auto_increment_field_not_null= false;
 
5449
  return(true);
3934
5450
}
3935
5451
 
3936
5452
 
3937
 
bool drizzle_rm_tmp_tables()
 
5453
bool drizzle_rm_tmp_tables(void)
3938
5454
{
 
5455
  uint32_t  idx;
 
5456
  char  filePath[FN_REFLEN], filePathCopy[FN_REFLEN];
 
5457
  MY_DIR *dirp;
 
5458
  FILEINFO *file;
3939
5459
  Session *session;
3940
5460
 
3941
 
  assert(drizzle_tmpdir.size());
 
5461
  assert(drizzle_tmpdir);
3942
5462
 
3943
 
  if (!(session= new Session(plugin::Listen::getNullClient())))
 
5463
  if (!(session= new Session(get_protocol())))
3944
5464
    return true;
3945
5465
  session->thread_stack= (char*) &session;
3946
 
  session->storeGlobals();
3947
 
 
3948
 
  plugin::StorageEngine::removeLostTemporaryTables(*session, drizzle_tmpdir.c_str());
 
5466
  session->store_globals();
 
5467
 
 
5468
  /* Remove all temp tables in the tmpdir */
 
5469
  /* See if the directory exists */
 
5470
  if ((dirp = my_dir(drizzle_tmpdir ,MYF(MY_WME | MY_DONT_SORT))))
 
5471
  {
 
5472
    /* Remove all SQLxxx tables from directory */
 
5473
    for (idx=0 ; idx < (uint32_t) dirp->number_off_files ; idx++)
 
5474
    {
 
5475
      file=dirp->dir_entry+idx;
 
5476
 
 
5477
      /* skiping . and .. */
 
5478
      if (file->name[0] == '.' && (!file->name[1] ||
 
5479
                                   (file->name[1] == '.' &&  !file->name[2])))
 
5480
        continue;
 
5481
 
 
5482
      if (!memcmp(file->name, TMP_FILE_PREFIX, TMP_FILE_PREFIX_LENGTH))
 
5483
      {
 
5484
        char *ext= fn_ext(file->name);
 
5485
        uint32_t ext_len= strlen(ext);
 
5486
        uint32_t filePath_len= snprintf(filePath, sizeof(filePath),
 
5487
                                        "%s%c%s", drizzle_tmpdir, FN_LIBCHAR,
 
5488
                                        file->name);
 
5489
        if (!memcmp(".dfe", ext, ext_len))
 
5490
        {
 
5491
          TableShare share;
 
5492
          handler *handler_file= 0;
 
5493
          /* We should cut file extention before deleting of table */
 
5494
          memcpy(filePathCopy, filePath, filePath_len - ext_len);
 
5495
          filePathCopy[filePath_len - ext_len]= 0;
 
5496
          share.init(NULL, filePathCopy);
 
5497
          if (!open_table_def(session, &share) &&
 
5498
              ((handler_file= get_new_handler(&share, session->mem_root,
 
5499
                                              share.db_type()))))
 
5500
          {
 
5501
            handler_file->ha_delete_table(filePathCopy);
 
5502
            delete handler_file;
 
5503
          }
 
5504
          share.free_table_share();
 
5505
        }
 
5506
        /*
 
5507
          File can be already deleted by tmp_table.file->delete_table().
 
5508
          So we hide error messages which happnes during deleting of these
 
5509
          files(MYF(0)).
 
5510
        */
 
5511
        my_delete(filePath, MYF(0));
 
5512
      }
 
5513
    }
 
5514
    my_dirend(dirp);
 
5515
  }
3949
5516
 
3950
5517
  delete session;
3951
5518
 
3958
5525
  unireg support functions
3959
5526
 *****************************************************************************/
3960
5527
 
3961
 
 
3962
 
 
3963
 
 
 
5528
/*
 
5529
  Invalidate any cache entries that are for some DB
 
5530
 
 
5531
  SYNOPSIS
 
5532
  remove_db_from_cache()
 
5533
  db            Database name. This will be in lower case if
 
5534
  lower_case_table_name is set
 
5535
 
 
5536
NOTE:
 
5537
We can't use hash_delete when looping hash_elements. We mark them first
 
5538
and afterwards delete those marked unused.
 
5539
*/
 
5540
 
 
5541
void remove_db_from_cache(const char *db)
 
5542
{
 
5543
  for (uint32_t idx=0 ; idx < open_cache.records ; idx++)
 
5544
  {
 
5545
    Table *table=(Table*) hash_element(&open_cache,idx);
 
5546
    if (!strcmp(table->s->db.str, db))
 
5547
    {
 
5548
      table->s->version= 0L;                    /* Free when thread is ready */
 
5549
      if (!table->in_use)
 
5550
        relink_unused(table);
 
5551
    }
 
5552
  }
 
5553
  while (unused_tables && !unused_tables->s->version)
 
5554
    hash_delete(&open_cache,(unsigned char*) unused_tables);
 
5555
}
 
5556
 
 
5557
 
 
5558
/*
 
5559
  Mark all entries with the table as deleted to force an reopen of the table
 
5560
 
 
5561
  The table will be closed (not stored in cache) by the current thread when
 
5562
  close_thread_tables() is called.
 
5563
 
 
5564
  PREREQUISITES
 
5565
  Lock on LOCK_open()
 
5566
 
 
5567
  RETURN
 
5568
  0  This thread now have exclusive access to this table and no other thread
 
5569
  can access the table until close_thread_tables() is called.
 
5570
  1  Table is in use by another thread
 
5571
*/
 
5572
 
 
5573
bool remove_table_from_cache(Session *session, const char *db, const char *table_name,
 
5574
                             uint32_t flags)
 
5575
{
 
5576
  char key[MAX_DBKEY_LENGTH];
 
5577
  char *key_pos= key;
 
5578
  uint32_t key_length;
 
5579
  Table *table;
 
5580
  TableShare *share;
 
5581
  bool result= 0, signalled= 0;
 
5582
 
 
5583
  key_pos= strcpy(key_pos, db) + strlen(db);
 
5584
  key_pos= strcpy(key_pos+1, table_name) + strlen(table_name);
 
5585
  key_length= (uint32_t) (key_pos-key)+1;
 
5586
 
 
5587
  for (;;)
 
5588
  {
 
5589
    HASH_SEARCH_STATE state;
 
5590
    result= signalled= 0;
 
5591
 
 
5592
    for (table= (Table*) hash_first(&open_cache, (unsigned char*) key, key_length,
 
5593
                                    &state);
 
5594
         table;
 
5595
         table= (Table*) hash_next(&open_cache, (unsigned char*) key, key_length,
 
5596
                                   &state))
 
5597
    {
 
5598
      Session *in_use;
 
5599
 
 
5600
      table->s->version=0L;             /* Free when thread is ready */
 
5601
      if (!(in_use=table->in_use))
 
5602
      {
 
5603
        relink_unused(table);
 
5604
      }
 
5605
      else if (in_use != session)
 
5606
      {
 
5607
        /*
 
5608
          Mark that table is going to be deleted from cache. This will
 
5609
          force threads that are in mysql_lock_tables() (but not yet
 
5610
          in thr_multi_lock()) to abort it's locks, close all tables and retry
 
5611
        */
 
5612
        in_use->some_tables_deleted= 1;
 
5613
        if (table->is_name_opened())
 
5614
        {
 
5615
          result=1;
 
5616
        }
 
5617
        /*
 
5618
          Now we must abort all tables locks used by this thread
 
5619
          as the thread may be waiting to get a lock for another table.
 
5620
          Note that we need to hold LOCK_open while going through the
 
5621
          list. So that the other thread cannot change it. The other
 
5622
          thread must also hold LOCK_open whenever changing the
 
5623
          open_tables list. Aborting the MERGE lock after a child was
 
5624
          closed and before the parent is closed would be fatal.
 
5625
        */
 
5626
        for (Table *session_table= in_use->open_tables;
 
5627
             session_table ;
 
5628
             session_table= session_table->next)
 
5629
        {
 
5630
          /* Do not handle locks of MERGE children. */
 
5631
          if (session_table->db_stat)   // If table is open
 
5632
            signalled|= mysql_lock_abort_for_thread(session, session_table);
 
5633
        }
 
5634
      }
 
5635
      else
 
5636
        result= result || (flags & RTFC_OWNED_BY_Session_FLAG);
 
5637
    }
 
5638
    while (unused_tables && !unused_tables->s->version)
 
5639
      hash_delete(&open_cache,(unsigned char*) unused_tables);
 
5640
 
 
5641
    /* Remove table from table definition cache if it's not in use */
 
5642
    if ((share= (TableShare*) hash_search(&table_def_cache,(unsigned char*) key,
 
5643
                                          key_length)))
 
5644
    {
 
5645
      share->version= 0;                          // Mark for delete
 
5646
      if (share->ref_count == 0)
 
5647
      {
 
5648
        pthread_mutex_lock(&share->mutex);
 
5649
        hash_delete(&table_def_cache, (unsigned char*) share);
 
5650
      }
 
5651
    }
 
5652
 
 
5653
    if (result && (flags & RTFC_WAIT_OTHER_THREAD_FLAG))
 
5654
    {
 
5655
      /*
 
5656
        Signal any thread waiting for tables to be freed to
 
5657
        reopen their tables
 
5658
      */
 
5659
      broadcast_refresh();
 
5660
      if (!(flags & RTFC_CHECK_KILLED_FLAG) || !session->killed)
 
5661
      {
 
5662
        dropping_tables++;
 
5663
        if (likely(signalled))
 
5664
          (void) pthread_cond_wait(&COND_refresh, &LOCK_open);
 
5665
        else
 
5666
        {
 
5667
          struct timespec abstime;
 
5668
          /*
 
5669
            It can happen that another thread has opened the
 
5670
            table but has not yet locked any table at all. Since
 
5671
            it can be locked waiting for a table that our thread
 
5672
            has done LOCK Table x WRITE on previously, we need to
 
5673
            ensure that the thread actually hears our signal
 
5674
            before we go to sleep. Thus we wait for a short time
 
5675
            and then we retry another loop in the
 
5676
            remove_table_from_cache routine.
 
5677
          */
 
5678
          set_timespec(abstime, 10);
 
5679
          pthread_cond_timedwait(&COND_refresh, &LOCK_open, &abstime);
 
5680
        }
 
5681
        dropping_tables--;
 
5682
        continue;
 
5683
      }
 
5684
    }
 
5685
    break;
 
5686
  }
 
5687
  return(result);
 
5688
}
 
5689
 
 
5690
 
 
5691
bool is_equal(const LEX_STRING *a, const LEX_STRING *b)
 
5692
{
 
5693
  return a->length == b->length && !strncmp(a->str, b->str, a->length);
 
5694
}
3964
5695
/**
3965
5696
  @} (end of group Data_Dictionary)
3966
5697
*/
3970
5701
  pthread_kill(signal_thread, SIGTERM);
3971
5702
  shutdown_in_progress= 1;                      // Safety if kill didn't work
3972
5703
}
3973
 
 
3974
 
} /* namespace drizzled */