~drizzle-trunk/drizzle/development

« back to all changes in this revision

Viewing changes to drizzled/sql_base.cc

Fixed the clock_gettime test.

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
 
#include "drizzled/plugin/authorization.h"
56
 
#include "drizzled/table/temporary.h"
57
 
#include "drizzled/table/placeholder.h"
58
 
#include "drizzled/table/unused.h"
 
54
 
59
55
 
60
56
using namespace std;
61
 
 
62
 
namespace drizzled
63
 
{
 
57
using namespace drizzled;
64
58
 
65
59
extern bool volatile shutdown_in_progress;
66
60
 
 
61
bool drizzle_rm_tmp_tables();
 
62
 
 
63
/**
 
64
  @defgroup Data_Dictionary Data Dictionary
 
65
  @{
 
66
*/
 
67
Table *unused_tables;                           /* Used by mysql_test */
 
68
HASH open_cache;                                /* Used by mysql_test */
 
69
static int open_unireg_entry(Session *session, Table *entry, TableList *table_list,
 
70
                             const char *alias,
 
71
                             char *cache_key, uint32_t cache_key_length);
 
72
extern "C"
 
73
{
 
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
 
 
81
 
 
82
unsigned char *table_cache_key(const unsigned char *record,
 
83
                               size_t *length,
 
84
                               bool )
 
85
{
 
86
  Table *entry=(Table*) record;
 
87
  *length= entry->s->table_cache_key.length;
 
88
  return (unsigned char*) entry->s->table_cache_key.str;
 
89
}
 
90
 
 
91
 
67
92
bool table_cache_init(void)
68
93
{
69
 
  return false;
70
 
}
71
 
 
72
 
uint32_t cached_open_tables(void)
73
 
{
74
 
  return table::getCache().size();
 
94
  return hash_init(&open_cache, &my_charset_bin,
 
95
                   (size_t) table_cache_size+16,
 
96
                   0, 0, table_cache_key,
 
97
                   free_cache_entry, 0);
75
98
}
76
99
 
77
100
void table_cache_free(void)
78
101
{
79
102
  refresh_version++;                            // Force close of open tables
80
103
 
81
 
  table::getUnused().clear();
82
 
  table::getCache().clear();
83
 
}
 
104
  while (unused_tables)
 
105
    hash_delete(&open_cache,(unsigned char*) unused_tables);
 
106
 
 
107
  if (!open_cache.records)                      // Safety first
 
108
    hash_free(&open_cache);
 
109
}
 
110
 
 
111
uint32_t cached_open_tables(void)
 
112
{
 
113
  return open_cache.records;
 
114
}
 
115
 
84
116
 
85
117
/*
86
118
  Close cursor handle, but leave the table in the table cache
93
125
  By leaving the table in the table cache, it disallows any other thread
94
126
  to open the table
95
127
 
96
 
  session->getKilled() will be set if we run out of memory
 
128
  session->killed will be set if we run out of memory
97
129
 
98
130
  If closing a MERGE child, the calling function has to take care for
99
131
  closing the parent too, if necessary.
102
134
 
103
135
void close_handle_and_leave_table_as_lock(Table *table)
104
136
{
 
137
  TableShare *share, *old_share= table->s;
 
138
  char *key_buff;
 
139
  memory::Root *mem_root= &table->mem_root;
 
140
 
105
141
  assert(table->db_stat);
106
 
  assert(table->getShare()->getType() == message::Table::STANDARD);
107
142
 
108
143
  /*
109
144
    Make a local copy of the table share and free the current one.
110
145
    This has to be done to ensure that the table share is removed from
111
146
    the table defintion cache as soon as the last instance is removed
112
147
  */
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()));
 
148
  if (multi_alloc_root(mem_root,
 
149
                       &share, sizeof(*share),
 
150
                       &key_buff, old_share->table_cache_key.length,
 
151
                       NULL))
 
152
  {
 
153
    memset(share, 0, sizeof(*share));
 
154
    share->set_table_cache_key(key_buff, old_share->table_cache_key.str,
 
155
                               old_share->table_cache_key.length);
 
156
    share->tmp_table= INTERNAL_TMP_TABLE;       // for intern_close_table()
 
157
  }
118
158
 
119
159
  table->cursor->close();
120
160
  table->db_stat= 0;                            // Mark cursor closed
121
 
  TableShare::release(table->getMutableShare());
122
 
  table->setShare(share);
123
 
}
124
 
 
 
161
  TableShare::release(table->s);
 
162
  table->s= share;
 
163
  table->cursor->change_table_ptr(table, table->s);
 
164
}
 
165
 
 
166
 
 
167
 
 
168
/*
 
169
  Create a list for all open tables matching SQL expression
 
170
 
 
171
  SYNOPSIS
 
172
  list_open_tables()
 
173
  wild          SQL like expression
 
174
 
 
175
  NOTES
 
176
  One gets only a list of tables for which one has any kind of privilege.
 
177
  db and table names are allocated in result struct, so one doesn't need
 
178
  a lock on LOCK_open when traversing the return list.
 
179
 
 
180
  RETURN VALUES
 
181
  true  Error 
 
182
*/
 
183
 
 
184
bool list_open_tables(const char *db, 
 
185
                      const char *wild, 
 
186
                      bool(*func)(Table *table, 
 
187
                                  open_table_list_st& open_list,
 
188
                                  plugin::InfoSchemaTable *schema_table), 
 
189
                      Table *display,
 
190
                      plugin::InfoSchemaTable *schema_table)
 
191
{
 
192
  vector<open_table_list_st> open_list;
 
193
  vector<open_table_list_st>::iterator it;
 
194
  open_table_list_st table;
 
195
 
 
196
  /* What we really need is an optimization for knowing unique tables */
 
197
  if (db && wild)
 
198
    open_list.reserve(sizeof(open_table_list_st) * (open_cache.records % 2));
 
199
  else
 
200
    open_list.reserve(sizeof(open_table_list_st) * open_cache.records);
 
201
 
 
202
  pthread_mutex_lock(&LOCK_open); /* List all open tables */
 
203
 
 
204
  for (uint32_t idx= 0; idx < open_cache.records; idx++)
 
205
  {
 
206
    bool found= false;
 
207
    Table *entry=(Table*) hash_element(&open_cache,idx);
 
208
 
 
209
    if (db && my_strcasecmp(system_charset_info, db, entry->s->db.str))
 
210
      continue;
 
211
    if (wild && wild_compare(entry->s->table_name.str, wild, 0))
 
212
      continue;
 
213
 
 
214
    for (it= open_list.begin(); it < open_list.end(); it++)
 
215
    {
 
216
      if (!(*it).table.compare(entry->s->table_name.str) &&
 
217
          !(*it).db.compare(entry->s->db.str))
 
218
      {
 
219
        if (entry->in_use)
 
220
          (*it).in_use++;
 
221
        if (entry->locked_by_name)
 
222
          (*it).locked++;
 
223
 
 
224
        found= true;
 
225
 
 
226
        break;
 
227
      }
 
228
    }
 
229
 
 
230
    if (found)
 
231
      continue;
 
232
 
 
233
    table.db= entry->s->db.str;
 
234
    table.table= entry->s->table_name.str;
 
235
    open_list.push_back(table);
 
236
  }
 
237
  pthread_mutex_unlock(&LOCK_open);
 
238
 
 
239
  for (it= open_list.begin(); it < open_list.end(); it++)
 
240
  {
 
241
    if (func(display, *it, schema_table))
 
242
      return true;
 
243
  }
 
244
 
 
245
  return false;
 
246
}
125
247
 
126
248
/*****************************************************************************
127
249
 *       Functions to free open table cache
132
254
{                                               // Free all structures
133
255
  free_io_cache();
134
256
  if (cursor)                              // Not true if name lock
 
257
    closefrm(true);                     // close cursor
 
258
}
 
259
 
 
260
/*
 
261
  Remove table from the open table cache
 
262
 
 
263
  SYNOPSIS
 
264
  free_cache_entry()
 
265
  entry         Table to remove
 
266
 
 
267
  NOTE
 
268
  We need to have a lock on LOCK_open when calling this
 
269
*/
 
270
 
 
271
void free_cache_entry(void *entry)
 
272
{
 
273
  Table *table= static_cast<Table *>(entry);
 
274
  table->intern_close_table();
 
275
  if (!table->in_use)
135
276
  {
136
 
    delete_table(true);                 // close cursor
 
277
    table->next->prev=table->prev;              /* remove from used chain */
 
278
    table->prev->next=table->next;
 
279
    if (table == unused_tables)
 
280
    {
 
281
      unused_tables=unused_tables->next;
 
282
      if (table == unused_tables)
 
283
        unused_tables= NULL;
 
284
    }
137
285
  }
 
286
  free(table);
138
287
}
139
288
 
140
289
/* Free resources allocated by filesort() and read_record() */
143
292
{
144
293
  if (sort.io_cache)
145
294
  {
146
 
    sort.io_cache->close_cached_file();
 
295
    close_cached_file(sort.io_cache);
147
296
    delete sort.io_cache;
148
297
    sort.io_cache= 0;
149
298
  }
155
304
 
156
305
  @param session Thread context (may be NULL)
157
306
  @param tables List of tables to remove from the cache
158
 
  @param have_lock If table::Cache::singleton().mutex() is locked
 
307
  @param have_lock If LOCK_open is locked
159
308
  @param wait_for_refresh Wait for a impending flush
160
309
  @param wait_for_placeholders Wait for tables being reopened so that the GRL
161
310
  won't proceed while write-locked tables are being reopened by other
170
319
  bool result= false;
171
320
  Session *session= this;
172
321
 
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
 
      {
 
322
  pthread_mutex_lock(&LOCK_open); /* Optionally lock for remove tables from open_cahe if not in use */
 
323
 
 
324
  if (tables == NULL)
 
325
  {
 
326
    refresh_version++;                          // Force close of open tables
 
327
    while (unused_tables)
 
328
      hash_delete(&open_cache,(unsigned char*) unused_tables);
 
329
 
 
330
    if (wait_for_refresh)
 
331
    {
 
332
      /*
 
333
        Other threads could wait in a loop in open_and_lock_tables(),
 
334
        trying to lock one or more of our tables.
 
335
 
 
336
        If they wait for the locks in thr_multi_lock(), their lock
 
337
        request is aborted. They loop in open_and_lock_tables() and
 
338
        enter open_table(). Here they notice the table is refreshed and
 
339
        wait for COND_refresh. Then they loop again in
 
340
        openTablesLock() and this time open_table() succeeds. At
 
341
        this moment, if we (the FLUSH TABLES thread) are scheduled and
 
342
        on another FLUSH TABLES enter close_cached_tables(), they could
 
343
        awake while we sleep below, waiting for others threads (us) to
 
344
        close their open tables. If this happens, the other threads
 
345
        would find the tables unlocked. They would get the locks, one
 
346
        after the other, and could do their destructive work. This is an
 
347
        issue if we have LOCK TABLES in effect.
 
348
 
 
349
        The problem is that the other threads passed all checks in
 
350
        open_table() before we refresh the table.
 
351
 
 
352
        The fix for this problem is to set some_tables_deleted for all
 
353
        threads with open tables. These threads can still get their
 
354
        locks, but will immediately release them again after checking
 
355
        this variable. They will then loop in openTablesLock()
 
356
        again. There they will wait until we update all tables version
 
357
        below.
 
358
 
 
359
        Setting some_tables_deleted is done by remove_table_from_cache()
 
360
        in the other branch.
 
361
 
 
362
        In other words (reviewer suggestion): You need this setting of
 
363
        some_tables_deleted for the case when table was opened and all
 
364
        related checks were passed before incrementing refresh_version
 
365
        (which you already have) but attempt to lock the table happened
 
366
        after the call to Session::close_old_data_files() i.e. after removal of
 
367
        current thread locks.
 
368
      */
 
369
      for (uint32_t idx=0 ; idx < open_cache.records ; idx++)
 
370
      {
 
371
        Table *table=(Table*) hash_element(&open_cache,idx);
 
372
        if (table->in_use)
 
373
          table->in_use->some_tables_deleted= false;
 
374
      }
 
375
    }
 
376
  }
 
377
  else
 
378
  {
 
379
    bool found= false;
 
380
    for (TableList *table= tables; table; table= table->next_local)
 
381
    {
 
382
      if (remove_table_from_cache(session, table->db, table->table_name,
 
383
                                  RTFC_OWNED_BY_Session_FLAG))
 
384
        found= true;
 
385
    }
 
386
    if (!found)
 
387
      wait_for_refresh= false;                  // Nothing to wait for
 
388
  }
 
389
 
 
390
  if (wait_for_refresh)
 
391
  {
 
392
    /*
 
393
      If there is any table that has a lower refresh_version, wait until
 
394
      this is closed (or this thread is killed) before returning
 
395
    */
 
396
    session->mysys_var->current_mutex= &LOCK_open;
 
397
    session->mysys_var->current_cond= &COND_refresh;
 
398
    session->set_proc_info("Flushing tables");
 
399
 
 
400
    session->close_old_data_files();
 
401
 
 
402
    bool found= true;
 
403
    /* Wait until all threads has closed all the tables we had locked */
 
404
    while (found && ! session->killed)
 
405
    {
 
406
      found= false;
 
407
      for (uint32_t idx=0 ; idx < open_cache.records ; idx++)
 
408
      {
 
409
        Table *table=(Table*) hash_element(&open_cache,idx);
 
410
        /* Avoid a self-deadlock. */
 
411
        if (table->in_use == session)
 
412
          continue;
184
413
        /*
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.
 
414
          Note that we wait here only for tables which are actually open, and
 
415
          not for placeholders with Table::open_placeholder set. Waiting for
 
416
          latter will cause deadlock in the following scenario, for example:
 
417
 
 
418
conn1: lock table t1 write;
 
419
conn2: lock table t2 write;
 
420
conn1: flush tables;
 
421
conn2: flush tables;
 
422
 
 
423
It also does not make sense to wait for those of placeholders that
 
424
are employed by CREATE TABLE as in this case table simply does not
 
425
exist yet.
220
426
        */
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))
 
427
        if (table->needs_reopen_or_name_lock() && (table->db_stat ||
 
428
                                                   (table->open_placeholder && wait_for_placeholders)))
239
429
        {
240
430
          found= true;
 
431
          pthread_cond_wait(&COND_refresh,&LOCK_open);
 
432
          break;
241
433
        }
242
434
      }
243
 
      if (!found)
244
 
        wait_for_refresh= false;                        // Nothing to wait for
245
435
    }
 
436
    /*
 
437
      No other thread has the locked tables open; reopen them and get the
 
438
      old locks. This should always succeed (unless some external process
 
439
      has removed the tables)
 
440
    */
 
441
    result= session->reopen_tables(true, true);
246
442
 
247
 
    if (wait_for_refresh)
 
443
    /* Set version for table */
 
444
    for (Table *table= session->open_tables; table ; table= table->next)
248
445
    {
249
446
      /*
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
 
      }
 
447
        Preserve the version (0) of write locked tables so that a impending
 
448
        global read lock won't sneak in.
 
449
      */
 
450
      if (table->reginfo.lock_type < TL_WRITE_ALLOW_WRITE)
 
451
        table->s->version= refresh_version;
314
452
    }
315
 
 
316
 
    table::Cache::singleton().mutex().unlock();
317
453
  }
