~drizzle-trunk/drizzle/development

« back to all changes in this revision

Viewing changes to drizzled/sql_base.cc

  • Committer: Stewart Smith
  • Date: 2010-06-04 02:51:04 UTC
  • mto: This revision was merged to the branch mainline in revision 1590.
  • Revision ID: stewart@flamingspork.com-20100604025104-ilf5mrvwbpd5crzv
have a constant for the maximum number of enum elements

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 */
31
31
# endif
32
32
#endif
33
33
#include "drizzled/internal/my_pthread.h"
34
 
#include "drizzled/internal/thread_var.h"
35
34
 
36
35
#include <drizzled/sql_select.h>
37
36
#include <drizzled/error.h>
47
46
#include "drizzled/cached_directory.h"
48
47
#include <drizzled/field/timestamp.h>
49
48
#include <drizzled/field/null.h>
 
49
#include "drizzled/memory/multi_malloc.h"
50
50
#include "drizzled/sql_table.h"
51
51
#include "drizzled/global_charset_info.h"
52
52
#include "drizzled/pthread_globals.h"
53
53
#include "drizzled/internal/iocache.h"
54
54
#include "drizzled/drizzled.h"
55
55
#include "drizzled/plugin/authorization.h"
56
 
#include "drizzled/table/temporary.h"
57
 
#include "drizzled/table/placeholder.h"
58
 
#include "drizzled/table/unused.h"
 
56
#include "drizzled/table_placeholder.h"
59
57
 
60
58
using namespace std;
61
59
 
64
62
 
65
63
extern bool volatile shutdown_in_progress;
66
64
 
 
65
/**
 
66
  @defgroup Data_Dictionary Data Dictionary
 
67
  @{
 
68
*/
 
69
Table *unused_tables;                           /* Used by mysql_test */
 
70
HASH open_cache;                                /* Used by mysql_test */
 
71
static int open_unireg_entry(Session *session,
 
72
                             Table *entry,
 
73
                             const char *alias,
 
74
                             char *cache_key, uint32_t cache_key_length);
 
75
void free_cache_entry(void *entry);
 
76
unsigned char *table_cache_key(const unsigned char *record,
 
77
                               size_t *length,
 
78
                               bool );
 
79
 
 
80
#if 0
 
81
static bool reopen_table(Table *table);
 
82
#endif
 
83
 
 
84
unsigned char *table_cache_key(const unsigned char *record,
 
85
                               size_t *length,
 
86
                               bool )
 
87
{
 
88
  Table *entry=(Table*) record;
 
89
  *length= entry->getShare()->getCacheKeySize();
 
90
  return (unsigned char*) entry->getMutableShare()->getCacheKey();
 
91
}
 
92
 
 
93
HASH *get_open_cache()
 
94
{
 
95
  return &open_cache;
 
96
}
 
97
 
 
98
 
67
99
bool table_cache_init(void)
68
100
{
69
 
  return false;
70
 
}
71
 
 
72
 
uint32_t cached_open_tables(void)
73
 
{
74
 
  return table::getCache().size();
 
101
  return hash_init(&open_cache, &my_charset_bin,
 
102
                   (size_t) table_cache_size+16,
 
103
                   0, 0, table_cache_key,
 
104
                   free_cache_entry, 0);
75
105
}
76
106
 
77
107
void table_cache_free(void)
78
108
{
79
109
  refresh_version++;                            // Force close of open tables
80
110
 
81
 
  table::getUnused().clear();
82
 
  table::getCache().clear();
83
 
}
 
111
  while (unused_tables)
 
112
    hash_delete(&open_cache, (unsigned char*) unused_tables);
 
113
 
 
114
  if (not open_cache.records)                   // Safety first
 
115
    hash_free(&open_cache);
 
116
}
 
117
 
 
118
uint32_t cached_open_tables(void)
 
119
{
 
120
  return open_cache.records;
 
121
}
 
122
 
84
123
 
85
124
/*
86
125
  Close cursor handle, but leave the table in the table cache
93
132
  By leaving the table in the table cache, it disallows any other thread
94
133
  to open the table
95
134
 
96
 
  session->getKilled() will be set if we run out of memory
 
135
  session->killed will be set if we run out of memory
97
136
 
98
137
  If closing a MERGE child, the calling function has to take care for
99
138
  closing the parent too, if necessary.
102
141
 
103
142
void close_handle_and_leave_table_as_lock(Table *table)
104
143
{
 
144
  TableShare *share, *old_share= table->getMutableShare();
 
145
 
105
146
  assert(table->db_stat);
106
 
  assert(table->getShare()->getType() == message::Table::STANDARD);
107
147
 
108
148
  /*
109
149
    Make a local copy of the table share and free the current one.
110
150
    This has to be done to ensure that the table share is removed from
111
151
    the table defintion cache as soon as the last instance is removed
112
152
  */
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()));
 
153
  share= new TableShare(const_cast<char *>(old_share->getCacheKey()),  static_cast<uint32_t>(old_share->getCacheKeySize()));
 
154
  share->tmp_table= message::Table::INTERNAL;       // for intern_close_table()
118
155
 
119
156
  table->cursor->close();
120
157
  table->db_stat= 0;                            // Mark cursor closed
121
158
  TableShare::release(table->getMutableShare());
122
159
  table->setShare(share);
 
160
  table->cursor->change_table_ptr(table, table->getMutableShare());
123
161
}
124
162
 
125
163
 
137
175
  }
138
176
}
139
177
 
 
178
/*
 
179
  Remove table from the open table cache
 
180
 
 
181
  SYNOPSIS
 
182
  free_cache_entry()
 
183
  entry         Table to remove
 
184
 
 
185
  NOTE
 
186
  We need to have a lock on LOCK_open when calling this
 
187
*/
 
188
 
 
189
void free_cache_entry(void *entry)
 
190
{
 
191
  Table *table= static_cast<Table *>(entry);
 
192
 
 
193
  table->intern_close_table();
 
194
  if (not table->in_use)
 
195
  {
 
196
    table->next->prev=table->prev;              /* remove from used chain */
 
197
    table->prev->next=table->next;
 
198
    if (table == unused_tables)
 
199
    {
 
200
      unused_tables= unused_tables->next;
 
201
      if (table == unused_tables)
 
202
        unused_tables= NULL;
 
203
    }
 
204
  }
 
205
 
 
206
  if (table->isPlaceHolder())
 
207
  {
 
208
    delete table;
 
209
  }
 
210
  else
 
211
  {
 
212
    free(table);
 
213
  }
 
214
}
 
215
 
140
216
/* Free resources allocated by filesort() and read_record() */
141
217
 
142
218
void Table::free_io_cache()
143
219
{
144
220
  if (sort.io_cache)
145
221
  {
146
 
    sort.io_cache->close_cached_file();
 
222
    close_cached_file(sort.io_cache);
147
223
    delete sort.io_cache;
148
224
    sort.io_cache= 0;
149
225
  }
155
231
 
156
232
  @param session Thread context (may be NULL)
157
233
  @param tables List of tables to remove from the cache
158
 
  @param have_lock If table::Cache::singleton().mutex() is locked
 
234
  @param have_lock If LOCK_open is locked
159
235
  @param wait_for_refresh Wait for a impending flush
160
236
  @param wait_for_placeholders Wait for tables being reopened so that the GRL
161
237
  won't proceed while write-locked tables are being reopened by other
170
246
  bool result= false;
171
247
  Session *session= this;
172
248
 
173
 
  {
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
 
      {
 
249
  pthread_mutex_lock(&LOCK_open); /* Optionally lock for remove tables from open_cahe if not in use */
 
250
 
 
251
  if (tables == NULL)
 
252
  {
 
253
    refresh_version++;                          // Force close of open tables
 
254
    while (unused_tables)
 
255
    {
 
256
      hash_delete(&open_cache,(unsigned char*) unused_tables);
 
257
    }
 
258
 
 
259
    if (wait_for_refresh)
 
260
    {
 
261
      /*
 
262
        Other threads could wait in a loop in open_and_lock_tables(),
 
263
        trying to lock one or more of our tables.
 
264
 
 
265
        If they wait for the locks in thr_multi_lock(), their lock
 
266
        request is aborted. They loop in open_and_lock_tables() and
 
267
        enter open_table(). Here they notice the table is refreshed and
 
268
        wait for COND_refresh. Then they loop again in
 
269
        openTablesLock() and this time open_table() succeeds. At
 
270
        this moment, if we (the FLUSH TABLES thread) are scheduled and
 
271
        on another FLUSH TABLES enter close_cached_tables(), they could
 
272
        awake while we sleep below, waiting for others threads (us) to
 
273
        close their open tables. If this happens, the other threads
 
274
        would find the tables unlocked. They would get the locks, one
 
275
        after the other, and could do their destructive work. This is an
 
276
        issue if we have LOCK TABLES in effect.
 
277
 
 
278
        The problem is that the other threads passed all checks in
 
279
        open_table() before we refresh the table.
 
280
 
 
281
        The fix for this problem is to set some_tables_deleted for all
 
282
        threads with open tables. These threads can still get their
 
283
        locks, but will immediately release them again after checking
 
284
        this variable. They will then loop in openTablesLock()
 
285
        again. There they will wait until we update all tables version
 
286
        below.
 
287
 
 
288
        Setting some_tables_deleted is done by remove_table_from_cache()
 
289
        in the other branch.
 
290
 
 
291
        In other words (reviewer suggestion): You need this setting of
 
292
        some_tables_deleted for the case when table was opened and all
 
293
        related checks were passed before incrementing refresh_version
 
294
        (which you already have) but attempt to lock the table happened
 
295
        after the call to Session::close_old_data_files() i.e. after removal of
 
296
        current thread locks.
 
297
      */
 
298
      for (uint32_t idx=0 ; idx < open_cache.records ; idx++)
 
299
      {
 
300
        Table *table=(Table*) hash_element(&open_cache,idx);
 
301
        if (table->in_use)
 
302
          table->in_use->some_tables_deleted= false;
 
303
      }
 
304
    }
 
305
  }
 
306
  else
 
307
  {
 
308
    bool found= false;
 
309
    for (TableList *table= tables; table; table= table->next_local)
 
310
    {
 
311
      if (remove_table_from_cache(session, table->db, table->table_name,
 
312
                                  RTFC_OWNED_BY_Session_FLAG))
 
313
        found= true;
 
314
    }
 
315
    if (!found)
 
316
      wait_for_refresh= false;                  // Nothing to wait for
 
317
  }
 
318
 
 
319
  if (wait_for_refresh)
 
320
  {
 
321
    /*
 
322
      If there is any table that has a lower refresh_version, wait until
 
323
      this is closed (or this thread is killed) before returning
 
324
    */
 
325
    session->mysys_var->current_mutex= &LOCK_open;
 
326
    session->mysys_var->current_cond= &COND_refresh;
 
327
    session->set_proc_info("Flushing tables");
 
328
 
 
329
    session->close_old_data_files();
 
330
 
 
331
    bool found= true;
 
332
    /* Wait until all threads has closed all the tables we had locked */
 
333
    while (found && ! session->killed)
 
334
    {
 
335
      found= false;
 
336
      for (uint32_t idx=0 ; idx < open_cache.records ; idx++)
 
337
      {
 
338
        Table *table=(Table*) hash_element(&open_cache,idx);
 
339
        /* Avoid a self-deadlock. */
 
340
        if (table->in_use == session)
 
341
          continue;
184
342
        /*
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.
 
343
          Note that we wait here only for tables which are actually open, and
 
344
          not for placeholders with Table::open_placeholder set. Waiting for
 
345
          latter will cause deadlock in the following scenario, for example:
 
346
 
 
347
conn1: lock table t1 write;
 
348
conn2: lock table t2 write;
 
349
conn1: flush tables;
 
350
conn2: flush tables;
 
351
 
 
352
It also does not make sense to wait for those of placeholders that
 
353
are employed by CREATE TABLE as in this case table simply does not
 
354
exist yet.
220
355
        */
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))
 
356
        if (table->needs_reopen_or_name_lock() && (table->db_stat ||
 
357
                                                   (table->open_placeholder && wait_for_placeholders)))
239
358
        {
240
359
          found= true;
 
360
          pthread_cond_wait(&COND_refresh,&LOCK_open);
 
361
          break;
241
362
        }
242
363
      }
243
 
      if (!found)
244
 
        wait_for_refresh= false;                        // Nothing to wait for
245
364
    }
 
365
    /*
 
366
      No other thread has the locked tables open; reopen them and get the
 
367
      old locks. This should always succeed (unless some external process
 
368
      has removed the tables)
 
369
    */
 
370
    result= session->reopen_tables(true, true);
246
371
 
247
 
    if (wait_for_refresh)
 
372
    /* Set version for table */
 
373
    for (Table *table= session->open_tables; table ; table= table->next)
248
374
    {
249
375
      /*
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
252
 
      */
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++)
267
 
        {
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
 
          }
295
 
        }
296
 
      }
