~drizzle-trunk/drizzle/development

« back to all changes in this revision

Viewing changes to drizzled/sql_base.cc

  • Committer: Stewart Smith
  • Date: 2010-03-18 12:01:34 UTC
  • mto: (1666.2.3 build)
  • mto: This revision was merged to the branch mainline in revision 1596.
  • Revision ID: stewart@flamingspork.com-20100318120134-45fdnsw8g3j6c7oy
move RAND() into a plugin

Show diffs side-by-side

added added

removed removed

Lines of Context:
11
11
 
12
12
  You should have received a copy of the GNU General Public License
13
13
  along with this program; if not, write to the Free Software
14
 
  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA */
 
14
  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA */
15
15
 
16
16
 
17
17
/* Basic functions needed by many modules */
31
31
# endif
32
32
#endif
33
33
#include "drizzled/internal/my_pthread.h"
34
 
#include "drizzled/internal/thread_var.h"
35
34
 
36
35
#include <drizzled/sql_select.h>
37
36
#include <drizzled/error.h>
47
46
#include "drizzled/cached_directory.h"
48
47
#include <drizzled/field/timestamp.h>
49
48
#include <drizzled/field/null.h>
 
49
#include "drizzled/memory/multi_malloc.h"
50
50
#include "drizzled/sql_table.h"
51
51
#include "drizzled/global_charset_info.h"
52
52
#include "drizzled/pthread_globals.h"
53
53
#include "drizzled/internal/iocache.h"
54
 
#include "drizzled/drizzled.h"
55
54
#include "drizzled/plugin/authorization.h"
56
 
#include "drizzled/table/temporary.h"
57
 
#include "drizzled/table/placeholder.h"
58
 
#include "drizzled/table/unused.h"
59
55
 
60
56
using namespace std;
61
57
 
64
60
 
65
61
extern bool volatile shutdown_in_progress;
66
62
 
 
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
 
67
95
bool table_cache_init(void)
68
96
{
69
 
  return false;
70
 
}
71
 
 
72
 
uint32_t cached_open_tables(void)
73
 
{
74
 
  return table::getCache().size();
 
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);
75
101
}
76
102
 
77
103
void table_cache_free(void)
78
104
{
79
105
  refresh_version++;                            // Force close of open tables
80
106
 
81
 
  table::getUnused().clear();
82
 
  table::getCache().clear();
83
 
}
 
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
 
84
119
 
85
120
/*
86
121
  Close cursor handle, but leave the table in the table cache
93
128
  By leaving the table in the table cache, it disallows any other thread
94
129
  to open the table
95
130
 
96
 
  session->getKilled() will be set if we run out of memory
 
131
  session->killed will be set if we run out of memory
97
132
 
98
133
  If closing a MERGE child, the calling function has to take care for
99
134
  closing the parent too, if necessary.
102
137
 
103
138
void close_handle_and_leave_table_as_lock(Table *table)
104
139
{
 
140
  TableShare *share, *old_share= table->s;
 
141
  char *key_buff;
 
142
  memory::Root *mem_root= &table->mem_root;
 
143
 
105
144
  assert(table->db_stat);
106
 
  assert(table->getShare()->getType() == message::Table::STANDARD);
107
145
 
108
146
  /*
109
147
    Make a local copy of the table share and free the current one.
110
148
    This has to be done to ensure that the table share is removed from
111
149
    the table defintion cache as soon as the last instance is removed
112
150
  */
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()));
 
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= INTERNAL_TMP_TABLE;       // for intern_close_table()
 
160
  }
118
161
 
119
162
  table->cursor->close();
120
163
  table->db_stat= 0;                            // Mark cursor closed
121
 
  TableShare::release(table->getMutableShare());
122
 
  table->setShare(share);
 
164
  TableShare::release(table->s);
 
165
  table->s= share;
 
166
  table->cursor->change_table_ptr(table, table->s);
123
167
}
124
168
 
125
169
 
132
176
{                                               // Free all structures
133
177
  free_io_cache();
134
178
  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)
135
198
  {
136
 
    delete_table(true);                 // close cursor
 
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
    }
137
207
  }
 
208
  free(table);
138
209
}
139
210
 
140
211
/* Free resources allocated by filesort() and read_record() */
143
214
{
144
215
  if (sort.io_cache)
145
216
  {
146
 
    sort.io_cache->close_cached_file();
 
217
    close_cached_file(sort.io_cache);
147
218
    delete sort.io_cache;
148
219
    sort.io_cache= 0;
149
220
  }
155
226
 
156
227
  @param session Thread context (may be NULL)
157
228
  @param tables List of tables to remove from the cache
158
 
  @param have_lock If table::Cache::singleton().mutex() is locked
 
229
  @param have_lock If LOCK_open is locked
159
230
  @param wait_for_refresh Wait for a impending flush
160
231
  @param wait_for_placeholders Wait for tables being reopened so that the GRL
161
232
  won't proceed while write-locked tables are being reopened by other
170
241
  bool result= false;
171
242
  Session *session= this;
172
243
 
173
 
  {
174
 
    table::Cache::singleton().mutex().lock(); /* Optionally lock for remove tables from open_cahe if not in use */
175
 
 
176
 
    if (tables == NULL)
177
 
    {
178
 
      refresh_version++;                                // Force close of open tables
179
 
 
180
 
      table::getUnused().clear();
181
 
 
182
 
      if (wait_for_refresh)
183
 
      {
 
244
  pthread_mutex_lock(&LOCK_open); /* Optionally lock for remove tables from open_cahe if not in use */
 
245
 
 
246
  if (tables == NULL)
 
247
  {
 
248
    refresh_version++;                          // Force close of open tables
 
249
    while (unused_tables)
 
250
      hash_delete(&open_cache,(unsigned char*) unused_tables);
 
251
 
 
252
    if (wait_for_refresh)
 
253
    {
 
254
      /*
 
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.
 
290
      */
 
291
      for (uint32_t idx=0 ; idx < open_cache.records ; idx++)
 
292
      {
 
293
        Table *table=(Table*) hash_element(&open_cache,idx);
 
294
        if (table->in_use)
 
295
          table->in_use->some_tables_deleted= false;
 
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++)
 
330
      {
 
331
        Table *table=(Table*) hash_element(&open_cache,idx);
 
332
        /* Avoid a self-deadlock. */
 
333
        if (table->in_use == session)
 
334
          continue;
184
335
        /*
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.
 
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.
220
348
        */
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))
 
349
        if (table->needs_reopen_or_name_lock() && (table->db_stat ||
 
350
                                                   (table->open_placeholder && wait_for_placeholders)))
239
351
        {
240
352
          found= true;
 
353
          pthread_cond_wait(&COND_refresh,&LOCK_open);
 
354
          break;
241
355
        }
242
356
      }
243
 
      if (!found)
244
 
        wait_for_refresh= false;                        // Nothing to wait for
245
357
    }
 
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);
246
364
 
247
 
    if (wait_for_refresh)
 
365
    /* Set version for table */
 
366
    for (Table *table= session->open_tables; table ; table= table->next)
248
367
    {
249
368
      /*
250
 
        If there is any table that has a lower refresh_version, wait until
251
 
        this is closed (or this thread is killed) before returning
252
 
      */
253
 
      session->mysys_var->current_mutex= &table::Cache::singleton().mutex();
254
 
      session->mysys_var->current_cond= &COND_refresh;
255
 
      session->set_proc_info("Flushing tables");
256
 
 
257
 
      session->close_old_data_files();
258
 
 
259
 
      bool found= true;
260
 
      /* Wait until all threads has closed all the tables we had locked */
261
 
      while (found && ! session->getKilled())
262
 
      {
263
 
        found= false;
264
 
        for (table::CacheMap::const_iterator iter= table::getCache().begin();
265
 
             iter != table::getCache().end();
266
 
             iter++)
267
 
        {
268
 
          Table *table= (*iter).second;
269
 
          /* Avoid a self-deadlock. */
270
 
          if (table->in_use == session)
271
 
            continue;
272
 
          /*
273
 
            Note that we wait here only for tables which are actually open, and
274
 
            not for placeholders with Table::open_placeholder set. Waiting for
275
 
            latter will cause deadlock in the following scenario, for example:
276
 
 
277
 
            conn1-> lock table t1 write;
278
 
            conn2-> lock table t2 write;
279
 
            conn1-> flush tables;
280
 
            conn2-> flush tables;
281
 
 
282
 
            It also does not make sense to wait for those of placeholders that
283
 
            are employed by CREATE TABLE as in this case table simply does not
284
 
            exist yet.
285
 
          */
286
 
          if (table->needs_reopen_or_name_lock() && (table->db_stat ||
287
 
                                                     (table->open_placeholder && wait_for_placeholders)))
288
 
          {
289
 
            found= true;
290
 
            boost_unique_lock_t scoped(table::Cache::singleton().mutex(), boost::adopt_lock_t());
291
 
            COND_refresh.wait(scoped);
292
 
            scoped.release();
293
 
            break;
294
 
          }
295
 
        }
296
 
      }
297
 
      /*
298
 
        No other thread has the locked tables open; reopen them and get the
299
 
        old locks. This should always succeed (unless some external process
300
 
        has removed the tables)
301
 
      */
302
 
      result= session->reopen_tables(true, true);
303
 
 
304
 
      /* Set version for table */
305
 
      for (Table *table= session->open_tables; table ; table= table->getNext())
306
 
      {
307
 
        /*
308
 
          Preserve the version (0) of write locked tables so that a impending
309
 
          global read lock won't sneak in.
310
 
        */
311
 
        if (table->reginfo.lock_type < TL_WRITE_ALLOW_WRITE)
312
 
          table->getMutableShare()->refreshVersion();
313
 
      }
 
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;
314
374
    }
315
 
 
316
 
    table::Cache::singleton().mutex().unlock();
317
375
  }
318
376
 
 
377
  pthread_mutex_unlock(&LOCK_open);
 
378
 
319
379
  if (wait_for_refresh)
320
380
  {
321
 
    boost_unique_lock_t scopedLock(session->mysys_var->mutex);
 
381
    pthread_mutex_lock(&session->mysys_var->mutex);
322
382
    session->mysys_var->current_mutex= 0;
323
383
    session->mysys_var->current_cond= 0;
324
384
    session->set_proc_info(0);
 
385
    pthread_mutex_unlock(&session->mysys_var->mutex);
325
386
  }
326
387
 
327
388
  return result;
335
396
bool Session::free_cached_table()
336
397
{
337
398
  bool found_old_table= false;
338
 
  table::Concurrent *table= static_cast<table::Concurrent *>(open_tables);
 
399
  Table *table= open_tables;
339
400
 
340
 
  safe_mutex_assert_owner(table::Cache::singleton().mutex().native_handle());
 
401
  safe_mutex_assert_owner(&LOCK_open);
341
402
  assert(table->key_read == 0);
342
403
  assert(!table->cursor || table->cursor->inited == Cursor::NONE);
343
404
 
344
 
  open_tables= table->getNext();
 
405
  open_tables= table->next;
345
406
 
346
407
  if (table->needs_reopen_or_name_lock() ||
347
408
      version != refresh_version || !table->db_stat)
348
409
  {
349
 
    table::remove_table(table);
 
410
    hash_delete(&open_cache,(unsigned char*) table);
350
411
    found_old_table= true;
351
412
  }
352
413
  else
355
416
      Open placeholders have Table::db_stat set to 0, so they should be
356
417
      handled by the first alternative.
357
418
    */
358
 
    assert(not table->open_placeholder);
 
419
    assert(!table->open_placeholder);
359
420
 
360
421
    /* Free memory and reset for next loop */
361
422
    table->cursor->ha_reset();
362
 
    table->in_use= NULL;
 
423
    table->in_use= false;
363
424
 
364
 
    table::getUnused().link(table);
 
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;
365
434
  }
366
435
 
367
436
  return found_old_table;
380
449
{
381
450
  bool found_old_table= false;
382
451
 
383
 
  safe_mutex_assert_not_owner(table::Cache::singleton().mutex().native_handle());
 
452
  safe_mutex_assert_not_owner(&LOCK_open);
384
453
 
385
 
  boost_unique_lock_t scoped_lock(table::Cache::singleton().mutex()); /* Close all open tables on Session */
 
454
  pthread_mutex_lock(&LOCK_open); /* Close all open tables on Session */
386
455
 
387
456
  while (open_tables)
388
 
  {
389
457
    found_old_table|= free_cached_table();
390
 
  }
391
458
  some_tables_deleted= false;
392
459
 
393
460
  if (found_old_table)
394
461
  {
395
462
    /* Tell threads waiting for refresh that something has happened */
396
 
    locking::broadcast_refresh();
 
463
    broadcast_refresh();
397
464
  }
 
465
 
 
466
  pthread_mutex_unlock(&LOCK_open);
398
467
}
399
468
 
400
469
/*
422
491
{
423
492
  for (; table; table= table->*link )
424
493
  {
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)
 
494
    if ((table->table == 0 || table->table->s->tmp_table == STANDARD_TABLE) &&
 
495
        strcmp(table->db, db_name) == 0 &&
 
496
        strcmp(table->table_name, table_name) == 0)
428
497
      break;
429
498
  }
430
499
  return table;
486
555
  if (table->table)
487
556
  {
488
557
    /* temporary table is always unique */
489
 
    if (table->table && table->table->getShare()->getType() != message::Table::STANDARD)
 
558
    if (table->table && table->table->s->tmp_table != STANDARD_TABLE)
490
559
      return 0;
491
560
    table= table->find_underlying_table(table->table);
492
561
    /*
495
564
    */
496
565
    assert(table);
497
566
  }