318
454
 
 
455
  pthread_mutex_unlock(&LOCK_open);
 
456
 
319
457
  if (wait_for_refresh)
320
458
  {
321
 
    boost_unique_lock_t scopedLock(session->mysys_var->mutex);
 
459
    pthread_mutex_lock(&session->mysys_var->mutex);
322
460
    session->mysys_var->current_mutex= 0;
323
461
    session->mysys_var->current_cond= 0;
324
462
    session->set_proc_info(0);
 
463
    pthread_mutex_unlock(&session->mysys_var->mutex);
325
464
  }
326
465
 
327
466
  return result;
335
474
bool Session::free_cached_table()
336
475
{
337
476
  bool found_old_table= false;
338
 
  table::Concurrent *table= static_cast<table::Concurrent *>(open_tables);
 
477
  Table *table= open_tables;
339
478
 
340
 
  safe_mutex_assert_owner(table::Cache::singleton().mutex().native_handle());
 
479
  safe_mutex_assert_owner(&LOCK_open);
341
480
  assert(table->key_read == 0);
342
481
  assert(!table->cursor || table->cursor->inited == Cursor::NONE);
343
482
 
344
 
  open_tables= table->getNext();
 
483
  open_tables= table->next;
345
484
 
346
485
  if (table->needs_reopen_or_name_lock() ||
347
486
      version != refresh_version || !table->db_stat)
348
487
  {
349
 
    table::remove_table(table);
 
488
    hash_delete(&open_cache,(unsigned char*) table);
350
489
    found_old_table= true;
351
490
  }
352
491
  else
355
494
      Open placeholders have Table::db_stat set to 0, so they should be
356
495
      handled by the first alternative.
357
496
    */
358
 
    assert(not table->open_placeholder);
 
497
    assert(!table->open_placeholder);
359
498
 
360
499
    /* Free memory and reset for next loop */
361
500
    table->cursor->ha_reset();
362
 
    table->in_use= NULL;
 
501
    table->in_use= false;
363
502
 
364
 
    table::getUnused().link(table);
 
503
    if (unused_tables)
 
504
    {
 
505
      table->next= unused_tables;               /* Link in last */
 
506
      table->prev= unused_tables->prev;
 
507
      unused_tables->prev= table;
 
508
      table->prev->next= table;
 
509
    }
 
510
    else
 
511
      unused_tables= table->next=table->prev=table;
365
512
  }
366
513
 
367
514
  return found_old_table;
380
527
{
381
528
  bool found_old_table= false;
382
529
 
383
 
  safe_mutex_assert_not_owner(table::Cache::singleton().mutex().native_handle());
 
530
  safe_mutex_assert_not_owner(&LOCK_open);
384
531
 
385
 
  boost_unique_lock_t scoped_lock(table::Cache::singleton().mutex()); /* Close all open tables on Session */
 
532
  pthread_mutex_lock(&LOCK_open); /* Close all open tables on Session */
386
533
 
387
534
  while (open_tables)
388
 
  {
389
535
    found_old_table|= free_cached_table();
390
 
  }
391
536
  some_tables_deleted= false;
392
537
 
393
538
  if (found_old_table)
394
539
  {
395
540
    /* Tell threads waiting for refresh that something has happened */
396
 
    locking::broadcast_refresh();
 
541
    broadcast_refresh();
397
542
  }
 
543
 
 
544
  pthread_mutex_unlock(&LOCK_open);
398
545
}
399
546
 
400
547
/*
422
569
{
423
570
  for (; table; table= table->*link )
424
571
  {
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)
 
572
    if ((table->table == 0 || table->table->s->tmp_table == NO_TMP_TABLE) &&
 
573
        strcmp(table->db, db_name) == 0 &&
 
574
        strcmp(table->table_name, table_name) == 0)
428
575
      break;
429
576
  }
430
577
  return table;
486
633
  if (table->table)
487
634
  {
488
635
    /* temporary table is always unique */
489
 
    if (table->table && table->table->getShare()->getType() != message::Table::STANDARD)
 
636
    if (table->table && table->table->s->tmp_table != NO_TMP_TABLE)
490
637
      return 0;
491
638
    table= table->find_underlying_table(table->table);
492
639
    /*
495
642
    */
496
643
    assert(table);
497
644
  }
498
 
  d_name= table->getSchemaName();
499
 
  t_name= table->getTableName();
 
645
  d_name= table->db;
 
646
  t_name= table->table_name;
500
647
  t_alias= table->alias;
501
648
 
502
649
  for (;;)
517
664
}
518
665
 
519
666
 
520
 
void Open_tables_state::doGetTableNames(const SchemaIdentifier &schema_identifier,
521
 
                                        std::set<std::string>& set_of_names)
522
 
{
523
 
  for (Table *table= getTemporaryTables() ; table ; table= table->getNext())
524
 
  {
525
 
    if (schema_identifier.compare(table->getShare()->getSchemaName()))
526
 
    {
527
 
      set_of_names.insert(table->getShare()->getTableName());
528
 
    }
529
 
  }
530
 
}
531
 
 
532
 
void Open_tables_state::doGetTableNames(CachedDirectory &,
533
 
                                        const SchemaIdentifier &schema_identifier,
534
 
                                        std::set<std::string> &set_of_names)
535
 
{
536
 
  doGetTableNames(schema_identifier, set_of_names);
537
 
}
538
 
 
539
 
void Open_tables_state::doGetTableIdentifiers(const SchemaIdentifier &schema_identifier,
540
 
                                              TableIdentifier::vector &set_of_identifiers)
541
 
{
542
 
  for (Table *table= getTemporaryTables() ; table ; table= table->getNext())
543
 
  {
544
 
    if (schema_identifier.compare(table->getShare()->getSchemaName()))
545
 
    {
546
 
      set_of_identifiers.push_back(TableIdentifier(table->getShare()->getSchemaName(),
547
 
                                                   table->getShare()->getTableName(),
548
 
                                                   table->getShare()->getPath()));
549
 
    }
550
 
  }
551
 
}
552
 
 
553
 
void Open_tables_state::doGetTableIdentifiers(CachedDirectory &,
554
 
                                              const SchemaIdentifier &schema_identifier,
555
 
                                              TableIdentifier::vector &set_of_identifiers)
556
 
{
557
 
  doGetTableIdentifiers(schema_identifier, set_of_identifiers);
558
 
}
559
 
 
560
 
bool Open_tables_state::doDoesTableExist(const TableIdentifier &identifier)
561
 
{
562
 
  for (Table *table= getTemporaryTables() ; table ; table= table->getNext())
563
 
  {
564
 
    if (table->getShare()->getType() == message::Table::TEMPORARY)
565
 
    {
566
 
      if (identifier.getKey() == table->getShare()->getCacheKey())
567
 
      {
568
 
        return true;
569
 
      }
570
 
    }
571
 
  }
572
 
 
573
 
  return false;
574
 
}
575
 
 
576
 
int Open_tables_state::doGetTableDefinition(const TableIdentifier &identifier,
577
 
                                  message::Table &table_proto)
578
 
{
579
 
  for (Table *table= getTemporaryTables() ; table ; table= table->getNext())
580
 
  {
581
 
    if (table->getShare()->getType() == message::Table::TEMPORARY)
582
 
    {
583
 
      if (identifier.getKey() == table->getShare()->getCacheKey())
584
 
      {
585
 
        table_proto.CopyFrom(*(table->getShare()->getTableProto()));
586
 
 
587
 
        return EEXIST;
588
 
      }
589
 
    }
590
 
  }
591
 
 
592
 
  return ENOENT;
593
 
}
594
 
 
595
 
Table *Open_tables_state::find_temporary_table(const TableIdentifier &identifier)
596
 