297
 
      /*
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)
301
 
      */
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
 
      }
 
376
        Preserve the version (0) of write locked tables so that a impending
 
377
        global read lock won't sneak in.
 
378
      */
 
379
      if (table->reginfo.lock_type < TL_WRITE_ALLOW_WRITE)
 
380
        table->getMutableShare()->version= refresh_version;
314
381
    }
315
 
 
316
 
    table::Cache::singleton().mutex().unlock();
317
382
  }
318
383
 
 
384
  pthread_mutex_unlock(&LOCK_open);
 
385
 
319
386
  if (wait_for_refresh)
320
387
  {
321
 
    boost_unique_lock_t scopedLock(session->mysys_var->mutex);
 
388
    pthread_mutex_lock(&session->mysys_var->mutex);
322
389
    session->mysys_var->current_mutex= 0;
323
390
    session->mysys_var->current_cond= 0;
324
391
    session->set_proc_info(0);
 
392
    pthread_mutex_unlock(&session->mysys_var->mutex);
325
393
  }
326
394
 
327
395
  return result;
335
403
bool Session::free_cached_table()
336
404
{
337
405
  bool found_old_table= false;
338
 
  table::Concurrent *table= static_cast<table::Concurrent *>(open_tables);
 
406
  Table *table= open_tables;
339
407
 
340
 
  safe_mutex_assert_owner(table::Cache::singleton().mutex().native_handle());
 
408
  safe_mutex_assert_owner(&LOCK_open);
341
409
  assert(table->key_read == 0);
342
410
  assert(!table->cursor || table->cursor->inited == Cursor::NONE);
343
411
 
344
 
  open_tables= table->getNext();
 
412
  open_tables= table->next;
345
413
 
346
414
  if (table->needs_reopen_or_name_lock() ||
347
415
      version != refresh_version || !table->db_stat)
348
416
  {
349
 
    table::remove_table(table);
 
417
    hash_delete(&open_cache,(unsigned char*) table);
350
418
    found_old_table= true;
351
419
  }
352
420
  else
359
427
 
360
428
    /* Free memory and reset for next loop */
361
429
    table->cursor->ha_reset();
362
 
    table->in_use= NULL;
 
430
    table->in_use= false;
363
431
 
364
 
    table::getUnused().link(table);
 
432
    if (unused_tables)
 
433
    {
 
434
      table->next= unused_tables;               /* Link in last */
 
435
      table->prev= unused_tables->prev;
 
436
      unused_tables->prev= table;
 
437
      table->prev->next= table;
 
438
    }
 
439
    else
 
440
    {
 
441
      unused_tables= table->next= table->prev=table;
 
442
    }
365
443
  }
366
444
 
367
445
  return found_old_table;
380
458
{
381
459
  bool found_old_table= false;
382
460
 
383
 
  safe_mutex_assert_not_owner(table::Cache::singleton().mutex().native_handle());
 
461
  safe_mutex_assert_not_owner(&LOCK_open);
384
462
 
385
 
  boost_unique_lock_t scoped_lock(table::Cache::singleton().mutex()); /* Close all open tables on Session */
 
463
  pthread_mutex_lock(&LOCK_open); /* Close all open tables on Session */
386
464
 
387
465
  while (open_tables)
388
466
  {
393
471
  if (found_old_table)
394
472
  {
395
473
    /* Tell threads waiting for refresh that something has happened */
396
 
    locking::broadcast_refresh();
 
474
    broadcast_refresh();
397
475
  }
 
476
 
 
477
  pthread_mutex_unlock(&LOCK_open);
398
478
}
399
479
 
400
480
/*
422
502
{
423
503
  for (; table; table= table->*link )
424
504
  {
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)
 
505
    if ((table->table == 0 || table->table->getShare()->tmp_table == message::Table::STANDARD) &&
 
506
        strcasecmp(table->db, db_name) == 0 &&
 
507
        strcasecmp(table->table_name, table_name) == 0)
428
508
      break;
429
509
  }
430
510
  return table;
486
566
  if (table->table)
487
567
  {
488
568
    /* temporary table is always unique */
489
 
    if (table->table && table->table->getShare()->getType() != message::Table::STANDARD)
 
569
    if (table->table && table->table->getShare()->tmp_table != message::Table::STANDARD)
490
570
      return 0;
491
571
    table= table->find_underlying_table(table->table);
492
572
    /*
495
575
    */
496
576
    assert(table);
497
577
  }
498
 
  d_name= table->getSchemaName();
499
 
  t_name= table->getTableName();
 
578
  d_name= table->db;
 
579
  t_name= table->table_name;
500
580
  t_alias= table->alias;
501
581
 
502
582
  for (;;)
517
597
}
518
598
 
519
599
 
520
 
void Open_tables_state::doGetTableNames(const SchemaIdentifier &schema_identifier,
521
 
                                        std::set<std::string>& set_of_names)
 
600
void Session::doGetTableNames(SchemaIdentifier &schema_identifier,
 
601
                              std::set<std::string>& set_of_names)