498
 
  d_name= table->getSchemaName();
499
 
  t_name= table->getTableName();
 
567
  d_name= table->db;
 
568
  t_name= table->table_name;
500
569
  t_alias= table->alias;
501
570
 
502
571
  for (;;)
517
586
}
518
587
 
519
588
 
520
 
void Open_tables_state::doGetTableNames(const SchemaIdentifier &schema_identifier,
521
 
                                        std::set<std::string>& set_of_names)
522
 
{
523
 
  for (Table *table= getTemporaryTables() ; table ; table= table->getNext())
524
 
  {
525
 
    if (schema_identifier.compare(table->getShare()->getSchemaName()))
526
 
    {
527
 
      set_of_names.insert(table->getShare()->getTableName());
528
 
    }
529
 
  }
530
 
}
531
 
 
532
 
void Open_tables_state::doGetTableNames(CachedDirectory &,
533
 
                                        const SchemaIdentifier &schema_identifier,
534
 
                                        std::set<std::string> &set_of_names)
535
 
{
536
 
  doGetTableNames(schema_identifier, set_of_names);
537
 
}
538
 
 
539
 
void Open_tables_state::doGetTableIdentifiers(const SchemaIdentifier &schema_identifier,
540
 
                                              TableIdentifier::vector &set_of_identifiers)
541
 
{
542
 
  for (Table *table= getTemporaryTables() ; table ; table= table->getNext())
543
 
  {
544
 
    if (schema_identifier.compare(table->getShare()->getSchemaName()))
545
 
    {
546
 
      set_of_identifiers.push_back(TableIdentifier(table->getShare()->getSchemaName(),
547
 
                                                   table->getShare()->getTableName(),
548
 
                                                   table->getShare()->getPath()));
549
 
    }
550
 
  }
551
 
}
552
 
 
553
 
void Open_tables_state::doGetTableIdentifiers(CachedDirectory &,
554
 
                                              const SchemaIdentifier &schema_identifier,
555
 
                                              TableIdentifier::vector &set_of_identifiers)
556
 
{
557
 
  doGetTableIdentifiers(schema_identifier, set_of_identifiers);
558
 
}
559
 
 
560
 
bool Open_tables_state::doDoesTableExist(const TableIdentifier &identifier)
561
 
{
562
 
  for (Table *table= getTemporaryTables() ; table ; table= table->getNext())
563
 
  {
564
 
    if (table->getShare()->getType() == message::Table::TEMPORARY)
565
 
    {
566
 
      if (identifier.getKey() == table->getShare()->getCacheKey())
567
 
      {
568
 
        return true;
569
 
      }
570
 
    }
571
 
  }
572
 
 
573
 
  return false;
574
 
}
575
 
 
576
 
int Open_tables_state::doGetTableDefinition(const TableIdentifier &identifier,
577
 
                                  message::Table &table_proto)
578
 