{
597
 
  for (Table *table= temporary_tables ; table ; table= table->getNext())
598
 
  {
599
 
    if (identifier.getKey() == table->getShare()->getCacheKey())
 
667
Table *Session::find_temporary_table(const char *new_db, const char *table_name)
 
668
{
 
669
  char  key[MAX_DBKEY_LENGTH];
 
670
  uint  key_length;
 
671
  Table *table;
 
672
 
 
673
  key_length= TableShare::createKey(key, new_db, table_name);
 
674
 
 
675
  for (table= temporary_tables ; table ; table= table->next)
 
676
  {
 
677
    if (table->s->table_cache_key.length == key_length &&
 
678
        !memcmp(table->s->table_cache_key.str, key, key_length))
600
679
      return table;
601
680
  }
602
 
 
603
681
  return NULL;                               // Not a temporary table
604
682
}
605
683
 
 
684
Table *Session::find_temporary_table(TableList *table_list)
 
685
{
 
686
  return find_temporary_table(table_list->db, table_list->table_name);
 
687
}
 
688
 
606
689
 
607
690
/**
608
691
  Drop a temporary table.
630
713
  @retval -1  the table is in use by a outer query
631
714
*/
632
715
 
633
 
int Open_tables_state::drop_temporary_table(const drizzled::TableIdentifier &identifier)
 
716
int Session::drop_temporary_table(TableList *table_list)
634
717
{
635
718
  Table *table;
636
719
 
637
 
  if (not (table= find_temporary_table(identifier)))
 
720
  if (!(table= find_temporary_table(table_list)))
638
721
    return 1;
639
722
 
640
723
  /* Table might be in use by some outer statement. */
641
 
  if (table->query_id && table->query_id != getQueryId())
 
724
  if (table->query_id && table->query_id != query_id)
642
725
  {
643
 
    my_error(ER_CANT_REOPEN_TABLE, MYF(0), table->getAlias());
 
726
    my_error(ER_CANT_REOPEN_TABLE, MYF(0), table->alias);
644
727
    return -1;
645
728
  }
646
729
 
650
733
}
651
734
 
652
735
 
 
736
/* move table first in unused links */
 
737
 
 
738
static void relink_unused(Table *table)
 
739
{
 
740
  if (table != unused_tables)
 
741
  {
 
742
    table->prev->next=table->next;              /* Remove from unused list */
 
743
    table->next->prev=table->prev;
 
744
    table->next=unused_tables;                  /* Link in unused tables */
 
745
    table->prev=unused_tables->prev;
 
746
    unused_tables->prev->next=table;
 
747
    unused_tables->prev=table;
 
748
    unused_tables=table;
 
749
  }
 
750
}
 
751
 
 
752
 
653
753
/**
654
754
  Remove all instances of table from thread's open list and
655
755
  table cache.
656
756
 
657
757
  @param  session     Thread context
658
758
  @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
759
*/
662
760
 
663
761
void Session::unlink_open_table(Table *find)
664
762
{
665
 
  const TableIdentifier::Key find_key(find->getShare()->getCacheKey());
666
 
  Table **prev;
667
 
  safe_mutex_assert_owner(table::Cache::singleton().mutex().native_handle());
668
 
 
 
763
  char key[MAX_DBKEY_LENGTH];
 
764
  uint32_t key_length= find->s->table_cache_key.length;
 
765
  Table *list, **prev;
 
766
 
 
767
  safe_mutex_assert_owner(&LOCK_open);
 
768
 
 
769
  memcpy(key, find->s->table_cache_key.str, key_length);
669
770
  /*
670
 
    Note that we need to hold table::Cache::singleton().mutex() while changing the
 
771
    Note that we need to hold LOCK_open while changing the
671
772
    open_tables list. Another thread may work on it.
672
 
    (See: table::Cache::singleton().removeTable(), mysql_wait_completed_table())
 
773
    (See: remove_table_from_cache(), mysql_wait_completed_table())
673
774
    Closing a MERGE child before the parent would be fatal if the
674
775
    other thread tries to abort the MERGE lock in between.
675
776
  */
676
777
  for (prev= &open_tables; *prev; )
677
778
  {
678
 
    Table *list= *prev;
 
779
    list= *prev;
679
780
 
680
 
    if (list->getShare()->getCacheKey() == find_key)
 
781
    if (list->s->table_cache_key.length == key_length &&
 
782
        !memcmp(list->s->table_cache_key.str, key, key_length))
681
783
    {
682
784
      /* Remove table from open_tables list. */
683
 
      *prev= list->getNext();
684
 
 
 
785
      *prev= list->next;
685
786
      /* Close table. */
686
 
      table::remove_table(static_cast<table::Concurrent *>(list));
 
787
      hash_delete(&open_cache,(unsigned char*) list); // Close table
687
788
    }
688
789
    else
689
790
    {
690
791
      /* Step to next entry in open_tables list. */
691
 
      prev= list->getNextPtr();
 
792
      prev= &list->next;
692
793
    }
693
794
  }
694
795
 
695
796
  // Notify any 'refresh' threads
696
 
  locking::broadcast_refresh();
 
797
  broadcast_refresh();
697
798
}
698
799
 
699
800
 
716
817
  table that was locked with LOCK TABLES.
717
818
*/
718
819
 
719
 
void Session::drop_open_table(Table *table, const TableIdentifier &identifier)
 
820
void Session::drop_open_table(Table *table, const char *db_name,
 
821
                              const char *table_name)
720
822
{
721
 
  if (table->getShare()->getType())
 
823
  if (table->s->tmp_table)
722
824
  {
723
825
    close_temporary_table(table);
724
826
  }
725
827
  else
726
828
  {
727
 
    boost_unique_lock_t scoped_lock(table::Cache::singleton().mutex()); /* Close and drop a table (AUX routine) */
 
829
    pthread_mutex_lock(&LOCK_open); /* Close and drop a table (AUX routine) */
728
830
    /*
729
831
      unlink_open_table() also tells threads waiting for refresh or close
730
832
      that something has happened.
731
833
    */
732
834
    unlink_open_table(table);
733
 
    plugin::StorageEngine::dropTable(*this, identifier);
 
835
    TableIdentifier identifier(db_name, table_name, NO_TMP_TABLE);
 
836
    quick_rm_table(*this, identifier);
 
837
    pthread_mutex_unlock(&LOCK_open);
734
838
  }
735
839
}
736
840
 
746
850
  cond  Condition to wait for
747
851
*/
748
852
 
749
 
void Session::wait_for_condition(boost::mutex &mutex, boost::condition_variable_any &cond)
 
853
void Session::wait_for_condition(pthread_mutex_t *mutex, pthread_cond_t *cond)
750
854
{
751
855
  /* Wait until the current table is up to date */
752
856
  const char *saved_proc_info;
753
 
  mysys_var->current_mutex= &mutex;
754
 
  mysys_var->current_cond= &cond;
 
857
  mysys_var->current_mutex= mutex;
 
858
  mysys_var->current_cond= cond;
755
859
  saved_proc_info= get_proc_info();
756
860
  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);
 
861
  if (!killed)
 
862
    (void) pthread_cond_wait(cond, mutex);
 
863
 
 
864
  /*
 
865
    We must unlock mutex first to avoid deadlock becasue conditions are
 
866
    sent to this thread by doing locks in the following order:
 
867
    lock(mysys_var->mutex)
 
868
    lock(mysys_var->current_mutex)
 
869
 
 
870
    One by effect of this that one can only use wait_for_condition with
 
871
    condition variables that are guranteed to not disapper (freed) even if this
 
872
    mutex is unlocked
 
873
  */
 
874
 
 
875
  pthread_mutex_unlock(mutex);
 
876
  pthread_mutex_lock(&mysys_var->mutex);
775
877
  mysys_var->current_mutex= 0;
776
878
  mysys_var->current_cond= 0;
777
879
  set_proc_info(saved_proc_info);
 
880
  pthread_mutex_unlock(&mysys_var->mutex);
 
881
}
 
882
 
 
883
 
 
884
/*
 
885
  Open table which is already name-locked by this thread.
 
886
 
 
887
  SYNOPSIS
 
888
  reopen_name_locked_table()
 
889
  session         Thread handle
 
890
  table_list  TableList object for table to be open, TableList::table
 
891
  member should point to Table object which was used for
 
892
  name-locking.
 
893
  link_in     true  - if Table object for table to be opened should be
 
894
  linked into Session::open_tables list.
 
895
  false - placeholder used for name-locking is already in
 
896
  this list so we only need to preserve Table::next
 
897
  pointer.
 
898
 
 
899
  NOTE
 
900
  This function assumes that its caller already acquired LOCK_open mutex.
 
901
 
 
902
  RETURN VALUE
 
903
  false - Success
 
904
  true  - Error
 
905
*/
 
906
 
 
907
bool Session::reopen_name_locked_table(TableList* table_list, bool link_in)
 
908
{
 
909
  Table *table= table_list->table;
 
910
  TableShare *share;
 
911
  char *table_name= table_list->table_name;
 
912
  Table orig_table;
 
913
 
 
914
  safe_mutex_assert_owner(&LOCK_open);
 
915
 
 
916
  if (killed || !table)
 
917
    return true;
 
918
 
 
919
  orig_table= *table;
 
920
 
 
921
  if (open_unireg_entry(this, table, table_list, table_name,
 
922
                        table->s->table_cache_key.str,
 
923
                        table->s->table_cache_key.length))
 
924
  {
 
925
    table->intern_close_table();
 
926
    /*
 
927
      If there was an error during opening of table (for example if it
 
928
      does not exist) '*table' object can be wiped out. To be able
 
929
      properly release name-lock in this case we should restore this
 
930
      object to its original state.
 
931
    */
 
932
    *table= orig_table;
 
933
    return true;
 
934
  }
 
935
 
 
936
  share= table->s;
 
937
  /*
 
938
    We want to prevent other connections from opening this table until end
 
939
    of statement as it is likely that modifications of table's metadata are
 
940
    not yet finished (for example CREATE TRIGGER have to change .TRG cursor,
 
941
    or we might want to drop table if CREATE TABLE ... SELECT fails).
 
942
    This also allows us to assume that no other connection will sneak in
 
943
    before we will get table-level lock on this table.
 
944
  */
 
945
  share->version=0;
 
946
  table->in_use = this;
 
947
 
 
948
  if (link_in)
 
949
  {
 
950
    table->next= open_tables;
 
951
    open_tables= table;
 
952
  }
 
953
  else
 
954
  {
 
955
    /*
 
956
      Table object should be already in Session::open_tables list so we just
 
957
      need to set Table::next correctly.
 
958
    */
 
959
    table->next= orig_table.next;
 
960
  }
 
961
 
 
962
  table->tablenr= current_tablenr++;
 
963
  table->used_fields= 0;
 
964
  table->const_table= 0;
 
965
  table->null_row= false;
 
966
  table->maybe_null= false;
 
967
  table->force_index= false;
 
968
  table->status= STATUS_NO_RECORD;
 
969
 
 
970
  return false;
778
971
}
779
972
 
780
973
 
791
984
  case of failure.
792
985
*/
793
986
 
794
 
table::Placeholder *Session::table_cache_insert_placeholder(const drizzled::TableIdentifier &arg)
 
987
Table *Session::table_cache_insert_placeholder(const char *key, uint32_t key_length)
795
988
{
796
 
  safe_mutex_assert_owner(table::Cache::singleton().mutex().native_handle());
 
989
  Table *table;
 
990
  TableShare *share;
 
991
  char *key_buff;
 
992
 
 
993
  safe_mutex_assert_owner(&LOCK_open);
797
994
 
798
995
  /*
799
996
    Create a table entry with the right key and with an old refresh version
 
997
    Note that we must use multi_malloc() here as this is freed by the
 
998
    table cache
800
999
  */
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))
 
1000
  if (! memory::multi_malloc(true,
 
1001
                             &table, sizeof(*table),
 
1002
                             &share, sizeof(*share),
 
1003
                             &key_buff, key_length,
 
1004
                             NULL))
 
1005
    return NULL;
 
1006
 
 
1007
  table->s= share;
 
1008
  share->set_table_cache_key(key_buff, key, key_length);
 
1009
  share->tmp_table= INTERNAL_TMP_TABLE;  // for intern_close_table
 
1010
  table->in_use= this;
 
1011
  table->locked_by_name=1;
 
1012
 
 
1013
  if (my_hash_insert(&open_cache, (unsigned char*)table))
805
1014
  {
806
 
    delete table;
807
 
 
 
1015
    free((unsigned char*) table);
808
1016
    return NULL;
809
1017
  }
810
1018
 
833
1041
  @retval  true   Error occured (OOM)
834
1042
  @retval  false  Success. 'table' parameter set according to above rules.
835
1043
*/
836
 
bool Session::lock_table_name_if_not_cached(const TableIdentifier &identifier, Table **table)
 
1044
 
 
1045
bool Session::lock_table_name_if_not_cached(const char *new_db,
 
1046
                                            const char *table_name, Table **table)
837
1047
{
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())
 
1048
  char key[MAX_DBKEY_LENGTH];
 
1049
  char *key_pos= key;
 
1050
  uint32_t key_length;
 
1051
 
 
1052
  key_pos= strcpy(key_pos, new_db) + strlen(new_db);
 
1053
  key_pos= strcpy(key_pos+1, table_name) + strlen(table_name);
 
1054
  key_length= (uint32_t) (key_pos-key)+1;
 
1055
 
 
1056
  pthread_mutex_lock(&LOCK_open); /* Obtain a name lock even though table is not in cache (like for create table)  */
 
1057
 
 
1058
  if (hash_search(&open_cache, (unsigned char *)key, key_length))
847
1059
  {
 
1060
    pthread_mutex_unlock(&LOCK_open);
848
1061
    *table= 0;
849
1062
    return false;
850
1063
  }
851
 
 
852
 
  if (not (*table= table_cache_insert_placeholder(identifier)))
 
1064
  if (!(*table= table_cache_insert_placeholder(key, key_length)))
853
1065
  {
 
1066
    pthread_mutex_unlock(&LOCK_open);
854
1067
    return true;
855
1068
  }
856
1069
  (*table)->open_placeholder= true;
857
 
  (*table)->setNext(open_tables);
 
1070
  (*table)->next= open_tables;
858
1071
  open_tables= *table;
 
1072
  pthread_mutex_unlock(&LOCK_open);
859
1073
 
860
1074
  return false;