522
602
{
523
 
  for (Table *table= getTemporaryTables() ; table ; table= table->getNext())
 
603
  for (Table *table= temporary_tables ; table ; table= table->next)
524
604
  {
525
605
    if (schema_identifier.compare(table->getShare()->getSchemaName()))
526
606
    {
529
609
  }
530
610
}
531
611
 
532
 
void Open_tables_state::doGetTableNames(CachedDirectory &,
533
 
                                        const SchemaIdentifier &schema_identifier,
534
 
                                        std::set<std::string> &set_of_names)
 
612
void Session::doGetTableNames(CachedDirectory &,
 
613
                              SchemaIdentifier &schema_identifier,
 
614
                              std::set<std::string> &set_of_names)
535
615
{
536
616
  doGetTableNames(schema_identifier, set_of_names);
537
617
}
538
618
 
539
 
void Open_tables_state::doGetTableIdentifiers(const SchemaIdentifier &schema_identifier,
540
 
                                              TableIdentifier::vector &set_of_identifiers)
 
619
void Session::doGetTableIdentifiers(SchemaIdentifier &schema_identifier,
 
620
                                    TableIdentifiers &set_of_identifiers)
541
621
{
542
 
  for (Table *table= getTemporaryTables() ; table ; table= table->getNext())
 
622
  for (Table *table= temporary_tables ; table ; table= table->next)
543
623
  {
544
624
    if (schema_identifier.compare(table->getShare()->getSchemaName()))
545
625
    {
550
630
  }
551
631
}
552
632
 
553
 
void Open_tables_state::doGetTableIdentifiers(CachedDirectory &,
554
 
                                              const SchemaIdentifier &schema_identifier,
555
 
                                              TableIdentifier::vector &set_of_identifiers)
 
633
void Session::doGetTableIdentifiers(CachedDirectory &,
 
634
                                    SchemaIdentifier &schema_identifier,
 
635
                                    TableIdentifiers &set_of_identifiers)
556
636
{
557
637
  doGetTableIdentifiers(schema_identifier, set_of_identifiers);
558
638
}
559
639
 
560
 
bool Open_tables_state::doDoesTableExist(const TableIdentifier &identifier)
 
640
bool Session::doDoesTableExist(TableIdentifier &identifier)
561
641
{
562
 
  for (Table *table= getTemporaryTables() ; table ; table= table->getNext())
 
642
  for (Table *table= temporary_tables ; table ; table= table->next)
563
643
  {
564
 
    if (table->getShare()->getType() == message::Table::TEMPORARY)
 
644
    if (table->getShare()->tmp_table == message::Table::TEMPORARY)
565
645
    {
566
 
      if (identifier.getKey() == table->getShare()->getCacheKey())
 
646
      if (identifier.compare(table->getShare()->getSchemaName(), table->getShare()->getTableName()))
567
647
      {
568
648
        return true;
569
649
      }
573
653
  return false;
574
654
}
575
655
 
576
 
int Open_tables_state::doGetTableDefinition(const TableIdentifier &identifier,
 
656
int Session::doGetTableDefinition(TableIdentifier &identifier,
577
657
                                  message::Table &table_proto)
578
658
{
579
 
  for (Table *table= getTemporaryTables() ; table ; table= table->getNext())
 
659
  for (Table *table= temporary_tables ; table ; table= table->next)
580
660
  {
581
 
    if (table->getShare()->getType() == message::Table::TEMPORARY)
 
661
    if (table->getShare()->tmp_table == message::Table::TEMPORARY)
582
662
    {
583
 
      if (identifier.getKey() == table->getShare()->getCacheKey())
 
663
      if (identifier.compare(table->getShare()->getSchemaName(), table->getShare()->getTableName()))
584
664
      {
585
665
        table_proto.CopyFrom(*(table->getShare()->getTableProto()));
586
666
 
592
672
  return ENOENT;
593
673
}
594
674
 
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())
 
675
Table *Session::find_temporary_table(const char *new_db, const char *table_name)
 
676
{
 
677
  char  key[MAX_DBKEY_LENGTH];
 
678
  uint  key_length;
 
679
 
 
680
  key_length= TableShare::createKey(key, new_db, table_name);
 
681
 
 
682
  for (Table *table= temporary_tables ; table ; table= table->next)
 
683
  {
 
684
    if (table->getShare()->getCacheKeySize() == key_length &&
 
685
        not memcmp(table->getMutableShare()->getCacheKey(), key, key_length))
 
686
    {
 
687
      return table;
 
688
    }
 
689
  }
 
690
  return NULL;                               // Not a temporary table
 
691
}
 
692
 
 
693
Table *Session::find_temporary_table(TableList *table_list)
 
694
{
 
695
  return find_temporary_table(table_list->db, table_list->table_name);
 
696
}
 
697
 
 
698
Table *Session::find_temporary_table(TableIdentifier &identifier)
 
699
{
 
700
  char  key[MAX_DBKEY_LENGTH];
 
701
  uint  key_length;
 
702
 
 
703
  key_length= TableShare::createKey(key, identifier);
 
704
 
 
705
  for (Table *table= temporary_tables ; table ; table= table->next)
 
706
  {
 
707
    if (table->getShare()->getCacheKeySize() == key_length &&
 
708
        not memcmp(table->getMutableShare()->getCacheKey(), key, key_length))
 
709
 
600
710
      return table;
601
711
  }
602
712
 
630
740
  @retval -1  the table is in use by a outer query
631
741
*/
632
742
 
633
 
int Open_tables_state::drop_temporary_table(const drizzled::TableIdentifier &identifier)
 
743
int Session::drop_temporary_table(TableList *table_list)
634
744
{
635
745
  Table *table;
636
746
 
637
 
  if (not (table= find_temporary_table(identifier)))
 
747
  if (not (table= find_temporary_table(table_list)))
638
748
    return 1;
639
749
 
640
750
  /* Table might be in use by some outer statement. */
641
 
  if (table->query_id && table->query_id != getQueryId())
 
751
  if (table->query_id && table->query_id != query_id)
642
752
  {
643
 
    my_error(ER_CANT_REOPEN_TABLE, MYF(0), table->getAlias());
 
753
    my_error(ER_CANT_REOPEN_TABLE, MYF(0), table->alias);
644
754
    return -1;
645
755
  }
646
756
 
650
760
}
651
761
 
652
762
 
 
763
/* move table first in unused links */
 
764
 
 
765
static void relink_unused(Table *table)
 
766
{
 
767
  if (table != unused_tables)
 
768
  {
 
769
    table->prev->next=table->next;              /* Remove from unused list */
 
770
    table->next->prev=table->prev;
 
771
    table->next=unused_tables;                  /* Link in unused tables */
 
772
    table->prev=unused_tables->prev;
 
773
    unused_tables->prev->next=table;
 
774
    unused_tables->prev=table;
 
775
    unused_tables=table;
 
776
  }
 
777
}
 
778
 
 
779
 
653
780
/**
654
781
  Remove all instances of table from thread's open list and
655
782
  table cache.
656
783
 
657
784
  @param  session     Thread context
658
785
  @param  find    Table to remove
659
 
 
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.
661
786
*/
662
787
 
663
788
void Session::unlink_open_table(Table *find)
664
789
{
665
 
  const TableIdentifier::Key find_key(find->getShare()->getCacheKey());
666
 
  Table **prev;
667
 
  safe_mutex_assert_owner(table::Cache::singleton().mutex().native_handle());
668
 
 
 
790
  char key[MAX_DBKEY_LENGTH];
 
791
  uint32_t key_length= find->getShare()->getCacheKeySize();
 
792
  Table *list, **prev;
 
793
 
 
794
  safe_mutex_assert_owner(&LOCK_open);
 
795
 
 
796
  memcpy(key, find->getMutableShare()->getCacheKey(), key_length);
669
797
  /*
670
 
    Note that we need to hold table::Cache::singleton().mutex() while changing the
 
798
    Note that we need to hold LOCK_open while changing the
671
799
    open_tables list. Another thread may work on it.
672
 
    (See: table::Cache::singleton().removeTable(), mysql_wait_completed_table())
 
800
    (See: remove_table_from_cache(), mysql_wait_completed_table())
673
801
    Closing a MERGE child before the parent would be fatal if the
674
802
    other thread tries to abort the MERGE lock in between.
675
803
  */
676
804
  for (prev= &open_tables; *prev; )
677
805
  {
678
 
    Table *list= *prev;
 
806
    list= *prev;
679
807
 
680
 
    if (list->getShare()->getCacheKey() == find_key)
 
808
    if (list->getShare()->getCacheKeySize() == key_length &&
 
809
        not memcmp(list->getMutableShare()->getCacheKey(), key, key_length))
681
810
    {
682
811
      /* Remove table from open_tables list. */
683
 
      *prev= list->getNext();
 
812
      *prev= list->next;
684
813
 
685
814
      /* Close table. */
686
 
      table::remove_table(static_cast<table::Concurrent *>(list));
 
815
      hash_delete(&open_cache,(unsigned char*) list); // Close table
687
816
    }
688
817
    else
689
818
    {
690
819
      /* Step to next entry in open_tables list. */
691
 
      prev= list->getNextPtr();
 
820
      prev= &list->next;
692
821
    }
693
822
  }
694
823
 
695
824
  // Notify any 'refresh' threads
696
 
  locking::broadcast_refresh();
 
825
  broadcast_refresh();
697
826
}
698
827
 
699
828
 
716
845
  table that was locked with LOCK TABLES.
717
846
*/
718
847
 
719
 
void Session::drop_open_table(Table *table, const TableIdentifier &identifier)
 
848
void Session::drop_open_table(Table *table, TableIdentifier &identifier)
720
849
{
721
 
  if (table->getShare()->getType())
 
850
  if (table->getShare()->tmp_table)
722
851
  {
723
852
    close_temporary_table(table);
724
853
  }
725
854
  else
726
855
  {
727
 
    boost_unique_lock_t scoped_lock(table::Cache::singleton().mutex()); /* Close and drop a table (AUX routine) */
 
856
    pthread_mutex_lock(&LOCK_open); /* Close and drop a table (AUX routine) */
728
857
    /*
729
858
      unlink_open_table() also tells threads waiting for refresh or close
730
859
      that something has happened.
731
860
    */
732
861
    unlink_open_table(table);
733
 
    plugin::StorageEngine::dropTable(*this, identifier);
 
862
    quick_rm_table(*this, identifier);
 
863
    pthread_mutex_unlock(&LOCK_open);
734
864
  }
735
865
}
736
866
 
746
876
  cond  Condition to wait for
747
877
*/
748
878
 
749
 
void Session::wait_for_condition(boost::mutex &mutex, boost::condition_variable_any &cond)
 
879
void Session::wait_for_condition(pthread_mutex_t *mutex, pthread_cond_t *cond)
750
880
{
751
881
  /* Wait until the current table is up to date */
752
882
  const char *saved_proc_info;
753
 
  mysys_var->current_mutex= &mutex;
754
 
  mysys_var->current_cond= &cond;
 
883
  mysys_var->current_mutex= mutex;
 
884
  mysys_var->current_cond= cond;
755
885
  saved_proc_info= get_proc_info();
756
886
  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);
 
887
  if (!killed)
 
888
    (void) pthread_cond_wait(cond, mutex);
 
889
 
 
890
  /*
 
891
    We must unlock mutex first to avoid deadlock becasue conditions are
 
892
    sent to this thread by doing locks in the following order:
 
893
    lock(mysys_var->mutex)
 
894
    lock(mysys_var->current_mutex)
 
895
 
 
896
    One by effect of this that one can only use wait_for_condition with
 
897
    condition variables that are guranteed to not disapper (freed) even if this
 
898
    mutex is unlocked
 
899
  */
 
900
 
 
901
  pthread_mutex_unlock(mutex);
 
902
  pthread_mutex_lock(&mysys_var->mutex);
775
903
  mysys_var->current_mutex= 0;
776
904
  mysys_var->current_cond= 0;
777
905
  set_proc_info(saved_proc_info);
 
906
  pthread_mutex_unlock(&mysys_var->mutex);
 
907
}
 
908
 
 
909
 
 
910
/*
 
911
  Open table which is already name-locked by this thread.
 
912
 
 
913
  SYNOPSIS
 
914
  reopen_name_locked_table()
 
915
  session         Thread handle
 
916
  table_list  TableList object for table to be open, TableList::table
 
917
  member should point to Table object which was used for
 
918
  name-locking.
 
919
  link_in     true  - if Table object for table to be opened should be
 
920
  linked into Session::open_tables list.
 
921
  false - placeholder used for name-locking is already in
 
922
  this list so we only need to preserve Table::next
 
923
  pointer.
 
924
 
 
925
  NOTE
 
926
  This function assumes that its caller already acquired LOCK_open mutex.
 
927
 
 
928
  RETURN VALUE
 
929
  false - Success
 
930
  true  - Error
 
931
*/
 
932
 
 
933
bool Session::reopen_name_locked_table(TableList* table_list, bool link_in)
 
934
{
 
935
  Table *table= table_list->table;
 
936
  TableShare *share;
 
937
  char *table_name= table_list->table_name;
 
938
  Table orig_table;
 
939
 
 
940
  safe_mutex_assert_owner(&LOCK_open);
 
941
 
 
942
  if (killed || !table)
 
943
    return true;
 
944
 
 
945
  orig_table= *table;
 
946
 
 
947
  if (open_unireg_entry(this, table, table_name,
 
948
                        const_cast<char *>(table->getMutableShare()->getCacheKey()),
 
949
                        table->getShare()->getCacheKeySize()))
 
950
  {
 
951
    table->intern_close_table();
 
952
    /*
 
953
      If there was an error during opening of table (for example if it
 
954
      does not exist) '*table' object can be wiped out. To be able
 
955
      properly release name-lock in this case we should restore this
 
956
      object to its original state.
 
957
    */
 
958
    *table= orig_table;
 
959
    return true;
 
960
  }
 
961
 
 
962
  share= table->getMutableShare();
 
963
  /*
 
964
    We want to prevent other connections from opening this table until end
 
965
    of statement as it is likely that modifications of table's metadata are
 
966
    not yet finished (for example CREATE TRIGGER have to change .TRG cursor,
 
967
    or we might want to drop table if CREATE TABLE ... SELECT fails).
 
968
    This also allows us to assume that no other connection will sneak in
 
969
    before we will get table-level lock on this table.
 
970
  */
 
971
  share->version=0;
 
972
  table->in_use = this;
 
973
 
 
974
  if (link_in)
 
975
  {
 
976
    table->next= open_tables;
 
977
    open_tables= table;
 
978
  }
 
979
  else
 
980
  {
 
981
    /*
 
982
      Table object should be already in Session::open_tables list so we just
 
983
      need to set Table::next correctly.
 
984
    */
 
985
    table->next= orig_table.next;
 
986
  }
 
987
 
 
988
  table->tablenr= current_tablenr++;
 
989
  table->used_fields= 0;
 
990
  table->const_table= 0;
 
991
  table->null_row= false;
 
992
  table->maybe_null= false;
 
993
  table->force_index= false;
 
994
  table->status= STATUS_NO_RECORD;
 
995
 
 
996
  return false;
778
997
}
779
998
 
780
999
 
791
1010
  case of failure.
792
1011
*/
793
1012
 
794
 
table::Placeholder *Session::table_cache_insert_placeholder(const drizzled::TableIdentifier &arg)
 
1013
Table *Session::table_cache_insert_placeholder(const char *key, uint32_t key_length)
795
1014
{
796
 
  safe_mutex_assert_owner(table::Cache::singleton().mutex().native_handle());
 
1015
  safe_mutex_assert_owner(&LOCK_open);
797
1016
 
798
1017
  /*
799
1018
    Create a table entry with the right key and with an old refresh version
 
1019
    Note that we must use multi_malloc() here as this is freed by the
 
1020
    table cache
800
1021
  */
801
 
  TableIdentifier identifier(arg.getSchemaName(), arg.getTableName(), message::Table::INTERNAL);
802
 
  table::Placeholder *table= new table::Placeholder(this, identifier);
 
1022
  TablePlaceholder *table= new TablePlaceholder(key, key_length);
 
1023
  table->in_use= this;
803
1024
 
804
 
  if (not table::Cache::singleton().insert(table))
 
1025
  if (my_hash_insert(&open_cache, (unsigned char*)table))
805
1026
  {
806
1027
    delete table;
807
1028
 
833
1054
  @retval  true   Error occured (OOM)
834
1055
  @retval  false  Success. 'table' parameter set according to above rules.
835
1056
*/
836
 
bool Session::lock_table_name_if_not_cached(const TableIdentifier &identifier, Table **table)
837
 
{
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())
 
1057
bool Session::lock_table_name_if_not_cached(TableIdentifier &identifier, Table **table)
 
1058
{
 
1059
  return lock_table_name_if_not_cached(identifier.getSchemaName().c_str(), identifier.getTableName().c_str(), table);
 
1060
}
 
1061
 
 
1062
bool Session::lock_table_name_if_not_cached(const char *new_db,
 
1063
                                            const char *table_name, Table **table)
 
1064
{
 
1065
  char key[MAX_DBKEY_LENGTH];
 
1066
  char *key_pos= key;
 
1067
  uint32_t key_length;
 
1068
 
 
1069
  key_pos= strcpy(key_pos, new_db) + strlen(new_db);
 
1070
  key_pos= strcpy(key_pos+1, table_name) + strlen(table_name);
 
1071
  key_length= (uint32_t) (key_pos-key)+1;
 
1072
 
 
1073
  pthread_mutex_lock(&LOCK_open); /* Obtain a name lock even though table is not in cache (like for create table)  */
 
1074
 
 
1075
  if (hash_search(&open_cache, (unsigned char *)key, key_length))
847
1076
  {
 
1077
    pthread_mutex_unlock(&LOCK_open);
848
1078
    *table= 0;
849
1079
    return false;
850
1080
  }
851
1081
 
852
 
  if (not (*table= table_cache_insert_placeholder(identifier)))
 
1082
  if (not (*table= table_cache_insert_placeholder(key, key_length)))
853
1083
  {
 
1084
    pthread_mutex_unlock(&LOCK_open);
854
1085
    return true;
855
1086
  }
856
1087
  (*table)->open_placeholder= true;
857
 
  (*table)->setNext(open_tables);
 
1088
  (*table)->next= open_tables;
858
1089
  open_tables= *table;
 
1090
  pthread_mutex_unlock(&LOCK_open);
859
1091
 
860
1092
  return false;
861
1093
}
896
1128
Table *Session::openTable(TableList *table_list, bool *refresh, uint32_t flags)
897
1129
{
898
1130
  Table *table;
 
1131
  char key[MAX_DBKEY_LENGTH];
 
1132
  unsigned int key_length;
899
1133
  const char *alias= table_list->alias;
 
1134
  HASH_SEARCH_STATE state;
900
1135
 
901
1136
  /* Parsing of partitioning information from .frm needs session->lex set up. */
902
1137
  assert(lex->is_lex_started);
909
1144
  if (check_stack_overrun(this, STACK_MIN_SIZE_FOR_OPEN, (unsigned char *)&alias))
910
1145
    return NULL;
911
1146
 
912
 
  if (getKilled())
 
1147
  if (killed)
913
1148
    return NULL;
914
1149
 
915
 
  TableIdentifier identifier(table_list->getSchemaName(), table_list->getTableName());
916
 
  const TableIdentifier::Key &key(identifier.getKey());
917
 
  table::CacheRange ppp;
 
1150
  key_length= table_list->create_table_def_key(key);
918
1151
 
919
1152
  /*
920
1153
    Unless requested otherwise, try to resolve this table in the list
923
1156
    same name. This block implements the behaviour.
924
1157
    TODO -> move this block into a separate function.
925
1158
  */
926
 
  bool reset= false;
927
 
  for (table= getTemporaryTables(); table ; table=table->getNext())
 
1159
  for (table= temporary_tables; table ; table=table->next)
928
1160
  {
929
 
    if (table->getShare()->getCacheKey() == key)
 
1161
    if (table->getShare()->getCacheKeySize() == key_length && !memcmp(table->getMutableShare()->getCacheKey(), key, key_length))
930
1162
    {
931
1163
      /*
932
1164
        We're trying to use the same temporary table twice in a query.
936
1168
      */
937
1169
      if (table->query_id)
938
1170
      {
939
 
        my_error(ER_CANT_REOPEN_TABLE, MYF(0), table->getAlias());
 
1171
        my_error(ER_CANT_REOPEN_TABLE, MYF(0), table->alias);
940
1172
        return NULL;
941
1173
      }
942
1174
      table->query_id= getQueryId();
943
 
      reset= true;
944
 
      break;
945
 
    }
946
 
  }
947
 
 
948
 
  if (not reset)
949
 
  {
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
 
 
 
1175
      goto reset;
 
1176
    }
 
1177
  }
 
1178
 
 
1179
  if (flags & DRIZZLE_OPEN_TEMPORARY_ONLY)
 
1180
  {
 
1181
    my_error(ER_NO_SUCH_TABLE, MYF(0), table_list->db, table_list->table_name);
 
1182
    return NULL;
 
1183
  }
 
1184
 
 
1185
  /*
 
1186
    If it's the first table from a list of tables used in a query,
 
1187
    remember refresh_version (the version of open_cache state).
 
1188
    If the version changes while we're opening the remaining tables,
 
1189
    we will have to back off, close all the tables opened-so-far,
 
1190
    and try to reopen them.
 
1191
 
 
1192
    Note-> refresh_version is currently changed only during FLUSH TABLES.
 
1193
  */
 
1194
  if (!open_tables)
 
1195
  {
 
1196
    version= refresh_version;
 
1197
  }
 
1198
  else if ((version != refresh_version) &&
 
1199
           ! (flags & DRIZZLE_LOCK_IGNORE_FLUSH))
 
1200
  {
 
1201
    /* Someone did a refresh while thread was opening tables */
 
1202
    if (refresh)
 
1203
      *refresh= true;
 
1204
 
 
1205
    return NULL;
 
1206
  }
 
1207
 
 
1208
  /*
 
1209
    Before we test the global cache, we test our local session cache.
 
1210
  */
 
1211
  if (cached_table)
 
1212
  {
 
1213
    assert(false); /* Not implemented yet */
 
1214
  }
 
1215
 
 
1216
  /*
 
1217
    Non pre-locked/LOCK TABLES mode, and the table is not temporary:
 
1218
    this is the normal use case.
 
1219
    Now we should:
 
1220
    - try to find the table in the table cache.
 
1221
    - if one of the discovered Table instances is name-locked
 
1222
    (table->getShare()->version == 0) back off -- we have to wait
 
1223
    until no one holds a name lock on the table.
 
1224
    - if there is no such Table in the name cache, read the table definition
 
1225
    and insert it into the cache.
 
1226
    We perform all of the above under LOCK_open which currently protects
 
1227
    the open cache (also known as table cache) and table definitions stored
 
1228
    on disk.
 
1229
  */
 
1230
 
 
1231
  pthread_mutex_lock(&LOCK_open); /* Lock for FLUSH TABLES for open table */
 
1232
 
 
1233
  /*
 
1234
    Actually try to find the table in the open_cache.
 
1235
    The cache may contain several "Table" instances for the same
 
1236
    physical table. The instances that are currently "in use" by
 
1237
    some thread have their "in_use" member != NULL.
 
1238
    There is no good reason for having more than one entry in the
 
1239
    hash for the same physical table, except that we use this as
 
1240
    an implicit "pending locks queue" - see
 
1241
    wait_for_locked_table_names for details.
 
1242
  */
 
1243
  for (table= (Table*) hash_first(&open_cache, (unsigned char*) key, key_length,
 
1244
                                  &state);
 
1245
       table && table->in_use ;
 
1246
       table= (Table*) hash_next(&open_cache, (unsigned char*) key, key_length,
 
1247
                                 &state))
 
1248
  {
956
1249
    /*
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.
 
1250
      Here we flush tables marked for flush.
 
1251
      Normally, table->getShare()->version contains the value of
 
1252
      refresh_version from the moment when this table was
 
1253
      (re-)opened and added to the cache.
 
1254
      If since then we did (or just started) FLUSH TABLES
 
1255
      statement, refresh_version has been increased.
 
1256
      For "name-locked" Table instances, table->getShare()->version is set
 
1257
      to 0 (see lock_table_name for details).
 
1258
      In case there is a pending FLUSH TABLES or a name lock, we
 
1259
      need to back off and re-start opening tables.
 
1260
      If we do not back off now, we may dead lock in case of lock
 
1261
      order mismatch with some other thread:
 
1262
c1: name lock t1; -- sort of exclusive lock
 
1263
c2: open t2;      -- sort of shared lock
 
1264
c1: name lock t2; -- blocks
 
1265
c2: open t1; -- blocks
964
1266
    */
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 */
 
1267
    if (table->needs_reopen_or_name_lock())
 
1268
    {
 
1269
      if (flags & DRIZZLE_LOCK_IGNORE_FLUSH)
 
1270
      {
 
1271
        /* Force close at once after usage */
 
1272
        version= table->getShare()->version;
 
1273
        continue;
 
1274
      }
 
1275
 
 
1276
      /* Avoid self-deadlocks by detecting self-dependencies. */
 
1277
      if (table->open_placeholder && table->in_use == this)
 
1278
      {
 
1279
        pthread_mutex_unlock(&LOCK_open);
 
1280
        my_error(ER_UPDATE_TABLE_USED, MYF(0), table->getMutableShare()->getTableName());
 
1281
        return NULL;
 
1282
      }
 
1283
 
 
1284
      /*
 
1285
        Back off, part 1: mark the table as "unused" for the
 
1286
        purpose of name-locking by setting table->db_stat to 0. Do
 
1287
        that only for the tables in this thread that have an old
 
1288
        table->getShare()->version (this is an optimization (?)).
 
1289
        table->db_stat == 0 signals wait_for_locked_table_names
 
1290
        that the tables in question are not used any more. See
 
1291
        table_is_used call for details.
 
1292
      */
 
1293
      close_old_data_files(false, false);
 
1294
 
 
1295
      /*
 
1296
        Back-off part 2: try to avoid "busy waiting" on the table:
 
1297
        if the table is in use by some other thread, we suspend
 
1298
        and wait till the operation is complete: when any
 
1299
        operation that juggles with table->getShare()->version completes,
 
1300
        it broadcasts COND_refresh condition variable.
 
1301
        If 'old' table we met is in use by current thread we return
 
1302
        without waiting since in this situation it's this thread
 
1303
        which is responsible for broadcasting on COND_refresh
 
1304
        (and this was done already in Session::close_old_data_files()).
 
1305
        Good example of such situation is when we have statement
 
1306
        that needs two instances of table and FLUSH TABLES comes
 
1307
        after we open first instance but before we open second
 
1308
        instance.
 
1309
      */
 
1310
      if (table->in_use != this)
 
1311
      {
 
1312
        /* wait_for_conditionwill unlock LOCK_open for us */
 
1313
        wait_for_condition(&LOCK_open, &COND_refresh);
 
1314
      }
 
1315
      else
 
1316
      {
 
1317
        pthread_mutex_unlock(&LOCK_open);
 
1318
      }
 
1319
      /*
 
1320
        There is a refresh in progress for this table.
 
1321
        Signal the caller that it has to try again.
 
1322
      */
973
1323
      if (refresh)
974
1324
        *refresh= true;
975
 
 
976
1325
      return NULL;
977
1326
    }
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 */
 
1327
  }
 
1328
  if (table)
 
1329
  {
 
1330
    /* Unlink the table from "unused_tables" list. */
 
1331
    if (table == unused_tables)
 
1332
    {  // First unused
 
1333
      unused_tables=unused_tables->next; // Remove from link
 
1334
      if (table == unused_tables)
 
1335
        unused_tables= NULL;
985
1336
    }
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
 
 
 
1337
    table->prev->next=table->next; /* Remove from unused list */
 
1338
    table->next->prev=table->prev;
 
1339
    table->in_use= this;
 
1340
  }
 
1341
  else
 
1342
  {
 
1343
    /* Insert a new Table instance into the open cache */
 
1344
    int error;
 
1345
    /* Free cache if too big */
 
1346
    while (open_cache.records > table_cache_size && unused_tables)
 
1347
      hash_delete(&open_cache,(unsigned char*) unused_tables);
 
1348
 
 
1349
    if (table_list->create)
1002
1350
    {
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)
 
1351
      TableIdentifier  lock_table_identifier(table_list->db, table_list->table_name, message::Table::STANDARD);
 
1352
 
 
1353
      if (not plugin::StorageEngine::doesTableExist(*this, lock_table_identifier))
1020
1354
      {
1021
 
        table= (*iter).second;
1022
 
 
1023
 
        if (not table->in_use)
1024
 
          break;
1025
1355
        /*
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
 
1356
          Table to be created, so we need to create placeholder in table-cache.
1042
1357
        */
1043
 
        if (table->needs_reopen_or_name_lock())
 
1358
        if (!(table= table_cache_insert_placeholder(key, key_length)))
1044
1359
        {
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;
 
1360
          pthread_mutex_unlock(&LOCK_open);
1101
1361
          return NULL;
1102
1362
        }
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)))
1126
 
            {
1127
 
              table::Cache::singleton().mutex().unlock();
1128
 
              return NULL;
1129
 
            }
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);
1163
 
        }
1164
 
      }
1165
 
 
1166
 
      table::Cache::singleton().mutex().unlock();
1167
 
    }
1168
 
    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
 
 
 
1363
        /*
 
1364
          Link placeholder to the open tables list so it will be automatically
 
1365
          removed once tables are closed. Also mark it so it won't be ignored
 
1366
          by other trying to take name-lock.
 
1367
        */
 
1368
        table->open_placeholder= true;
 
1369
        table->next= open_tables;
 
1370
        open_tables= table;
 
1371
        pthread_mutex_unlock(&LOCK_open);
 
1372
 
 
1373
        return table ;
 
1374
      }
 
1375
      /* Table exists. Let us try to open it. */
 
1376
    }
 
1377
 
 
1378
    /* make a new table */
 
1379
    table= (Table *)malloc(sizeof(Table));
 
1380
    memset(table, 0, sizeof(Table));
 
1381
    if (table == NULL)
 
1382
    {
 
1383
      pthread_mutex_unlock(&LOCK_open);
 
1384
      return NULL;
 
1385
    }
 
1386
 
 
1387
    error= open_unireg_entry(this, table, alias, key, key_length);
 
1388
    if (error != 0)
 
1389
    {
 
1390
      free(table);
 
1391
      pthread_mutex_unlock(&LOCK_open);
 
1392
      return NULL;
 
1393
    }
 
1394
    my_hash_insert(&open_cache, (unsigned char*) table);
 
1395
  }
 
1396
 
 
1397
  pthread_mutex_unlock(&LOCK_open);
 
1398
  if (refresh)
 
1399
  {
 
1400
    table->next= open_tables; /* Link into simple list */
 
1401
    open_tables= table;
 
1402
  }
 
1403
  table->reginfo.lock_type= TL_READ; /* Assume read */
 
1404
 
 
1405
reset:
 
1406
  assert(table->getShare()->ref_count > 0 || table->getShare()->tmp_table != message::Table::STANDARD);
 
1407
 
 
1408
  if (lex->need_correct_ident())
 
1409
    table->alias_name_used= my_strcasecmp(table_alias_charset,
 
1410
                                          table->getMutableShare()->getTableName(), alias);
1178
1411
  /* Fix alias if table name changes */
1179
 
  if (strcmp(table->getAlias(), alias))
 
1412
  if (strcmp(table->alias, alias))
1180
1413
  {
1181
 
    table->setAlias(alias);
 
1414
    uint32_t length=(uint32_t) strlen(alias)+1;
 
1415
    table->alias= (char*) realloc((char*) table->alias, length);
 
1416
    memcpy((void*) table->alias, alias, length);
1182
1417
  }
1183
1418
 
1184
1419
  /* These variables are also set in reopen_table() */
1189
1424
  table->maybe_null= false;
1190
1425
  table->force_index= false;
1191
1426
  table->status=STATUS_NO_RECORD;
1192
 
  table->insert_values.clear();
 
1427
  table->insert_values= 0;
1193
1428
  /* Catch wrong handling of the auto_increment_field_not_null. */
1194
1429
  assert(!table->auto_increment_field_not_null);
1195
1430
  table->auto_increment_field_not_null= false;
1196
1431
  if (table->timestamp_field)
1197
 
  {
1198
1432
    table->timestamp_field_type= table->timestamp_field->get_auto_set_type();
1199
 
  }
1200
1433
  table->pos_in_table_list= table_list;
1201
1434
  table->clear_column_bitmaps();
1202
1435
  assert(table->key_read == 0);
1205
1438
}
1206
1439
 