{
579
 
  for (Table *table= getTemporaryTables() ; table ; table= table->getNext())
580
 
  {
581
 
    if (table->getShare()->getType() == message::Table::TEMPORARY)
582
 
    {
583
 
      if (identifier.getKey() == table->getShare()->getCacheKey())
584
 
      {
585
 
        table_proto.CopyFrom(*(table->getShare()->getTableProto()));
586
 
 
587
 
        return EEXIST;
 
589
void Session::doGetTableNames(CachedDirectory &,
 
590
                              const std::string& db_name,
 
591
                              std::set<std::string>& set_of_names)
 
592
{
 
593
  for (Table *table= temporary_tables ; table ; table= table->next)
 
594
  {
 
595
    if (not db_name.compare(table->s->getSchemaName()))
 
596
    {
 
597
      set_of_names.insert(table->s->table_name.str);
 
598
    }
 
599
  }
 
600
}
 
601
 
 
602
int Session::doGetTableDefinition(const char *,
 
603
                                  const char *db_arg,
 
604
                                  const char *table_name_arg,
 
605
                                  const bool ,
 
606
                                  message::Table *table_proto)
 
607
{
 
608
  for (Table *table= temporary_tables ; table ; table= table->next)
 
609
  {
 
610
    if (table->s->tmp_table == TEMP_TABLE)
 
611
    {
 
612
      if (not strcmp(db_arg, table->s->getSchemaName()))
 
613
      {
 
614
        if (not strcmp(table_name_arg, table->s->table_name.str))
 
615
        {
 
616
          if (table_proto)
 
617
            table_proto->CopyFrom(*(table->s->getTableProto()));
 
618
 
 
619
          return EEXIST;
 
620
        }
588
621
      }
589
622
    }
590
623
  }
592
625
  return ENOENT;
593
626
}
594
627
 
595
 
Table *Open_tables_state::find_temporary_table(const TableIdentifier &identifier)
 
628
Table *Session::find_temporary_table(const char *new_db, const char *table_name)
596
629
{
597
 
  for (Table *table= temporary_tables ; table ; table= table->getNext())
 
630
  char  key[MAX_DBKEY_LENGTH];
 
631
  uint  key_length;
 
632
  Table *table;
 
633
 
 
634
  key_length= TableShare::createKey(key, new_db, table_name);
 
635
 
 
636
  for (table= temporary_tables ; table ; table= table->next)
598
637
  {
599
 
    if (identifier.getKey() == table->getShare()->getCacheKey())
 
638
    if (table->s->table_cache_key.length == key_length &&
 
639
        !memcmp(table->s->table_cache_key.str, key, key_length))
600
640
      return table;
601
641
  }
602
 
 
603
642
  return NULL;                               // Not a temporary table
604
643
}
605
644
 
 
645
Table *Session::find_temporary_table(TableList *table_list)
 
646
{
 
647
  return find_temporary_table(table_list->db, table_list->table_name);
 
648
}
 
649
 
606
650
 
607
651
/**
608
652
  Drop a temporary table.
630
674
  @retval -1  the table is in use by a outer query
631
675
*/
632
676
 
633
 
int Open_tables_state::drop_temporary_table(const drizzled::TableIdentifier &identifier)
 
677
int Session::drop_temporary_table(TableList *table_list)
634
678
{
635
679
  Table *table;
636
680
 
637
 
  if (not (table= find_temporary_table(identifier)))
 
681
  if (!(table= find_temporary_table(table_list)))
638
682
    return 1;
639
683
 
640
684
  /* Table might be in use by some outer statement. */
641
 
  if (table->query_id && table->query_id != getQueryId())
 
685
  if (table->query_id && table->query_id != query_id)
642
686
  {
643
 
    my_error(ER_CANT_REOPEN_TABLE, MYF(0), table->getAlias());
 
687
    my_error(ER_CANT_REOPEN_TABLE, MYF(0), table->alias);
644
688
    return -1;
645
689
  }
646
690
 
650
694
}
651
695
 
652
696
 
 
697
/* move table first in unused links */
 
698
 
 
699
static void relink_unused(Table *table)
 
700
{
 
701
  if (table != unused_tables)
 
702
  {
 
703
    table->prev->next=table->next;              /* Remove from unused list */
 
704
    table->next->prev=table->prev;
 
705
    table->next=unused_tables;                  /* Link in unused tables */
 
706
    table->prev=unused_tables->prev;
 
707
    unused_tables->prev->next=table;
 
708
    unused_tables->prev=table;
 
709
    unused_tables=table;
 
710
  }
 
711
}
 
712
 
 
713
 
653
714
/**
654
715
  Remove all instances of table from thread's open list and
655
716
  table cache.
656
717
 
657
718
  @param  session     Thread context
658
719
  @param  find    Table to remove
659
 
 
660
 
  @note because we risk the chance of deleting the share, we can't assume that it will exist past, this should be modified once we can use a TableShare::shared_ptr here.
661
720
*/
662
721
 
663
722
void Session::unlink_open_table(Table *find)
664
723
{
665
 
  const TableIdentifier::Key find_key(find->getShare()->getCacheKey());
666
 
  Table **prev;
667
 
  safe_mutex_assert_owner(table::Cache::singleton().mutex().native_handle());
668
 
 
 
724
  char key[MAX_DBKEY_LENGTH];
 
725
  uint32_t key_length= find->s->table_cache_key.length;
 
726
  Table *list, **prev;
 
727
 
 
728
  safe_mutex_assert_owner(&LOCK_open);
 
729
 
 
730
  memcpy(key, find->s->table_cache_key.str, key_length);
669
731
  /*
670
 
    Note that we need to hold table::Cache::singleton().mutex() while changing the
 
732
    Note that we need to hold LOCK_open while changing the
671
733
    open_tables list. Another thread may work on it.
672
 
    (See: table::Cache::singleton().removeTable(), mysql_wait_completed_table())
 
734
    (See: remove_table_from_cache(), mysql_wait_completed_table())
673
735
    Closing a MERGE child before the parent would be fatal if the
674
736
    other thread tries to abort the MERGE lock in between.
675
737
  */
676
738
  for (prev= &open_tables; *prev; )
677
739
  {
678
 
    Table *list= *prev;
 
740
    list= *prev;
679
741
 
680
 
    if (list->getShare()->getCacheKey() == find_key)
 
742
    if (list->s->table_cache_key.length == key_length &&
 
743
        !memcmp(list->s->table_cache_key.str, key, key_length))
681
744
    {
682
745
      /* Remove table from open_tables list. */
683
 
      *prev= list->getNext();
684
 
 
 
746
      *prev= list->next;
685
747
      /* Close table. */
686
 
      table::remove_table(static_cast<table::Concurrent *>(list));
 
748
      hash_delete(&open_cache,(unsigned char*) list); // Close table
687
749
    }
688
750
    else
689
751
    {
690
752
      /* Step to next entry in open_tables list. */
691
 
      prev= list->getNextPtr();
 
753
      prev= &list->next;
692
754
    }
693
755
  }
694
756
 
695
757
  // Notify any 'refresh' threads
696
 
  locking::broadcast_refresh();
 
758
  broadcast_refresh();
697
759
}
698
760
 
699
761
 
716
778
  table that was locked with LOCK TABLES.
717
779
*/
718
780
 
719
 
void Session::drop_open_table(Table *table, const TableIdentifier &identifier)
 
781
void Session::drop_open_table(Table *table, const char *db_name,
 
782
                              const char *table_name)
720
783
{
721
 
  if (table->getShare()->getType())
 
784
  if (table->s->tmp_table)
722
785
  {
723
786
    close_temporary_table(table);
724
787
  }
725
788
  else
726
789
  {
727
 
    boost_unique_lock_t scoped_lock(table::Cache::singleton().mutex()); /* Close and drop a table (AUX routine) */
 
790
    pthread_mutex_lock(&LOCK_open); /* Close and drop a table (AUX routine) */
728
791
    /*
729
792
      unlink_open_table() also tells threads waiting for refresh or close
730
793
      that something has happened.
731
794
    */
732
795
    unlink_open_table(table);
733
 
    plugin::StorageEngine::dropTable(*this, identifier);
 
796
    TableIdentifier identifier(db_name, table_name, STANDARD_TABLE);
 
797
    quick_rm_table(*this, identifier);
 
798
    pthread_mutex_unlock(&LOCK_open);
734
799
  }
735
800
}
736
801
 
746
811
  cond  Condition to wait for
747
812
*/
748
813
 
749
 
void Session::wait_for_condition(boost::mutex &mutex, boost::condition_variable_any &cond)
 
814
void Session::wait_for_condition(pthread_mutex_t *mutex, pthread_cond_t *cond)
750
815
{
751
816
  /* Wait until the current table is up to date */
752
817
  const char *saved_proc_info;
753
 
  mysys_var->current_mutex= &mutex;
754
 
  mysys_var->current_cond= &cond;
 
818
  mysys_var->current_mutex= mutex;
 
819
  mysys_var->current_cond= cond;
755
820
  saved_proc_info= get_proc_info();
756
821
  set_proc_info("Waiting for table");
757
 
  {
758
 
    /*
759
 
      We must unlock mutex first to avoid deadlock becasue conditions are
760
 
      sent to this thread by doing locks in the following order:
761
 
      lock(mysys_var->mutex)
762
 
      lock(mysys_var->current_mutex)
763
 
 
764
 
      One by effect of this that one can only use wait_for_condition with
765
 
      condition variables that are guranteed to not disapper (freed) even if this
766
 
      mutex is unlocked
767
 
    */
768
 
    boost_unique_lock_t scopedLock(mutex, boost::adopt_lock_t());
769
 
    if (not getKilled())
770
 
    {
771
 
      cond.wait(scopedLock);
772
 
    }
773
 
  }
774
 
  boost_unique_lock_t mysys_scopedLock(mysys_var->mutex);
 
822
  if (!killed)
 
823
    (void) pthread_cond_wait(cond, mutex);
 
824
 
 
825
  /*
 
826
    We must unlock mutex first to avoid deadlock becasue conditions are
 
827
    sent to this thread by doing locks in the following order:
 
828
    lock(mysys_var->mutex)
 
829
    lock(mysys_var->current_mutex)
 
830
 
 
831
    One by effect of this that one can only use wait_for_condition with
 
832
    condition variables that are guranteed to not disapper (freed) even if this
 
833
    mutex is unlocked
 
834
  */
 
835
 
 
836
  pthread_mutex_unlock(mutex);
 
837
  pthread_mutex_lock(&mysys_var->mutex);
775
838
  mysys_var->current_mutex= 0;
776
839
  mysys_var->current_cond= 0;
777
840
  set_proc_info(saved_proc_info);
 
841
  pthread_mutex_unlock(&mysys_var->mutex);
 
842
}
 
843
 
 
844
 
 
845
/*
 
846
  Open table which is already name-locked by this thread.
 
847
 
 
848
  SYNOPSIS
 
849
  reopen_name_locked_table()
 
850
  session         Thread handle
 
851
  table_list  TableList object for table to be open, TableList::table
 
852
  member should point to Table object which was used for
 
853
  name-locking.
 
854
  link_in     true  - if Table object for table to be opened should be
 
855
  linked into Session::open_tables list.
 
856
  false - placeholder used for name-locking is already in
 
857
  this list so we only need to preserve Table::next
 
858
  pointer.
 
859
 
 
860
  NOTE
 
861
  This function assumes that its caller already acquired LOCK_open mutex.
 
862
 
 
863
  RETURN VALUE
 
864
  false - Success
 
865
  true  - Error
 
866
*/
 
867
 
 
868
bool Session::reopen_name_locked_table(TableList* table_list, bool link_in)
 
869
{
 
870
  Table *table= table_list->table;
 
871
  TableShare *share;
 
872
  char *table_name= table_list->table_name;
 
873
  Table orig_table;
 
874
 
 
875
  safe_mutex_assert_owner(&LOCK_open);
 
876
 
 
877
  if (killed || !table)
 
878
    return true;
 
879
 
 
880
  orig_table= *table;
 
881
 
 
882
  if (open_unireg_entry(this, table, table_list, table_name,
 
883
                        table->s->table_cache_key.str,
 
884
                        table->s->table_cache_key.length))
 
885
  {
 
886
    table->intern_close_table();
 
887
    /*
 
888
      If there was an error during opening of table (for example if it
 
889
      does not exist) '*table' object can be wiped out. To be able
 
890
      properly release name-lock in this case we should restore this
 
891
      object to its original state.
 
892
    */
 
893
    *table= orig_table;
 
894
    return true;
 
895
  }
 
896
 
 
897
  share= table->s;
 
898
  /*
 
899
    We want to prevent other connections from opening this table until end
 
900
    of statement as it is likely that modifications of table's metadata are
 
901
    not yet finished (for example CREATE TRIGGER have to change .TRG cursor,
 
902
    or we might want to drop table if CREATE TABLE ... SELECT fails).
 
903
    This also allows us to assume that no other connection will sneak in
 
904
    before we will get table-level lock on this table.
 
905
  */
 
906
  share->version=0;
 
907
  table->in_use = this;
 
908
 
 
909
  if (link_in)
 
910
  {
 
911
    table->next= open_tables;
 
912
    open_tables= table;
 
913
  }
 
914
  else
 
915
  {
 
916
    /*
 
917
      Table object should be already in Session::open_tables list so we just
 
918
      need to set Table::next correctly.
 
919
    */
 
920
    table->next= orig_table.next;
 
921
  }
 
922
 
 
923
  table->tablenr= current_tablenr++;
 
924
  table->used_fields= 0;
 
925
  table->const_table= 0;
 
926
  table->null_row= false;
 
927
  table->maybe_null= false;
 
928
  table->force_index= false;
 
929
  table->status= STATUS_NO_RECORD;
 
930
 
 
931
  return false;
778
932
}
779
933
 
780
934
 
791
945
  case of failure.
792
946
*/
793
947
 
794
 
table::Placeholder *Session::table_cache_insert_placeholder(const drizzled::TableIdentifier &arg)
 
948
Table *Session::table_cache_insert_placeholder(const char *key, uint32_t key_length)
795
949
{
796
 
  safe_mutex_assert_owner(table::Cache::singleton().mutex().native_handle());
 
950
  Table *table;
 
951
  TableShare *share;
 
952
  char *key_buff;
 
953
 
 
954
  safe_mutex_assert_owner(&LOCK_open);
797
955
 
798
956
  /*
799
957
    Create a table entry with the right key and with an old refresh version
 
958
    Note that we must use multi_malloc() here as this is freed by the
 
959
    table cache
800
960
  */
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))
 
961
  if (! memory::multi_malloc(true,
 
962
                             &table, sizeof(*table),
 
963
                             &share, sizeof(*share),
 
964
                             &key_buff, key_length,
 
965
                             NULL))
 
966
    return NULL;
 
967
 
 
968
  table->s= share;
 
969
  share->set_table_cache_key(key_buff, key, key_length);
 
970
  share->tmp_table= INTERNAL_TMP_TABLE;  // for intern_close_table
 
971
  table->in_use= this;
 
972
  table->locked_by_name=1;
 
973
 
 
974
  if (my_hash_insert(&open_cache, (unsigned char*)table))
805
975
  {
806
 
    delete table;
807
 
 
 
976
    free((unsigned char*) table);
808
977
    return NULL;
809
978
  }
810
979
 
833
1002
  @retval  true   Error occured (OOM)
834
1003
  @retval  false  Success. 'table' parameter set according to above rules.
835
1004
*/
836
 
bool Session::lock_table_name_if_not_cached(const TableIdentifier &identifier, Table **table)
 
1005
 
 
1006
bool Session::lock_table_name_if_not_cached(const char *new_db,
 
1007
                                            const char *table_name, Table **table)
837
1008
{
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())
 
1009
  char key[MAX_DBKEY_LENGTH];
 
1010
  char *key_pos= key;
 
1011
  uint32_t key_length;
 
1012
 
 
1013
  key_pos= strcpy(key_pos, new_db) + strlen(new_db);
 
1014
  key_pos= strcpy(key_pos+1, table_name) + strlen(table_name);
 
1015
  key_length= (uint32_t) (key_pos-key)+1;
 
1016
 
 
1017
  pthread_mutex_lock(&LOCK_open); /* Obtain a name lock even though table is not in cache (like for create table)  */
 
1018
 
 
1019
  if (hash_search(&open_cache, (unsigned char *)key, key_length))
847
1020
  {
 
1021
    pthread_mutex_unlock(&LOCK_open);
848
1022
    *table= 0;
849
1023
    return false;
850
1024
  }
851
 
 
852
 
  if (not (*table= table_cache_insert_placeholder(identifier)))
 
1025
  if (!(*table= table_cache_insert_placeholder(key, key_length)))
853
1026
  {
 
1027
    pthread_mutex_unlock(&LOCK_open);
854
1028
    return true;
855
1029
  }
856
1030
  (*table)->open_placeholder= true;
857
 
  (*table)->setNext(open_tables);
 
1031
  (*table)->next= open_tables;
858
1032
  open_tables= *table;
 
1033
  pthread_mutex_unlock(&LOCK_open);
859
1034
 
860
1035
  return false;
861
1036
}
896
1071
Table *Session::openTable(TableList *table_list, bool *refresh, uint32_t flags)
897
1072
{
898
1073
  Table *table;
 
1074
  char key[MAX_DBKEY_LENGTH];
 
1075
  unsigned int key_length;
899
1076
  const char *alias= table_list->alias;
 
1077
  HASH_SEARCH_STATE state;
900
1078
 
901
1079
  /* Parsing of partitioning information from .frm needs session->lex set up. */
902
1080
  assert(lex->is_lex_started);
909
1087
  if (check_stack_overrun(this, STACK_MIN_SIZE_FOR_OPEN, (unsigned char *)&alias))
910
1088
    return NULL;
911
1089
 
912
 
  if (getKilled())
 
1090
  if (killed)
913
1091
    return NULL;
914
1092
 
915
 
  TableIdentifier identifier(table_list->getSchemaName(), table_list->getTableName());
916
 
  const TableIdentifier::Key &key(identifier.getKey());
917
 
  table::CacheRange ppp;
 
1093
  key_length= table_list->create_table_def_key(key);
918
1094
 
919
1095
  /*
920
1096
    Unless requested otherwise, try to resolve this table in the list
923
1099
    same name. This block implements the behaviour.
924
1100
    TODO -> move this block into a separate function.
925
1101
  */
926
 
  bool reset= false;
927
 
  for (table= getTemporaryTables(); table ; table=table->getNext())
 
1102
  for (table= temporary_tables; table ; table=table->next)
928
1103
  {
929
 
    if (table->getShare()->getCacheKey() == key)
 
1104
    if (table->s->table_cache_key.length == key_length && !memcmp(table->s->table_cache_key.str, key, key_length))
930
1105
    {
931
1106
      /*
932
1107
        We're trying to use the same temporary table twice in a query.
936
1111
      */
937
1112
      if (table->query_id)
938
1113
      {
939
 
        my_error(ER_CANT_REOPEN_TABLE, MYF(0), table->getAlias());
 
1114
        my_error(ER_CANT_REOPEN_TABLE, MYF(0), table->alias);
940
1115
        return NULL;
941
1116
      }
942
1117
      table->query_id= getQueryId();
943
 
      reset= true;
944
 
      break;
945
 
    }
946
 
  }
947
 
 
948
 
  if (not reset)
949
 
  {
950
 
    if (flags & DRIZZLE_OPEN_TEMPORARY_ONLY)
951
 
    {
952
 
      my_error(ER_NO_SUCH_TABLE, MYF(0), table_list->getSchemaName(), table_list->getTableName());
953
 
      return NULL;
954
 
    }
955
 
 
 
1118
      goto reset;
 
1119
    }
 
1120
  }
 
1121
 
 
1122
  if (flags & DRIZZLE_OPEN_TEMPORARY_ONLY)
 
1123
  {
 
1124
    my_error(ER_NO_SUCH_TABLE, MYF(0), table_list->db, table_list->table_name);
 
1125
    return NULL;
 
1126
  }
 
1127
 
 
1128
  /*
 
1129
    If it's the first table from a list of tables used in a query,
 
1130
    remember refresh_version (the version of open_cache state).
 
1131
    If the version changes while we're opening the remaining tables,
 
1132
    we will have to back off, close all the tables opened-so-far,
 
1133
    and try to reopen them.
 
1134
 
 
1135
    Note-> refresh_version is currently changed only during FLUSH TABLES.
 
1136
  */
 
1137
  if (!open_tables)
 
1138
    version= refresh_version;
 
1139
  else if ((version != refresh_version) &&
 
1140
           ! (flags & DRIZZLE_LOCK_IGNORE_FLUSH))
 
1141
  {
 
1142
    /* Someone did a refresh while thread was opening tables */
 
1143
    if (refresh)
 
1144
      *refresh= true;
 
1145
 
 
1146
    return NULL;
 
1147
  }
 
1148
 
 
1149
  /*
 
1150
    Before we test the global cache, we test our local session cache.
 
1151
  */
 
1152
  if (cached_table)
 
1153
  {
 
1154
    assert(false); /* Not implemented yet */
 
1155
  }
 
1156
 
 
1157
  /*
 
1158
    Non pre-locked/LOCK TABLES mode, and the table is not temporary:
 
1159
    this is the normal use case.
 
1160
    Now we should:
 
1161
    - try to find the table in the table cache.
 
1162
    - if one of the discovered Table instances is name-locked
 
1163
    (table->s->version == 0) back off -- we have to wait
 
1164
    until no one holds a name lock on the table.
 
1165
    - if there is no such Table in the name cache, read the table definition
 
1166
    and insert it into the cache.
 
1167
    We perform all of the above under LOCK_open which currently protects
 
1168
    the open cache (also known as table cache) and table definitions stored
 
1169
    on disk.
 
1170
  */
 
1171
 
 
1172
  pthread_mutex_lock(&LOCK_open); /* Lock for FLUSH TABLES for open table */
 
1173
 
 
1174
  /*
 
1175
    Actually try to find the table in the open_cache.
 
1176
    The cache may contain several "Table" instances for the same
 
1177
    physical table. The instances that are currently "in use" by
 
1178
    some thread have their "in_use" member != NULL.
 
1179
    There is no good reason for having more than one entry in the
 
1180
    hash for the same physical table, except that we use this as
 
1181
    an implicit "pending locks queue" - see
 
1182
    wait_for_locked_table_names for details.
 
1183
  */
 
1184
  for (table= (Table*) hash_first(&open_cache, (unsigned char*) key, key_length,
 
1185
                                  &state);
 
1186
       table && table->in_use ;
 
1187
       table= (Table*) hash_next(&open_cache, (unsigned char*) key, key_length,
 
1188
                                 &state))
 
1189
  {
956
1190
    /*
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.
 
1191
      Here we flush tables marked for flush.
 
1192
      Normally, table->s->version contains the value of
 
1193
      refresh_version from the moment when this table was
 
1194
      (re-)opened and added to the cache.
 
1195
      If since then we did (or just started) FLUSH TABLES
 
1196
      statement, refresh_version has been increased.
 
1197
      For "name-locked" Table instances, table->s->version is set
 
1198
      to 0 (see lock_table_name for details).
 
1199
      In case there is a pending FLUSH TABLES or a name lock, we
 
1200
      need to back off and re-start opening tables.
 
1201
      If we do not back off now, we may dead lock in case of lock
 
1202
      order mismatch with some other thread:
 
1203
c1: name lock t1; -- sort of exclusive lock
 
1204
c2: open t2;      -- sort of shared lock
 
1205
c1: name lock t2; -- blocks
 
1206
c2: open t1; -- blocks
964
1207
    */
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 */
 
1208
    if (table->needs_reopen_or_name_lock())
 
1209
    {
 
1210
      if (flags & DRIZZLE_LOCK_IGNORE_FLUSH)
 
1211
      {
 
1212
        /* Force close at once after usage */
 
1213
        version= table->s->version;
 
1214
        continue;
 
1215
      }
 
1216
 
 
1217
      /* Avoid self-deadlocks by detecting self-dependencies. */
 
1218
      if (table->open_placeholder && table->in_use == this)
 
1219
      {
 
1220
        pthread_mutex_unlock(&LOCK_open);
 
1221
        my_error(ER_UPDATE_TABLE_USED, MYF(0), table->s->table_name.str);
 
1222
        return NULL;
 
1223
      }
 
1224
 
 
1225
      /*
 
1226
        Back off, part 1: mark the table as "unused" for the
 
1227
        purpose of name-locking by setting table->db_stat to 0. Do
 
1228
        that only for the tables in this thread that have an old
 
1229
        table->s->version (this is an optimization (?)).
 
1230
        table->db_stat == 0 signals wait_for_locked_table_names
 
1231
        that the tables in question are not used any more. See
 
1232
        table_is_used call for details.
 
1233
      */
 
1234
      close_old_data_files(false, false);
 
1235
 
 
1236
      /*
 
1237
        Back-off part 2: try to avoid "busy waiting" on the table:
 
1238
        if the table is in use by some other thread, we suspend
 
1239
        and wait till the operation is complete: when any
 
1240
        operation that juggles with table->s->version completes,
 
1241
        it broadcasts COND_refresh condition variable.
 
1242
        If 'old' table we met is in use by current thread we return
 
1243
        without waiting since in this situation it's this thread
 
1244
        which is responsible for broadcasting on COND_refresh
 
1245
        (and this was done already in Session::close_old_data_files()).
 
1246
        Good example of such situation is when we have statement
 
1247
        that needs two instances of table and FLUSH TABLES comes
 
1248
        after we open first instance but before we open second
 
1249
        instance.
 
1250
      */
 
1251
      if (table->in_use != this)
 
1252
      {
 
1253
        /* wait_for_conditionwill unlock LOCK_open for us */
 
1254
        wait_for_condition(&LOCK_open, &COND_refresh);
 
1255
      }
 
1256
      else
 
1257
      {
 
1258
        pthread_mutex_unlock(&LOCK_open);
 
1259
      }
 
1260
      /*
 
1261
        There is a refresh in progress for this table.
 
1262
        Signal the caller that it has to try again.
 
1263
      */
973
1264
      if (refresh)
974
1265
        *refresh= true;
975
 
 
976
1266
      return NULL;
977
1267
    }
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 */
 
1268
  }
 
1269
  if (table)
 
1270
  {
 
1271
    /* Unlink the table from "unused_tables" list. */
 
1272
    if (table == unused_tables)
 
1273
    {  // First unused
 
1274
      unused_tables=unused_tables->next; // Remove from link
 
1275
      if (table == unused_tables)
 
1276
        unused_tables= NULL;
985
1277
    }
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
 
 
 
1278
    table->prev->next=table->next; /* Remove from unused list */
 
1279
    table->next->prev=table->prev;
 
1280
    table->in_use= this;
 
1281
  }
 
1282
  else
 
1283
  {
 
1284
    /* Insert a new Table instance into the open cache */
 
1285
    int error;
 
1286
    /* Free cache if too big */
 
1287
    while (open_cache.records > table_cache_size && unused_tables)
 
1288
      hash_delete(&open_cache,(unsigned char*) unused_tables);
 
1289
 
 
1290
    if (table_list->create)
1002
1291
    {
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)
 
1292
      TableIdentifier  lock_table_identifier(table_list->db, table_list->table_name, STANDARD_TABLE);
 
1293
 
 
1294
      if (not plugin::StorageEngine::doesTableExist(*this, lock_table_identifier))
1020
1295
      {
1021
 
        table= (*iter).second;
1022
 
 
1023
 
        if (not table->in_use)
1024
 
          break;
1025
1296
        /*
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
 
1297
          Table to be created, so we need to create placeholder in table-cache.
1042
1298
        */
1043
 
        if (table->needs_reopen_or_name_lock())
 
1299
        if (!(table= table_cache_insert_placeholder(key, key_length)))
1044
1300
        {
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;
 
1301
          pthread_mutex_unlock(&LOCK_open);
1101
1302
          return NULL;
1102
1303
        }
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
 
 
 
1304
        /*
 
1305
          Link placeholder to the open tables list so it will be automatically
 
1306
          removed once tables are closed. Also mark it so it won't be ignored
 
1307
          by other trying to take name-lock.
 
1308
        */
 
1309
        table->open_placeholder= true;
 
1310
        table->next= open_tables;
 
1311
        open_tables= table;
 
1312
        pthread_mutex_unlock(&LOCK_open);
 
1313
 
 
1314
        return table ;
 
1315
      }
 
1316
      /* Table exists. Let us try to open it. */
 
1317
    }
 
1318
 
 
1319
    /* make a new table */
 
1320
    table= (Table *)malloc(sizeof(Table));
 
1321
    if (table == NULL)
 
1322
    {
 
1323
      pthread_mutex_unlock(&LOCK_open);
 
1324
      return NULL;
 
1325
    }
 
1326
 
 
1327
    error= open_unireg_entry(this, table, table_list, alias, key, key_length);
 
1328
    if (error != 0)
 
1329
    {
 
1330
      free(table);
 
1331
      pthread_mutex_unlock(&LOCK_open);
 
1332
      return NULL;
 
1333
    }
 
1334
    my_hash_insert(&open_cache, (unsigned char*) table);
 
1335
  }
 
1336
 
 
1337
  pthread_mutex_unlock(&LOCK_open);
 
1338
  if (refresh)
 
1339
  {
 
1340
    table->next= open_tables; /* Link into simple list */
 
1341
    open_tables=table;
 
1342
  }
 
1343
  table->reginfo.lock_type= TL_READ; /* Assume read */
 
1344
 
 
1345
reset:
 
1346
  assert(table->s->ref_count > 0 || table->s->tmp_table != STANDARD_TABLE);
 
1347
 
 
1348
  if (lex->need_correct_ident())
 
1349
    table->alias_name_used= my_strcasecmp(table_alias_charset,
 
1350
                                          table->s->table_name.str, alias);
1178
1351
  /* Fix alias if table name changes */
1179
 
  if (strcmp(table->getAlias(), alias))
 
1352
  if (strcmp(table->alias, alias))
1180
1353
  {
1181
 
    table->setAlias(alias);
 
1354
    uint32_t length=(uint32_t) strlen(alias)+1;
 
1355
    table->alias= (char*) realloc((char*) table->alias, length);
 
1356
    memcpy((void*) table->alias, alias, length);
1182
1357
  }
1183
1358
 
1184
1359
  /* These variables are also set in reopen_table() */
1189
1364
  table->maybe_null= false;
1190
1365
  table->force_index= false;
1191
1366
  table->status=STATUS_NO_RECORD;
1192
 
  table->insert_values.clear();
 
1367
  table->insert_values= 0;
1193
1368
  /* Catch wrong handling of the auto_increment_field_not_null. */
1194
1369
  assert(!table->auto_increment_field_not_null);
1195
1370
  table->auto_increment_field_not_null= false;
1196
1371
  if (table->timestamp_field)
1197
 
  {
1198
1372
    table->timestamp_field_type= table->timestamp_field->get_auto_set_type();
1199
 
  }
1200
1373
  table->pos_in_table_list= table_list;
1201
1374
  table->clear_column_bitmaps();
1202
1375
  assert(table->key_read == 0);
1205
1378
}
1206
1379
 