861
1075
}
896
1110
Table *Session::openTable(TableList *table_list, bool *refresh, uint32_t flags)
897
1111
{
898
1112
  Table *table;
 
1113
  char key[MAX_DBKEY_LENGTH];
 
1114
  unsigned int key_length;
899
1115
  const char *alias= table_list->alias;
 
1116
  HASH_SEARCH_STATE state;
900
1117
 
901
1118
  /* Parsing of partitioning information from .frm needs session->lex set up. */
902
1119
  assert(lex->is_lex_started);
909
1126
  if (check_stack_overrun(this, STACK_MIN_SIZE_FOR_OPEN, (unsigned char *)&alias))
910
1127
    return NULL;
911
1128
 
912
 
  if (getKilled())
 
1129
  if (killed)
913
1130
    return NULL;
914
1131
 
915
 
  TableIdentifier identifier(table_list->getSchemaName(), table_list->getTableName());
916
 
  const TableIdentifier::Key &key(identifier.getKey());
917
 
  table::CacheRange ppp;
 
1132
  key_length= table_list->create_table_def_key(key);
918
1133
 
919
1134
  /*
920
1135
    Unless requested otherwise, try to resolve this table in the list
923
1138
    same name. This block implements the behaviour.
924
1139
    TODO -> move this block into a separate function.
925
1140
  */
926
 
  bool reset= false;
927
 
  for (table= getTemporaryTables(); table ; table=table->getNext())
 
1141
  for (table= temporary_tables; table ; table=table->next)
928
1142
  {
929
 
    if (table->getShare()->getCacheKey() == key)
 
1143
    if (table->s->table_cache_key.length == key_length && !memcmp(table->s->table_cache_key.str, key, key_length))
930
1144
    {
931
1145
      /*
932
1146
        We're trying to use the same temporary table twice in a query.
936
1150
      */
937
1151
      if (table->query_id)
938
1152
      {
939
 
        my_error(ER_CANT_REOPEN_TABLE, MYF(0), table->getAlias());
 
1153
        my_error(ER_CANT_REOPEN_TABLE, MYF(0), table->alias);
940
1154
        return NULL;
941
1155
      }
942
 
      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
 
 
 
1156
      table->query_id= query_id;
 
1157
      goto reset;
 
1158
    }
 
1159
  }
 
1160
 
 
1161
  if (flags & DRIZZLE_OPEN_TEMPORARY_ONLY)
 
1162
  {
 
1163
    my_error(ER_NO_SUCH_TABLE, MYF(0), table_list->db, table_list->table_name);
 
1164
    return NULL;
 
1165
  }
 
1166
 
 
1167
  /*
 
1168
    If it's the first table from a list of tables used in a query,
 
1169
    remember refresh_version (the version of open_cache state).
 
1170
    If the version changes while we're opening the remaining tables,
 
1171
    we will have to back off, close all the tables opened-so-far,
 
1172
    and try to reopen them.
 
1173
 
 
1174
    Note-> refresh_version is currently changed only during FLUSH TABLES.
 
1175
  */
 
1176
  if (!open_tables)
 
1177
    version= refresh_version;
 
1178
  else if ((version != refresh_version) &&
 
1179
           ! (flags & DRIZZLE_LOCK_IGNORE_FLUSH))
 
1180
  {
 
1181
    /* Someone did a refresh while thread was opening tables */
 
1182
    if (refresh)
 
1183
      *refresh= true;
 
1184
 
 
1185
    return NULL;
 
1186
  }
 
1187
 
 
1188
  /*
 
1189
    Before we test the global cache, we test our local session cache.
 
1190
  */
 
1191
  if (cached_table)
 
1192
  {
 
1193
    assert(false); /* Not implemented yet */
 
1194
  }
 
1195
 
 
1196
  /*
 
1197
    Non pre-locked/LOCK TABLES mode, and the table is not temporary:
 
1198
    this is the normal use case.
 
1199
    Now we should:
 
1200
    - try to find the table in the table cache.
 
1201
    - if one of the discovered Table instances is name-locked
 
1202
    (table->s->version == 0) back off -- we have to wait
 
1203
    until no one holds a name lock on the table.
 
1204
    - if there is no such Table in the name cache, read the table definition
 
1205
    and insert it into the cache.
 
1206
    We perform all of the above under LOCK_open which currently protects
 
1207
    the open cache (also known as table cache) and table definitions stored
 
1208
    on disk.
 
1209
  */
 
1210
 
 
1211
  pthread_mutex_lock(&LOCK_open); /* Lock for FLUSH TABLES for open table */
 
1212
 
 
1213
  /*
 
1214
    Actually try to find the table in the open_cache.
 
1215
    The cache may contain several "Table" instances for the same
 
1216
    physical table. The instances that are currently "in use" by
 
1217
    some thread have their "in_use" member != NULL.
 
1218
    There is no good reason for having more than one entry in the
 
1219
    hash for the same physical table, except that we use this as
 
1220
    an implicit "pending locks queue" - see
 
1221
    wait_for_locked_table_names for details.
 
1222
  */
 
1223
  for (table= (Table*) hash_first(&open_cache, (unsigned char*) key, key_length,
 
1224
                                  &state);
 
1225
       table && table->in_use ;
 
1226
       table= (Table*) hash_next(&open_cache, (unsigned char*) key, key_length,
 
1227
                                 &state))
 
1228
  {
956
1229
    /*
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.
 
1230
      Here we flush tables marked for flush.
 
1231
      Normally, table->s->version contains the value of
 
1232
      refresh_version from the moment when this table was
 
1233
      (re-)opened and added to the cache.
 
1234
      If since then we did (or just started) FLUSH TABLES
 
1235
      statement, refresh_version has been increased.
 
1236
      For "name-locked" Table instances, table->s->version is set
 
1237
      to 0 (see lock_table_name for details).
 
1238
      In case there is a pending FLUSH TABLES or a name lock, we
 
1239
      need to back off and re-start opening tables.
 
1240
      If we do not back off now, we may dead lock in case of lock
 
1241
      order mismatch with some other thread:
 
1242
c1: name lock t1; -- sort of exclusive lock
 
1243
c2: open t2;      -- sort of shared lock
 
1244
c1: name lock t2; -- blocks
 
1245
c2: open t1; -- blocks
964
1246
    */
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 */
 
1247
    if (table->needs_reopen_or_name_lock())
 
1248
    {
 
1249
      if (flags & DRIZZLE_LOCK_IGNORE_FLUSH)
 
1250
      {
 
1251
        /* Force close at once after usage */
 
1252
        version= table->s->version;
 
1253
        continue;
 
1254
      }
 
1255
 
 
1256
      /* Avoid self-deadlocks by detecting self-dependencies. */
 
1257
      if (table->open_placeholder && table->in_use == this)
 
1258
      {
 
1259
        pthread_mutex_unlock(&LOCK_open);
 
1260
        my_error(ER_UPDATE_TABLE_USED, MYF(0), table->s->table_name.str);
 
1261
        return NULL;
 
1262
      }
 
1263
 
 
1264
      /*
 
1265
        Back off, part 1: mark the table as "unused" for the
 
1266
        purpose of name-locking by setting table->db_stat to 0. Do
 
1267
        that only for the tables in this thread that have an old
 
1268
        table->s->version (this is an optimization (?)).
 
1269
        table->db_stat == 0 signals wait_for_locked_table_names
 
1270
        that the tables in question are not used any more. See
 
1271
        table_is_used call for details.
 
1272
      */
 
1273
      close_old_data_files(false, false);
 
1274
 
 
1275
      /*
 
1276
        Back-off part 2: try to avoid "busy waiting" on the table:
 
1277
        if the table is in use by some other thread, we suspend
 
1278
        and wait till the operation is complete: when any
 
1279
        operation that juggles with table->s->version completes,
 
1280
        it broadcasts COND_refresh condition variable.
 
1281
        If 'old' table we met is in use by current thread we return
 
1282
        without waiting since in this situation it's this thread
 
1283
        which is responsible for broadcasting on COND_refresh
 
1284
        (and this was done already in Session::close_old_data_files()).
 
1285
        Good example of such situation is when we have statement
 
1286
        that needs two instances of table and FLUSH TABLES comes
 
1287
        after we open first instance but before we open second
 
1288
        instance.
 
1289
      */
 
1290
      if (table->in_use != this)
 
1291
      {
 
1292
        /* wait_for_conditionwill unlock LOCK_open for us */
 
1293
        wait_for_condition(&LOCK_open, &COND_refresh);
 
1294
      }
 
1295
      else
 
1296
      {
 
1297
        pthread_mutex_unlock(&LOCK_open);
 
1298
      }
 
1299
      /*
 
1300
        There is a refresh in progress for this table.
 
1301
        Signal the caller that it has to try again.
 
1302
      */
973
1303
      if (refresh)
974
1304
        *refresh= true;
975
 
 
976
1305
      return NULL;
977
1306
    }
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 */
 
1307
  }
 
1308
  if (table)
 
1309
  {
 
1310
    /* Unlink the table from "unused_tables" list. */
 
1311
    if (table == unused_tables)
 
1312
    {  // First unused
 
1313
      unused_tables=unused_tables->next; // Remove from link
 
1314
      if (table == unused_tables)
 
1315
        unused_tables= NULL;
985
1316
    }
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
 
 
 
1317
    table->prev->next=table->next; /* Remove from unused list */
 
1318
    table->next->prev=table->prev;
 
1319
    table->in_use= this;
 
1320
  }
 
1321
  else
 
1322
  {
 
1323
    /* Insert a new Table instance into the open cache */
 
1324
    int error;
 
1325
    /* Free cache if too big */
 
1326
    while (open_cache.records > table_cache_size && unused_tables)
 
1327
      hash_delete(&open_cache,(unsigned char*) unused_tables);
 
1328
 
 
1329
    if (table_list->create)
1002
1330
    {
1003
 
      table::Cache::singleton().mutex().lock(); /* Lock for FLUSH TABLES for open table */
1004
 
 
1005
 
      /*
1006
 
        Actually try to find the table in the open_cache.
1007
 
        The cache may contain several "Table" instances for the same
1008
 
        physical table. The instances that are currently "in use" by
1009
 
        some thread have their "in_use" member != NULL.
1010
 
        There is no good reason for having more than one entry in the
1011
 
        hash for the same physical table, except that we use this as
1012
 
        an implicit "pending locks queue" - see
1013
 
        wait_for_locked_table_names for details.
1014
 
      */
1015
 
      ppp= table::getCache().equal_range(key);
1016
 
 
1017
 
      table= NULL;
1018
 
      for (table::CacheMap::const_iterator iter= ppp.first;
1019
 
           iter != ppp.second; ++iter, table= NULL)
 
1331
      TableIdentifier  lock_table_identifier(table_list->db, table_list->table_name, NO_TMP_TABLE);
 
1332
 
 
1333
      if (plugin::StorageEngine::getTableDefinition(*this, lock_table_identifier) != EEXIST)
1020
1334
      {
1021
 
        table= (*iter).second;
1022
 
 
1023
 
        if (not table->in_use)
1024
 
          break;
1025
1335
        /*
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
 
1336
          Table to be created, so we need to create placeholder in table-cache.
1042
1337
        */
1043
 
        if (table->needs_reopen_or_name_lock())
 
1338
        if (!(table= table_cache_insert_placeholder(key, key_length)))
1044
1339
        {
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;
 
1340
          pthread_mutex_unlock(&LOCK_open);
1101
1341
          return NULL;
1102
1342
        }
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
 
 
 
1343
        /*
 
1344
          Link placeholder to the open tables list so it will be automatically
 
1345
          removed once tables are closed. Also mark it so it won't be ignored
 
1346
          by other trying to take name-lock.
 
1347
        */
 
1348
        table->open_placeholder= true;
 
1349
        table->next= open_tables;
 
1350
        open_tables= table;
 
1351
        pthread_mutex_unlock(&LOCK_open);
 
1352
 
 
1353
        return table ;
 
1354
      }
 
1355
      /* Table exists. Let us try to open it. */
 
1356
    }
 
1357
 
 
1358
    /* make a new table */
 
1359
    table= (Table *)malloc(sizeof(Table));
 
1360
    if (table == NULL)
 
1361
    {
 
1362
      pthread_mutex_unlock(&LOCK_open);
 
1363
      return NULL;
 
1364
    }
 
1365
 
 
1366
    error= open_unireg_entry(this, table, table_list, alias, key, key_length);
 
1367
    if (error != 0)
 
1368
    {
 
1369
      free(table);
 
1370
      pthread_mutex_unlock(&LOCK_open);
 
1371
      return NULL;
 
1372
    }
 
1373
    my_hash_insert(&open_cache, (unsigned char*) table);
 
1374
  }
 
1375
 
 
1376
  pthread_mutex_unlock(&LOCK_open);
 
1377
  if (refresh)
 
1378
  {
 
1379
    table->next= open_tables; /* Link into simple list */
 
1380
    open_tables=table;
 
1381
  }
 
1382
  table->reginfo.lock_type= TL_READ; /* Assume read */
 
1383
 
 
1384
reset:
 
1385
  assert(table->s->ref_count > 0 || table->s->tmp_table != NO_TMP_TABLE);
 
1386
 
 
1387
  if (lex->need_correct_ident())
 
1388
    table->alias_name_used= my_strcasecmp(table_alias_charset,
 
1389
                                          table->s->table_name.str, alias);
1178
1390
  /* Fix alias if table name changes */
1179
 
  if (strcmp(table->getAlias(), alias))
 
1391
  if (strcmp(table->alias, alias))
1180
1392
  {
1181
 
    table->setAlias(alias);
 
1393
    uint32_t length=(uint32_t) strlen(alias)+1;
 
1394
    table->alias= (char*) realloc((char*) table->alias, length);
 
1395
    memcpy((void*) table->alias, alias, length);
1182
1396
  }
1183
1397
 
1184
1398
  /* These variables are also set in reopen_table() */
1189
1403
  table->maybe_null= false;
1190
1404
  table->force_index= false;
1191
1405
  table->status=STATUS_NO_RECORD;
1192
 
  table->insert_values.clear();
 
1406
  table->insert_values= 0;
1193
1407
  /* Catch wrong handling of the auto_increment_field_not_null. */
1194
1408
  assert(!table->auto_increment_field_not_null);
1195
1409
  table->auto_increment_field_not_null= false;
1196
1410
  if (table->timestamp_field)
1197
 
  {
1198
1411
    table->timestamp_field_type= table->timestamp_field->get_auto_set_type();
1199
 
  }
1200
1412
  table->pos_in_table_list= table_list;
1201
1413
  table->clear_column_bitmaps();
1202
1414
  assert(table->key_read == 0);
1205
1417
}
1206
1418
 
1207
1419
 
 
1420
/*
 
1421
  Reopen an table because the definition has changed.
 
1422
 
 
1423
  SYNOPSIS
 
1424
  reopen_table()
 
1425
  table Table object
 
1426
 
 
1427
  NOTES
 
1428
  The data cursor for the table is already closed and the share is released
 
1429
  The table has a 'dummy' share that mainly contains database and table name.
 
1430
 
 
1431
  RETURN
 
1432
  0  ok
 
1433
  1  error. The old table object is not changed.
 
1434
*/
 
1435
 
 
1436
bool reopen_table(Table *table)
 
