~drizzle-trunk/drizzle/development

« back to all changes in this revision

Viewing changes to drizzled/sql_base.cc

  • Committer: Brian Aker
  • Date: 2010-12-18 02:06:13 UTC
  • Revision ID: brian@tangent.org-20101218020613-8lxhcvsy812bu960
Formatting + remove default from switch/case.

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