1207
1380
 
 
1381
/*
 
1382
  Reopen an table because the definition has changed.
 
1383
 
 
1384
  SYNOPSIS
 
1385
  reopen_table()
 
1386
  table Table object
 
1387
 
 
1388
  NOTES
 
1389
  The data cursor for the table is already closed and the share is released
 
1390
  The table has a 'dummy' share that mainly contains database and table name.
 
1391
 
 
1392
  RETURN
 
1393
  0  ok
 
1394
  1  error. The old table object is not changed.
 
1395
*/
 
1396
 
 
1397
bool reopen_table(Table *table)
 
1398
{
 
1399
  Table tmp;
 
1400
  bool error= 1;
 
1401
  Field **field;
 
1402
  uint32_t key,part;
 
1403
  TableList table_list;
 
1404
  Session *session= table->in_use;
 
1405
 
 
1406
  assert(table->s->ref_count == 0);
 
1407
  assert(!table->sort.io_cache);
 
1408
 
 
1409
#ifdef EXTRA_DEBUG
 
1410
  if (table->db_stat)
 
1411
    errmsg_printf(ERRMSG_LVL_ERROR, _("Table %s had a open data Cursor in reopen_table"),
 
1412
                  table->alias);
 
1413
#endif
 
1414
  table_list.db=         const_cast<char *>(table->s->getSchemaName());
 
1415
  table_list.table_name= table->s->table_name.str;
 
1416
  table_list.table=      table;
 
1417
 
 
1418
  if (wait_for_locked_table_names(session, &table_list))
 
1419
    return true;                             // Thread was killed
 
1420
 
 
1421
  if (open_unireg_entry(session, &tmp, &table_list,
 
1422
                        table->alias,
 
1423
                        table->s->table_cache_key.str,
 
1424
                        table->s->table_cache_key.length))
 
1425
    goto end;
 
1426
 
 
1427
  /* This list copies variables set by open_table */
 
1428
  tmp.tablenr=          table->tablenr;
 
1429
  tmp.used_fields=      table->used_fields;
 
1430
  tmp.const_table=      table->const_table;
 
1431
  tmp.null_row=         table->null_row;
 
1432
  tmp.maybe_null=       table->maybe_null;
 
1433
  tmp.status=           table->status;
 
1434
 
 
1435
  /* Get state */
 
1436
  tmp.in_use=           session;
 
1437
  tmp.reginfo.lock_type=table->reginfo.lock_type;
 
1438
 
 
1439
  /* Replace table in open list */
 
1440
  tmp.next=             table->next;
 
1441
  tmp.prev=             table->prev;
 
1442
 
 
1443
  if (table->cursor)
 
1444
    table->closefrm(true);              // close cursor, free everything
 
1445
 
 
1446
  *table= tmp;
 
1447
  table->default_column_bitmaps();
 
1448
  table->cursor->change_table_ptr(table, table->s);
 
1449
 
 
1450
  assert(table->alias != 0);
 
1451
  for (field=table->field ; *field ; field++)
 
1452
  {
 
1453
    (*field)->table= (*field)->orig_table= table;
 
1454
    (*field)->table_name= &table->alias;
 
1455
  }
 
1456
  for (key=0 ; key < table->s->keys ; key++)
 
1457
  {
 
1458
    for (part=0 ; part < table->key_info[key].usable_key_parts ; part++)
 
1459
      table->key_info[key].key_part[part].field->table= table;
 
1460
  }
 
1461
 
 
1462
  broadcast_refresh();
 
1463
  error= false;
 
1464
 
 
1465
end:
 
1466
  return(error);
 
1467
}
 