1437
{
 
1438
  Table tmp;
 
1439
  bool error= 1;
 
1440
  Field **field;
 
1441
  uint32_t key,part;
 
1442
  TableList table_list;
 
1443
  Session *session= table->in_use;
 
1444
 
 
1445
  assert(table->s->ref_count == 0);
 
1446
  assert(!table->sort.io_cache);
 
1447
 
 
1448
#ifdef EXTRA_DEBUG
 
1449
  if (table->db_stat)
 
1450
    errmsg_printf(ERRMSG_LVL_ERROR, _("Table %s had a open data Cursor in reopen_table"),
 
1451
                  table->alias);
 
1452
#endif
 
1453
  table_list.db=         table->s->db.str;
 
1454
  table_list.table_name= table->s->table_name.str;
 
1455
  table_list.table=      table;
 
1456
 
 
1457
  if (wait_for_locked_table_names(session, &table_list))
 
1458
    return true;                             // Thread was killed
 
1459
 
 
1460
  if (open_unireg_entry(session, &tmp, &table_list,
 
1461
                        table->alias,
 
1462
                        table->s->table_cache_key.str,
 
1463
                        table->s->table_cache_key.length))
 
1464
    goto end;
 
1465
 
 
1466
  /* This list copies variables set by open_table */
 
1467
  tmp.tablenr=          table->tablenr;
 
1468
  tmp.used_fields=      table->used_fields;
 
1469
  tmp.const_table=      table->const_table;
 
1470
  tmp.null_row=         table->null_row;
 
1471
  tmp.maybe_null=       table->maybe_null;
 
1472
  tmp.status=           table->status;
 
1473
 
 
1474
  /* Get state */
 
1475
  tmp.in_use=           session;
 
1476
  tmp.reginfo.lock_type=table->reginfo.lock_type;
 
1477
 
 
1478
  /* Replace table in open list */
 
1479
  tmp.next=             table->next;
 
1480
  tmp.prev=             table->prev;
 
1481
 
 
1482
  if (table->cursor)
 
1483
    table->closefrm(true);              // close cursor, free everything
 
1484
 
 
1485
  *table= tmp;
 
1486
  table->default_column_bitmaps();
 
1487
  table->cursor->change_table_ptr(table, table->s);
 
1488
 
 
1489
  assert(table->alias != 0);
 
1490
  for (field=table->field ; *field ; field++)
 
1491
  {
 
1492
    (*field)->table= (*field)->orig_table= table;
 
1493
    (*field)->table_name= &table->alias;
 
1494
  }
 
1495
  for (key=0 ; key < table->s->keys ; key++)
 
1496
  {
 
1497
    for (part=0 ; part < table->key_info[key].usable_key_parts ; part++)
 
1498
      table->key_info[key].key_part[part].field->table= table;
 
1499
  }
 
1500
 
 
1501
  broadcast_refresh();
 
1502
  error= false;
 
1503
 
 
1504
end:
 
1505
  return(error);
 
1506
}
 
1507
 
 
1508
 
1208
1509
/**
1209
1510
  Close all instances of a table open by this thread and replace
1210
1511
  them with exclusive name-locks.
1222
1523
  the strings are used in a loop even after the share may be freed.
1223
1524
*/
1224
1525
 
1225
 
void Session::close_data_files_and_morph_locks(const TableIdentifier &identifier)
 
1526
void Session::close_data_files_and_morph_locks(const char *new_db, const char *new_table_name)
1226
1527
{
1227
 
  safe_mutex_assert_owner(table::Cache::singleton().mutex().native_handle()); /* Adjust locks at the end of ALTER TABLEL */
 
1528
  Table *table;
 
1529
 
 
1530
  safe_mutex_assert_owner(&LOCK_open); /* Adjust locks at the end of ALTER TABLEL */
1228
1531
 
1229
1532
  if (lock)
1230
1533
  {
1232
1535
      If we are not under LOCK TABLES we should have only one table
1233
1536
      open and locked so it makes sense to remove the lock at once.
1234
1537
    */
1235
 
    unlockTables(lock);
 
1538
    mysql_unlock_tables(this, lock);
1236
1539
    lock= 0;
1237
1540
  }
1238
1541
 
1241
1544
    for target table name if we process ALTER Table ... RENAME.
1242
1545
    So loop below makes sense even if we are not under LOCK TABLES.
1243
1546
  */
1244
 
  for (Table *table= open_tables; table ; table=table->getNext())
 
1547
  for (table= open_tables; table ; table=table->next)
1245
1548
  {
1246
 
    if (table->getShare()->getCacheKey() == identifier.getKey())
 
1549
    if (!strcmp(table->s->table_name.str, new_table_name) &&
 
1550
        !strcmp(table->s->db.str, new_db))
1247
1551
    {
1248
1552
      table->open_placeholder= true;
1249
1553
      close_handle_and_leave_table_as_lock(table);
1267
1571
  combination when one needs tables to be reopened (for
1268
1572
  example see openTablesLock()).
1269
1573
 
1270
 
  @note One should have lock on table::Cache::singleton().mutex() when calling this.
 
1574
  @note One should have lock on LOCK_open when calling this.
1271
1575
 
1272
1576
  @return false in case of success, true - otherwise.
1273
1577
*/
1274
1578
 
1275
 
bool Session::reopen_tables(bool get_locks, bool)
 
1579
bool Session::reopen_tables(bool get_locks, bool mark_share_as_old)
1276
1580
{
1277
1581
  Table *table,*next,**prev;
1278
1582
  Table **tables,**tables_ptr;                  // For locks
1284
1588
  if (open_tables == NULL)
1285
1589
    return false;
1286
1590
 
1287
 
  safe_mutex_assert_owner(table::Cache::singleton().mutex().native_handle());
 
1591
  safe_mutex_assert_owner(&LOCK_open);
1288
1592
  if (get_locks)
1289
1593
  {
1290
1594
    /*
1293
1597
    */
1294
1598
    uint32_t opens= 0;
1295
1599
 
1296
 
    for (table= open_tables; table ; table=table->getNext())
1297
 
    {
 
1600
    for (table= open_tables; table ; table=table->next)
1298
1601
      opens++;
1299
 
    }
1300
1602
    tables= new Table *[opens];
1301
1603
  }
1302
1604
  else
1303
 
  {
1304
1605
    tables= &open_tables;
1305
 
  }
1306
1606
  tables_ptr =tables;
1307
1607
 
1308
1608
  prev= &open_tables;
1309
1609
  for (table= open_tables; table ; table=next)
1310
1610
  {
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;
 
1611
    uint32_t db_stat= table->db_stat;
 
1612
    next= table->next;
 
1613
    if (!tables || (!db_stat && reopen_table(table)))
 
1614
    {
 
1615
      my_error(ER_CANT_REOPEN_TABLE, MYF(0), table->alias);
 
1616
      hash_delete(&open_cache,(unsigned char*) table);
 
1617
      error= 1;
 
1618
    }
 
1619
    else
 
1620
    {
 
1621
      *prev= table;
 
1622
      prev= &table->next;
 
1623
      /* Do not handle locks of MERGE children. */
 
1624
      if (get_locks && !db_stat)
 
1625
        *tables_ptr++= table;                   // need new lock on this
 
1626
      if (mark_share_as_old)
 
1627
      {
 
1628
        table->s->version= 0;
 
1629
        table->open_placeholder= false;
 
1630
      }
 
1631
    }
1316
1632
  }
1317
1633
  *prev=0;
1318
1634
  if (tables != tables_ptr)                     // Should we get back old locks
1319
1635
  {
1320
 
    DrizzleLock *local_lock;
 
1636
    DRIZZLE_LOCK *local_lock;
1321
1637
    /*
1322
1638
      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
 
1639
      wait_for_tables() as it tries to acquire LOCK_open, which is
1324
1640
      already locked.
1325
1641
    */
1326
1642
    some_tables_deleted= false;
1327
1643
 
1328
 
    if ((local_lock= lockTables(tables, (uint32_t) (tables_ptr - tables),
1329
 
                                       flags, &not_used)))
 
1644
    if ((local_lock= mysql_lock_tables(this, tables, (uint32_t) (tables_ptr - tables),
 
1645
                                 flags, &not_used)))
1330
1646
    {
1331
1647
      /* unused */
1332
1648
    }
1345
1661
  if (get_locks && tables)
1346
1662
    delete [] tables;
1347
1663
 
1348
 
  locking::broadcast_refresh();
 
1664
  broadcast_refresh();
1349
1665
 
1350
1666
  return(error);
1351
1667
}
1371
1687
 
1372
1688
  Table *table= open_tables;
1373
1689
 
1374
 
  for (; table ; table=table->getNext())
 
1690
  for (; table ; table=table->next)
1375
1691
  {
1376
1692
    /*
1377
1693
      Reopen marked for flush.
1392
1708
              lock on it. This will also give them a chance to close their
1393
1709
              instances of this table.
1394
1710
            */
1395
 
            abortLock(ulcktbl);
1396
 
            removeLock(ulcktbl);
 
1711
            mysql_lock_abort(this, ulcktbl);
 
1712
            mysql_lock_remove(this, ulcktbl);
1397
1713
            ulcktbl->lock_count= 0;
1398
1714
          }
1399
1715
          if ((ulcktbl != table) && ulcktbl->db_stat)
1433
1749
    }
1434
1750
  }
1435
1751
  if (found)
1436
 
    locking::broadcast_refresh();
 
1752
    broadcast_refresh();
 
1753
}
 
1754
 
 
1755
 
 
1756
/*
 
1757
  Wait until all threads has closed the tables in the list
 
1758
  We have also to wait if there is thread that has a lock on this table even
 
1759
  if the table is closed
 
1760
*/
 
1761
 
 
1762
bool table_is_used(Table *table, bool wait_for_name_lock)
 
1763
{
 
1764
  do
 
1765
  {
 
1766
    char *key= table->s->table_cache_key.str;
 
1767
    uint32_t key_length= table->s->table_cache_key.length;
 
1768
 
 
1769
    HASH_SEARCH_STATE state;
 
1770
    for (Table *search= (Table*) hash_first(&open_cache, (unsigned char*) key,
 
1771
                                            key_length, &state);
 
1772
         search ;
 
1773
         search= (Table*) hash_next(&open_cache, (unsigned char*) key,
 
1774
                                    key_length, &state))
 
1775
    {
 
1776
      if (search->in_use == table->in_use)
 
1777
        continue;                               // Name locked by this thread
 
1778
      /*
 
1779
        We can't use the table under any of the following conditions:
 
1780
        - There is an name lock on it (Table is to be deleted or altered)
 
1781
        - If we are in flush table and we didn't execute the flush
 
1782
        - If the table engine is open and it's an old version
 
1783
        (We must wait until all engines are shut down to use the table)
 
1784
      */
 
1785
      if ( (search->locked_by_name && wait_for_name_lock) ||
 
1786
           (search->is_name_opened() && search->needs_reopen_or_name_lock()))
 
1787
        return 1;
 
1788
    }
 
1789
  } while ((table=table->next));
 
1790
  return 0;
1437
1791
}
1438
1792
 
1439
1793
 
1444
1798
  bool result;
1445
1799
 
1446
1800
  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
 
  }
 
1801
  pthread_mutex_lock(&LOCK_open); /* Lock for all tables to be refreshed */
 
1802
  while (!session->killed)
 
1803
  {
 
1804
    session->some_tables_deleted= false;
 
1805
    session->close_old_data_files(false, dropping_tables != 0);
 
1806
    if (!table_is_used(session->open_tables, 1))
 
1807
      break;
 
1808
    (void) pthread_cond_wait(&COND_refresh,&LOCK_open);
 
1809
  }
 
1810
  if (session->killed)
 
1811
    result= true;                                       // aborted
 
1812
  else
 
1813
  {
 
1814
    /* Now we can open all tables without any interference */
 
1815
    session->set_proc_info("Reopen tables");
 
1816
    session->version= refresh_version;
 
1817
    result= session->reopen_tables(false, false);
 
1818
  }
 
1819
  pthread_mutex_unlock(&LOCK_open);
1469
1820
  session->set_proc_info(0);
1470
1821
 
1471
1822
  return result;
1496
1847
*/
1497
1848
 
1498
1849
 
1499
 
Table *drop_locked_tables(Session *session, const drizzled::TableIdentifier &identifier)
 