1207
1440
 
 
1441
#if 0
 
1442
/*
 
1443
  Reopen an table because the definition has changed.
 
1444
 
 
1445
  SYNOPSIS
 
1446
  reopen_table()
 
1447
  table Table object
 
1448
 
 
1449
  NOTES
 
1450
  The data cursor for the table is already closed and the share is released
 
1451
  The table has a 'dummy' share that mainly contains database and table name.
 
1452
 
 
1453
  RETURN
 
1454
  0  ok
 
1455
  1  error. The old table object is not changed.
 
1456
*/
 
1457
 
 
1458
bool reopen_table(Table *table)
 
1459
{
 
1460
  Table tmp;
 
1461
  bool error= 1;
 
1462
  Field **field;
 
1463
  uint32_t key,part;
 
1464
  TableList table_list;
 
1465
  Session *session= table->in_use;
 
1466
 
 
1467
  assert(table->getShare()->ref_count == 0);
 
1468
  assert(!table->sort.io_cache);
 
1469
 
 
1470
#ifdef EXTRA_DEBUG
 
1471
  if (table->db_stat)
 
1472
    errmsg_printf(ERRMSG_LVL_ERROR, _("Table %s had a open data Cursor in reopen_table"),
 
1473
                  table->alias);
 
1474
#endif
 
1475
  table_list.db=         const_cast<char *>(table->getShare()->getSchemaName());
 
1476
  table_list.table_name= table->getShare()->getTableName();
 
1477
  table_list.table=      table;
 
1478
 
 
1479
  if (wait_for_locked_table_names(session, &table_list))
 
1480
    return true;                             // Thread was killed
 
1481
 
 
1482
  if (open_unireg_entry(session, &tmp, &table_list,
 
1483
                        table->alias,
 
1484
                        table->getShare()->getCacheKey(),
 
1485
                        table->getShare()->getCacheKeySize()))
 
1486
    goto end;
 
1487
 
 
1488
  /* This list copies variables set by open_table */
 
1489
  tmp.tablenr=          table->tablenr;
 
1490
  tmp.used_fields=      table->used_fields;
 
1491
  tmp.const_table=      table->const_table;
 
1492
  tmp.null_row=         table->null_row;
 
1493
  tmp.maybe_null=       table->maybe_null;
 
1494
  tmp.status=           table->status;
 
1495
 
 
1496
  /* Get state */
 
1497
  tmp.in_use=           session;
 
1498
  tmp.reginfo.lock_type=table->reginfo.lock_type;
 
1499
 
 
1500
  /* Replace table in open list */
 
1501
  tmp.next=             table->next;
 
1502
  tmp.prev=             table->prev;
 
1503
 
 
1504
  if (table->cursor)
 
1505
    table->delete_table(true);          // close cursor, free everything
 
1506
 
 
1507
  *table= tmp;
 
1508
  table->default_column_bitmaps();
 
1509
  table->cursor->change_table_ptr(table, table->s);
 
1510
 
 
1511
  assert(table->alias != 0);
 
1512
  for (field=table->field ; *field ; field++)
 
1513
  {
 
1514
    (*field)->table= (*field)->orig_table= table;
 
1515
    (*field)->table_name= &table->alias;
 
1516
  }
 
1517
  for (key=0 ; key < table->getShare()->keys ; key++)
 
1518
  {
 
1519
    for (part=0 ; part < table->key_info[key].usable_key_parts ; part++)
 
1520
      table->key_info[key].key_part[part].field->table= table;
 
1521
  }
 
1522
 
 
1523
  broadcast_refresh();
 
1524
  error= false;
 
1525
 
 
1526
end:
 
1527
  return(error);
 
1528
}
 