1468
 
 
1469
 
1208
1470
/**
1209
1471
  Close all instances of a table open by this thread and replace
1210
1472
  them with exclusive name-locks.
1222
1484
  the strings are used in a loop even after the share may be freed.
1223
1485
*/
1224
1486
 
1225
 
void Session::close_data_files_and_morph_locks(const TableIdentifier &identifier)
 
1487
void Session::close_data_files_and_morph_locks(const char *new_db, const char *new_table_name)
1226
1488
{
1227
 
  safe_mutex_assert_owner(table::Cache::singleton().mutex().native_handle()); /* Adjust locks at the end of ALTER TABLEL */
 
1489
  Table *table;
 
1490
 
 
1491
  safe_mutex_assert_owner(&LOCK_open); /* Adjust locks at the end of ALTER TABLEL */
1228
1492
 
1229
1493
  if (lock)
1230
1494
  {
1232
1496
      If we are not under LOCK TABLES we should have only one table
1233
1497
      open and locked so it makes sense to remove the lock at once.
1234
1498
    */
1235
 
    unlockTables(lock);
 
1499
    mysql_unlock_tables(this, lock);
1236
1500
    lock= 0;
1237
1501
  }
1238
1502
 
1241
1505
    for target table name if we process ALTER Table ... RENAME.
1242
1506
    So loop below makes sense even if we are not under LOCK TABLES.
1243
1507
  */
1244
 
  for (Table *table= open_tables; table ; table=table->getNext())
 
1508
  for (table= open_tables; table ; table=table->next)
1245
1509
  {
1246
 
    if (table->getShare()->getCacheKey() == identifier.getKey())
 
1510
    if (!strcmp(table->s->table_name.str, new_table_name) &&
 
1511
        !strcmp(table->s->getSchemaName(), new_db))
1247
1512
    {
1248
1513
      table->open_placeholder= true;
1249
1514
      close_handle_and_leave_table_as_lock(table);
1267
1532
  combination when one needs tables to be reopened (for
1268
1533
  example see openTablesLock()).
1269
1534
 
1270
 
  @note One should have lock on table::Cache::singleton().mutex() when calling this.
 
1535
  @note One should have lock on LOCK_open when calling this.
1271
1536
 
1272
1537
  @return false in case of success, true - otherwise.
1273
1538
*/
1274
1539
 
1275
 
bool Session::reopen_tables(bool get_locks, bool)
 
1540
bool Session::reopen_tables(bool get_locks, bool mark_share_as_old)
1276
1541
{
1277
1542
  Table *table,*next,**prev;
1278
1543
  Table **tables,**tables_ptr;                  // For locks
1284
1549
  if (open_tables == NULL)
1285
1550
    return false;
1286
1551
 
1287
 
  safe_mutex_assert_owner(table::Cache::singleton().mutex().native_handle());
 
1552
  safe_mutex_assert_owner(&LOCK_open);
1288
1553
  if (get_locks)
1289
1554
  {
1290
1555
    /*
1293
1558
    */
1294
1559
    uint32_t opens= 0;
1295
1560
 
1296
 
    for (table= open_tables; table ; table=table->getNext())
1297
 
    {
 
1561
    for (table= open_tables; table ; table=table->next)
1298
1562
      opens++;
1299
 
    }
1300
1563
    tables= new Table *[opens];
1301
1564
  }
1302
1565
  else
1303
 
  {
1304
1566
    tables= &open_tables;
1305
 
  }
1306
1567
  tables_ptr =tables;
1307
1568
 
1308
1569
  prev= &open_tables;
1309
1570
  for (table= open_tables; table ; table=next)
1310
1571
  {
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;
 
1572
    uint32_t db_stat= table->db_stat;
 
1573
    next= table->next;
 
1574
    if (!tables || (!db_stat && reopen_table(table)))
 
1575
    {
 
1576
      my_error(ER_CANT_REOPEN_TABLE, MYF(0), table->alias);
 
1577
      hash_delete(&open_cache,(unsigned char*) table);
 
1578
      error= 1;
 
1579
    }
 
1580
    else
 
1581
    {
 
1582
      *prev= table;
 
1583
      prev= &table->next;
 
1584
      /* Do not handle locks of MERGE children. */
 
1585
      if (get_locks && !db_stat)
 
1586
        *tables_ptr++= table;                   // need new lock on this
 
1587
      if (mark_share_as_old)
 
1588
      {
 
1589
        table->s->version= 0;
 
1590
        table->open_placeholder= false;
 
1591
      }
 
1592
    }
1316
1593
  }
1317
1594
  *prev=0;
1318
1595
  if (tables != tables_ptr)                     // Should we get back old locks
1319
1596
  {
1320
 
    DrizzleLock *local_lock;
 
1597
    DRIZZLE_LOCK *local_lock;
1321
1598
    /*
1322
1599
      We should always get these locks. Anyway, we must not go into
1323
 
      wait_for_tables() as it tries to acquire table::Cache::singleton().mutex(), which is
 
1600
      wait_for_tables() as it tries to acquire LOCK_open, which is
1324
1601
      already locked.
1325
1602
    */
1326
1603
    some_tables_deleted= false;
1327
1604
 
1328
 
    if ((local_lock= lockTables(tables, (uint32_t) (tables_ptr - tables),
1329
 
                                       flags, &not_used)))
 
1605
    if ((local_lock= mysql_lock_tables(this, tables, (uint32_t) (tables_ptr - tables),
 
1606
                                 flags, &not_used)))
1330
1607
    {
1331
1608
      /* unused */
1332
1609
    }
1345
1622
  if (get_locks && tables)
1346
1623
    delete [] tables;
1347
1624
 
1348
 
  locking::broadcast_refresh();
 
1625
  broadcast_refresh();
1349
1626
 
1350
1627
  return(error);
1351
1628
}
1371
1648
 
1372
1649
  Table *table= open_tables;
1373
1650
 
1374
 
  for (; table ; table=table->getNext())
 
1651
  for (; table ; table=table->next)
1375
1652
  {
1376
1653
    /*
1377
1654
      Reopen marked for flush.
1392
1669
              lock on it. This will also give them a chance to close their
1393
1670
              instances of this table.
1394
1671
            */
1395
 
            abortLock(ulcktbl);
1396
 
            removeLock(ulcktbl);
 
1672
            mysql_lock_abort(this, ulcktbl);
 
1673
            mysql_lock_remove(this, ulcktbl);
1397
1674
            ulcktbl->lock_count= 0;
1398
1675
          }
1399
1676
          if ((ulcktbl != table) && ulcktbl->db_stat)
1433
1710
    }
1434
1711
  }
1435
1712
  if (found)
1436
 
    locking::broadcast_refresh();
 
1713
    broadcast_refresh();
 
1714
}
 
1715
 
 
1716
 
 
1717
/*
 
1718
  Wait until all threads has closed the tables in the list
 
1719
  We have also to wait if there is thread that has a lock on this table even
 
1720
  if the table is closed
 
1721
*/
 
1722
 
 
1723
bool table_is_used(Table *table, bool wait_for_name_lock)
 
1724
{
 
1725
  do
 
1726
  {
 
1727
    char *key= table->s->table_cache_key.str;
 
1728
    uint32_t key_length= table->s->table_cache_key.length;
 
1729
 
 
1730
    HASH_SEARCH_STATE state;
 
1731
    for (Table *search= (Table*) hash_first(&open_cache, (unsigned char*) key,
 
1732
                                            key_length, &state);
 
1733
         search ;
 
1734
         search= (Table*) hash_next(&open_cache, (unsigned char*) key,
 
1735
                                    key_length, &state))
 
1736
    {
 
1737
      if (search->in_use == table->in_use)
 
1738
        continue;                               // Name locked by this thread
 
1739
      /*
 
1740
        We can't use the table under any of the following conditions:
 
1741
        - There is an name lock on it (Table is to be deleted or altered)
 
1742
        - If we are in flush table and we didn't execute the flush
 
1743
        - If the table engine is open and it's an old version
 
1744
        (We must wait until all engines are shut down to use the table)
 
1745
      */
 
1746
      if ( (search->locked_by_name && wait_for_name_lock) ||
 
1747
           (search->is_name_opened() && search->needs_reopen_or_name_lock()))
 
1748
        return 1;
 
1749
    }
 
1750
  } while ((table=table->next));
 
1751
  return 0;
1437
1752
}
1438
1753
 
1439
1754
 
1444
1759
  bool result;
1445
1760
 
1446
1761
  session->set_proc_info("Waiting for tables");
1447
 
  {
1448
 
    boost_unique_lock_t lock(table::Cache::singleton().mutex());
1449
 
    while (not session->getKilled())
1450
 
    {
1451
 
      session->some_tables_deleted= false;
1452
 
      session->close_old_data_files(false, dropping_tables != 0);
1453
 
      if (not table::Cache::singleton().areTablesUsed(session->open_tables, 1))
1454
 
      {
1455
 
        break;
1456
 
      }
1457
 
      COND_refresh.wait(lock);
1458
 
    }
1459
 
    if (session->getKilled())
1460
 
      result= true;                                     // aborted
1461
 
    else
1462
 
    {
1463
 
      /* Now we can open all tables without any interference */
1464
 
      session->set_proc_info("Reopen tables");
1465
 
      session->version= refresh_version;
1466
 
      result= session->reopen_tables(false, false);
1467
 
    }
1468
 
  }
 
1762
  pthread_mutex_lock(&LOCK_open); /* Lock for all tables to be refreshed */
 
1763
  while (!session->killed)
 
1764
  {
 
1765
    session->some_tables_deleted= false;
 
1766
    session->close_old_data_files(false, dropping_tables != 0);
 
1767
    if (!table_is_used(session->open_tables, 1))
 
1768
      break;
 
1769
    (void) pthread_cond_wait(&COND_refresh,&LOCK_open);
 
1770
  }
 
1771
  if (session->killed)
 
1772
    result= true;                                       // aborted
 
1773
  else
 
1774
  {
 
1775
    /* Now we can open all tables without any interference */
 
1776
    session->set_proc_info("Reopen tables");
 
1777
    session->version= refresh_version;
 
1778
    result= session->reopen_tables(false, false);
 
1779
  }
 
1780
  pthread_mutex_unlock(&LOCK_open);
1469
1781
  session->set_proc_info(0);
1470
1782
 
1471
1783
  return result;
1496
1808
*/
1497
1809
 
1498
1810
 
1499
 
Table *drop_locked_tables(Session *session, const drizzled::TableIdentifier &identifier)
 
1811
Table *drop_locked_tables(Session *session,const char *db, const char *table_name)
1500
1812
{
1501
1813
  Table *table,*next,**prev, *found= 0;
1502
1814
  prev= &session->open_tables;
1503
1815
 
1504
1816
  /*
1505
 
    Note that we need to hold table::Cache::singleton().mutex() while changing the
 
1817
    Note that we need to hold LOCK_open while changing the
1506
1818
    open_tables list. Another thread may work on it.
1507
 
    (See: table::Cache::singleton().removeTable(), mysql_wait_completed_table())
 
1819
    (See: remove_table_from_cache(), mysql_wait_completed_table())
1508
1820
    Closing a MERGE child before the parent would be fatal if the
1509
1821
    other thread tries to abort the MERGE lock in between.
1510
1822
  */
1511
1823
  for (table= session->open_tables; table ; table=next)
1512
1824
  {
1513
 
    next=table->getNext();
1514
 
    if (table->getShare()->getCacheKey() == identifier.getKey())
 
1825
    next=table->next;
 
1826
    if (!strcmp(table->s->table_name.str, table_name) &&
 
1827
        !strcmp(table->s->getSchemaName(), db))
1515
1828
    {
1516
 
      session->removeLock(table);
 
1829
      mysql_lock_remove(session, table);
1517
1830
 
1518
1831
      if (!found)
1519
1832
      {
1528
1841
      else
1529
1842
      {
1530
1843
        /* We already have a name lock, remove copy */
1531
 
        table::remove_table(static_cast<table::Concurrent *>(table));
 
1844
        hash_delete(&open_cache,(unsigned char*) table);
1532
1845
      }
1533
1846
    }
1534
1847
    else
1535
1848
    {
1536
1849
      *prev=table;
1537
 
      prev= table->getNextPtr();
 
1850
      prev= &table->next;
1538
1851
    }
1539
1852
  }
1540
1853
  *prev=0;
1541
1854
  if (found)
1542
 
    locking::broadcast_refresh();
 
1855
    broadcast_refresh();
1543
1856
 
1544
1857
  return(found);
1545
1858
}
1551
1864
  other threads trying to get the lock.
1552
1865
*/
1553
1866
 
1554
 
void abort_locked_tables(Session *session, const drizzled::TableIdentifier &identifier)
 
1867
void abort_locked_tables(Session *session,const char *db, const char *table_name)
1555
1868
{
1556
1869
  Table *table;
1557
 
  for (table= session->open_tables; table ; table= table->getNext())
 
1870
  for (table= session->open_tables; table ; table= table->next)
1558
1871
  {
1559
 
    if (table->getShare()->getCacheKey() == identifier.getKey())
 
1872
    if (!strcmp(table->s->table_name.str, table_name) &&
 
1873
        !strcmp(table->s->getSchemaName(), db))
1560
1874
    {
1561
1875
      /* If MERGE child, forward lock handling to parent. */
1562
 
      session->abortLock(table);
 
1876
      mysql_lock_abort(session, table);
1563
1877
      break;
1564
1878
    }
1565
1879
  }
1566
1880
}
1567
1881
 
 
1882
/*
 
1883
  Load a table definition from cursor and open unireg table
 
1884
 
 
1885
  SYNOPSIS
 
1886
  open_unireg_entry()
 
1887
  session                       Thread handle
 
1888
  entry         Store open table definition here
 
1889
  table_list            TableList with db, table_name
 
1890
  alias         Alias name
 
1891
  cache_key             Key for share_cache
 
1892
  cache_key_length      length of cache_key
 
1893
 
 
1894
  NOTES
 
1895
  Extra argument for open is taken from session->open_options
 
1896
  One must have a lock on LOCK_open when calling this function
 
1897
 
 
1898
  RETURN
 
1899
  0     ok
 
1900
#       Error
 
1901
*/
 
1902
 
 
1903
static int open_unireg_entry(Session *session, Table *entry, TableList *table_list,
 
1904
                             const char *alias,
 
1905
                             char *cache_key, uint32_t cache_key_length)
 
1906
{
 
1907
  int error;
 
1908
  TableShare *share;
 
1909
  uint32_t discover_retry_count= 0;
 
1910
 
 
1911
  safe_mutex_assert_owner(&LOCK_open);
 
1912
retry:
 
1913
  if (!(share= TableShare::getShare(session, table_list, cache_key,
 
1914
                                    cache_key_length,
 
1915
                                    table_list->i_s_requested_object,
 
1916
                                    &error)))
 
1917
    return 1;
 
1918
 
 
1919
  while ((error= open_table_from_share(session, share, alias,
 
1920
                                       (uint32_t) (HA_OPEN_KEYFILE |
 
1921
                                                   HA_OPEN_RNDFILE |
 
1922
                                                   HA_GET_INDEX |
 
1923
                                                   HA_TRY_READ_ONLY),
 
1924
                                       session->open_options, entry)))
 
1925
  {
 
1926
    if (error == 7)                             // Table def changed
 
1927
    {
 
1928
      share->version= 0;                        // Mark share as old
 
1929
      if (discover_retry_count++)               // Retry once
 
1930
        goto err;
 
1931
 
 
1932
      /*
 
1933
        TODO->
 
1934
        Here we should wait until all threads has released the table.
 
1935
        For now we do one retry. This may cause a deadlock if there
 
1936
        is other threads waiting for other tables used by this thread.
 
1937
 
 
1938
        Proper fix would be to if the second retry failed:
 
1939
        - Mark that table def changed
 
1940
        - Return from open table
 
1941
        - Close all tables used by this thread
 
1942
        - Start waiting that the share is released
 
1943
        - Retry by opening all tables again
 
1944
      */
 
1945
 
 
1946
      /*
 
1947
        TO BE FIXED
 
1948
        To avoid deadlock, only wait for release if no one else is
 
1949
        using the share.
 
1950
      */
 
1951
      if (share->ref_count != 1)
 
1952
        goto err;
 
1953
      /* Free share and wait until it's released by all threads */
 
1954
      TableShare::release(share);
 
1955
 
 
1956
      if (!session->killed)
 
1957
      {
 
1958
        drizzle_reset_errors(session, 1);         // Clear warnings
 
1959
        session->clear_error();                 // Clear error message
 
1960
        goto retry;
 
1961
      }
 
1962
      return 1;
 
1963
    }
 
1964
 
 
1965
    goto err;
 
1966
  }
 
1967
 
 
1968
  return 0;
 
1969
 
 
1970
err:
 
1971
  TableShare::release(share);
 
1972
 
 
1973
  return 1;
 
1974
}
 
1975
 
1568
1976
 
1569
1977
/*
1570
1978
  Open all tables in list
1632
2040
     * to see if it exists so that an unauthorized user cannot phish for
1633
2041
     * table/schema information via error messages
1634
2042
     */
1635
 
    TableIdentifier the_table(tables->getSchemaName(), tables->getTableName());
1636
2043
    if (not plugin::Authorization::isAuthorized(getSecurityContext(),
1637
 
                                                the_table))
 
2044
                                                string(tables->db),
 
2045
                                                string(tables->table_name)))