1850
Table *drop_locked_tables(Session *session,const char *db, const char *table_name)
1500
1851
{
1501
1852
  Table *table,*next,**prev, *found= 0;
1502
1853
  prev= &session->open_tables;
1503
1854
 
1504
1855
  /*
1505
 
    Note that we need to hold table::Cache::singleton().mutex() while changing the
 
1856
    Note that we need to hold LOCK_open while changing the
1506
1857
    open_tables list. Another thread may work on it.
1507
 
    (See: table::Cache::singleton().removeTable(), mysql_wait_completed_table())
 
1858
    (See: remove_table_from_cache(), mysql_wait_completed_table())
1508
1859
    Closing a MERGE child before the parent would be fatal if the
1509
1860
    other thread tries to abort the MERGE lock in between.
1510
1861
  */
1511
1862
  for (table= session->open_tables; table ; table=next)
1512
1863
  {
1513
 
    next=table->getNext();
1514
 
    if (table->getShare()->getCacheKey() == identifier.getKey())
 
1864
    next=table->next;
 
1865
    if (!strcmp(table->s->table_name.str, table_name) &&
 
1866
        !strcmp(table->s->db.str, db))
1515
1867
    {
1516
 
      session->removeLock(table);
 
1868
      mysql_lock_remove(session, table);
1517
1869
 
1518
1870
      if (!found)
1519
1871
      {
1528
1880
      else
1529
1881
      {
1530
1882
        /* We already have a name lock, remove copy */
1531
 
        table::remove_table(static_cast<table::Concurrent *>(table));
 
1883
        hash_delete(&open_cache,(unsigned char*) table);
1532
1884
      }
1533
1885
    }
1534
1886
    else
1535
1887
    {
1536
1888
      *prev=table;
1537
 
      prev= table->getNextPtr();
 
1889
      prev= &table->next;
1538
1890
    }
1539
1891
  }
1540
1892
  *prev=0;
1541
1893
  if (found)
1542
 
    locking::broadcast_refresh();
 
1894
    broadcast_refresh();
1543
1895
 
1544
1896
  return(found);
1545
1897
}
1551
1903
  other threads trying to get the lock.
1552
1904
*/
1553
1905
 
1554
 
void abort_locked_tables(Session *session, const drizzled::TableIdentifier &identifier)
 
1906
void abort_locked_tables(Session *session,const char *db, const char *table_name)
1555
1907
{
1556
1908
  Table *table;
1557
 
  for (table= session->open_tables; table ; table= table->getNext())
 
1909
  for (table= session->open_tables; table ; table= table->next)
1558
1910
  {
1559
 
    if (table->getShare()->getCacheKey() == identifier.getKey())
 
1911
    if (!strcmp(table->s->table_name.str, table_name) &&
 
1912
        !strcmp(table->s->db.str, db))
1560
1913
    {
1561
1914
      /* If MERGE child, forward lock handling to parent. */
1562
 
      session->abortLock(table);
 
1915
      mysql_lock_abort(session, table);
1563
1916
      break;
1564
1917
    }
1565
1918
  }
1566
1919
}
1567
1920
 
 
1921
/*
 
1922
  Load a table definition from cursor and open unireg table
 
1923
 
 
1924
  SYNOPSIS
 
1925
  open_unireg_entry()
 
1926
  session                       Thread handle
 
1927
  entry         Store open table definition here
 
1928
  table_list            TableList with db, table_name
 
1929
  alias         Alias name
 
1930
  cache_key             Key for share_cache
 
1931
  cache_key_length      length of cache_key
 
1932
 
 
1933
  NOTES
 
1934
  Extra argument for open is taken from session->open_options
 
1935
  One must have a lock on LOCK_open when calling this function
 
1936
 
 
1937
  RETURN
 
1938
  0     ok
 
1939
#       Error
 
1940
*/
 
1941
 
 
1942
static int open_unireg_entry(Session *session, Table *entry, TableList *table_list,
 
1943
                             const char *alias,
 
1944
                             char *cache_key, uint32_t cache_key_length)
 
1945
{
 
1946
  int error;
 
1947
  TableShare *share;
 
1948
  uint32_t discover_retry_count= 0;
 
1949
 
 
1950
  safe_mutex_assert_owner(&LOCK_open);
 
1951
retry:
 
1952
  if (!(share= TableShare::getShare(session, table_list, cache_key,
 
1953
                                    cache_key_length,
 
1954
                                    table_list->i_s_requested_object,
 
1955
                                    &error)))
 
1956
    return 1;
 
1957
 
 
1958
  while ((error= open_table_from_share(session, share, alias,
 
1959
                                       (uint32_t) (HA_OPEN_KEYFILE |
 
1960
                                                   HA_OPEN_RNDFILE |
 
1961
                                                   HA_GET_INDEX |
 
1962
                                                   HA_TRY_READ_ONLY),
 
1963
                                       session->open_options, entry)))
 
1964
  {
 
1965
    if (error == 7)                             // Table def changed
 
1966
    {
 
1967
      share->version= 0;                        // Mark share as old
 
1968
      if (discover_retry_count++)               // Retry once
 
1969
        goto err;
 
1970
 
 
1971
      /*
 
1972
        TODO->
 
1973
        Here we should wait until all threads has released the table.
 
1974
        For now we do one retry. This may cause a deadlock if there
 
1975
        is other threads waiting for other tables used by this thread.
 
1976
 
 
1977
        Proper fix would be to if the second retry failed:
 
1978
        - Mark that table def changed
 
1979
        - Return from open table
 
1980
        - Close all tables used by this thread
 
1981
        - Start waiting that the share is released
 
1982
        - Retry by opening all tables again
 
1983
      */
 
1984
 
 
1985
      /*
 
1986
        TO BE FIXED
 
1987
        To avoid deadlock, only wait for release if no one else is
 
1988
        using the share.
 
1989
      */
 
1990
      if (share->ref_count != 1)
 
1991
        goto err;
 
1992
      /* Free share and wait until it's released by all threads */
 
1993
      TableShare::release(share);
 
1994
 
 
1995
      if (!session->killed)
 
1996
      {
 
1997
        drizzle_reset_errors(session, 1);         // Clear warnings
 
1998
        session->clear_error();                 // Clear error message
 
1999
        goto retry;
 
2000
      }
 
2001
      return 1;
 
2002
    }
 
2003
 
 
2004
    goto err;
 
2005
  }
 
2006
 
 
2007
  return 0;
 
2008
 
 
2009
err:
 
2010
  TableShare::release(share);
 
2011
 
 
2012
  return 1;
 
2013
}
 
2014
 
1568
2015
 
1569
2016
/*
1570
2017
  Open all tables in list
1628
2075
    (*counter)++;
1629
2076
 
1630
2077
    /*
1631
 
     * Is the user authorized to see this table? Do this before we check
1632
 
     * to see if it exists so that an unauthorized user cannot phish for
1633
 
     * table/schema information via error messages
1634
 
     */
1635
 
    TableIdentifier the_table(tables->getSchemaName(), tables->getTableName());
1636
 
    if (not plugin::Authorization::isAuthorized(getSecurityContext(),
1637
 
                                                the_table))
1638
 
    {
1639
 
      result= -1;                               // Fatal error
1640
 
      break;
1641
 
    }
1642
 
 
1643
 
 
1644
 
    /*
1645
2078
      Not a placeholder: must be a base table or a view, and the table is
1646
2079
      not opened yet. Try to open the table.
1647
2080
    */
1680
2113
    {
1681
2114
      if (tables->lock_type == TL_WRITE_DEFAULT)
1682
2115
        tables->table->reginfo.lock_type= update_lock_default;
1683
 
      else if (tables->table->getShare()->getType() == message::Table::STANDARD)
 
2116
      else if (tables->table->s->tmp_table == NO_TMP_TABLE)
1684
2117
        tables->table->reginfo.lock_type= tables->lock_type;
1685
2118
    }
1686
2119
  }
1742
2175
 
1743
2176
    assert(lock == 0);  // You must lock everything at once
1744
2177
    if ((table->reginfo.lock_type= lock_type) != TL_UNLOCK)
1745
 
      if (! (lock= lockTables(&table_list->table, 1, 0, &refresh)))
 
2178
      if (! (lock= mysql_lock_tables(this, &table_list->table, 1, 0, &refresh)))
1746
2179
        table= 0;
1747
2180
  }
1748
2181
 
1805
2238
      *(ptr++)= table->table;
1806
2239
  }
1807
2240
 
1808
 
  if (!(session->lock= session->lockTables(start, (uint32_t) (ptr - start), lock_flag, need_reopen)))
 
2241
  if (!(session->lock= mysql_lock_tables(session, start, (uint32_t) (ptr - start),
 
2242
                                         lock_flag, need_reopen)))
1809
2243
  {
1810
2244
    return -1;
1811
2245
  }
1834
2268
#  Table object
1835
2269
*/
1836
2270
 
1837
 
Table *Open_tables_state::open_temporary_table(const TableIdentifier &identifier,
1838
 
                                               bool link_in_list)
 
2271
Table *Session::open_temporary_table(TableIdentifier &identifier,
 
2272
                                     bool link_in_list)
1839
2273
{
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)
 
2274
  Table *new_tmp_table;
 
2275
  TableShare *share;
 
2276
  char cache_key[MAX_DBKEY_LENGTH], *saved_cache_key, *tmp_path;
 
2277
  uint32_t key_length, path_length;
 
2278
  TableList table_list;
 
2279
 
 
2280
  table_list.db=         (char*) identifier.getDBName();
 
2281
  table_list.table_name= (char*) identifier.getTableName();
 
2282
  /* Create the cache_key for temporary tables */
 
2283
  key_length= table_list.create_table_def_key(cache_key);
 
2284
  path_length= strlen(identifier.getPath());
 
2285
 
 
2286
  if (!(new_tmp_table= (Table*) malloc(sizeof(*new_tmp_table) + sizeof(*share) +
 
2287
                                       path_length + 1 + key_length)))
1848
2288
    return NULL;
1849
2289
 
 
2290
  share= (TableShare*) (new_tmp_table+1);
 
2291
  tmp_path= (char*) (share+1);
 
2292
  saved_cache_key= strcpy(tmp_path, identifier.getPath())+path_length+1;
 
2293
  memcpy(saved_cache_key, cache_key, key_length);
 
2294
 
 
2295
  share->init(saved_cache_key, key_length, strchr(saved_cache_key, '\0')+1, tmp_path);
 
2296
 
1850
2297
  /*
1851
2298
    First open the share, and then open the table from the share we just opened.
1852
2299
  */
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))
 
2300
  if (open_table_def(*this, share) ||
 
2301
      open_table_from_share(this, share, identifier.getTableName(),
 
2302
                            (uint32_t) (HA_OPEN_KEYFILE | HA_OPEN_RNDFILE |
 
2303
                                        HA_GET_INDEX),
 
2304
                            ha_open_options,
 
2305
                            new_tmp_table))
1859
2306
  {
1860
2307
    /* 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
 
 
 
2308
    share->free_table_share();
 
2309
    free((char*) new_tmp_table);
1864
2310
    return 0;
1865
2311
  }
1866
2312
 
1867
2313
  new_tmp_table->reginfo.lock_type= TL_WRITE;    // Simulate locked
 
2314
  share->tmp_table= TEMP_TABLE;
1868
2315
 
1869
2316
  if (link_in_list)
1870
2317
  {
1871
2318
    /* 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
 
    }
 
2319
    new_tmp_table->next= this->temporary_tables;
 
2320
    if (new_tmp_table->next)
 
2321
      new_tmp_table->next->prev= new_tmp_table;
1877
2322
    this->temporary_tables= new_tmp_table;
1878
 
    this->temporary_tables->setPrev(0);
 
2323
    this->temporary_tables->prev= 0;
1879
2324
  }
1880
2325
  new_tmp_table->pos_in_table_list= 0;
1881
2326
 
1900
2345
{
1901
2346
  if (session->mark_used_columns != MARK_COLUMNS_NONE)
1902
2347
  {
1903
 
    boost::dynamic_bitset<> *current_bitmap= NULL;
 
2348
    MyBitmap *current_bitmap, *other_bitmap;
1904
2349
 
1905
2350
    /*
1906
2351
      We always want to register the used keys, as the column bitmap may have
1913
2358
    if (session->mark_used_columns == MARK_COLUMNS_READ)
1914
2359
    {
1915
2360
      current_bitmap= table->read_set;
 
2361
      other_bitmap=   table->write_set;
1916
2362
    }
1917
2363
    else
1918
2364
    {
1919
2365
      current_bitmap= table->write_set;
 
2366
      other_bitmap=   table->read_set;
1920
2367
    }
1921
2368
 
1922
 
    //if (current_bitmap->testAndSet(field->position()))
1923
 
    if (current_bitmap->test(field->position()))
 
2369
    if (current_bitmap->testAndSet(field->field_index))
1924
2370
    {
1925
2371
      if (session->mark_used_columns == MARK_COLUMNS_WRITE)
1926
2372
        session->dup_field= field;
1989
2435
    return NULL;
1990
2436
  {
1991
2437
    /* This is a base table. */
1992
 
    assert(nj_col->table_ref->table == nj_col->table_field->getTable());
 
2438
    assert(nj_col->table_ref->table == nj_col->table_field->table);
1993
2439
    found_field= nj_col->table_field;
1994
2440
    update_field_dependencies(session, found_field, nj_col->table_ref->table);
1995
2441
  }
2026
2472
  uint32_t cached_field_index= *cached_field_index_ptr;
2027
2473
 
2028
2474
  /* We assume here that table->field < NO_CACHED_FIELD_INDEX = UINT_MAX */
2029
 
  if (cached_field_index < table->getShare()->sizeFields() &&
 
2475
  if (cached_field_index < table->s->fields &&
2030
2476
      !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));
 
2477
                     table->field[cached_field_index]->field_name, name))
 
2478
    field_ptr= table->field + cached_field_index;
 
2479
  else if (table->s->name_hash.records)
 