1529
#endif
 
1530
 
 
1531
 
1208
1532
/**
1209
1533
  Close all instances of a table open by this thread and replace
1210
1534
  them with exclusive name-locks.
1222
1546
  the strings are used in a loop even after the share may be freed.
1223
1547
*/
1224
1548
 
1225
 
void Session::close_data_files_and_morph_locks(const TableIdentifier &identifier)
 
1549
void Session::close_data_files_and_morph_locks(TableIdentifier &identifier)
1226
1550
{
1227
 
  safe_mutex_assert_owner(table::Cache::singleton().mutex().native_handle()); /* Adjust locks at the end of ALTER TABLEL */
 
1551
  Table *table;
 
1552
 
 
1553
  safe_mutex_assert_owner(&LOCK_open); /* Adjust locks at the end of ALTER TABLEL */
1228
1554
 
1229
1555
  if (lock)
1230
1556
  {
1232
1558
      If we are not under LOCK TABLES we should have only one table
1233
1559
      open and locked so it makes sense to remove the lock at once.
1234
1560
    */
1235
 
    unlockTables(lock);
 
1561
    mysql_unlock_tables(this, lock);
1236
1562
    lock= 0;
1237
1563
  }
1238
1564
 
1241
1567
    for target table name if we process ALTER Table ... RENAME.
1242
1568
    So loop below makes sense even if we are not under LOCK TABLES.
1243
1569
  */
1244
 
  for (Table *table= open_tables; table ; table=table->getNext())
 
1570
  for (table= open_tables; table ; table=table->next)
1245
1571
  {
1246
 
    if (table->getShare()->getCacheKey() == identifier.getKey())
 
1572
    if (!strcmp(table->getMutableShare()->getTableName(), identifier.getTableName().c_str()) &&
 
1573
        !strcasecmp(table->getMutableShare()->getSchemaName(), identifier.getSchemaName().c_str()))
1247
1574
    {
1248
1575
      table->open_placeholder= true;
1249
1576
      close_handle_and_leave_table_as_lock(table);
1267
1594
  combination when one needs tables to be reopened (for
1268
1595
  example see openTablesLock()).
1269
1596
 
1270
 
  @note One should have lock on table::Cache::singleton().mutex() when calling this.
 
1597
  @note One should have lock on LOCK_open when calling this.
1271
1598
 
1272
1599
  @return false in case of success, true - otherwise.
1273
1600
*/
1284
1611
  if (open_tables == NULL)
1285
1612
    return false;
1286
1613
 
1287
 
  safe_mutex_assert_owner(table::Cache::singleton().mutex().native_handle());
 
1614
  safe_mutex_assert_owner(&LOCK_open);
1288
1615
  if (get_locks)
1289
1616
  {
1290
1617
    /*
1293
1620
    */
1294
1621
    uint32_t opens= 0;
1295
1622
 
1296
 
    for (table= open_tables; table ; table=table->getNext())
 
1623
    for (table= open_tables; table ; table=table->next)
1297
1624
    {
1298
1625
      opens++;
1299
1626
    }
1308
1635
  prev= &open_tables;
1309
1636
  for (table= open_tables; table ; table=next)
1310
1637
  {
1311
 
    next= table->getNext();
 
1638
    next= table->next;
1312
1639
 
1313
 
    my_error(ER_CANT_REOPEN_TABLE, MYF(0), table->getAlias());
1314
 
    table::remove_table(static_cast<table::Concurrent *>(table));
 
1640
    my_error(ER_CANT_REOPEN_TABLE, MYF(0), table->alias);
 
1641
    hash_delete(&open_cache,(unsigned char*) table);
1315
1642
    error= 1;
1316
1643
  }
1317
1644
  *prev=0;
1318
1645
  if (tables != tables_ptr)                     // Should we get back old locks
1319
1646
  {
1320
 
    DrizzleLock *local_lock;
 
1647
    DRIZZLE_LOCK *local_lock;
1321
1648
    /*
1322
1649
      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
 
1650
      wait_for_tables() as it tries to acquire LOCK_open, which is
1324
1651
      already locked.
1325
1652
    */
1326
1653
    some_tables_deleted= false;
1327
1654
 
1328
 
    if ((local_lock= lockTables(tables, (uint32_t) (tables_ptr - tables),
1329
 
                                       flags, &not_used)))
 
1655
    if ((local_lock= mysql_lock_tables(this, tables, (uint32_t) (tables_ptr - tables),
 
1656
                                 flags, &not_used)))
1330
1657
    {
1331
1658
      /* unused */
1332
1659
    }
1345
1672
  if (get_locks && tables)
1346
1673
    delete [] tables;
1347
1674
 
1348
 
  locking::broadcast_refresh();
 
1675
  broadcast_refresh();
1349
1676
 
1350
1677
  return(error);
1351
1678
}
1371
1698
 
1372
1699
  Table *table= open_tables;
1373
1700
 
1374
 
  for (; table ; table=table->getNext())
 
1701
  for (; table ; table=table->next)
1375
1702
  {
1376
1703
    /*
1377
1704
      Reopen marked for flush.
1392
1719
              lock on it. This will also give them a chance to close their
1393
1720
              instances of this table.
1394
1721
            */
1395
 
            abortLock(ulcktbl);
1396
 
            removeLock(ulcktbl);
 
1722
            mysql_lock_abort(this, ulcktbl);
 
1723
            mysql_lock_remove(this, ulcktbl);
1397
1724
            ulcktbl->lock_count= 0;
1398
1725
          }
1399
1726
          if ((ulcktbl != table) && ulcktbl->db_stat)
1433
1760
    }
1434
1761
  }
1435
1762
  if (found)
1436
 
    locking::broadcast_refresh();
 
1763
    broadcast_refresh();
 
1764
}
 
1765
 
 
1766
 
 
1767
/*
 
1768
  Wait until all threads has closed the tables in the list
 
1769
  We have also to wait if there is thread that has a lock on this table even
 
1770
  if the table is closed
 
1771
*/
 
1772
 
 
1773
bool table_is_used(Table *table, bool wait_for_name_lock)
 
1774
{
 
1775
  do
 
1776
  {
 
1777
    char *key= const_cast<char *>(table->getMutableShare()->getCacheKey());
 
1778
    uint32_t key_length= table->getShare()->getCacheKeySize();
 
1779
 
 
1780
    HASH_SEARCH_STATE state;
 
1781
    for (Table *search= (Table*) hash_first(&open_cache, (unsigned char*) key,
 
1782
                                            key_length, &state);
 
1783
         search ;
 
1784
         search= (Table*) hash_next(&open_cache, (unsigned char*) key,
 
1785
                                    key_length, &state))
 
1786
    {
 
1787
      if (search->in_use == table->in_use)
 
1788
        continue;                               // Name locked by this thread
 
1789
      /*
 
1790
        We can't use the table under any of the following conditions:
 
1791
        - There is an name lock on it (Table is to be deleted or altered)
 
1792
        - If we are in flush table and we didn't execute the flush
 
1793
        - If the table engine is open and it's an old version
 
1794
        (We must wait until all engines are shut down to use the table)
 
1795
      */
 
1796
      if ( (search->locked_by_name && wait_for_name_lock) ||
 
1797
           (search->is_name_opened() && search->needs_reopen_or_name_lock()))
 
1798
        return 1;
 
1799
    }
 
1800
  } while ((table=table->next));
 
1801
  return 0;
1437
1802
}
1438
1803
 
1439
1804
 
1444
1809
  bool result;
1445
1810
 
1446
1811
  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
 
  }
 
1812
  pthread_mutex_lock(&LOCK_open); /* Lock for all tables to be refreshed */
 
1813
  while (!session->killed)
 
1814
  {
 
1815
    session->some_tables_deleted= false;
 
1816
    session->close_old_data_files(false, dropping_tables != 0);
 
1817
    if (!table_is_used(session->open_tables, 1))
 
1818
      break;
 
1819
    (void) pthread_cond_wait(&COND_refresh,&LOCK_open);
 
1820
  }
 
1821
  if (session->killed)
 
1822
    result= true;                                       // aborted
 
1823
  else
 
1824
  {
 
1825
    /* Now we can open all tables without any interference */
 
1826
    session->set_proc_info("Reopen tables");
 
1827
    session->version= refresh_version;
 
1828
    result= session->reopen_tables(false, false);
 
1829
  }
 
1830
  pthread_mutex_unlock(&LOCK_open);
1469
1831
  session->set_proc_info(0);
1470
1832
 
1471
1833
  return result;
1496
1858
*/
1497
1859
 
1498
1860
 
1499
 
Table *drop_locked_tables(Session *session, const drizzled::TableIdentifier &identifier)
 