1638
2046
    {
1639
2047
      result= -1;                               // Fatal error
1640
2048
      break;
1680
2088
    {
1681
2089
      if (tables->lock_type == TL_WRITE_DEFAULT)
1682
2090
        tables->table->reginfo.lock_type= update_lock_default;
1683
 
      else if (tables->table->getShare()->getType() == message::Table::STANDARD)
 
2091
      else if (tables->table->s->tmp_table == STANDARD_TABLE)
1684
2092
        tables->table->reginfo.lock_type= tables->lock_type;
1685
2093
    }
1686
2094
  }
1742
2150
 
1743
2151
    assert(lock == 0);  // You must lock everything at once
1744
2152
    if ((table->reginfo.lock_type= lock_type) != TL_UNLOCK)
1745
 
      if (! (lock= lockTables(&table_list->table, 1, 0, &refresh)))
 
2153
      if (! (lock= mysql_lock_tables(this, &table_list->table, 1, 0, &refresh)))
1746
2154
        table= 0;
1747
2155
  }
1748
2156
 
1805
2213
      *(ptr++)= table->table;
1806
2214
  }
1807
2215
 
1808
 
  if (!(session->lock= session->lockTables(start, (uint32_t) (ptr - start), lock_flag, need_reopen)))
 
2216
  if (!(session->lock= mysql_lock_tables(session, start, (uint32_t) (ptr - start),
 
2217
                                         lock_flag, need_reopen)))
1809
2218
  {
1810
2219
    return -1;
1811
2220
  }
1834
2243
#  Table object
1835
2244
*/
1836
2245
 
1837
 
Table *Open_tables_state::open_temporary_table(const TableIdentifier &identifier,
1838
 
                                               bool link_in_list)
 
2246
Table *Session::open_temporary_table(TableIdentifier &identifier,
 
2247
                                     bool link_in_list)
1839
2248
{
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)
 
2249
  Table *new_tmp_table;
 
2250
  TableShare *share;
 
2251
  char cache_key[MAX_DBKEY_LENGTH], *saved_cache_key, *tmp_path;
 
2252
  uint32_t key_length, path_length;
 
2253
  TableList table_list;
 
2254
 
 
2255
  table_list.db=         (char*) identifier.getDBName();
 
2256
  table_list.table_name= (char*) identifier.getTableName();
 
2257
  /* Create the cache_key for temporary tables */
 
2258
  key_length= table_list.create_table_def_key(cache_key);
 
2259
  path_length= strlen(identifier.getPath());
 
2260
 
 
2261
  if (!(new_tmp_table= (Table*) malloc(sizeof(*new_tmp_table) + sizeof(*share) +
 
2262
                                       path_length + 1 + key_length)))
1848
2263
    return NULL;
1849
2264
 
 
2265
  share= (TableShare*) (new_tmp_table+1);
 
2266
  tmp_path= (char*) (share+1);
 
2267
  saved_cache_key= strcpy(tmp_path, identifier.getPath())+path_length+1;
 
2268
  memcpy(saved_cache_key, cache_key, key_length);
 
2269
 
 
2270
  share->init(saved_cache_key, key_length, strchr(saved_cache_key, '\0')+1, tmp_path);
 
2271
 
1850
2272
  /*
1851
2273
    First open the share, and then open the table from the share we just opened.
1852
2274
  */
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))
 
2275
  if (open_table_def(*this, share) ||
 
2276
      open_table_from_share(this, share, identifier.getTableName(),
 
2277
                            (uint32_t) (HA_OPEN_KEYFILE | HA_OPEN_RNDFILE |
 
2278
                                        HA_GET_INDEX),
 
2279
                            ha_open_options,
 
2280
                            new_tmp_table))
1859
2281
  {
1860
2282
    /* No need to lock share->mutex as this is not needed for tmp tables */
1861
 
    delete new_tmp_table->getMutableShare();
1862
 
    delete new_tmp_table;
1863
 
 
 
2283
    share->free_table_share();
 
2284
    free((char*) new_tmp_table);
1864
2285
    return 0;
1865
2286
  }
1866
2287
 
1867
2288
  new_tmp_table->reginfo.lock_type= TL_WRITE;    // Simulate locked
 
2289
  share->tmp_table= TEMP_TABLE;
1868
2290
 
1869
2291
  if (link_in_list)
1870
2292
  {
1871
2293
    /* growing temp list at the head */
1872
 
    new_tmp_table->setNext(this->temporary_tables);
1873
 
    if (new_tmp_table->getNext())
1874
 
    {
1875
 
      new_tmp_table->getNext()->setPrev(new_tmp_table);
1876
 
    }
 
2294
    new_tmp_table->next= this->temporary_tables;
 
2295
    if (new_tmp_table->next)
 
2296
      new_tmp_table->next->prev= new_tmp_table;
1877
2297
    this->temporary_tables= new_tmp_table;
1878
 
    this->temporary_tables->setPrev(0);
 
2298
    this->temporary_tables->prev= 0;
1879
2299
  }
1880
2300
  new_tmp_table->pos_in_table_list= 0;
1881
2301
 
1900
2320
{
1901
2321
  if (session->mark_used_columns != MARK_COLUMNS_NONE)
1902
2322
  {
1903
 
    boost::dynamic_bitset<> *current_bitmap= NULL;
 
2323
    MyBitmap *current_bitmap, *other_bitmap;
1904
2324
 
1905
2325
    /*
1906
2326
      We always want to register the used keys, as the column bitmap may have
1913
2333
    if (session->mark_used_columns == MARK_COLUMNS_READ)
1914
2334
    {
1915
2335
      current_bitmap= table->read_set;
 
2336
      other_bitmap=   table->write_set;
1916
2337
    }
1917
2338
    else
1918
2339
    {
1919
2340
      current_bitmap= table->write_set;
 
2341
      other_bitmap=   table->read_set;
1920
2342
    }
1921
2343
 
1922
 
    //if (current_bitmap->testAndSet(field->position()))
1923
 
    if (current_bitmap->test(field->position()))
 
2344
    if (current_bitmap->testAndSet(field->field_index))
1924
2345
    {
1925
2346
      if (session->mark_used_columns == MARK_COLUMNS_WRITE)
1926
2347
        session->dup_field= field;
1989
2410
    return NULL;
1990
2411
  {
1991
2412
    /* This is a base table. */
1992
 
    assert(nj_col->table_ref->table == nj_col->table_field->getTable());
 
2413
    assert(nj_col->table_ref->table == nj_col->table_field->table);
1993
2414
    found_field= nj_col->table_field;
1994
2415
    update_field_dependencies(session, found_field, nj_col->table_ref->table);
1995
2416
  }
2026
2447
  uint32_t cached_field_index= *cached_field_index_ptr;
2027
2448
 
2028
2449
  /* We assume here that table->field < NO_CACHED_FIELD_INDEX = UINT_MAX */
2029
 
  if (cached_field_index < table->getShare()->sizeFields() &&
 
2450
  if (cached_field_index < table->s->fields &&
2030
2451
      !my_strcasecmp(system_charset_info,
2031
 
                     table->getField(cached_field_index)->field_name, name))
2032
 
  {
2033
 
    field_ptr= table->getFields() + cached_field_index;
2034
 
  }
2035
 
  else if (table->getShare()->getNamedFieldSize())
2036
 
  {
2037
 
    field_ptr= table->getMutableShare()->getNamedField(std::string(name, length));
 
2452
                     table->field[cached_field_index]->field_name, name))
 
2453
    field_ptr= table->field + cached_field_index;
 
2454
  else if (table->s->name_hash.records)
 
2455
  {
 
2456
    field_ptr= (Field**) hash_search(&table->s->name_hash, (unsigned char*) name,
 
2457
                                     length);
2038
2458
    if (field_ptr)
2039
2459
    {
2040
2460
      /*
2041
2461
        field_ptr points to field in TableShare. Convert it to the matching
2042
2462
        field in table
2043
2463
      */
2044
 
      field_ptr= (table->getFields() + table->getShare()->positionFields(field_ptr));
 
2464
      field_ptr= (table->field + (field_ptr - table->s->field));
2045
2465
    }
2046
2466
  }
2047
2467
  else
2048
2468
  {
2049
 
    if (!(field_ptr= table->getFields()))
 
2469
    if (!(field_ptr= table->field))
2050
2470
      return((Field *)0);
2051
2471
    for (; *field_ptr; ++field_ptr)
2052
2472
      if (!my_strcasecmp(system_charset_info, (*field_ptr)->field_name, name))
2055
2475
 
2056
2476
  if (field_ptr && *field_ptr)
2057
2477
  {
2058
 
    *cached_field_index_ptr= field_ptr - table->getFields();
 
2478
    *cached_field_index_ptr= field_ptr - table->field;
2059
2479
    field= *field_ptr;
2060
2480
  }
2061
2481
  else
2062
2482
  {
2063
2483
    if (!allow_rowid ||
2064
2484
        my_strcasecmp(system_charset_info, name, "_rowid") ||
2065
 
        table->getShare()->rowid_field_offset == 0)
 
2485
        table->s->rowid_field_offset == 0)
2066
2486
      return((Field*) 0);
2067
 
    field= table->getField(table->getShare()->rowid_field_offset-1);
 
2487
    field= table->field[table->s->rowid_field_offset-1];
2068
2488
  }
2069
2489
 
2070
2490
  update_field_dependencies(session, field, table);
2143
2563
    inside the view, but we want to search directly in the view columns
2144
2564
    which are represented as a 'field_translation'.
2145
2565
 
2146
 
    TODO-> Ensure that table_name, db_name and tables->db always points to something !
 
2566
TODO: Ensure that table_name, db_name and tables->db always points to
 
2567
something !
2147
2568
  */
2148
2569
  if (/* Exclude nested joins. */
2149
 
      (!table_list->getNestedJoin()) &&
 
2570
      (!table_list->nested_join) &&
2150
2571
      /* Include merge views and information schema tables. */
2151
2572
      /*
2152
2573
        Test if the field qualifiers match the table reference we plan
2154
2575
      */
2155
2576
      table_name && table_name[0] &&
2156
2577
      (my_strcasecmp(table_alias_charset, table_list->alias, table_name) ||
2157
 
       (db_name && db_name[0] && table_list->getSchemaName() && table_list->getSchemaName()[0] &&
2158
 
        strcmp(db_name, table_list->getSchemaName()))))
 
2578
       (db_name && db_name[0] && table_list->db && table_list->db[0] &&
 
2579
        strcmp(db_name, table_list->db))))
