~drizzle-trunk/drizzle/development

« back to all changes in this revision

Viewing changes to drizzled/sql_base.cc

  • Committer: Monty Taylor
  • Date: 2009-12-14 22:00:27 UTC
  • mto: (1241.9.10 out-of-tree)
  • mto: This revision was merged to the branch mainline in revision 1250.
  • Revision ID: mordred@inaugust.com-20091214220027-kpmfbl452nctzc0g
pandora-build v0.85 - Fixed C++ standard setting.

Show diffs side-by-side

added added

removed removed

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