1861
Table *drop_locked_tables(Session *session,const char *db, const char *table_name)
1500
1862
{
1501
1863
  Table *table,*next,**prev, *found= 0;
1502
1864
  prev= &session->open_tables;
1503
1865
 
1504
1866
  /*
1505
 
    Note that we need to hold table::Cache::singleton().mutex() while changing the
 
1867
    Note that we need to hold LOCK_open while changing the
1506
1868
    open_tables list. Another thread may work on it.
1507
 
    (See: table::Cache::singleton().removeTable(), mysql_wait_completed_table())
 
1869
    (See: remove_table_from_cache(), mysql_wait_completed_table())
1508
1870
    Closing a MERGE child before the parent would be fatal if the
1509
1871
    other thread tries to abort the MERGE lock in between.
1510
1872
  */
1511
1873
  for (table= session->open_tables; table ; table=next)
1512
1874
  {
1513
 
    next=table->getNext();
1514
 
    if (table->getShare()->getCacheKey() == identifier.getKey())
 
1875
    next=table->next;
 
1876
    if (!strcmp(table->getMutableShare()->getTableName(), table_name) &&
 
1877
        !strcasecmp(table->getMutableShare()->getSchemaName(), db))
1515
1878
    {
1516
 
      session->removeLock(table);
 
1879
      mysql_lock_remove(session, table);
1517
1880
 
1518
1881
      if (!found)
1519
1882
      {
1528
1891
      else
1529
1892
      {
1530
1893
        /* We already have a name lock, remove copy */
1531
 
        table::remove_table(static_cast<table::Concurrent *>(table));
 
1894
        hash_delete(&open_cache,(unsigned char*) table);
1532
1895
      }
1533
1896
    }
1534
1897
    else
1535
1898
    {
1536
1899
      *prev=table;
1537
 
      prev= table->getNextPtr();
 
1900
      prev= &table->next;
1538
1901
    }
1539
1902
  }
1540
1903
  *prev=0;
1541
1904
  if (found)
1542
 
    locking::broadcast_refresh();
 
1905
    broadcast_refresh();
1543
1906
 
1544
1907
  return(found);
1545
1908
}
1551
1914
  other threads trying to get the lock.
1552
1915
*/
1553
1916
 
1554
 
void abort_locked_tables(Session *session, const drizzled::TableIdentifier &identifier)
 
1917
void abort_locked_tables(Session *session,const char *db, const char *table_name)
1555
1918
{
1556
1919
  Table *table;
1557
 
  for (table= session->open_tables; table ; table= table->getNext())
 
1920
  for (table= session->open_tables; table ; table= table->next)
1558
1921
  {
1559
 
    if (table->getShare()->getCacheKey() == identifier.getKey())
 
1922
    if (!strcmp(table->getMutableShare()->getTableName(), table_name) &&
 
1923
        !strcmp(table->getMutableShare()->getSchemaName(), db))
1560
1924
    {
1561
1925
      /* If MERGE child, forward lock handling to parent. */
1562
 
      session->abortLock(table);
 
1926
      mysql_lock_abort(session, table);
1563
1927
      break;
1564
1928
    }
1565
1929
  }
1566
1930
}
1567
1931
 
 
1932
/*
 
1933
  Load a table definition from cursor and open unireg table
 
1934
 
 
1935
  SYNOPSIS
 
1936
  open_unireg_entry()
 
1937
  session                       Thread handle
 
1938
  entry         Store open table definition here
 
1939
  table_list            TableList with db, table_name
 
1940
  alias         Alias name
 
1941
  cache_key             Key for share_cache
 
1942
  cache_key_length      length of cache_key
 
1943
 
 
1944
  NOTES
 
1945
  Extra argument for open is taken from session->open_options
 
1946
  One must have a lock on LOCK_open when calling this function
 
1947
 
 
1948
  RETURN
 
1949
  0     ok
 
1950
#       Error
 
1951
*/
 
1952
 
 
1953
static int open_unireg_entry(Session *session,
 
1954
                             Table *entry,
 
1955
                             const char *alias,
 
1956
                             char *cache_key, uint32_t cache_key_length)
 
1957
{
 
1958
  int error;
 
1959
  TableShare *share;
 
1960
  uint32_t discover_retry_count= 0;
 
1961
 
 
1962
  safe_mutex_assert_owner(&LOCK_open);
 
1963
retry:
 
1964
  if (not (share= TableShare::getShare(session, cache_key,
 
1965
                                       cache_key_length,
 
1966
                                       &error)))
 
1967
    return 1;
 
1968
 
 
1969
  while ((error= share->open_table_from_share(session, alias,
 
1970
                                              (uint32_t) (HA_OPEN_KEYFILE |
 
1971
                                                          HA_OPEN_RNDFILE |
 
1972
                                                          HA_GET_INDEX |
 
1973
                                                          HA_TRY_READ_ONLY),
 
1974
                                              session->open_options, *entry)))
 
1975
  {
 
1976
    if (error == 7)                             // Table def changed
 
1977
    {
 
1978
      share->version= 0;                        // Mark share as old
 
1979
      if (discover_retry_count++)               // Retry once
 
1980
        goto err;
 
1981
 
 
1982
      /*
 
1983
        TODO->
 
1984
        Here we should wait until all threads has released the table.
 
1985
        For now we do one retry. This may cause a deadlock if there
 
1986
        is other threads waiting for other tables used by this thread.
 
1987
 
 
1988
        Proper fix would be to if the second retry failed:
 
1989
        - Mark that table def changed
 
1990
        - Return from open table
 
1991
        - Close all tables used by this thread
 
1992
        - Start waiting that the share is released
 
1993
        - Retry by opening all tables again
 
1994
      */
 
1995
 
 
1996
      /*
 
1997
        TO BE FIXED
 
1998
        To avoid deadlock, only wait for release if no one else is
 
1999
        using the share.
 
2000
      */
 
2001
      if (share->ref_count != 1)
 
2002
        goto err;
 
2003
      /* Free share and wait until it's released by all threads */
 
2004
      TableShare::release(share);
 
2005
 
 
2006
      if (!session->killed)
 
2007
      {
 
2008
        drizzle_reset_errors(session, 1);         // Clear warnings
 
2009
        session->clear_error();                 // Clear error message
 
2010
        goto retry;
 
2011
      }
 
2012
      return 1;
 
2013
    }
 
2014
 
 
2015
    goto err;
 
2016
  }
 
2017
 
 
2018
  return 0;
 
2019
 
 
2020
err:
 
2021
  TableShare::release(share);
 
2022
 
 
2023
  return 1;
 
2024
}
 
2025
 
1568
2026
 
1569
2027
/*
1570
2028
  Open all tables in list
1632
2090
     * to see if it exists so that an unauthorized user cannot phish for
1633
2091
     * table/schema information via error messages
1634
2092
     */
1635
 
    TableIdentifier the_table(tables->getSchemaName(), tables->getTableName());
 
2093
    TableIdentifier the_table(tables->db, tables->table_name);
1636
2094
    if (not plugin::Authorization::isAuthorized(getSecurityContext(),
1637
2095
                                                the_table))
1638
2096
    {
1680
2138
    {
1681
2139
      if (tables->lock_type == TL_WRITE_DEFAULT)
1682
2140
        tables->table->reginfo.lock_type= update_lock_default;
1683
 
      else if (tables->table->getShare()->getType() == message::Table::STANDARD)
 
2141
      else if (tables->table->getShare()->tmp_table == message::Table::STANDARD)
1684
2142
        tables->table->reginfo.lock_type= tables->lock_type;
1685
2143
    }
1686
2144
  }
1742
2200
 
1743
2201
    assert(lock == 0);  // You must lock everything at once
1744
2202
    if ((table->reginfo.lock_type= lock_type) != TL_UNLOCK)
1745
 
      if (! (lock= lockTables(&table_list->table, 1, 0, &refresh)))
 
2203
      if (! (lock= mysql_lock_tables(this, &table_list->table, 1, 0, &refresh)))
1746
2204
        table= 0;
1747
2205
  }
1748
2206
 
1805
2263
      *(ptr++)= table->table;
1806
2264
  }
1807
2265
 
1808
 
  if (!(session->lock= session->lockTables(start, (uint32_t) (ptr - start), lock_flag, need_reopen)))
 
2266
  if (!(session->lock= mysql_lock_tables(session, start, (uint32_t) (ptr - start),
 
2267
                                         lock_flag, need_reopen)))
1809
2268
  {
1810
2269
    return -1;
1811
2270
  }
1834
2293
#  Table object
1835
2294
*/
1836
2295
 
1837
 
Table *Open_tables_state::open_temporary_table(const TableIdentifier &identifier,
1838
 
                                               bool link_in_list)
 
2296
Table *Session::open_temporary_table(TableIdentifier &identifier,
 
2297
                                     bool link_in_list)
1839
2298
{
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)
 
2299
  Table *new_tmp_table;
 
2300
  TableShare *share;
 
2301
  char cache_key[MAX_DBKEY_LENGTH];
 
2302
  uint32_t key_length;
 
2303
 
 
2304
  /* Create the cache_key for temporary tables */
 
2305
  key_length= TableShare::createKey(cache_key, const_cast<char*>(identifier.getSchemaName().c_str()),
 
2306
                                    const_cast<char*>(identifier.getTableName().c_str()));
 
2307
 
 
2308
  share= new TableShare(cache_key, key_length,
 
2309
                        const_cast<char *>(identifier.getPath().c_str()), static_cast<uint32_t>(identifier.getPath().length()));
 
2310
 
 
2311
  if (!(new_tmp_table= (Table*) malloc(sizeof(*new_tmp_table))))
1848
2312
    return NULL;
1849
2313
 
 
2314
  memset(new_tmp_table, 0, sizeof(*new_tmp_table));
 
2315
 
 
2316
 
1850
2317
  /*
1851
2318
    First open the share, and then open the table from the share we just opened.
1852
2319
  */
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))
 
2320
  if (share->open_table_def(*this, identifier) ||
 
2321
      share->open_table_from_share(this, identifier.getTableName().c_str(),
 
2322
                            (uint32_t) (HA_OPEN_KEYFILE | HA_OPEN_RNDFILE |
 
2323
                                        HA_GET_INDEX),
 
2324
                            ha_open_options,
 
2325
                            *new_tmp_table))
1859
2326
  {
1860
2327
    /* 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;
 
2328
    delete share;
 
2329
    free((char*) new_tmp_table);
1863
2330
 
1864
2331
    return 0;
1865
2332
  }
1866
2333
 
1867
2334
  new_tmp_table->reginfo.lock_type= TL_WRITE;    // Simulate locked
 
2335
  share->tmp_table= message::Table::TEMPORARY;
1868
2336
 
1869
2337
  if (link_in_list)
1870
2338
  {
1871
2339
    /* 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
 
    }
 
2340
    new_tmp_table->next= this->temporary_tables;
 
2341
    if (new_tmp_table->next)
 
2342
      new_tmp_table->next->prev= new_tmp_table;
1877
2343
    this->temporary_tables= new_tmp_table;
1878
 
    this->temporary_tables->setPrev(0);
 
2344
    this->temporary_tables->prev= 0;
1879
2345
  }
1880
2346
  new_tmp_table->pos_in_table_list= 0;
1881
2347
 
1900
2366
{
1901
2367
  if (session->mark_used_columns != MARK_COLUMNS_NONE)
1902
2368
  {
1903
 
    boost::dynamic_bitset<> *current_bitmap= NULL;
 
2369
    MyBitmap *current_bitmap, *other_bitmap;
1904
2370
 
1905
2371
    /*
1906
2372
      We always want to register the used keys, as the column bitmap may have
1913
2379
    if (session->mark_used_columns == MARK_COLUMNS_READ)
1914
2380
    {
1915
2381
      current_bitmap= table->read_set;
 
2382
      other_bitmap=   table->write_set;
1916
2383
    }
1917
2384
    else
1918
2385
    {
1919
2386
      current_bitmap= table->write_set;
 
2387
      other_bitmap=   table->read_set;
1920
2388
    }
1921
2389
 
1922
 
    //if (current_bitmap->testAndSet(field->position()))
1923
 
    if (current_bitmap->test(field->position()))
 
2390
    if (current_bitmap->testAndSet(field->field_index))
1924
2391
    {
1925
2392
      if (session->mark_used_columns == MARK_COLUMNS_WRITE)
1926
2393
        session->dup_field= field;
1989
2456
    return NULL;
1990
2457
  {
1991
2458
    /* This is a base table. */
1992
 
    assert(nj_col->table_ref->table == nj_col->table_field->getTable());
 
2459
    assert(nj_col->table_ref->table == nj_col->table_field->table);
1993
2460
    found_field= nj_col->table_field;
1994
2461
    update_field_dependencies(session, found_field, nj_col->table_ref->table);
1995
2462
  }
2026
2493
  uint32_t cached_field_index= *cached_field_index_ptr;
2027
2494
 