2159
2580
    return 0;
2160
2581
 
2161
2582
  *actual_table= NULL;
2162
2583
 
2163
 
  if (!table_list->getNestedJoin())
 
2584
  if (!table_list->nested_join)
2164
2585
  {
2165
2586
    /* 'table_list' is a stored table. */
2166
2587
    assert(table_list->table);
2180
2601
    */
2181
2602
    if (table_name && table_name[0])
2182
2603
    {
2183
 
      List_iterator<TableList> it(table_list->getNestedJoin()->join_list);
 
2604
      List_iterator<TableList> it(table_list->nested_join->join_list);
2184
2605
      TableList *table;
2185
2606
      while ((table= it++))
2186
2607
      {
2228
2649
        field_to_set= fld;
2229
2650
      if (field_to_set)
2230
2651
      {
2231
 
        Table *table= field_to_set->getTable();
 
2652
        Table *table= field_to_set->table;
2232
2653
        if (session->mark_used_columns == MARK_COLUMNS_READ)
2233
 
          table->setReadSet(field_to_set->position());
 
2654
          table->setReadSet(field_to_set->field_index);
2234
2655
        else
2235
 
          table->setWriteSet(field_to_set->position());
 
2656
          table->setWriteSet(field_to_set->field_index);
2236
2657
      }
2237
2658
    }
2238
2659
  }
2474
2895
 
2475
2896
 
2476
2897
Item **
2477
 
find_item_in_list(Session *session,
2478
 
                  Item *find, List<Item> &items, uint32_t *counter,
 
2898
find_item_in_list(Item *find, List<Item> &items, uint32_t *counter,
2479
2899
                  find_item_error_report_type report_error,
2480
2900
                  enum_resolution_type *resolution)
2481
2901
{
2555
2975
            */
2556
2976
            if (report_error != IGNORE_ERRORS)
2557
2977
              my_error(ER_NON_UNIQ_ERROR, MYF(0),
2558
 
                       find->full_name(), session->where);
 
2978
                       find->full_name(), current_session->where);
2559
2979
            return (Item**) 0;
2560
2980
          }
2561
2981
          found_unaliased= li.ref();
2586
3006
              continue;                           // Same field twice
2587
3007
            if (report_error != IGNORE_ERRORS)
2588
3008
              my_error(ER_NON_UNIQ_ERROR, MYF(0),
2589
 
                       find->full_name(), session->where);
 
3009
                       find->full_name(), current_session->where);
2590
3010
            return (Item**) 0;
2591
3011
          }
2592
3012
          found= li.ref();
2638
3058
    {
2639
3059
      if (report_error != IGNORE_ERRORS)
2640
3060
        my_error(ER_NON_UNIQ_ERROR, MYF(0),
2641
 
                 find->full_name(), session->where);
 
3061
                 find->full_name(), current_session->where);
2642
3062
      return (Item **) 0;
2643
3063
    }
2644
3064
    if (found_unaliased)
2654
3074
  {
2655
3075
    if (report_error == REPORT_ALL_ERRORS)
2656
3076
      my_error(ER_BAD_FIELD_ERROR, MYF(0),
2657
 
               find->full_name(), session->where);
 
3077
               find->full_name(), current_session->where);
2658
3078
    return (Item **) 0;
2659
3079
  }
2660
3080
  else
2772
3192
    Leaf table references to which new natural join columns are added
2773
3193
    if the leaves are != NULL.
2774
3194
  */
2775
 
  TableList *leaf_1= (table_ref_1->getNestedJoin() &&
2776
 
                      ! table_ref_1->is_natural_join) ?
 
3195
  TableList *leaf_1= (table_ref_1->nested_join &&
 
3196
                      !table_ref_1->is_natural_join) ?
2777
3197
    NULL : table_ref_1;
2778
 
  TableList *leaf_2= (table_ref_2->getNestedJoin() &&
2779
 
                      ! table_ref_2->is_natural_join) ?
 
3198
  TableList *leaf_2= (table_ref_2->nested_join &&
 
3199
                      !table_ref_2->is_natural_join) ?
2780
3200
    NULL : table_ref_2;
2781
3201
 
2782
3202
  *found_using_fields= 0;
2788
3208
    /* true if field_name_1 is a member of using_fields */
2789
3209
    bool is_using_column_1;
2790
3210
    if (!(nj_col_1= it_1.get_or_create_column_ref(leaf_1)))
2791
 
      return(result);
 
3211
      goto err;
2792
3212
    field_name_1= nj_col_1->name();
2793
3213
    is_using_column_1= using_fields &&
2794
3214
      test_if_string_in_list(field_name_1, using_fields);
2806
3226
      Natural_join_column *cur_nj_col_2;
2807
3227
      const char *cur_field_name_2;
2808
3228
      if (!(cur_nj_col_2= it_2.get_or_create_column_ref(leaf_2)))
2809
 
        return(result);
 
3229
        goto err;
2810
3230
      cur_field_name_2= cur_nj_col_2->name();
2811
3231
 
2812
3232
      /*
2826
3246
            (found && (!using_fields || is_using_column_1)))
2827
3247
        {
2828
3248
          my_error(ER_NON_UNIQ_ERROR, MYF(0), field_name_1, session->where);
2829
 
          return(result);
 
3249
          goto err;
2830
3250
        }
2831
3251
        nj_col_2= cur_nj_col_2;
2832
3252
        found= true;
2859
3279
      Item_func_eq *eq_cond;
2860
3280
 
2861
3281
      if (!item_1 || !item_2)
2862
 
        return(result); // out of memory
 
3282
        goto err;                               // out of memory
2863
3283
 
2864
3284
      /*
2865
3285
        In the case of no_wrap_view_item == 0, the created items must be
2884
3304
      */
2885
3305
      if (set_new_item_local_context(session, item_ident_1, nj_col_1->table_ref) ||
2886
3306
          set_new_item_local_context(session, item_ident_2, nj_col_2->table_ref))
2887
 
        return(result);
 
3307
        goto err;
2888
3308
 
2889
3309
      if (!(eq_cond= new Item_func_eq(item_ident_1, item_ident_2)))
2890
 
        return(result);                               /* Out of memory. */
 
3310
        goto err;                               /* Out of memory. */
2891
3311
 
2892
3312
      /*
2893
3313
        Add the new equi-join condition to the ON clause. Notice that
2904
3324
      {
2905
3325
        Table *table_1= nj_col_1->table_ref->table;
2906
3326
        /* Mark field_1 used for table cache. */
2907
 
        table_1->setReadSet(field_1->position());
 
3327
        table_1->setReadSet(field_1->field_index);
2908
3328
        table_1->covering_keys&= field_1->part_of_key;
2909
3329
        table_1->merge_keys|= field_1->part_of_key;
2910
3330
      }
2912
3332
      {
2913
3333
        Table *table_2= nj_col_2->table_ref->table;
2914
3334
        /* Mark field_2 used for table cache. */
2915
 
        table_2->setReadSet(field_2->position());
 
3335
        table_2->setReadSet(field_2->field_index);
2916
3336
        table_2->covering_keys&= field_2->part_of_key;
2917
3337
        table_2->merge_keys|= field_2->part_of_key;
2918
3338
      }
2933
3353
  */
2934
3354
  result= false;
2935
3355
 
 
3356
err:
2936
3357
  return(result);
2937
3358
}
2938
3359
 
2974
3395
*/
2975
3396
 
2976
3397
static bool
2977
 
store_natural_using_join_columns(Session *session,
 
3398
store_natural_using_join_columns(Session *,
2978
3399
                                 TableList *natural_using_join,
2979
3400
                                 TableList *table_ref_1,
2980
3401
                                 TableList *table_ref_2,
2990
3411
 
2991
3412
  if (!(non_join_columns= new List<Natural_join_column>) ||
2992
3413
      !(natural_using_join->join_columns= new List<Natural_join_column>))
2993
 
  {
2994
 
    return(result);
2995
 
  }
 
3414
    goto err;
2996
3415
 
2997
3416
  /* Append the columns of the first join operand. */
2998
3417
  for (it_1.set(table_ref_1); !it_1.end_of_fields(); it_1.next())
3030
3449
        if (!(common_field= it++))
3031
3450
        {
3032
3451
          my_error(ER_BAD_FIELD_ERROR, MYF(0), using_field_name_ptr,
3033
 
                   session->where);
3034
 
          return(result);
 
3452
                   current_session->where);
 
3453
          goto err;
3035
3454
        }
3036
3455
        if (!my_strcasecmp(system_charset_info,
3037
3456
                           common_field->name(), using_field_name_ptr))
3059
3478
 
3060
3479
  result= false;
3061
3480
 
 
3481
err:
3062
3482
  return(result);
3063
3483
}
3064
3484
 
3101
3521
  bool result= true;
3102
3522
 
3103
3523
  /* Call the procedure recursively for each nested table reference. */
3104
 
  if (table_ref->getNestedJoin())
 
3524
  if (table_ref->nested_join)
3105
3525
  {
3106
 
    List_iterator_fast<TableList> nested_it(table_ref->getNestedJoin()->join_list);
 
3526
    List_iterator_fast<TableList> nested_it(table_ref->nested_join->join_list);
3107
3527
    TableList *same_level_left_neighbor= nested_it++;
3108
3528
    TableList *same_level_right_neighbor= NULL;
3109
3529
    /* Left/right-most neighbors, possibly at higher levels in the join tree. */
3128
3548
          cur_table_ref->outer_join & JOIN_TYPE_RIGHT)
3129
3549
      {
3130
3550
        /* This can happen only for JOIN ... ON. */
3131
 
        assert(table_ref->getNestedJoin()->join_list.elements == 2);
 
3551
        assert(table_ref->nested_join->join_list.elements == 2);
3132
3552
        std::swap(same_level_left_neighbor, cur_table_ref);
3133
3553
      }
3134
3554
 
3141
3561
      real_right_neighbor= (same_level_right_neighbor) ?
3142
3562
        same_level_right_neighbor : right_neighbor;
3143
3563
 
3144
 
      if (cur_table_ref->getNestedJoin() &&
 
3564
      if (cur_table_ref->nested_join &&
3145
3565
          store_top_level_join_columns(session, cur_table_ref,
3146
3566
                                       real_left_neighbor, real_right_neighbor))
3147
 
        return(result);
 
3567
        goto err;
3148
3568
      same_level_right_neighbor= cur_table_ref;
3149
3569
    }
3150
3570
  }
3155
3575
  */
3156
3576
  if (table_ref->is_natural_join)
3157
3577
  {
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);
 