2480
  {
 
2481
    field_ptr= (Field**) hash_search(&table->s->name_hash, (unsigned char*) name,
 
2482
                                     length);
2038
2483
    if (field_ptr)
2039
2484
    {
2040
2485
      /*
2041
2486
        field_ptr points to field in TableShare. Convert it to the matching
2042
2487
        field in table
2043
2488
      */
2044
 
      field_ptr= (table->getFields() + table->getShare()->positionFields(field_ptr));
 
2489
      field_ptr= (table->field + (field_ptr - table->s->field));
2045
2490
    }
2046
2491
  }
2047
2492
  else
2048
2493
  {
2049
 
    if (!(field_ptr= table->getFields()))
 
2494
    if (!(field_ptr= table->field))
2050
2495
      return((Field *)0);
2051
2496
    for (; *field_ptr; ++field_ptr)
2052
2497
      if (!my_strcasecmp(system_charset_info, (*field_ptr)->field_name, name))
2055
2500
 
2056
2501
  if (field_ptr && *field_ptr)
2057
2502
  {
2058
 
    *cached_field_index_ptr= field_ptr - table->getFields();
 
2503
    *cached_field_index_ptr= field_ptr - table->field;
2059
2504
    field= *field_ptr;
2060
2505
  }
2061
2506
  else
2062
2507
  {
2063
2508
    if (!allow_rowid ||
2064
2509
        my_strcasecmp(system_charset_info, name, "_rowid") ||
2065
 
        table->getShare()->rowid_field_offset == 0)
 
2510
        table->s->rowid_field_offset == 0)
2066
2511
      return((Field*) 0);
2067
 
    field= table->getField(table->getShare()->rowid_field_offset-1);
 
2512
    field= table->field[table->s->rowid_field_offset-1];
2068
2513
  }
2069
2514
 
2070
2515
  update_field_dependencies(session, field, table);
2143
2588
    inside the view, but we want to search directly in the view columns
2144
2589
    which are represented as a 'field_translation'.
2145
2590
 
2146
 
    TODO-> Ensure that table_name, db_name and tables->db always points to something !
 
2591
TODO: Ensure that table_name, db_name and tables->db always points to
 
2592
something !
2147
2593
  */
2148
2594
  if (/* Exclude nested joins. */
2149
 
      (!table_list->getNestedJoin()) &&
 
2595
      (!table_list->nested_join) &&
2150
2596
      /* Include merge views and information schema tables. */
2151
2597
      /*
2152
2598
        Test if the field qualifiers match the table reference we plan
2154
2600
      */
2155
2601
      table_name && table_name[0] &&
2156
2602
      (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()))))
 
2603
       (db_name && db_name[0] && table_list->db && table_list->db[0] &&
 
2604
        strcmp(db_name, table_list->db))))
2159
2605
    return 0;
2160
2606
 
2161
2607
  *actual_table= NULL;
2162
2608
 
2163
 
  if (!table_list->getNestedJoin())
 
2609
  if (!table_list->nested_join)
2164
2610
  {
2165
2611
    /* 'table_list' is a stored table. */
2166
2612
    assert(table_list->table);
2180
2626
    */
2181
2627
    if (table_name && table_name[0])
2182
2628
    {
2183
 
      List_iterator<TableList> it(table_list->getNestedJoin()->join_list);
 
2629
      List_iterator<TableList> it(table_list->nested_join->join_list);
2184
2630
      TableList *table;
2185
2631
      while ((table= it++))
2186
2632
      {
2228
2674
        field_to_set= fld;
2229
2675
      if (field_to_set)
2230
2676
      {
2231
 
        Table *table= field_to_set->getTable();
 
2677
        Table *table= field_to_set->table;
2232
2678
        if (session->mark_used_columns == MARK_COLUMNS_READ)
2233
 
          table->setReadSet(field_to_set->position());
 
2679
          table->setReadSet(field_to_set->field_index);
2234
2680
        else
2235
 
          table->setWriteSet(field_to_set->position());
 
2681
          table->setWriteSet(field_to_set->field_index);
2236
2682
      }
2237
2683
    }
2238
2684
  }
2474
2920
 
2475
2921
 
2476
2922
Item **
2477
 
find_item_in_list(Session *session,
2478
 
                  Item *find, List<Item> &items, uint32_t *counter,
 
2923
find_item_in_list(Item *find, List<Item> &items, uint32_t *counter,
2479
2924
                  find_item_error_report_type report_error,
2480
2925
                  enum_resolution_type *resolution)
2481
2926
{
2555
3000
            */
2556
3001
            if (report_error != IGNORE_ERRORS)
2557
3002
              my_error(ER_NON_UNIQ_ERROR, MYF(0),
2558
 
                       find->full_name(), session->where);
 
3003
                       find->full_name(), current_session->where);
2559
3004
            return (Item**) 0;
2560
3005
          }
2561
3006
          found_unaliased= li.ref();
2586
3031
              continue;                           // Same field twice
2587
3032
            if (report_error != IGNORE_ERRORS)
2588
3033
              my_error(ER_NON_UNIQ_ERROR, MYF(0),
2589
 
                       find->full_name(), session->where);
 
3034
                       find->full_name(), current_session->where);
2590
3035
            return (Item**) 0;
2591
3036
          }
2592
3037
          found= li.ref();
2638
3083
    {
2639
3084
      if (report_error != IGNORE_ERRORS)
2640
3085
        my_error(ER_NON_UNIQ_ERROR, MYF(0),
2641
 
                 find->full_name(), session->where);
 
3086
                 find->full_name(), current_session->where);
2642
3087
      return (Item **) 0;
2643
3088
    }
2644
3089
    if (found_unaliased)
2654
3099
  {
2655
3100
    if (report_error == REPORT_ALL_ERRORS)
2656
3101
      my_error(ER_BAD_FIELD_ERROR, MYF(0),
2657
 
               find->full_name(), session->where);
 
3102
               find->full_name(), current_session->where);
2658
3103
    return (Item **) 0;
2659
3104
  }
2660
3105
  else
2772
3217
    Leaf table references to which new natural join columns are added
2773
3218
    if the leaves are != NULL.
2774
3219
  */
2775
 
  TableList *leaf_1= (table_ref_1->getNestedJoin() &&
2776
 
                      ! table_ref_1->is_natural_join) ?
 
3220
  TableList *leaf_1= (table_ref_1->nested_join &&
 
3221
                      !table_ref_1->is_natural_join) ?
2777
3222
    NULL : table_ref_1;
2778
 
  TableList *leaf_2= (table_ref_2->getNestedJoin() &&
2779
 
                      ! table_ref_2->is_natural_join) ?
 
3223
  TableList *leaf_2= (table_ref_2->nested_join &&
 
3224
                      !table_ref_2->is_natural_join) ?
2780
3225
    NULL : table_ref_2;
2781
3226
 
2782
3227
  *found_using_fields= 0;
2788
3233
    /* true if field_name_1 is a member of using_fields */
2789
3234
    bool is_using_column_1;
2790
3235
    if (!(nj_col_1= it_1.get_or_create_column_ref(leaf_1)))
2791
 
      return(result);
 
3236
      goto err;
2792
3237
    field_name_1= nj_col_1->name();
2793
3238
    is_using_column_1= using_fields &&
2794
3239
      test_if_string_in_list(field_name_1, using_fields);
2806
3251
      Natural_join_column *cur_nj_col_2;
2807
3252
      const char *cur_field_name_2;
2808
3253
      if (!(cur_nj_col_2= it_2.get_or_create_column_ref(leaf_2)))
2809
 
        return(result);
 
3254
        goto err;
2810
3255
      cur_field_name_2= cur_nj_col_2->name();
2811
3256
 
2812
3257
      /*
2826
3271
            (found && (!using_fields || is_using_column_1)))
2827
3272
        {
2828
3273
          my_error(ER_NON_UNIQ_ERROR, MYF(0), field_name_1, session->where);
2829
 
          return(result);
 
3274
          goto err;
2830
3275
        }
2831
3276
        nj_col_2= cur_nj_col_2;
2832
3277
        found= true;
2859
3304
      Item_func_eq *eq_cond;
2860
3305
 
2861
3306
      if (!item_1 || !item_2)
2862
 
        return(result); // out of memory
 
3307
        goto err;                               // out of memory
2863
3308
 
2864
3309
      /*
2865
3310
        In the case of no_wrap_view_item == 0, the created items must be
2884
3329
      */
2885
3330
      if (set_new_item_local_context(session, item_ident_1, nj_col_1->table_ref) ||
2886
3331
          set_new_item_local_context(session, item_ident_2, nj_col_2->table_ref))
2887
 
        return(result);
 
3332
        goto err;
2888
3333
 
2889
3334
      if (!(eq_cond= new Item_func_eq(item_ident_1, item_ident_2)))
2890
 
        return(result);                               /* Out of memory. */
 
3335
        goto err;                               /* Out of memory. */
2891
3336
 
2892
3337
      /*
2893
3338
        Add the new equi-join condition to the ON clause. Notice that
2904
3349
      {
2905
3350
        Table *table_1= nj_col_1->table_ref->table;
2906
3351
        /* Mark field_1 used for table cache. */
2907
 
        table_1->setReadSet(field_1->position());
 
3352
        table_1->setReadSet(field_1->field_index);
2908
3353
        table_1->covering_keys&= field_1->part_of_key;
2909
3354
        table_1->merge_keys|= field_1->part_of_key;
2910
3355
      }
2912
3357
      {
2913
3358
        Table *table_2= nj_col_2->table_ref->table;
2914
3359
        /* Mark field_2 used for table cache. */
2915
 
        table_2->setReadSet(field_2->position());
 
3360
        table_2->setReadSet(field_2->field_index);
2916
3361
        table_2->covering_keys&= field_2->part_of_key;
2917
3362
        table_2->merge_keys|= field_2->part_of_key;
2918
3363
      }
2933
3378
  */
2934
3379
  result= false;
2935
3380
 
 
3381
err:
2936
3382
  return(result);
2937
3383
}
2938
3384
 
2974
3420
*/
2975
3421
 
2976
3422
static bool
2977
 
store_natural_using_join_columns(Session *session,
 
3423
store_natural_using_join_columns(Session *,
2978
3424
                                 TableList *natural_using_join,
2979
3425
                                 TableList *table_ref_1,
2980
3426
                                 TableList *table_ref_2,
2990
3436
 
2991
3437
  if (!(non_join_columns= new List<Natural_join_column>) ||
2992
3438
      !(natural_using_join->join_columns= new List<Natural_join_column>))
2993
 
  {
2994
 
    return(result);
2995
 
  }
 
3439
    goto err;
2996
3440
 
2997
3441
  /* Append the columns of the first join operand. */
2998
3442
  for (it_1.set(table_ref_1); !it_1.end_of_fields(); it_1.next())
3030
3474
        if (!(common_field= it++))
3031
3475
        {
3032
3476
          my_error(ER_BAD_FIELD_ERROR, MYF(0), using_field_name_ptr,
3033
 
                   session->where);
3034
 
          return(result);
 
3477
                   current_session->where);
 
3478
          goto err;
3035
3479
        }
3036
3480
        if (!my_strcasecmp(system_charset_info,
3037
3481
                           common_field->name(), using_field_name_ptr))
3059
3503
 
3060
3504
  result= false;
3061
3505
 
 
3506
err:
3062
3507
  return(result);
3063
3508
}
3064
3509
 
3101
3546
  bool result= true;
3102
3547
 
3103
3548
  /* Call the procedure recursively for each nested table reference. */
3104
 
  if (table_ref->getNestedJoin())
 
3549
  if (table_ref->nested_join)
3105
3550
  {
3106
 
    List_iterator_fast<TableList> nested_it(table_ref->getNestedJoin()->join_list);
 
3551
    List_iterator_fast<TableList> nested_it(table_ref->nested_join->join_list);
3107
3552
    TableList *same_level_left_neighbor= nested_it++;
3108
3553
    TableList *same_level_right_neighbor= NULL;
3109
3554
    /* Left/right-most neighbors, possibly at higher levels in the join tree. */
3128
3573
          cur_table_ref->outer_join & JOIN_TYPE_RIGHT)
3129
3574
      {
3130
3575
        /* This can happen only for JOIN ... ON. */
3131
 
        assert(table_ref->getNestedJoin()->join_list.elements == 2);
 
3576
        assert(table_ref->nested_join->join_list.elements == 2);
3132
3577
        std::swap(same_level_left_neighbor, cur_table_ref);
3133
3578
      }
3134
3579
 
3141
3586
      real_right_neighbor= (same_level_right_neighbor) ?
3142
3587
        same_level_right_neighbor : right_neighbor;
3143
3588
 
3144
 
      if (cur_table_ref->getNestedJoin() &&
 
3589
      if (cur_table_ref->nested_join &&
3145
3590
          store_top_level_join_columns(session, cur_table_ref,
3146
3591
                                       real_left_neighbor, real_right_neighbor))
3147
 
        return(result);
 
3592
        goto err;
3148
3593
      same_level_right_neighbor= cur_table_ref;
3149
3594
    }
3150
3595
  }
3155
3600
  */
3156
3601
  if (table_ref->is_natural_join)
3157
3602
  {
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);
 