2028
2495
  /* We assume here that table->field < NO_CACHED_FIELD_INDEX = UINT_MAX */
2029
 
  if (cached_field_index < table->getShare()->sizeFields() &&
 
2496
  if (cached_field_index < table->getShare()->fields &&
2030
2497
      !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));
 
2498
                     table->field[cached_field_index]->field_name, name))
 
2499
    field_ptr= table->field + cached_field_index;
 
2500
  else if (table->getShare()->name_hash.records)
 
2501
  {
 
2502
    field_ptr= (Field**) hash_search(&table->getShare()->name_hash, (unsigned char*) name,
 
2503
                                     length);
2038
2504
    if (field_ptr)
2039
2505
    {
2040
2506
      /*
2041
2507
        field_ptr points to field in TableShare. Convert it to the matching
2042
2508
        field in table
2043
2509
      */
2044
 
      field_ptr= (table->getFields() + table->getShare()->positionFields(field_ptr));
 
2510
      field_ptr= (table->field + (field_ptr - table->getMutableShare()->getFields()));
2045
2511
    }
2046
2512
  }
2047
2513
  else
2048
2514
  {
2049
 
    if (!(field_ptr= table->getFields()))
 
2515
    if (!(field_ptr= table->field))
2050
2516
      return((Field *)0);
2051
2517
    for (; *field_ptr; ++field_ptr)
2052
2518
      if (!my_strcasecmp(system_charset_info, (*field_ptr)->field_name, name))
2055
2521
 
2056
2522
  if (field_ptr && *field_ptr)
2057
2523
  {
2058
 
    *cached_field_index_ptr= field_ptr - table->getFields();
 
2524
    *cached_field_index_ptr= field_ptr - table->field;
2059
2525
    field= *field_ptr;
2060
2526
  }
2061
2527
  else
2064
2530
        my_strcasecmp(system_charset_info, name, "_rowid") ||
2065
2531
        table->getShare()->rowid_field_offset == 0)
2066
2532
      return((Field*) 0);
2067
 
    field= table->getField(table->getShare()->rowid_field_offset-1);
 
2533
    field= table->field[table->getShare()->rowid_field_offset-1];
2068
2534
  }
2069
2535
 
2070
2536
  update_field_dependencies(session, field, table);
2146
2612
    TODO-> Ensure that table_name, db_name and tables->db always points to something !
2147
2613
  */
2148
2614
  if (/* Exclude nested joins. */
2149
 
      (!table_list->getNestedJoin()) &&
 
2615
      (!table_list->nested_join) &&
2150
2616
      /* Include merge views and information schema tables. */
2151
2617
      /*
2152
2618
        Test if the field qualifiers match the table reference we plan
2154
2620
      */
2155
2621
      table_name && table_name[0] &&
2156
2622
      (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()))))
 
2623
       (db_name && db_name[0] && table_list->db && table_list->db[0] &&
 
2624
        strcmp(db_name, table_list->db))))
2159
2625
    return 0;
2160
2626
 
2161
2627
  *actual_table= NULL;
2162
2628
 
2163
 
  if (!table_list->getNestedJoin())
 
2629
  if (!table_list->nested_join)
2164
2630
  {
2165
2631
    /* 'table_list' is a stored table. */
2166
2632
    assert(table_list->table);
2180
2646
    */
2181
2647
    if (table_name && table_name[0])
2182
2648
    {
2183
 
      List_iterator<TableList> it(table_list->getNestedJoin()->join_list);
 
2649
      List_iterator<TableList> it(table_list->nested_join->join_list);
2184
2650
      TableList *table;
2185
2651
      while ((table= it++))
2186
2652
      {
2228
2694
        field_to_set= fld;
2229
2695
      if (field_to_set)
2230
2696
      {
2231
 
        Table *table= field_to_set->getTable();
 
2697
        Table *table= field_to_set->table;
2232
2698
        if (session->mark_used_columns == MARK_COLUMNS_READ)
2233
 
          table->setReadSet(field_to_set->position());
 
2699
          table->setReadSet(field_to_set->field_index);
2234
2700
        else
2235
 
          table->setWriteSet(field_to_set->position());
 
2701
          table->setWriteSet(field_to_set->field_index);
2236
2702
      }
2237
2703
    }
2238
2704
  }
2474
2940
 
2475
2941
 
2476
2942
Item **
2477
 
find_item_in_list(Session *session,
2478
 
                  Item *find, List<Item> &items, uint32_t *counter,
 
2943
find_item_in_list(Item *find, List<Item> &items, uint32_t *counter,
2479
2944
                  find_item_error_report_type report_error,
2480
2945
                  enum_resolution_type *resolution)
2481
2946
{
2555
3020
            */
2556
3021
            if (report_error != IGNORE_ERRORS)
2557
3022
              my_error(ER_NON_UNIQ_ERROR, MYF(0),
2558
 
                       find->full_name(), session->where);
 
3023
                       find->full_name(), current_session->where);
2559
3024
            return (Item**) 0;
2560
3025
          }
2561
3026
          found_unaliased= li.ref();
2586
3051
              continue;                           // Same field twice
2587
3052
            if (report_error != IGNORE_ERRORS)
2588
3053
              my_error(ER_NON_UNIQ_ERROR, MYF(0),
2589
 
                       find->full_name(), session->where);
 
3054
                       find->full_name(), current_session->where);
2590
3055
            return (Item**) 0;
2591
3056
          }
2592
3057
          found= li.ref();
2638
3103
    {
2639
3104
      if (report_error != IGNORE_ERRORS)
2640
3105
        my_error(ER_NON_UNIQ_ERROR, MYF(0),
2641
 
                 find->full_name(), session->where);
 
3106
                 find->full_name(), current_session->where);
2642
3107
      return (Item **) 0;
2643
3108
    }
2644
3109
    if (found_unaliased)
2654
3119
  {
2655
3120
    if (report_error == REPORT_ALL_ERRORS)
2656
3121
      my_error(ER_BAD_FIELD_ERROR, MYF(0),
2657
 
               find->full_name(), session->where);
 
3122
               find->full_name(), current_session->where);
2658
3123
    return (Item **) 0;
2659
3124
  }
2660
3125
  else
2772
3237
    Leaf table references to which new natural join columns are added
2773
3238
    if the leaves are != NULL.
2774
3239
  */
2775
 
  TableList *leaf_1= (table_ref_1->getNestedJoin() &&
2776
 
                      ! table_ref_1->is_natural_join) ?
 
3240
  TableList *leaf_1= (table_ref_1->nested_join &&
 
3241
                      !table_ref_1->is_natural_join) ?
2777
3242
    NULL : table_ref_1;
2778
 
  TableList *leaf_2= (table_ref_2->getNestedJoin() &&
2779
 
                      ! table_ref_2->is_natural_join) ?
 
3243
  TableList *leaf_2= (table_ref_2->nested_join &&
 
3244
                      !table_ref_2->is_natural_join) ?
2780
3245
    NULL : table_ref_2;
2781
3246
 
2782
3247
  *found_using_fields= 0;
2788
3253
    /* true if field_name_1 is a member of using_fields */
2789
3254
    bool is_using_column_1;
2790
3255
    if (!(nj_col_1= it_1.get_or_create_column_ref(leaf_1)))
2791
 
      return(result);
 
3256
      goto err;
2792
3257
    field_name_1= nj_col_1->name();
2793
3258
    is_using_column_1= using_fields &&
2794
3259
      test_if_string_in_list(field_name_1, using_fields);
2806
3271
      Natural_join_column *cur_nj_col_2;
2807
3272
      const char *cur_field_name_2;
2808
3273
      if (!(cur_nj_col_2= it_2.get_or_create_column_ref(leaf_2)))
2809
 
        return(result);
 
3274
        goto err;
2810
3275
      cur_field_name_2= cur_nj_col_2->name();
2811
3276
 
2812
3277
      /*
2826
3291
            (found && (!using_fields || is_using_column_1)))
2827
3292
        {
2828
3293
          my_error(ER_NON_UNIQ_ERROR, MYF(0), field_name_1, session->where);
2829
 
          return(result);
 
3294
          goto err;
2830
3295
        }
2831
3296
        nj_col_2= cur_nj_col_2;
2832
3297
        found= true;
2859
3324
      Item_func_eq *eq_cond;
2860
3325
 
2861
3326
      if (!item_1 || !item_2)
2862
 
        return(result); // out of memory
 
3327
        goto err;                               // out of memory
2863
3328
 
2864
3329
      /*
2865
3330
        In the case of no_wrap_view_item == 0, the created items must be
2884
3349
      */
2885
3350
      if (set_new_item_local_context(session, item_ident_1, nj_col_1->table_ref) ||
2886
3351
          set_new_item_local_context(session, item_ident_2, nj_col_2->table_ref))
2887
 
        return(result);
 
3352
        goto err;
2888
3353
 
2889
3354
      if (!(eq_cond= new Item_func_eq(item_ident_1, item_ident_2)))
2890
 
        return(result);                               /* Out of memory. */
 
3355
        goto err;                               /* Out of memory. */
2891
3356
 
2892
3357
      /*
2893
3358
        Add the new equi-join condition to the ON clause. Notice that
2904
3369
      {
2905
3370
        Table *table_1= nj_col_1->table_ref->table;
2906
3371
        /* Mark field_1 used for table cache. */
2907
 
        table_1->setReadSet(field_1->position());
 
3372
        table_1->setReadSet(field_1->field_index);
2908
3373
        table_1->covering_keys&= field_1->part_of_key;
2909
3374
        table_1->merge_keys|= field_1->part_of_key;
2910
3375
      }
2912
3377
      {
2913
3378
        Table *table_2= nj_col_2->table_ref->table;
2914
3379
        /* Mark field_2 used for table cache. */
2915
 
        table_2->setReadSet(field_2->position());
 
3380
        table_2->setReadSet(field_2->field_index);
2916
3381
        table_2->covering_keys&= field_2->part_of_key;
2917
3382
        table_2->merge_keys|= field_2->part_of_key;
2918
3383
      }
2933
3398
  */
2934
3399
  result= false;
2935
3400
 
 
3401
err:
2936
3402
  return(result);
2937
3403
}
2938
3404
 
2974
3440
*/
2975
3441
 
2976
3442
static bool
2977
 
store_natural_using_join_columns(Session *session,
 
3443
store_natural_using_join_columns(Session *,
2978
3444
                                 TableList *natural_using_join,
2979
3445
                                 TableList *table_ref_1,
2980
3446
                                 TableList *table_ref_2,
2990
3456
 
2991
3457
  if (!(non_join_columns= new List<Natural_join_column>) ||
2992
3458
      !(natural_using_join->join_columns= new List<Natural_join_column>))
2993
 
  {
2994
 
    return(result);
2995
 
  }
 
3459
    goto err;
2996
3460
 
2997
3461
  /* Append the columns of the first join operand. */
2998
3462
  for (it_1.set(table_ref_1); !it_1.end_of_fields(); it_1.next())
3030
3494
        if (!(common_field= it++))
3031
3495
        {
3032
3496
          my_error(ER_BAD_FIELD_ERROR, MYF(0), using_field_name_ptr,
3033
 
                   session->where);
3034
 
          return(result);
 
3497
                   current_session->where);
 
3498
          goto err;
3035
3499
        }
3036
3500
        if (!my_strcasecmp(system_charset_info,
3037
3501
                           common_field->name(), using_field_name_ptr))
3059
3523
 
3060
3524
  result= false;
3061
3525
 
 
3526
err:
3062
3527
  return(result);
3063
3528
}
3064
3529
 
3101
3566
  bool result= true;
3102
3567
 
3103
3568
  /* Call the procedure recursively for each nested table reference. */
3104
 
  if (table_ref->getNestedJoin())
 
3569
  if (table_ref->nested_join)
3105
3570
  {
3106
 
    List_iterator_fast<TableList> nested_it(table_ref->getNestedJoin()->join_list);
 
3571
    List_iterator_fast<TableList> nested_it(table_ref->nested_join->join_list);
3107
3572
    TableList *same_level_left_neighbor= nested_it++;
3108
3573
    TableList *same_level_right_neighbor= NULL;
3109
3574
    /* Left/right-most neighbors, possibly at higher levels in the join tree. */
3128
3593
          cur_table_ref->outer_join & JOIN_TYPE_RIGHT)
3129
3594
      {
3130
3595
        /* This can happen only for JOIN ... ON. */
3131
 
        assert(table_ref->getNestedJoin()->join_list.elements == 2);
 
3596
        assert(table_ref->nested_join->join_list.elements == 2);
3132
3597
        std::swap(same_level_left_neighbor, cur_table_ref);
3133
3598
      }
3134
3599
 