3578
    assert(table_ref->nested_join &&
 
3579
           table_ref->nested_join->join_list.elements == 2);
 
3580
    List_iterator_fast<TableList> operand_it(table_ref->nested_join->join_list);
3161
3581
    /*
3162
3582
      Notice that the order of join operands depends on whether table_ref
3163
3583
      represents a LEFT or a RIGHT join. In a RIGHT join, the operands are
3176
3596
      std::swap(table_ref_1, table_ref_2);
3177
3597
    if (mark_common_columns(session, table_ref_1, table_ref_2,
3178
3598
                            using_fields, &found_using_fields))
3179
 
      return(result);
 
3599
      goto err;
3180
3600
 
3181
3601
    /*
3182
3602
      Swap the join operands back, so that we pick the columns of the second
3188
3608
    if (store_natural_using_join_columns(session, table_ref, table_ref_1,
3189
3609
                                         table_ref_2, using_fields,
3190
3610
                                         found_using_fields))
3191
 
      return(result);
 
3611
      goto err;
3192
3612
 
3193
3613
    /*
3194
3614
      Change NATURAL JOIN to JOIN ... ON. We do this for both operands
3221
3641
  }
3222
3642
  result= false; /* All is OK. */
3223
3643
 
 
3644
err:
3224
3645
  return(result);
3225
3646
}
3226
3647
 
3622
4043
    assert(tables->is_leaf_for_name_resolution());
3623
4044
 
3624
4045
    if ((table_name && my_strcasecmp(table_alias_charset, table_name, tables->alias)) ||
3625
 
        (db_name && strcasecmp(tables->getSchemaName(),db_name)))
 
4046
        (db_name && strcmp(tables->db,db_name)))
3626
4047
      continue;
3627
4048
 
3628
4049
    /*
3658
4079
      if ((field= field_iterator.field()))
3659
4080
      {
3660
4081
        /* Mark fields as used to allow storage engine to optimze access */
3661
 
        field->getTable()->setReadSet(field->position());
 
4082
        field->table->setReadSet(field->field_index);
3662
4083
        if (table)
3663
4084
        {
3664
4085
          table->covering_keys&= field->part_of_key;
3696
4117
      For NATURAL joins, used_tables is updated in the IF above.
3697
4118
    */
3698
4119
    if (table)
3699
 
      table->used_fields= table->getShare()->sizeFields();
 
4120
      table->used_fields= table->s->fields;
3700
4121
  }
3701
4122
  if (found)
3702
4123
    return false;
3786
4207
          goto err_no_arena;
3787
4208
        select_lex->cond_count++;
3788
4209
      }
3789
 
      embedding= embedded->getEmbedding();
 
4210
      embedding= embedded->embedding;
3790
4211
    }
3791
4212
    while (embedding &&
3792
 
           embedding->getNestedJoin()->join_list.head() == embedded);
 
4213
           embedding->nested_join->join_list.head() == embedded);
3793
4214
 
3794
4215
  }
3795
4216
  session->session_marker= save_session_marker;
3848
4269
      thus we safely can take table from the first field.
3849
4270
    */
3850
4271
    field= static_cast<Item_field *>(f++);
3851
 
    table= field->field->getTable();
 
4272
    table= field->field->table;
3852
4273
    table->auto_increment_field_not_null= false;
3853
4274
    f.rewind();
3854
4275
  }
3858
4279
    value= v++;
3859
4280
 
3860
4281
    Field *rfield= field->field;
3861
 
    table= rfield->getTable();
 
4282
    table= rfield->table;
3862
4283
 
3863
4284
    if (rfield == table->next_number_field)
3864
4285
      table->auto_increment_field_not_null= true;
3865
4286
    if ((value->save_in_field(rfield, 0) < 0) && !ignore_errors)
3866
4287
    {
3867
4288
      my_message(ER_UNKNOWN_ERROR, ER(ER_UNKNOWN_ERROR), MYF(0));
3868
 
      if (table)
3869
 
        table->auto_increment_field_not_null= false;
3870
 
 
3871
 
      return true;
 
4289
      goto err;
3872
4290
    }
3873
4291
  }
3874
4292
 
3875
4293
  return session->is_error();
 
4294
 
 
4295
err:
 
4296
  if (table)
 
4297
    table->auto_increment_field_not_null= false;
 
4298
 
 
4299
  return true;
3876
4300
}
3877
4301
 
3878
4302
 
3912
4336
      On INSERT or UPDATE fields are checked to be from the same table,
3913
4337
      thus we safely can take table from the first field.
3914
4338
    */
3915
 
    table= (*ptr)->getTable();
 
4339
    table= (*ptr)->table;
3916
4340
    table->auto_increment_field_not_null= false;
3917
4341
  }
3918
4342
  while ((field = *ptr++) && ! session->is_error())
3919
4343
  {
3920
4344
    value=v++;
3921
 
    table= field->getTable();
 
4345
    table= field->table;
3922
4346
    if (field == table->next_number_field)
3923
4347
      table->auto_increment_field_not_null= true;
3924
4348
    if (value->save_in_field(field, 0) < 0)
3925
 
    {
3926
 
      if (table)
3927
 
        table->auto_increment_field_not_null= false;
3928
 
 
3929
 
      return true;
3930
 
    }
 
4349
      goto err;
3931
4350
  }
3932
4351
 
3933
4352
  return(session->is_error());
 
4353
 
 
4354
err:
 
4355
  if (table)
 
4356
    table->auto_increment_field_not_null= false;
 
4357
 
 
4358
  return true;
3934
4359
}
3935
4360
 
3936
4361
 
3938
4363
{
3939
4364
  Session *session;
3940
4365
 
3941
 
  assert(drizzle_tmpdir.size());
 
4366
  assert(drizzle_tmpdir);
3942
4367
 
3943
4368
  if (!(session= new Session(plugin::Listen::getNullClient())))
3944
4369
    return true;
3945
4370
  session->thread_stack= (char*) &session;
3946
4371
  session->storeGlobals();
3947
4372
 
3948
 
  plugin::StorageEngine::removeLostTemporaryTables(*session, drizzle_tmpdir.c_str());
 
4373
  plugin::StorageEngine::removeLostTemporaryTables(*session, drizzle_tmpdir);
3949
4374
 
3950
4375
  delete session;
3951
4376
 
3958
4383
  unireg support functions
3959
4384
 *****************************************************************************/
3960
4385
 
3961
 
 
 
4386
/*
 
4387
  Invalidate any cache entries that are for some DB
 
4388
 
 
4389
  SYNOPSIS
 
4390
  remove_db_from_cache()
 
4391
  db            Database name. This will be in lower case if
 
4392
  lower_case_table_name is set
 
4393
 
 
4394
NOTE:
 
4395
We can't use hash_delete when looping hash_elements. We mark them first
 
4396
and afterwards delete those marked unused.
 
4397
*/
 
4398
 
 
4399
void remove_db_from_cache(const std::string schema_name)
 
4400
{
 
4401
  safe_mutex_assert_owner(&LOCK_open);
 
4402
 
 
4403
  for (uint32_t idx=0 ; idx < open_cache.records ; idx++)
 
4404
  {
 
4405
    Table *table=(Table*) hash_element(&open_cache,idx);
 
4406
    if (not strcmp(table->s->getSchemaName(), schema_name.c_str()))
 
4407
    {
 
4408
      table->s->version= 0L;                    /* Free when thread is ready */
 
4409
      if (not table->in_use)
 
4410
        relink_unused(table);
 
4411
    }
 
4412
  }
 
4413
  while (unused_tables && !unused_tables->s->version)
 
4414
    hash_delete(&open_cache,(unsigned char*) unused_tables);
 
4415
}
 
4416
 
 
4417
 
 
4418
/*
 
4419
  Mark all entries with the table as deleted to force an reopen of the table
 
4420
 
 
4421
  The table will be closed (not stored in cache) by the current thread when
 
4422
  close_thread_tables() is called.
 
4423
 
 
4424
  PREREQUISITES
 
4425
  Lock on LOCK_open()
 
4426
 
 
4427
  RETURN
 
4428
  0  This thread now have exclusive access to this table and no other thread
 
4429
  can access the table until close_thread_tables() is called.
 
4430
  1  Table is in use by another thread
 
4431
*/
 
4432
 
 
4433
bool remove_table_from_cache(Session *session, const char *db, const char *table_name,
 
4434
                             uint32_t flags)
 
4435
{
 
4436
  char key[MAX_DBKEY_LENGTH];
 
4437
  char *key_pos= key;
 
4438
  uint32_t key_length;
 
4439
  Table *table;
 
4440
  bool result= false; 
 
4441
  bool signalled= false;
 
4442
 
 
4443
  key_pos= strcpy(key_pos, db) + strlen(db);
 
4444
  key_pos= strcpy(key_pos+1, table_name) + strlen(table_name);
 
4445
  key_length= (uint32_t) (key_pos-key)+1;
 
4446
 
 
4447
  for (;;)
 
4448
  {
 
4449
    HASH_SEARCH_STATE state;
 
4450
    result= signalled= false;
 
4451
 
 
4452
    for (table= (Table*) hash_first(&open_cache, (unsigned char*) key, key_length,
 
4453
                                    &state);
 
4454
         table;
 
4455
         table= (Table*) hash_next(&open_cache, (unsigned char*) key, key_length,
 
4456
                                   &state))
 
4457
    {
 
4458
      Session *in_use;
 
4459
 
 
4460
      table->s->version=0L;             /* Free when thread is ready */
 
4461
      if (!(in_use=table->in_use))
 
4462
      {
 
4463
        relink_unused(table);
 
4464
      }
 
4465
      else if (in_use != session)
 
4466
      {
 
4467
        /*
 
4468
          Mark that table is going to be deleted from cache. This will
 
4469
          force threads that are in mysql_lock_tables() (but not yet
 
4470
          in thr_multi_lock()) to abort it's locks, close all tables and retry
 
4471
        */
 
4472
        in_use->some_tables_deleted= true;
 
4473
        if (table->is_name_opened())
 
4474
        {
 
4475
          result= true;
 
4476
        }
 
4477
        /*
 
4478
          Now we must abort all tables locks used by this thread
 
4479
          as the thread may be waiting to get a lock for another table.
 
4480
          Note that we need to hold LOCK_open while going through the
 
4481
          list. So that the other thread cannot change it. The other
 
4482
          thread must also hold LOCK_open whenever changing the
 
4483
          open_tables list. Aborting the MERGE lock after a child was
 
4484
          closed and before the parent is closed would be fatal.
 
4485
        */
 
4486
        for (Table *session_table= in_use->open_tables;
 
4487
             session_table ;
 
4488
             session_table= session_table->next)
 
4489
        {
 
4490
          /* Do not handle locks of MERGE children. */
 
4491
          if (session_table->db_stat)   // If table is open
 
4492
            signalled|= mysql_lock_abort_for_thread(session, session_table);
 
4493
        }
 
4494
      }
 
4495
      else
 
4496
        result= result || (flags & RTFC_OWNED_BY_Session_FLAG);
 
4497
    }
 
4498
    while (unused_tables && !unused_tables->s->version)
 
4499
      hash_delete(&open_cache,(unsigned char*) unused_tables);
 
4500
 
 
4501
    /* Remove table from table definition cache if it's not in use */
 
4502
    TableShare::release(key, key_length);
 
4503
 
 
4504
    if (result && (flags & RTFC_WAIT_OTHER_THREAD_FLAG))
 
4505
    {
 
4506
      /*
 
4507
        Signal any thread waiting for tables to be freed to
 
4508
        reopen their tables
 
4509
      */
 
4510
      broadcast_refresh();
 
4511
      if (!(flags & RTFC_CHECK_KILLED_FLAG) || !session->killed)
 
4512
      {
 
4513
        dropping_tables++;
 
4514
        if (likely(signalled))
 
4515
          (void) pthread_cond_wait(&COND_refresh, &LOCK_open);
 
4516
        else
 
4517
        {
 
4518
          struct timespec abstime;
 
4519
          /*
 
4520
            It can happen that another thread has opened the
 
4521
            table but has not yet locked any table at all. Since
 
4522
            it can be locked waiting for a table that our thread
 
4523
            has done LOCK Table x WRITE on previously, we need to
 
4524
            ensure that the thread actually hears our signal
 
4525
            before we go to sleep. Thus we wait for a short time
 
4526
            and then we retry another loop in the
 
4527
            remove_table_from_cache routine.
 
4528
          */
 
4529
          set_timespec(abstime, 10);
 
4530
          pthread_cond_timedwait(&COND_refresh, &LOCK_open, &abstime);
 
4531
        }
 
4532
        dropping_tables--;
 
4533
        continue;
 
4534
      }
 
4535
    }
 
4536
    break;
 
4537
  }
 
4538
  return result;
 
4539
}
3962
4540
 
3963
4541
 
3964
4542
/**