3603
    assert(table_ref->nested_join &&
 
3604
           table_ref->nested_join->join_list.elements == 2);
 
3605
    List_iterator_fast<TableList> operand_it(table_ref->nested_join->join_list);
3161
3606
    /*
3162
3607
      Notice that the order of join operands depends on whether table_ref
3163
3608
      represents a LEFT or a RIGHT join. In a RIGHT join, the operands are
3176
3621
      std::swap(table_ref_1, table_ref_2);
3177
3622
    if (mark_common_columns(session, table_ref_1, table_ref_2,
3178
3623
                            using_fields, &found_using_fields))
3179
 
      return(result);
 
3624
      goto err;
3180
3625
 
3181
3626
    /*
3182
3627
      Swap the join operands back, so that we pick the columns of the second
3188
3633
    if (store_natural_using_join_columns(session, table_ref, table_ref_1,
3189
3634
                                         table_ref_2, using_fields,
3190
3635
                                         found_using_fields))
3191
 
      return(result);
 
3636
      goto err;
3192
3637
 
3193
3638
    /*
3194
3639
      Change NATURAL JOIN to JOIN ... ON. We do this for both operands
3221
3666
  }
3222
3667
  result= false; /* All is OK. */
3223
3668
 
 
3669
err:
3224
3670
  return(result);
3225
3671
}
3226
3672
 
3622
4068
    assert(tables->is_leaf_for_name_resolution());
3623
4069
 
3624
4070
    if ((table_name && my_strcasecmp(table_alias_charset, table_name, tables->alias)) ||
3625
 
        (db_name && strcasecmp(tables->getSchemaName(),db_name)))
 
4071
        (db_name && strcmp(tables->db,db_name)))
3626
4072
      continue;
3627
4073
 
3628
4074
    /*
3658
4104
      if ((field= field_iterator.field()))
3659
4105
      {
3660
4106
        /* Mark fields as used to allow storage engine to optimze access */
3661
 
        field->getTable()->setReadSet(field->position());
 
4107
        field->table->setReadSet(field->field_index);
3662
4108
        if (table)
3663
4109
        {
3664
4110
          table->covering_keys&= field->part_of_key;
3696
4142
      For NATURAL joins, used_tables is updated in the IF above.
3697
4143
    */
3698
4144
    if (table)
3699
 
      table->used_fields= table->getShare()->sizeFields();
 
4145
      table->used_fields= table->s->fields;
3700
4146
  }
3701
4147
  if (found)
3702
4148
    return false;
3703
4149
 
3704
4150
  /*
3705
 
    @TODO in the case when we skipped all columns because there was a
3706
 
    qualified '*', and all columns were coalesced, we have to give a more
3707
 
    meaningful message than ER_BAD_TABLE_ERROR.
 
4151
TODO: in the case when we skipped all columns because there was a
 
4152
qualified '*', and all columns were coalesced, we have to give a more
 
4153
meaningful message than ER_BAD_TABLE_ERROR.
3708
4154
  */
3709
4155
  if (!table_name)
3710
4156
    my_message(ER_NO_TABLES_USED, ER(ER_NO_TABLES_USED), MYF(0));
3786
4232
          goto err_no_arena;
3787
4233
        select_lex->cond_count++;
3788
4234
      }
3789
 
      embedding= embedded->getEmbedding();
 
4235
      embedding= embedded->embedding;
3790
4236
    }
3791
4237
    while (embedding &&
3792
 
           embedding->getNestedJoin()->join_list.head() == embedded);
 
4238
           embedding->nested_join->join_list.head() == embedded);
3793
4239
 
3794
4240
  }
3795
4241
  session->session_marker= save_session_marker;
3848
4294
      thus we safely can take table from the first field.
3849
4295
    */
3850
4296
    field= static_cast<Item_field *>(f++);
3851
 
    table= field->field->getTable();
 
4297
    table= field->field->table;
3852
4298
    table->auto_increment_field_not_null= false;
3853
4299
    f.rewind();
3854
4300
  }
3858
4304
    value= v++;
3859
4305
 
3860
4306
    Field *rfield= field->field;
3861
 
    table= rfield->getTable();
 
4307
    table= rfield->table;
3862
4308
 
3863
4309
    if (rfield == table->next_number_field)
3864
4310
      table->auto_increment_field_not_null= true;
3865
4311
    if ((value->save_in_field(rfield, 0) < 0) && !ignore_errors)
3866
4312
    {
3867
4313
      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;
 
4314
      goto err;
3872
4315
    }
3873
4316
  }
3874
4317
 
3875
4318
  return session->is_error();
 
4319
 
 
4320
err:
 
4321
  if (table)
 
4322
    table->auto_increment_field_not_null= false;
 
4323
 
 
4324
  return true;
3876
4325
}
3877
4326
 
3878
4327
 
3912
4361
      On INSERT or UPDATE fields are checked to be from the same table,
3913
4362
      thus we safely can take table from the first field.
3914
4363
    */
3915
 
    table= (*ptr)->getTable();
 
4364
    table= (*ptr)->table;
3916
4365
    table->auto_increment_field_not_null= false;
3917
4366
  }
3918
4367
  while ((field = *ptr++) && ! session->is_error())
3919
4368
  {
3920
4369
    value=v++;
3921
 
    table= field->getTable();
 
4370
    table= field->table;
3922
4371
    if (field == table->next_number_field)
3923
4372
      table->auto_increment_field_not_null= true;
3924
4373
    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
 
    }
 
4374
      goto err;
3931
4375
  }
3932
4376
 
3933
4377
  return(session->is_error());
 
4378
 
 
4379
err:
 
4380
  if (table)
 
4381
    table->auto_increment_field_not_null= false;
 
4382
 
 
4383
  return true;
3934
4384
}
3935
4385
 
3936
4386
 
3938
4388
{
3939
4389
  Session *session;
3940
4390
 
3941
 
  assert(drizzle_tmpdir.size());
 
4391
  assert(drizzle_tmpdir);
3942
4392
 
3943
4393
  if (!(session= new Session(plugin::Listen::getNullClient())))
3944
4394
    return true;
3945
4395
  session->thread_stack= (char*) &session;
3946
4396
  session->storeGlobals();
3947
4397
 
3948
 
  plugin::StorageEngine::removeLostTemporaryTables(*session, drizzle_tmpdir.c_str());
 
4398
  plugin::StorageEngine::removeLostTemporaryTables(*session, drizzle_tmpdir);
3949
4399
 
3950
4400
  delete session;
3951
4401
 
3958
4408
  unireg support functions
3959
4409
 *****************************************************************************/
3960
4410
 
3961
 
 
 
4411
/*
 
4412
  Invalidate any cache entries that are for some DB
 
4413
 
 
4414
  SYNOPSIS
 
4415
  remove_db_from_cache()
 
4416
  db            Database name. This will be in lower case if
 
4417
  lower_case_table_name is set
 
4418
 
 
4419
NOTE:
 
4420
We can't use hash_delete when looping hash_elements. We mark them first
 
4421
and afterwards delete those marked unused.
 
4422
*/
 
4423
 
 
4424
void remove_db_from_cache(const char *db)
 
4425
{
 
4426
  safe_mutex_assert_owner(&LOCK_open);
 
4427
 
 
4428
  for (uint32_t idx=0 ; idx < open_cache.records ; idx++)
 
4429
  {
 
4430
    Table *table=(Table*) hash_element(&open_cache,idx);
 
4431
    if (!strcmp(table->s->db.str, db))
 
4432
    {
 
4433
      table->s->version= 0L;                    /* Free when thread is ready */
 
4434
      if (!table->in_use)
 
4435
        relink_unused(table);
 
4436
    }
 
4437
  }
 
4438
  while (unused_tables && !unused_tables->s->version)
 
4439
    hash_delete(&open_cache,(unsigned char*) unused_tables);
 
4440
}
 
4441
 
 
4442
 
 
4443
/*
 
4444
  Mark all entries with the table as deleted to force an reopen of the table
 
4445
 
 
4446
  The table will be closed (not stored in cache) by the current thread when
 
4447
  close_thread_tables() is called.
 
4448
 
 
4449
  PREREQUISITES
 
4450
  Lock on LOCK_open()
 
4451
 
 
4452
  RETURN
 
4453
  0  This thread now have exclusive access to this table and no other thread
 
4454
  can access the table until close_thread_tables() is called.
 
4455
  1  Table is in use by another thread
 
4456
*/
 
4457
 
 
4458
bool remove_table_from_cache(Session *session, const char *db, const char *table_name,
 
4459
                             uint32_t flags)
 
4460
{
 
4461
  char key[MAX_DBKEY_LENGTH];
 
4462
  char *key_pos= key;
 
4463
  uint32_t key_length;
 
4464
  Table *table;
 
4465
  bool result= false; 
 
4466
  bool signalled= false;
 
4467
 
 
4468
  key_pos= strcpy(key_pos, db) + strlen(db);
 
4469
  key_pos= strcpy(key_pos+1, table_name) + strlen(table_name);
 
4470
  key_length= (uint32_t) (key_pos-key)+1;
 
4471
 
 
4472
  for (;;)
 
4473
  {
 
4474
    HASH_SEARCH_STATE state;
 
4475
    result= signalled= false;
 
4476
 
 
4477
    for (table= (Table*) hash_first(&open_cache, (unsigned char*) key, key_length,
 
4478
                                    &state);
 
4479
         table;
 
4480
         table= (Table*) hash_next(&open_cache, (unsigned char*) key, key_length,
 
4481
                                   &state))
 
4482
    {
 
4483
      Session *in_use;
 
4484
 
 
4485
      table->s->version=0L;             /* Free when thread is ready */
 
4486
      if (!(in_use=table->in_use))
 
4487
      {
 
4488
        relink_unused(table);
 
4489
      }
 
4490
      else if (in_use != session)
 
4491
      {
 
4492
        /*
 
4493
          Mark that table is going to be deleted from cache. This will
 
4494
          force threads that are in mysql_lock_tables() (but not yet
 
4495
          in thr_multi_lock()) to abort it's locks, close all tables and retry
 
4496
        */
 
4497
        in_use->some_tables_deleted= true;
 
4498
        if (table->is_name_opened())
 
4499
        {
 
4500
          result= true;
 
4501
        }
 
4502
        /*
 
4503
          Now we must abort all tables locks used by this thread
 
4504
          as the thread may be waiting to get a lock for another table.
 
4505
          Note that we need to hold LOCK_open while going through the
 
4506
          list. So that the other thread cannot change it. The other
 
4507
          thread must also hold LOCK_open whenever changing the
 
4508
          open_tables list. Aborting the MERGE lock after a child was
 
4509
          closed and before the parent is closed would be fatal.
 
4510
        */
 
4511
        for (Table *session_table= in_use->open_tables;
 
4512
             session_table ;
 
4513
             session_table= session_table->next)
 
4514
        {
 
4515
          /* Do not handle locks of MERGE children. */
 
4516
          if (session_table->db_stat)   // If table is open
 
4517
            signalled|= mysql_lock_abort_for_thread(session, session_table);
 
4518
        }
 
4519
      }
 
4520
      else
 
4521
        result= result || (flags & RTFC_OWNED_BY_Session_FLAG);
 
4522
    }
 
4523
    while (unused_tables && !unused_tables->s->version)
 
4524
      hash_delete(&open_cache,(unsigned char*) unused_tables);
 
4525
 
 
4526
    /* Remove table from table definition cache if it's not in use */
 
4527
    TableShare::release(key, key_length);
 
4528
 
 
4529
    if (result && (flags & RTFC_WAIT_OTHER_THREAD_FLAG))
 
4530
    {
 
4531
      /*
 
4532
        Signal any thread waiting for tables to be freed to
 
4533
        reopen their tables
 
4534
      */
 
4535
      broadcast_refresh();
 
4536
      if (!(flags & RTFC_CHECK_KILLED_FLAG) || !session->killed)
 
4537
      {
 
4538
        dropping_tables++;
 
4539
        if (likely(signalled))
 
4540
          (void) pthread_cond_wait(&COND_refresh, &LOCK_open);
 
4541
        else
 
4542
        {
 
4543
          struct timespec abstime;
 
4544
          /*
 
4545
            It can happen that another thread has opened the
 
4546
            table but has not yet locked any table at all. Since
 
4547
            it can be locked waiting for a table that our thread
 
4548
            has done LOCK Table x WRITE on previously, we need to
 
4549
            ensure that the thread actually hears our signal
 
4550
            before we go to sleep. Thus we wait for a short time
 
4551
            and then we retry another loop in the
 
4552
            remove_table_from_cache routine.
 
4553
          */
 
4554
          set_timespec(abstime, 10);
 
4555
          pthread_cond_timedwait(&COND_refresh, &LOCK_open, &abstime);
 
4556
        }
 
4557
        dropping_tables--;
 
4558
        continue;
 
4559
      }
 
4560
    }
 
4561
    break;
 
4562
  }
 
4563
  return result;
 
4564
}
3962
4565
 
3963
4566
 
3964
4567
/**
3970
4573
  pthread_kill(signal_thread, SIGTERM);
3971
4574
  shutdown_in_progress= 1;                      // Safety if kill didn't work
3972
4575
}
3973
 
 
3974
 
} /* namespace drizzled */