3141
3606
      real_right_neighbor= (same_level_right_neighbor) ?
3142
3607
        same_level_right_neighbor : right_neighbor;
3143
3608
 
3144
 
      if (cur_table_ref->getNestedJoin() &&
 
3609
      if (cur_table_ref->nested_join &&
3145
3610
          store_top_level_join_columns(session, cur_table_ref,
3146
3611
                                       real_left_neighbor, real_right_neighbor))
3147
 
        return(result);
 
3612
        goto err;
3148
3613
      same_level_right_neighbor= cur_table_ref;
3149
3614
    }
3150
3615
  }
3155
3620
  */
3156
3621
  if (table_ref->is_natural_join)
3157
3622
  {
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);
 
3623
    assert(table_ref->nested_join &&
 
3624
           table_ref->nested_join->join_list.elements == 2);
 
3625
    List_iterator_fast<TableList> operand_it(table_ref->nested_join->join_list);
3161
3626
    /*
3162
3627
      Notice that the order of join operands depends on whether table_ref
3163
3628
      represents a LEFT or a RIGHT join. In a RIGHT join, the operands are
3176
3641
      std::swap(table_ref_1, table_ref_2);
3177
3642
    if (mark_common_columns(session, table_ref_1, table_ref_2,
3178
3643
                            using_fields, &found_using_fields))
3179
 
      return(result);
 
3644
      goto err;
3180
3645
 
3181
3646
    /*
3182
3647
      Swap the join operands back, so that we pick the columns of the second
3188
3653
    if (store_natural_using_join_columns(session, table_ref, table_ref_1,
3189
3654
                                         table_ref_2, using_fields,
3190
3655
                                         found_using_fields))
3191
 
      return(result);
 
3656
      goto err;
3192
3657
 
3193
3658
    /*
3194
3659
      Change NATURAL JOIN to JOIN ... ON. We do this for both operands
3221
3686
  }
3222
3687
  result= false; /* All is OK. */
3223
3688
 
 
3689
err:
3224
3690
  return(result);
3225
3691
}
3226
3692
 
3622
4088
    assert(tables->is_leaf_for_name_resolution());
3623
4089
 
3624
4090
    if ((table_name && my_strcasecmp(table_alias_charset, table_name, tables->alias)) ||
3625
 
        (db_name && strcasecmp(tables->getSchemaName(),db_name)))
 
4091
        (db_name && strcasecmp(tables->db,db_name)))
3626
4092
      continue;
3627
4093
 
3628
4094
    /*
3658
4124
      if ((field= field_iterator.field()))
3659
4125
      {
3660
4126
        /* Mark fields as used to allow storage engine to optimze access */
3661
 
        field->getTable()->setReadSet(field->position());
 
4127
        field->table->setReadSet(field->field_index);
3662
4128
        if (table)
3663
4129
        {
3664
4130
          table->covering_keys&= field->part_of_key;
3696
4162
      For NATURAL joins, used_tables is updated in the IF above.
3697
4163
    */
3698
4164
    if (table)
3699
 
      table->used_fields= table->getShare()->sizeFields();
 
4165
      table->used_fields= table->getShare()->fields;
3700
4166
  }
3701
4167
  if (found)
3702
4168
    return false;
3786
4252
          goto err_no_arena;
3787
4253
        select_lex->cond_count++;
3788
4254
      }
3789
 
      embedding= embedded->getEmbedding();
 
4255
      embedding= embedded->embedding;
3790
4256
    }
3791
4257
    while (embedding &&
3792
 
           embedding->getNestedJoin()->join_list.head() == embedded);
 
4258
           embedding->nested_join->join_list.head() == embedded);
3793
4259
 
3794
4260
  }
3795
4261
  session->session_marker= save_session_marker;
3848
4314
      thus we safely can take table from the first field.
3849
4315
    */
3850
4316
    field= static_cast<Item_field *>(f++);
3851
 
    table= field->field->getTable();
 
4317
    table= field->field->table;
3852
4318
    table->auto_increment_field_not_null= false;
3853
4319
    f.rewind();
3854
4320
  }
3858
4324
    value= v++;
3859
4325
 
3860
4326
    Field *rfield= field->field;
3861
 
    table= rfield->getTable();
 
4327
    table= rfield->table;
3862
4328
 
3863
4329
    if (rfield == table->next_number_field)
3864
4330
      table->auto_increment_field_not_null= true;
3865
4331
    if ((value->save_in_field(rfield, 0) < 0) && !ignore_errors)
3866
4332
    {
3867
4333
      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;
 
4334
      goto err;
3872
4335
    }
3873
4336
  }
3874
4337
 
3875
4338
  return session->is_error();
 
4339
 
 
4340
err:
 
4341
  if (table)
 
4342
    table->auto_increment_field_not_null= false;
 
4343
 
 
4344
  return true;
3876
4345
}
3877
4346
 
3878
4347
 
3912
4381
      On INSERT or UPDATE fields are checked to be from the same table,
3913
4382
      thus we safely can take table from the first field.
3914
4383
    */
3915
 
    table= (*ptr)->getTable();
 
4384
    table= (*ptr)->table;
3916
4385
    table->auto_increment_field_not_null= false;
3917
4386
  }
3918
4387
  while ((field = *ptr++) && ! session->is_error())
3919
4388
  {
3920
4389
    value=v++;
3921
 
    table= field->getTable();
 
4390
    table= field->table;
3922
4391
    if (field == table->next_number_field)
3923
4392
      table->auto_increment_field_not_null= true;
3924
4393
    if (value->save_in_field(field, 0) < 0)
3925
 
    {
3926
 
      if (table)
3927
 
        table->auto_increment_field_not_null= false;
3928
 
 
3929
 
      return true;
3930
 
    }
 
4394
      goto err;
3931
4395
  }
3932
4396
 
3933
4397
  return(session->is_error());
 
4398
 
 
4399
err:
 
4400
  if (table)
 
4401
    table->auto_increment_field_not_null= false;
 
4402
 
 
4403
  return true;
3934
4404
}
3935
4405
 
3936
4406
 
3958
4428
  unireg support functions
3959
4429
 *****************************************************************************/
3960
4430
 
3961
 
 
 
4431
/*
 
4432
  Invalidate any cache entries that are for some DB
 
4433
 
 
4434
  SYNOPSIS
 
4435
  remove_db_from_cache()
 
4436
  db            Database name. This will be in lower case if
 
4437
  lower_case_table_name is set
 
4438
 
 
4439
NOTE:
 
4440
We can't use hash_delete when looping hash_elements. We mark them first
 
4441
and afterwards delete those marked unused.
 
4442
*/
 
4443
 
 
4444
void remove_db_from_cache(SchemaIdentifier &schema_identifier)
 
4445
{
 
4446
  safe_mutex_assert_owner(&LOCK_open);
 
4447
 
 
4448
  for (uint32_t idx=0 ; idx < open_cache.records ; idx++)
 
4449
  {
 
4450
    Table *table=(Table*) hash_element(&open_cache,idx);
 
4451
    if (not schema_identifier.getPath().compare(table->getMutableShare()->getSchemaName()))
 
4452
    {
 
4453
      table->getMutableShare()->version= 0L;                    /* Free when thread is ready */
 
4454
      if (not table->in_use)
 
4455
        relink_unused(table);
 
4456
    }
 
4457
  }
 
4458
  while (unused_tables && !unused_tables->getShare()->version)
 
4459
    hash_delete(&open_cache,(unsigned char*) unused_tables);
 
4460
}
 
4461
 
 
4462
 
 
4463
/*
 
4464
  Mark all entries with the table as deleted to force an reopen of the table
 
4465
 
 
4466
  The table will be closed (not stored in cache) by the current thread when
 
4467
  close_thread_tables() is called.
 
4468
 
 
4469
  PREREQUISITES
 
4470
  Lock on LOCK_open()
 
4471
 
 
4472
  RETURN
 
4473
  0  This thread now have exclusive access to this table and no other thread
 
4474
  can access the table until close_thread_tables() is called.
 
4475
  1  Table is in use by another thread
 
4476
*/
 
4477
 
 
4478
bool remove_table_from_cache(Session *session, const char *db, const char *table_name,
 
4479
                             uint32_t flags)
 
4480
{
 
4481
  char key[MAX_DBKEY_LENGTH];
 
4482
  char *key_pos= key;
 
4483
  uint32_t key_length;
 
4484
  Table *table;
 
4485
  bool result= false; 
 
4486
  bool signalled= false;
 
4487
 
 
4488
  key_pos= strcpy(key_pos, db) + strlen(db);
 
4489
  key_pos= strcpy(key_pos+1, table_name) + strlen(table_name);
 
4490
  key_length= (uint32_t) (key_pos-key)+1;
 
4491
 
 
4492
  for (;;)
 
4493
  {
 
4494
    HASH_SEARCH_STATE state;
 
4495
    result= signalled= false;
 
4496
 
 
4497
    for (table= (Table*) hash_first(&open_cache, (unsigned char*) key, key_length,
 
4498
                                    &state);
 
4499
         table;
 
4500
         table= (Table*) hash_next(&open_cache, (unsigned char*) key, key_length,
 
4501
                                   &state))
 
4502
    {
 
4503
      Session *in_use;
 
4504
 
 
4505
      table->getMutableShare()->version=0L;             /* Free when thread is ready */
 
4506
      if (!(in_use=table->in_use))
 
4507
      {
 
4508
        relink_unused(table);
 
4509
      }
 
4510
      else if (in_use != session)
 
4511
      {
 
4512
        /*
 
4513
          Mark that table is going to be deleted from cache. This will
 
4514
          force threads that are in mysql_lock_tables() (but not yet
 
4515
          in thr_multi_lock()) to abort it's locks, close all tables and retry
 
4516
        */
 
4517
        in_use->some_tables_deleted= true;
 
4518
        if (table->is_name_opened())
 
4519
        {
 
4520
          result= true;
 
4521
        }
 
4522
        /*
 
4523
          Now we must abort all tables locks used by this thread
 
4524
          as the thread may be waiting to get a lock for another table.
 
4525
          Note that we need to hold LOCK_open while going through the
 
4526
          list. So that the other thread cannot change it. The other
 
4527
          thread must also hold LOCK_open whenever changing the
 
4528
          open_tables list. Aborting the MERGE lock after a child was
 
4529
          closed and before the parent is closed would be fatal.
 
4530
        */
 
4531
        for (Table *session_table= in_use->open_tables;
 
4532
             session_table ;
 
4533
             session_table= session_table->next)
 
4534
        {
 
4535
          /* Do not handle locks of MERGE children. */
 
4536
          if (session_table->db_stat)   // If table is open
 
4537
            signalled|= mysql_lock_abort_for_thread(session, session_table);
 
4538
        }
 
4539
      }
 
4540
      else
 
4541
        result= result || (flags & RTFC_OWNED_BY_Session_FLAG);
 
4542
    }
 
4543
    while (unused_tables && !unused_tables->getShare()->version)
 
4544
      hash_delete(&open_cache,(unsigned char*) unused_tables);
 
4545
 
 
4546
    /* Remove table from table definition cache if it's not in use */
 
4547
    TableShare::release(key, key_length);
 
4548
 
 
4549
    if (result && (flags & RTFC_WAIT_OTHER_THREAD_FLAG))
 
4550
    {
 
4551
      /*
 
4552
        Signal any thread waiting for tables to be freed to
 
4553
        reopen their tables
 
4554
      */
 
4555
      broadcast_refresh();
 
4556
      if (!(flags & RTFC_CHECK_KILLED_FLAG) || !session->killed)
 
4557
      {
 
4558
        dropping_tables++;
 
4559
        if (likely(signalled))
 
4560
          (void) pthread_cond_wait(&COND_refresh, &LOCK_open);
 
4561
        else
 
4562
        {
 
4563
          struct timespec abstime;
 
4564
          /*
 
4565
            It can happen that another thread has opened the
 
4566
            table but has not yet locked any table at all. Since
 
4567
            it can be locked waiting for a table that our thread
 
4568
            has done LOCK Table x WRITE on previously, we need to
 
4569
            ensure that the thread actually hears our signal
 
4570
            before we go to sleep. Thus we wait for a short time
 
4571
            and then we retry another loop in the
 
4572
            remove_table_from_cache routine.
 
4573
          */
 
4574
          set_timespec(abstime, 10);
 
4575
          pthread_cond_timedwait(&COND_refresh, &LOCK_open, &abstime);
 
4576
        }
 
4577
        dropping_tables--;
 
4578
        continue;
 
4579
      }
 
4580
    }
 
4581
    break;
 
4582
  }
 
4583
  return result;
 
4584
}
3962
4585
 
3963
4586
 
3964
4587
/**