~drizzle-trunk/drizzle/development

« back to all changes in this revision

Viewing changes to drizzled/sql_base.cc

  • Committer: Stewart Smith
  • Date: 2010-07-27 19:43:43 UTC
  • mto: (1720.1.1 drizzle)
  • mto: This revision was merged to the branch mainline in revision 1721.
  • Revision ID: stewart@flamingspork.com-20100727194343-rj79lftdvityzqlg
fix SHOW CREATE TABLE tests for explicit COLLATE in CREATE TABLE

Show diffs side-by-side

added added

removed removed

Lines of Context:
11
11
 
12
12
  You should have received a copy of the GNU General Public License
13
13
  along with this program; if not, write to the Free Software
14
 
  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA */
 
14
  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA */
15
15
 
16
16
 
17
17
/* Basic functions needed by many modules */
31
31
# endif
32
32
#endif
33
33
#include "drizzled/internal/my_pthread.h"
34
 
#include "drizzled/internal/thread_var.h"
35
34
 
36
35
#include <drizzled/sql_select.h>
37
36
#include <drizzled/error.h>
47
46
#include "drizzled/cached_directory.h"
48
47
#include <drizzled/field/timestamp.h>
49
48
#include <drizzled/field/null.h>
 
49
#include "drizzled/memory/multi_malloc.h"
50
50
#include "drizzled/sql_table.h"
51
51
#include "drizzled/global_charset_info.h"
52
52
#include "drizzled/pthread_globals.h"
53
53
#include "drizzled/internal/iocache.h"
54
54
#include "drizzled/drizzled.h"
55
55
#include "drizzled/plugin/authorization.h"
56
 
#include "drizzled/table/temporary.h"
57
 
#include "drizzled/table/placeholder.h"
58
 
#include "drizzled/table/unused.h"
 
56
#include "drizzled/table_placeholder.h"
59
57
 
60
58
using namespace std;
61
59
 
64
62
 
65
63
extern bool volatile shutdown_in_progress;
66
64
 
 
65
/**
 
66
  @defgroup Data_Dictionary Data Dictionary
 
67
  @{
 
68
*/
 
69
 
 
70
 
 
71
HASH &get_open_cache()
 
72
{
 
73
  static HASH open_cache;                               /* Used by mysql_test */
 
74
 
 
75
  return open_cache;
 
76
}
 
77
 
 
78
class UnusedTables {
 
79
  Table *tables;                                /* Used by mysql_test */
 
80
 
 
81
  Table *getTable() const
 
82
  {
 
83
    return tables;
 
84
  }
 
85
 
 
86
  Table *setTable(Table *arg)
 
87
  {
 
88
    return tables= arg;
 
89
  }
 
90
 
 
91
public:
 
92
 
 
93
  void cull()
 
94
  {
 
95
    /* Free cache if too big */
 
96
    while (get_open_cache().records > table_cache_size && getTable())
 
97
      hash_delete(&get_open_cache(), (unsigned char*) getTable());
 
98
  }
 
99
 
 
100
  void cullByVersion()
 
101
  {
 
102
    while (getTable() && not getTable()->getShare()->getVersion())
 
103
      hash_delete(&get_open_cache(), (unsigned char*) getTable());
 
104
  }
 
105
  
 
106
  void link(Table *table)
 
107
  {
 
108
    if (getTable())
 
109
    {
 
110
      table->setNext(getTable());               /* Link in last */
 
111
      table->setPrev(getTable()->getPrev());
 
112
      getTable()->setPrev(table);
 
113
      table->getPrev()->setNext(table);
 
114
    }
 
115
    else
 
116
    {
 
117
      table->setPrev(setTable(table));
 
118
      table->setNext(table->getPrev());
 
119
      assert(table->getNext() == table && table->getPrev() == table);
 
120
    }
 
121
  }
 
122
 
 
123
 
 
124
  void unlink(Table *table)
 
125
  {
 
126
    table->unlink();
 
127
 
 
128
    /* Unlink the table from "unused_tables" list. */
 
129
    if (table == getTable())
 
130
    {  // First unused
 
131
      setTable(getTable()->getNext()); // Remove from link
 
132
      if (table == getTable())
 
133
        setTable(NULL);
 
134
    }
 
135
  }
 
136
 
 
137
/* move table first in unused links */
 
138
 
 
139
  void relink(Table *table)
 
140
  {
 
141
    if (table != getTable())
 
142
    {
 
143
      table->unlink();
 
144
 
 
145
      table->setNext(getTable());                       /* Link in unused tables */
 
146
      table->setPrev(getTable()->getPrev());
 
147
      getTable()->getPrev()->setNext(table);
 
148
      getTable()->setPrev(table);
 
149
      setTable(table);
 
150
    }
 
151
  }
 
152
 
 
153
 
 
154
  void clear()
 
155
  {
 
156
    while (getTable())
 
157
      hash_delete(&get_open_cache(), (unsigned char*) getTable());
 
158
  }
 
159
 
 
160
  UnusedTables():
 
161
    tables(NULL)
 
162
  { }
 
163
 
 
164
  ~UnusedTables()
 
165
  { 
 
166
  }
 
167
};
 
168
 
 
169
static UnusedTables unused_tables;
 
170
static int open_unireg_entry(Session *session,
 
171
                             Table *entry,
 
172
                             const char *alias,
 
173
                             TableIdentifier &identifier);
 
174
void free_cache_entry(void *entry);
 
175
unsigned char *table_cache_key(const unsigned char *record,
 
176
                               size_t *length,
 
177
                               bool );
 
178
 
 
179
#if 0
 
180
static bool reopen_table(Table *table);
 
181
#endif
 
182
 
 
183
unsigned char *table_cache_key(const unsigned char *record,
 
184
                               size_t *length,
 
185
                               bool )
 
186
{
 
187
  Table *entry=(Table*) record;
 
188
  *length= entry->getShare()->getCacheKey().size();
 
189
  return (unsigned char*) &entry->getShare()->getCacheKey()[0];
 
190
}
 
191
 
67
192
bool table_cache_init(void)
68
193
{
69
 
  return false;
70
 
}
71
 
 
72
 
uint32_t cached_open_tables(void)
73
 
{
74
 
  return table::getCache().size();
 
194
  return hash_init(&get_open_cache(), &my_charset_bin,
 
195
                   (size_t) table_cache_size+16,
 
196
                   0, 0, table_cache_key,
 
197
                   free_cache_entry, 0);
75
198
}
76
199
 
77
200
void table_cache_free(void)
78
201
{
79
202
  refresh_version++;                            // Force close of open tables
80
203
 
81
 
  table::getUnused().clear();
82
 
  table::getCache().clear();
83
 
}
 
204
  unused_tables.clear();
 
205
 
 
206
  if (not get_open_cache().records)                     // Safety first
 
207
    hash_free(&get_open_cache());
 
208
}
 
209
 
 
210
uint32_t cached_open_tables(void)
 
211
{
 
212
  return get_open_cache().records;
 
213
}
 
214
 
84
215
 
85
216
/*
86
217
  Close cursor handle, but leave the table in the table cache
93
224
  By leaving the table in the table cache, it disallows any other thread
94
225
  to open the table
95
226
 
96
 
  session->getKilled() will be set if we run out of memory
 
227
  session->killed will be set if we run out of memory
97
228
 
98
229
  If closing a MERGE child, the calling function has to take care for
99
230
  closing the parent too, if necessary.
102
233
 
103
234
void close_handle_and_leave_table_as_lock(Table *table)
104
235
{
 
236
  TableShare *share, *old_share= table->getMutableShare();
105
237
  assert(table->db_stat);
106
238
  assert(table->getShare()->getType() == message::Table::STANDARD);
107
239
 
112
244
  */
113
245
  TableIdentifier identifier(table->getShare()->getSchemaName(), table->getShare()->getTableName(), message::Table::INTERNAL);
114
246
  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()));
 
247
  share= new TableShare(identifier.getType(),
 
248
                        identifier,
 
249
                        const_cast<char *>(&key[0]),  static_cast<uint32_t>(old_share->getCacheKeySize()));
118
250
 
119
251
  table->cursor->close();
120
252
  table->db_stat= 0;                            // Mark cursor closed
121
253
  TableShare::release(table->getMutableShare());
122
254
  table->setShare(share);
 
255
  table->cursor->change_table_ptr(table, table->getMutableShare());
123
256
}
124
257
 
125
258
 
137
270
  }
138
271
}
139
272
 
 
273
/*
 
274
  Remove table from the open table cache
 
275
 
 
276
  SYNOPSIS
 
277
  free_cache_entry()
 
278
  entry         Table to remove
 
279
 
 
280
  NOTE
 
281
  We need to have a lock on LOCK_open when calling this
 
282
*/
 
283
 
 
284
void free_cache_entry(void *entry)
 
285
{
 
286
  Table *table= static_cast<Table *>(entry);
 
287
 
 
288
  table->intern_close_table();
 
289
  if (not table->in_use)
 
290
  {
 
291
    unused_tables.unlink(table);
 
292
  }
 
293
 
 
294
  if (table->isPlaceHolder())
 
295
  {
 
296
    delete table;
 
297
  }
 
298
  else
 
299
  {
 
300
    free(table);
 
301
  }
 
302
}
 
303
 
140
304
/* Free resources allocated by filesort() and read_record() */
141
305
 
142
306
void Table::free_io_cache()
143
307
{
144
308
  if (sort.io_cache)
145
309
  {
146
 
    sort.io_cache->close_cached_file();
 
310
    close_cached_file(sort.io_cache);
147
311
    delete sort.io_cache;
148
312
    sort.io_cache= 0;
149
313
  }
155
319
 
156
320
  @param session Thread context (may be NULL)
157
321
  @param tables List of tables to remove from the cache
158
 
  @param have_lock If table::Cache::singleton().mutex() is locked
 
322
  @param have_lock If LOCK_open is locked
159
323
  @param wait_for_refresh Wait for a impending flush
160
324
  @param wait_for_placeholders Wait for tables being reopened so that the GRL
161
325
  won't proceed while write-locked tables are being reopened by other
170
334
  bool result= false;
171
335
  Session *session= this;
172
336
 
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
 
      {
 
337
  pthread_mutex_lock(&LOCK_open); /* Optionally lock for remove tables from open_cahe if not in use */
 
338
 
 
339
  if (tables == NULL)
 
340
  {
 
341
    refresh_version++;                          // Force close of open tables
 
342
 
 
343
    unused_tables.clear();
 
344
 
 
345
    if (wait_for_refresh)
 
346
    {
 
347
      /*
 
348
        Other threads could wait in a loop in open_and_lock_tables(),
 
349
        trying to lock one or more of our tables.
 
350
 
 
351
        If they wait for the locks in thr_multi_lock(), their lock
 
352
        request is aborted. They loop in open_and_lock_tables() and
 
353
        enter open_table(). Here they notice the table is refreshed and
 
354
        wait for COND_refresh. Then they loop again in
 
355
        openTablesLock() and this time open_table() succeeds. At
 
356
        this moment, if we (the FLUSH TABLES thread) are scheduled and
 
357
        on another FLUSH TABLES enter close_cached_tables(), they could
 
358
        awake while we sleep below, waiting for others threads (us) to
 
359
        close their open tables. If this happens, the other threads
 
360
        would find the tables unlocked. They would get the locks, one
 
361
        after the other, and could do their destructive work. This is an
 
362
        issue if we have LOCK TABLES in effect.
 
363
 
 
364
        The problem is that the other threads passed all checks in
 
365
        open_table() before we refresh the table.
 
366
 
 
367
        The fix for this problem is to set some_tables_deleted for all
 
368
        threads with open tables. These threads can still get their
 
369
        locks, but will immediately release them again after checking
 
370
        this variable. They will then loop in openTablesLock()
 
371
        again. There they will wait until we update all tables version
 
372
        below.
 
373
 
 
374
        Setting some_tables_deleted is done by remove_table_from_cache()
 
375
        in the other branch.
 
376
 
 
377
        In other words (reviewer suggestion): You need this setting of
 
378
        some_tables_deleted for the case when table was opened and all
 
379
        related checks were passed before incrementing refresh_version
 
380
        (which you already have) but attempt to lock the table happened
 
381
        after the call to Session::close_old_data_files() i.e. after removal of
 
382
        current thread locks.
 
383
      */
 
384
      for (uint32_t idx=0 ; idx < get_open_cache().records ; idx++)
 
385
      {
 
386
        Table *table=(Table*) hash_element(&get_open_cache(),idx);
 
387
        if (table->in_use)
 
388
          table->in_use->some_tables_deleted= false;
 
389
      }
 
390
    }
 
391
  }
 
392
  else
 
393
  {
 
394
    bool found= false;
 
395
    for (TableList *table= tables; table; table= table->next_local)
 
396
    {
 
397
      TableIdentifier identifier(table->db, table->table_name);
 
398
      if (remove_table_from_cache(session, identifier,
 
399
                                  RTFC_OWNED_BY_Session_FLAG))
 
400
      {
 
401
        found= true;
 
402
      }
 
403
    }
 
404
    if (!found)
 
405
      wait_for_refresh= false;                  // Nothing to wait for
 
406
  }
 
407
 
 
408
  if (wait_for_refresh)
 
409
  {
 
410
    /*
 
411
      If there is any table that has a lower refresh_version, wait until
 
412
      this is closed (or this thread is killed) before returning
 
413
    */
 
414
    session->mysys_var->current_mutex= &LOCK_open;
 
415
    session->mysys_var->current_cond= &COND_refresh;
 
416
    session->set_proc_info("Flushing tables");
 
417
 
 
418
    session->close_old_data_files();
 
419
 
 
420
    bool found= true;
 
421
    /* Wait until all threads has closed all the tables we had locked */
 
422
    while (found && ! session->killed)
 
423
    {
 
424
      found= false;
 
425
      for (uint32_t idx=0 ; idx < get_open_cache().records ; idx++)
 
426
      {
 
427
        Table *table=(Table*) hash_element(&get_open_cache(), idx);
 
428
        /* Avoid a self-deadlock. */
 
429
        if (table->in_use == session)
 
430
          continue;
184
431
        /*
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.
 
432
          Note that we wait here only for tables which are actually open, and
 
433
          not for placeholders with Table::open_placeholder set. Waiting for
 
434
          latter will cause deadlock in the following scenario, for example:
 
435
 
 
436
conn1: lock table t1 write;
 
437
conn2: lock table t2 write;
 
438
conn1: flush tables;
 
439
conn2: flush tables;
 
440
 
 
441
It also does not make sense to wait for those of placeholders that
 
442
are employed by CREATE TABLE as in this case table simply does not
 
443
exist yet.
220
444
        */
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))
 
445
        if (table->needs_reopen_or_name_lock() && (table->db_stat ||
 
446
                                                   (table->open_placeholder && wait_for_placeholders)))
239
447
        {
240
448
          found= true;
 
449
          pthread_cond_wait(&COND_refresh,&LOCK_open);
 
450
          break;
241
451
        }
242
452
      }
243
 
      if (!found)
244
 
        wait_for_refresh= false;                        // Nothing to wait for
245
453
    }
 
454
    /*
 
455
      No other thread has the locked tables open; reopen them and get the
 
456
      old locks. This should always succeed (unless some external process
 
457
      has removed the tables)
 
458
    */
 
459
    result= session->reopen_tables(true, true);
246
460
 
247
 
    if (wait_for_refresh)
 
461
    /* Set version for table */
 
462
    for (Table *table= session->open_tables; table ; table= table->getNext())
248
463
    {
249
464
      /*
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
 
      }
 
465
        Preserve the version (0) of write locked tables so that a impending
 
466
        global read lock won't sneak in.
 
467
      */
 
468
      if (table->reginfo.lock_type < TL_WRITE_ALLOW_WRITE)
 
469
        table->getMutableShare()->refreshVersion();
314
470
    }
315
 
 
316
 
    table::Cache::singleton().mutex().unlock();
317
471
  }
318
472
 
 
473
  pthread_mutex_unlock(&LOCK_open);
 
474
 
319
475
  if (wait_for_refresh)
320
476
  {
321
 
    boost_unique_lock_t scopedLock(session->mysys_var->mutex);
 
477
    pthread_mutex_lock(&session->mysys_var->mutex);
322
478
    session->mysys_var->current_mutex= 0;
323
479
    session->mysys_var->current_cond= 0;
324
480
    session->set_proc_info(0);
 
481
    pthread_mutex_unlock(&session->mysys_var->mutex);
325
482
  }
326
483
 
327
484
  return result;
335
492
bool Session::free_cached_table()
336
493
{
337
494
  bool found_old_table= false;
338
 
  table::Concurrent *table= static_cast<table::Concurrent *>(open_tables);
 
495
  Table *table= open_tables;
339
496
 
340
 
  safe_mutex_assert_owner(table::Cache::singleton().mutex().native_handle());
 
497
  safe_mutex_assert_owner(&LOCK_open);
341
498
  assert(table->key_read == 0);
342
499
  assert(!table->cursor || table->cursor->inited == Cursor::NONE);
343
500
 
346
503
  if (table->needs_reopen_or_name_lock() ||
347
504
      version != refresh_version || !table->db_stat)
348
505
  {
349
 
    table::remove_table(table);
 
506
    hash_delete(&get_open_cache(), (unsigned char*) table);
350
507
    found_old_table= true;
351
508
  }
352
509
  else
359
516
 
360
517
    /* Free memory and reset for next loop */
361
518
    table->cursor->ha_reset();
362
 
    table->in_use= NULL;
 
519
    table->in_use= false;
363
520
 
364
 
    table::getUnused().link(table);
 
521
    unused_tables.link(table);
365
522
  }
366
523
 
367
524
  return found_old_table;
380
537
{
381
538
  bool found_old_table= false;
382
539
 
383
 
  safe_mutex_assert_not_owner(table::Cache::singleton().mutex().native_handle());
 
540
  safe_mutex_assert_not_owner(&LOCK_open);
384
541
 
385
 
  boost_unique_lock_t scoped_lock(table::Cache::singleton().mutex()); /* Close all open tables on Session */
 
542
  pthread_mutex_lock(&LOCK_open); /* Close all open tables on Session */
386
543
 
387
544
  while (open_tables)
388
545
  {
393
550
  if (found_old_table)
394
551
  {
395
552
    /* Tell threads waiting for refresh that something has happened */
396
 
    locking::broadcast_refresh();
 
553
    broadcast_refresh();
397
554
  }
 
555
 
 
556
  pthread_mutex_unlock(&LOCK_open);
398
557
}
399
558
 
400
559
/*
423
582
  for (; table; table= table->*link )
424
583
  {
425
584
    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)
 
585
        strcasecmp(table->db, db_name) == 0 &&
 
586
        strcasecmp(table->table_name, table_name) == 0)
428
587
      break;
429
588
  }
430
589
  return table;
495
654
    */
496
655
    assert(table);
497
656
  }
498
 
  d_name= table->getSchemaName();
499
 
  t_name= table->getTableName();
 
657
  d_name= table->db;
 
658
  t_name= table->table_name;
500
659
  t_alias= table->alias;
501
660
 
502
661
  for (;;)
517
676
}
518
677
 
519
678
 
520
 
void Open_tables_state::doGetTableNames(const SchemaIdentifier &schema_identifier,
521
 
                                        std::set<std::string>& set_of_names)
 
679
void Session::doGetTableNames(const SchemaIdentifier &schema_identifier,
 
680
                              std::set<std::string>& set_of_names)
522
681
{
523
 
  for (Table *table= getTemporaryTables() ; table ; table= table->getNext())
 
682
  for (Table *table= temporary_tables ; table ; table= table->getNext())
524
683
  {
525
684
    if (schema_identifier.compare(table->getShare()->getSchemaName()))
526
685
    {
529
688
  }
530
689
}
531
690
 
532
 
void Open_tables_state::doGetTableNames(CachedDirectory &,
533
 
                                        const SchemaIdentifier &schema_identifier,
534
 
                                        std::set<std::string> &set_of_names)
 
691
void Session::doGetTableNames(CachedDirectory &,
 
692
                              const SchemaIdentifier &schema_identifier,
 
693
                              std::set<std::string> &set_of_names)
535
694
{
536
695
  doGetTableNames(schema_identifier, set_of_names);
537
696
}
538
697
 
539
 
void Open_tables_state::doGetTableIdentifiers(const SchemaIdentifier &schema_identifier,
540
 
                                              TableIdentifier::vector &set_of_identifiers)
 
698
void Session::doGetTableIdentifiers(const SchemaIdentifier &schema_identifier,
 
699
                                    TableIdentifiers &set_of_identifiers)
541
700
{
542
 
  for (Table *table= getTemporaryTables() ; table ; table= table->getNext())
 
701
  for (Table *table= temporary_tables ; table ; table= table->getNext())
543
702
  {
544
703
    if (schema_identifier.compare(table->getShare()->getSchemaName()))
545
704
    {
550
709
  }
551
710
}
552
711
 
553
 
void Open_tables_state::doGetTableIdentifiers(CachedDirectory &,
554
 
                                              const SchemaIdentifier &schema_identifier,
555
 
                                              TableIdentifier::vector &set_of_identifiers)
 
712
void Session::doGetTableIdentifiers(CachedDirectory &,
 
713
                                    const SchemaIdentifier &schema_identifier,
 
714
                                    TableIdentifiers &set_of_identifiers)
556
715
{
557
716
  doGetTableIdentifiers(schema_identifier, set_of_identifiers);
558
717
}
559
718
 
560
 
bool Open_tables_state::doDoesTableExist(const TableIdentifier &identifier)
 
719
bool Session::doDoesTableExist(const TableIdentifier &identifier)
561
720
{
562
 
  for (Table *table= getTemporaryTables() ; table ; table= table->getNext())
 
721
  for (Table *table= temporary_tables ; table ; table= table->getNext())
563
722
  {
564
723
    if (table->getShare()->getType() == message::Table::TEMPORARY)
565
724
    {
566
 
      if (identifier.getKey() == table->getShare()->getCacheKey())
 
725
      if (identifier.compare(table->getShare()->getSchemaName(), table->getShare()->getTableName()))
567
726
      {
568
727
        return true;
569
728
      }
573
732
  return false;
574
733
}
575
734
 
576
 
int Open_tables_state::doGetTableDefinition(const TableIdentifier &identifier,
 
735
int Session::doGetTableDefinition(const TableIdentifier &identifier,
577
736
                                  message::Table &table_proto)
578
737
{
579
 
  for (Table *table= getTemporaryTables() ; table ; table= table->getNext())
 
738
  for (Table *table= temporary_tables ; table ; table= table->getNext())
580
739
  {
581
740
    if (table->getShare()->getType() == message::Table::TEMPORARY)
582
741
    {
583
 
      if (identifier.getKey() == table->getShare()->getCacheKey())
 
742
      if (identifier.compare(table->getShare()->getSchemaName(), table->getShare()->getTableName()))
584
743
      {
585
744
        table_proto.CopyFrom(*(table->getShare()->getTableProto()));
586
745
 
592
751
  return ENOENT;
593
752
}
594
753
 
595
 
Table *Open_tables_state::find_temporary_table(const TableIdentifier &identifier)
 
754
Table *Session::find_temporary_table(const char *new_db, const char *table_name)
 
755
{
 
756
  char  key[MAX_DBKEY_LENGTH];
 
757
  uint  key_length;
 
758
 
 
759
  key_length= TableIdentifier::createKey(key, new_db, table_name);
 
760
 
 
761
  for (Table *table= temporary_tables ; table ; table= table->getNext())
 
762
  {
 
763
    const TableIdentifier::Key &share_key(table->getShare()->getCacheKey());
 
764
    if (share_key.size() == key_length &&
 
765
        not memcmp(&share_key[0], key, key_length))
 
766
    {
 
767
      return table;
 
768
    }
 
769
  }
 
770
  return NULL;                               // Not a temporary table
 
771
}
 
772
 
 
773
Table *Session::find_temporary_table(TableList *table_list)
 
774
{
 
775
  return find_temporary_table(table_list->db, table_list->table_name);
 
776
}
 
777
 
 
778
Table *Session::find_temporary_table(TableIdentifier &identifier)
596
779
{
597
780
  for (Table *table= temporary_tables ; table ; table= table->getNext())
598
781
  {
630
813
  @retval -1  the table is in use by a outer query
631
814
*/
632
815
 
633
 
int Open_tables_state::drop_temporary_table(const drizzled::TableIdentifier &identifier)
 
816
int Session::drop_temporary_table(TableList *table_list)
634
817
{
635
818
  Table *table;
636
819
 
637
 
  if (not (table= find_temporary_table(identifier)))
 
820
  if (not (table= find_temporary_table(table_list)))
638
821
    return 1;
639
822
 
640
823
  /* Table might be in use by some outer statement. */
641
 
  if (table->query_id && table->query_id != getQueryId())
 
824
  if (table->query_id && table->query_id != query_id)
642
825
  {
643
 
    my_error(ER_CANT_REOPEN_TABLE, MYF(0), table->getAlias());
 
826
    my_error(ER_CANT_REOPEN_TABLE, MYF(0), table->alias);
644
827
    return -1;
645
828
  }
646
829
 
656
839
 
657
840
  @param  session     Thread context
658
841
  @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
842
*/
662
843
 
663
844
void Session::unlink_open_table(Table *find)
664
845
{
665
 
  const TableIdentifier::Key find_key(find->getShare()->getCacheKey());
666
 
  Table **prev;
667
 
  safe_mutex_assert_owner(table::Cache::singleton().mutex().native_handle());
 
846
  char key[MAX_DBKEY_LENGTH];
 
847
  uint32_t key_length= find->getShare()->getCacheKeySize();
 
848
  Table *list, **prev;
 
849
  safe_mutex_assert_owner(&LOCK_open);
668
850
 
 
851
  memcpy(key, &find->getMutableShare()->getCacheKey()[0], key_length);
669
852
  /*
670
 
    Note that we need to hold table::Cache::singleton().mutex() while changing the
 
853
    Note that we need to hold LOCK_open while changing the
671
854
    open_tables list. Another thread may work on it.
672
 
    (See: table::Cache::singleton().removeTable(), mysql_wait_completed_table())
 
855
    (See: remove_table_from_cache(), mysql_wait_completed_table())
673
856
    Closing a MERGE child before the parent would be fatal if the
674
857
    other thread tries to abort the MERGE lock in between.
675
858
  */
676
859
  for (prev= &open_tables; *prev; )
677
860
  {
678
 
    Table *list= *prev;
 
861
    list= *prev;
679
862
 
680
 
    if (list->getShare()->getCacheKey() == find_key)
 
863
    if (list->getShare()->getCacheKeySize() == key_length &&
 
864
        not memcmp(&list->getShare()->getCacheKey()[0], key, key_length))
681
865
    {
682
866
      /* Remove table from open_tables list. */
683
867
      *prev= list->getNext();
684
868
 
685
869
      /* Close table. */
686
 
      table::remove_table(static_cast<table::Concurrent *>(list));
 
870
      hash_delete(&get_open_cache(),(unsigned char*) list); // Close table
687
871
    }
688
872
    else
689
873
    {
693
877
  }
694
878
 
695
879
  // Notify any 'refresh' threads
696
 
  locking::broadcast_refresh();
 
880
  broadcast_refresh();
697
881
}
698
882
 
699
883
 
716
900
  table that was locked with LOCK TABLES.
717
901
*/
718
902
 
719
 
void Session::drop_open_table(Table *table, const TableIdentifier &identifier)
 
903
void Session::drop_open_table(Table *table, TableIdentifier &identifier)
720
904
{
721
905
  if (table->getShare()->getType())
722
906
  {
724
908
  }
725
909
  else
726
910
  {
727
 
    boost_unique_lock_t scoped_lock(table::Cache::singleton().mutex()); /* Close and drop a table (AUX routine) */
 
911
    pthread_mutex_lock(&LOCK_open); /* Close and drop a table (AUX routine) */
728
912
    /*
729
913
      unlink_open_table() also tells threads waiting for refresh or close
730
914
      that something has happened.
731
915
    */
732
916
    unlink_open_table(table);
733
 
    plugin::StorageEngine::dropTable(*this, identifier);
 
917
    quick_rm_table(*this, identifier);
 
918
    pthread_mutex_unlock(&LOCK_open);
734
919
  }
735
920
}
736
921
 
746
931
  cond  Condition to wait for
747
932
*/
748
933
 
749
 
void Session::wait_for_condition(boost::mutex &mutex, boost::condition_variable_any &cond)
 
934
void Session::wait_for_condition(pthread_mutex_t *mutex, pthread_cond_t *cond)
750
935
{
751
936
  /* Wait until the current table is up to date */
752
937
  const char *saved_proc_info;
753
 
  mysys_var->current_mutex= &mutex;
754
 
  mysys_var->current_cond= &cond;
 
938
  mysys_var->current_mutex= mutex;
 
939
  mysys_var->current_cond= cond;
755
940
  saved_proc_info= get_proc_info();
756
941
  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);
 
942
  if (!killed)
 
943
    (void) pthread_cond_wait(cond, mutex);
 
944
 
 
945
  /*
 
946
    We must unlock mutex first to avoid deadlock becasue conditions are
 
947
    sent to this thread by doing locks in the following order:
 
948
    lock(mysys_var->mutex)
 
949
    lock(mysys_var->current_mutex)
 
950
 
 
951
    One by effect of this that one can only use wait_for_condition with
 
952
    condition variables that are guranteed to not disapper (freed) even if this
 
953
    mutex is unlocked
 
954
  */
 
955
 
 
956
  pthread_mutex_unlock(mutex);
 
957
  pthread_mutex_lock(&mysys_var->mutex);
775
958
  mysys_var->current_mutex= 0;
776
959
  mysys_var->current_cond= 0;
777
960
  set_proc_info(saved_proc_info);
 
961
  pthread_mutex_unlock(&mysys_var->mutex);
 
962
}
 
963
 
 
964
 
 
965
/*
 
966
  Open table which is already name-locked by this thread.
 
967
 
 
968
  SYNOPSIS
 
969
  reopen_name_locked_table()
 
970
  session         Thread handle
 
971
  table_list  TableList object for table to be open, TableList::table
 
972
  member should point to Table object which was used for
 
973
  name-locking.
 
974
  link_in     true  - if Table object for table to be opened should be
 
975
  linked into Session::open_tables list.
 
976
  false - placeholder used for name-locking is already in
 
977
  this list so we only need to preserve Table::next
 
978
  pointer.
 
979
 
 
980
  NOTE
 
981
  This function assumes that its caller already acquired LOCK_open mutex.
 
982
 
 
983
  RETURN VALUE
 
984
  false - Success
 
985
  true  - Error
 
986
*/
 
987
 
 
988
bool Session::reopen_name_locked_table(TableList* table_list, bool link_in)
 
989
{
 
990
  Table *table= table_list->table;
 
991
  TableShare *share;
 
992
  char *table_name= table_list->table_name;
 
993
  Table orig_table;
 
994
 
 
995
  safe_mutex_assert_owner(&LOCK_open);
 
996
 
 
997
  if (killed || !table)
 
998
    return true;
 
999
 
 
1000
  orig_table= *table;
 
1001
 
 
1002
  TableIdentifier identifier(table_list->db, table_list->table_name);
 
1003
  if (open_unireg_entry(this, table, table_name, identifier))
 
1004
  {
 
1005
    table->intern_close_table();
 
1006
    /*
 
1007
      If there was an error during opening of table (for example if it
 
1008
      does not exist) '*table' object can be wiped out. To be able
 
1009
      properly release name-lock in this case we should restore this
 
1010
      object to its original state.
 
1011
    */
 
1012
    *table= orig_table;
 
1013
    return true;
 
1014
  }
 
1015
 
 
1016
  share= table->getMutableShare();
 
1017
  /*
 
1018
    We want to prevent other connections from opening this table until end
 
1019
    of statement as it is likely that modifications of table's metadata are
 
1020
    not yet finished (for example CREATE TRIGGER have to change .TRG cursor,
 
1021
    or we might want to drop table if CREATE TABLE ... SELECT fails).
 
1022
    This also allows us to assume that no other connection will sneak in
 
1023
    before we will get table-level lock on this table.
 
1024
  */
 
1025
  share->resetVersion();
 
1026
  table->in_use = this;
 
1027
 
 
1028
  if (link_in)
 
1029
  {
 
1030
    table->setNext(open_tables);
 
1031
    open_tables= table;
 
1032
  }
 
1033
  else
 
1034
  {
 
1035
    /*
 
1036
      Table object should be already in Session::open_tables list so we just
 
1037
      need to set Table::next correctly.
 
1038
    */
 
1039
    table->setNext(orig_table.getNext());
 
1040
  }
 
1041
 
 
1042
  table->tablenr= current_tablenr++;
 
1043
  table->used_fields= 0;
 
1044
  table->const_table= 0;
 
1045
  table->null_row= false;
 
1046
  table->maybe_null= false;
 
1047
  table->force_index= false;
 
1048
  table->status= STATUS_NO_RECORD;
 
1049
 
 
1050
  return false;
778
1051
}
779
1052
 
780
1053
 
791
1064
  case of failure.
792
1065
*/
793
1066
 
794
 
table::Placeholder *Session::table_cache_insert_placeholder(const drizzled::TableIdentifier &arg)
 
1067
Table *Session::table_cache_insert_placeholder(const char *db_name, const char *table_name, const char *, uint32_t)
795
1068
{
796
 
  safe_mutex_assert_owner(table::Cache::singleton().mutex().native_handle());
 
1069
  safe_mutex_assert_owner(&LOCK_open);
797
1070
 
798
1071
  /*
799
1072
    Create a table entry with the right key and with an old refresh version
 
1073
    Note that we must use multi_malloc() here as this is freed by the
 
1074
    table cache
800
1075
  */
801
 
  TableIdentifier identifier(arg.getSchemaName(), arg.getTableName(), message::Table::INTERNAL);
802
 
  table::Placeholder *table= new table::Placeholder(this, identifier);
 
1076
  TableIdentifier identifier(db_name, table_name, message::Table::INTERNAL);
 
1077
  TablePlaceholder *table= new TablePlaceholder(this, identifier);
803
1078
 
804
 
  if (not table::Cache::singleton().insert(table))
 
1079
  if (my_hash_insert(&get_open_cache(), (unsigned char*)table))
805
1080
  {
806
1081
    delete table;
807
1082
 
833
1108
  @retval  true   Error occured (OOM)
834
1109
  @retval  false  Success. 'table' parameter set according to above rules.
835
1110
*/
836
 
bool Session::lock_table_name_if_not_cached(const TableIdentifier &identifier, Table **table)
837
 
{
838
 
  const TableIdentifier::Key &key(identifier.getKey());
839
 
 
840
 
  boost_unique_lock_t scope_lock(table::Cache::singleton().mutex()); /* Obtain a name lock even though table is not in cache (like for create table)  */
841
 
 
842
 
  table::CacheMap::iterator iter;
843
 
 
844
 
  iter= table::getCache().find(key);
845
 
 
846
 
  if (iter != table::getCache().end())
 
1111
bool Session::lock_table_name_if_not_cached(TableIdentifier &identifier, Table **table)
 
1112
{
 
1113
  return lock_table_name_if_not_cached(identifier.getSchemaName().c_str(), identifier.getTableName().c_str(), table);
 
1114
}
 
1115
 
 
1116
bool Session::lock_table_name_if_not_cached(const char *new_db,
 
1117
                                            const char *table_name, Table **table)
 
1118
{
 
1119
  char key[MAX_DBKEY_LENGTH];
 
1120
  uint32_t key_length;
 
1121
 
 
1122
  key_length= TableIdentifier::createKey(key, new_db, table_name);
 
1123
 
 
1124
  pthread_mutex_lock(&LOCK_open); /* Obtain a name lock even though table is not in cache (like for create table)  */
 
1125
 
 
1126
  if (hash_search(&get_open_cache(), (unsigned char *)key, key_length))
847
1127
  {
 
1128
    pthread_mutex_unlock(&LOCK_open);
848
1129
    *table= 0;
849
1130
    return false;
850
1131
  }
851
1132
 
852
 
  if (not (*table= table_cache_insert_placeholder(identifier)))
 
1133
  if (not (*table= table_cache_insert_placeholder(new_db, table_name, key, key_length)))
853
1134
  {
 
1135
    pthread_mutex_unlock(&LOCK_open);
854
1136
    return true;
855
1137
  }
856
1138
  (*table)->open_placeholder= true;
857
1139
  (*table)->setNext(open_tables);
858
1140
  open_tables= *table;
 
1141
  pthread_mutex_unlock(&LOCK_open);
859
1142
 
860
1143
  return false;
861
1144
}
896
1179
Table *Session::openTable(TableList *table_list, bool *refresh, uint32_t flags)
897
1180
{
898
1181
  Table *table;
 
1182
  unsigned int key_length;
899
1183
  const char *alias= table_list->alias;
 
1184
  HASH_SEARCH_STATE state;
900
1185
 
901
1186
  /* Parsing of partitioning information from .frm needs session->lex set up. */
902
1187
  assert(lex->is_lex_started);
909
1194
  if (check_stack_overrun(this, STACK_MIN_SIZE_FOR_OPEN, (unsigned char *)&alias))
910
1195
    return NULL;
911
1196
 
912
 
  if (getKilled())
 
1197
  if (killed)
913
1198
    return NULL;
914
1199
 
915
 
  TableIdentifier identifier(table_list->getSchemaName(), table_list->getTableName());
 
1200
  TableIdentifier identifier(table_list->db, table_list->table_name);
916
1201
  const TableIdentifier::Key &key(identifier.getKey());
917
 
  table::CacheRange ppp;
 
1202
  key_length= key.size();
918
1203
 
919
1204
  /*
920
1205
    Unless requested otherwise, try to resolve this table in the list
923
1208
    same name. This block implements the behaviour.
924
1209
    TODO -> move this block into a separate function.
925
1210
  */
926
 
  bool reset= false;
927
 
  for (table= getTemporaryTables(); table ; table=table->getNext())
 
1211
  for (table= temporary_tables; table ; table=table->getNext())
928
1212
  {
929
1213
    if (table->getShare()->getCacheKey() == key)
930
1214
    {
936
1220
      */
937
1221
      if (table->query_id)
938
1222
      {
939
 
        my_error(ER_CANT_REOPEN_TABLE, MYF(0), table->getAlias());
 
1223
        my_error(ER_CANT_REOPEN_TABLE, MYF(0), table->alias);
940
1224
        return NULL;
941
1225
      }
942
1226
      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
 
 
 
1227
      goto reset;
 
1228
    }
 
1229
  }
 
1230
 
 
1231
  if (flags & DRIZZLE_OPEN_TEMPORARY_ONLY)
 
1232
  {
 
1233
    my_error(ER_NO_SUCH_TABLE, MYF(0), table_list->db, table_list->table_name);
 
1234
    return NULL;
 
1235
  }
 
1236
 
 
1237
  /*
 
1238
    If it's the first table from a list of tables used in a query,
 
1239
    remember refresh_version (the version of open_cache state).
 
1240
    If the version changes while we're opening the remaining tables,
 
1241
    we will have to back off, close all the tables opened-so-far,
 
1242
    and try to reopen them.
 
1243
 
 
1244
    Note-> refresh_version is currently changed only during FLUSH TABLES.
 
1245
  */
 
1246
  if (!open_tables)
 
1247
  {
 
1248
    version= refresh_version;
 
1249
  }
 
1250
  else if ((version != refresh_version) &&
 
1251
           ! (flags & DRIZZLE_LOCK_IGNORE_FLUSH))
 
1252
  {
 
1253
    /* Someone did a refresh while thread was opening tables */
 
1254
    if (refresh)
 
1255
      *refresh= true;
 
1256
 
 
1257
    return NULL;
 
1258
  }
 
1259
 
 
1260
  /*
 
1261
    Before we test the global cache, we test our local session cache.
 
1262
  */
 
1263
  if (cached_table)
 
1264
  {
 
1265
    assert(false); /* Not implemented yet */
 
1266
  }
 
1267
 
 
1268
  /*
 
1269
    Non pre-locked/LOCK TABLES mode, and the table is not temporary:
 
1270
    this is the normal use case.
 
1271
    Now we should:
 
1272
    - try to find the table in the table cache.
 
1273
    - if one of the discovered Table instances is name-locked
 
1274
    (table->getShare()->version == 0) back off -- we have to wait
 
1275
    until no one holds a name lock on the table.
 
1276
    - if there is no such Table in the name cache, read the table definition
 
1277
    and insert it into the cache.
 
1278
    We perform all of the above under LOCK_open which currently protects
 
1279
    the open cache (also known as table cache) and table definitions stored
 
1280
    on disk.
 
1281
  */
 
1282
 
 
1283
  pthread_mutex_lock(&LOCK_open); /* Lock for FLUSH TABLES for open table */
 
1284
 
 
1285
  /*
 
1286
    Actually try to find the table in the open_cache.
 
1287
    The cache may contain several "Table" instances for the same
 
1288
    physical table. The instances that are currently "in use" by
 
1289
    some thread have their "in_use" member != NULL.
 
1290
    There is no good reason for having more than one entry in the
 
1291
    hash for the same physical table, except that we use this as
 
1292
    an implicit "pending locks queue" - see
 
1293
    wait_for_locked_table_names for details.
 
1294
  */
 
1295
  for (table= (Table*) hash_first(&get_open_cache(), (unsigned char*) &key[0], key_length,
 
1296
                                  &state);
 
1297
       table && table->in_use ;
 
1298
       table= (Table*) hash_next(&get_open_cache(), (unsigned char*) &key[0], key_length,
 
1299
                                 &state))
 
1300
  {
956
1301
    /*
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.
 
1302
      Here we flush tables marked for flush.
 
1303
      Normally, table->getShare()->version contains the value of
 
1304
      refresh_version from the moment when this table was
 
1305
      (re-)opened and added to the cache.
 
1306
      If since then we did (or just started) FLUSH TABLES
 
1307
      statement, refresh_version has been increased.
 
1308
      For "name-locked" Table instances, table->getShare()->version is set
 
1309
      to 0 (see lock_table_name for details).
 
1310
      In case there is a pending FLUSH TABLES or a name lock, we
 
1311
      need to back off and re-start opening tables.
 
1312
      If we do not back off now, we may dead lock in case of lock
 
1313
      order mismatch with some other thread:
 
1314
c1: name lock t1; -- sort of exclusive lock
 
1315
c2: open t2;      -- sort of shared lock
 
1316
c1: name lock t2; -- blocks
 
1317
c2: open t1; -- blocks
964
1318
    */
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 */
 
1319
    if (table->needs_reopen_or_name_lock())
 
1320
    {
 
1321
      if (flags & DRIZZLE_LOCK_IGNORE_FLUSH)
 
1322
      {
 
1323
        /* Force close at once after usage */
 
1324
        version= table->getShare()->getVersion();
 
1325
        continue;
 
1326
      }
 
1327
 
 
1328
      /* Avoid self-deadlocks by detecting self-dependencies. */
 
1329
      if (table->open_placeholder && table->in_use == this)
 
1330
      {
 
1331
        pthread_mutex_unlock(&LOCK_open);
 
1332
        my_error(ER_UPDATE_TABLE_USED, MYF(0), table->getMutableShare()->getTableName());
 
1333
        return NULL;
 
1334
      }
 
1335
 
 
1336
      /*
 
1337
        Back off, part 1: mark the table as "unused" for the
 
1338
        purpose of name-locking by setting table->db_stat to 0. Do
 
1339
        that only for the tables in this thread that have an old
 
1340
        table->getShare()->version (this is an optimization (?)).
 
1341
        table->db_stat == 0 signals wait_for_locked_table_names
 
1342
        that the tables in question are not used any more. See
 
1343
        table_is_used call for details.
 
1344
      */
 
1345
      close_old_data_files(false, false);
 
1346
 
 
1347
      /*
 
1348
        Back-off part 2: try to avoid "busy waiting" on the table:
 
1349
        if the table is in use by some other thread, we suspend
 
1350
        and wait till the operation is complete: when any
 
1351
        operation that juggles with table->getShare()->version completes,
 
1352
        it broadcasts COND_refresh condition variable.
 
1353
        If 'old' table we met is in use by current thread we return
 
1354
        without waiting since in this situation it's this thread
 
1355
        which is responsible for broadcasting on COND_refresh
 
1356
        (and this was done already in Session::close_old_data_files()).
 
1357
        Good example of such situation is when we have statement
 
1358
        that needs two instances of table and FLUSH TABLES comes
 
1359
        after we open first instance but before we open second
 
1360
        instance.
 
1361
      */
 
1362
      if (table->in_use != this)
 
1363
      {
 
1364
        /* wait_for_conditionwill unlock LOCK_open for us */
 
1365
        wait_for_condition(&LOCK_open, &COND_refresh);
 
1366
      }
 
1367
      else
 
1368
      {
 
1369
        pthread_mutex_unlock(&LOCK_open);
 
1370
      }
 
1371
      /*
 
1372
        There is a refresh in progress for this table.
 
1373
        Signal the caller that it has to try again.
 
1374
      */
973
1375
      if (refresh)
974
1376
        *refresh= true;
975
 
 
976
1377
      return NULL;
977
1378
    }
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 */
985
 
    }
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
 
 
1002
 
    {
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)
 
1379
  }
 
1380
  if (table)
 
1381
  {
 
1382
    unused_tables.unlink(table);
 
1383
    table->in_use= this;
 
1384
  }
 
1385
  else
 
1386
  {
 
1387
    /* Insert a new Table instance into the open cache */
 
1388
    int error;
 
1389
    /* Free cache if too big */
 
1390
    unused_tables.cull();
 
1391
 
 
1392
    if (table_list->isCreate())
 
1393
    {
 
1394
      TableIdentifier  lock_table_identifier(table_list->db, table_list->table_name, message::Table::STANDARD);
 
1395
 
 
1396
      if (not plugin::StorageEngine::doesTableExist(*this, lock_table_identifier))
1020
1397
      {
1021
 
        table= (*iter).second;
1022
 
 
1023
 
        if (not table->in_use)
1024
 
          break;
1025
1398
        /*
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
 
1399
          Table to be created, so we need to create placeholder in table-cache.
1042
1400
        */
1043
 
        if (table->needs_reopen_or_name_lock())
 
1401
        if (!(table= table_cache_insert_placeholder(table_list->db, table_list->table_name, &key[0], key_length)))
1044
1402
        {
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;
 
1403
          pthread_mutex_unlock(&LOCK_open);
1101
1404
          return NULL;
1102
1405
        }
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
 
  }
 
1406
        /*
 
1407
          Link placeholder to the open tables list so it will be automatically
 
1408
          removed once tables are closed. Also mark it so it won't be ignored
 
1409
          by other trying to take name-lock.
 
1410
        */
 
1411
        table->open_placeholder= true;
 
1412
        table->setNext(open_tables);
 
1413
        open_tables= table;
 
1414
        pthread_mutex_unlock(&LOCK_open);
 
1415
 
 
1416
        return table ;
 
1417
      }
 
1418
      /* Table exists. Let us try to open it. */
 
1419
    }
 
1420
 
 
1421
    /* make a new table */
 
1422
    table= (Table *)malloc(sizeof(Table));
 
1423
    memset(table, 0, sizeof(Table));
 
1424
    if (table == NULL)
 
1425
    {
 
1426
      pthread_mutex_unlock(&LOCK_open);
 
1427
      return NULL;
 
1428
    }
 
1429
 
 
1430
    error= open_unireg_entry(this, table, alias, identifier);
 
1431
    if (error != 0)
 
1432
    {
 
1433
      free(table);
 
1434
      pthread_mutex_unlock(&LOCK_open);
 
1435
      return NULL;
 
1436
    }
 
1437
    my_hash_insert(&get_open_cache(), (unsigned char*) table);
 
1438
  }
 
1439
 
 
1440
  pthread_mutex_unlock(&LOCK_open);
 
1441
  if (refresh)
 
1442
  {
 
1443
    table->setNext(open_tables); /* Link into simple list */
 
1444
    open_tables= table;
 
1445
  }
 
1446
  table->reginfo.lock_type= TL_READ; /* Assume read */
 
1447
 
 
1448
reset:
1176
1449
  assert(table->getShare()->getTableCount() > 0 || table->getShare()->getType() != message::Table::STANDARD);
1177
1450
 
 
1451
  if (lex->need_correct_ident())
 
1452
    table->alias_name_used= my_strcasecmp(table_alias_charset,
 
1453
                                          table->getMutableShare()->getTableName(), alias);
1178
1454
  /* Fix alias if table name changes */
1179
 
  if (strcmp(table->getAlias(), alias))
 
1455
  if (strcmp(table->alias, alias))
1180
1456
  {
1181
 
    table->setAlias(alias);
 
1457
    uint32_t length=(uint32_t) strlen(alias)+1;
 
1458
    table->alias= (char*) realloc((char*) table->alias, length);
 
1459
    memcpy((void*) table->alias, alias, length);
1182
1460
  }
1183
1461
 
1184
1462
  /* These variables are also set in reopen_table() */
1189
1467
  table->maybe_null= false;
1190
1468
  table->force_index= false;
1191
1469
  table->status=STATUS_NO_RECORD;
1192
 
  table->insert_values.clear();
 
1470
  table->insert_values= 0;
1193
1471
  /* Catch wrong handling of the auto_increment_field_not_null. */
1194
1472
  assert(!table->auto_increment_field_not_null);
1195
1473
  table->auto_increment_field_not_null= false;
1205
1483
}
1206
1484
 
1207
1485
 
 
1486
#if 0
 
1487
/*
 
1488
  Reopen an table because the definition has changed.
 
1489
 
 
1490
  SYNOPSIS
 
1491
  reopen_table()
 
1492
  table Table object
 
1493
 
 
1494
  NOTES
 
1495
  The data cursor for the table is already closed and the share is released
 
1496
  The table has a 'dummy' share that mainly contains database and table name.
 
1497
 
 
1498
  RETURN
 
1499
  0  ok
 
1500
  1  error. The old table object is not changed.
 
1501
*/
 
1502
 
 
1503
bool reopen_table(Table *table)
 
1504
{
 
1505
  Table tmp;
 
1506
  bool error= 1;
 
1507
  Field **field;
 
1508
  uint32_t key,part;
 
1509
  TableList table_list;
 
1510
  Session *session= table->in_use;
 
1511
 
 
1512
  assert(table->getShare()->ref_count == 0);
 
1513
  assert(!table->sort.io_cache);
 
1514
 
 
1515
#ifdef EXTRA_DEBUG
 
1516
  if (table->db_stat)
 
1517
    errmsg_printf(ERRMSG_LVL_ERROR, _("Table %s had a open data Cursor in reopen_table"),
 
1518
                  table->alias);
 
1519
#endif
 
1520
  table_list.db=         const_cast<char *>(table->getShare()->getSchemaName());
 
1521
  table_list.table_name= table->getShare()->getTableName();
 
1522
  table_list.table=      table;
 
1523
 
 
1524
  if (wait_for_locked_table_names(session, &table_list))
 
1525
    return true;                             // Thread was killed
 
1526
 
 
1527
  if (open_unireg_entry(session, &tmp, &table_list,
 
1528
                        table->alias,
 
1529
                        table->getShare()->getCacheKey(),
 
1530
                        table->getShare()->getCacheKeySize()))
 
1531
    goto end;
 
1532
 
 
1533
  /* This list copies variables set by open_table */
 
1534
  tmp.tablenr=          table->tablenr;
 
1535
  tmp.used_fields=      table->used_fields;
 
1536
  tmp.const_table=      table->const_table;
 
1537
  tmp.null_row=         table->null_row;
 
1538
  tmp.maybe_null=       table->maybe_null;
 
1539
  tmp.status=           table->status;
 
1540
 
 
1541
  /* Get state */
 
1542
  tmp.in_use=           session;
 
1543
  tmp.reginfo.lock_type=table->reginfo.lock_type;
 
1544
 
 
1545
  /* Replace table in open list */
 
1546
  tmp.next=             table->next;
 
1547
  tmp.prev=             table->prev;
 
1548
 
 
1549
  if (table->cursor)
 
1550
    table->delete_table(true);          // close cursor, free everything
 
1551
 
 
1552
  *table= tmp;
 
1553
  table->default_column_bitmaps();
 
1554
  table->cursor->change_table_ptr(table, table->s);
 
1555
 
 
1556
  assert(table->alias != 0);
 
1557
  for (field=table->field ; *field ; field++)
 
1558
  {
 
1559
    (*field)->table= (*field)->orig_table= table;
 
1560
    (*field)->table_name= &table->alias;
 
1561
  }
 
1562
  for (key=0 ; key < table->getShare()->keys ; key++)
 
1563
  {
 
1564
    for (part=0 ; part < table->key_info[key].usable_key_parts ; part++)
 
1565
      table->key_info[key].key_part[part].field->table= table;
 
1566
  }
 
1567
 
 
1568
  broadcast_refresh();
 
1569
  error= false;
 
1570
 
 
1571
end:
 
1572
  return(error);
 
1573
}
 
1574
#endif
 
1575
 
 
1576
 
1208
1577
/**
1209
1578
  Close all instances of a table open by this thread and replace
1210
1579
  them with exclusive name-locks.
1222
1591
  the strings are used in a loop even after the share may be freed.
1223
1592
*/
1224
1593
 
1225
 
void Session::close_data_files_and_morph_locks(const TableIdentifier &identifier)
 
1594
void Session::close_data_files_and_morph_locks(TableIdentifier &identifier)
1226
1595
{
1227
 
  safe_mutex_assert_owner(table::Cache::singleton().mutex().native_handle()); /* Adjust locks at the end of ALTER TABLEL */
 
1596
  Table *table;
 
1597
 
 
1598
  safe_mutex_assert_owner(&LOCK_open); /* Adjust locks at the end of ALTER TABLEL */
1228
1599
 
1229
1600
  if (lock)
1230
1601
  {
1232
1603
      If we are not under LOCK TABLES we should have only one table
1233
1604
      open and locked so it makes sense to remove the lock at once.
1234
1605
    */
1235
 
    unlockTables(lock);
 
1606
    mysql_unlock_tables(this, lock);
1236
1607
    lock= 0;
1237
1608
  }
1238
1609
 
1241
1612
    for target table name if we process ALTER Table ... RENAME.
1242
1613
    So loop below makes sense even if we are not under LOCK TABLES.
1243
1614
  */
1244
 
  for (Table *table= open_tables; table ; table=table->getNext())
 
1615
  for (table= open_tables; table ; table=table->getNext())
1245
1616
  {
1246
 
    if (table->getShare()->getCacheKey() == identifier.getKey())
 
1617
    if (!strcmp(table->getMutableShare()->getTableName(), identifier.getTableName().c_str()) &&
 
1618
        !strcasecmp(table->getMutableShare()->getSchemaName(), identifier.getSchemaName().c_str()))
1247
1619
    {
1248
1620
      table->open_placeholder= true;
1249
1621
      close_handle_and_leave_table_as_lock(table);
1267
1639
  combination when one needs tables to be reopened (for
1268
1640
  example see openTablesLock()).
1269
1641
 
1270
 
  @note One should have lock on table::Cache::singleton().mutex() when calling this.
 
1642
  @note One should have lock on LOCK_open when calling this.
1271
1643
 
1272
1644
  @return false in case of success, true - otherwise.
1273
1645
*/
1284
1656
  if (open_tables == NULL)
1285
1657
    return false;
1286
1658
 
1287
 
  safe_mutex_assert_owner(table::Cache::singleton().mutex().native_handle());
 
1659
  safe_mutex_assert_owner(&LOCK_open);
1288
1660
  if (get_locks)
1289
1661
  {
1290
1662
    /*
1310
1682
  {
1311
1683
    next= table->getNext();
1312
1684
 
1313
 
    my_error(ER_CANT_REOPEN_TABLE, MYF(0), table->getAlias());
1314
 
    table::remove_table(static_cast<table::Concurrent *>(table));
 
1685
    my_error(ER_CANT_REOPEN_TABLE, MYF(0), table->alias);
 
1686
    hash_delete(&get_open_cache(),(unsigned char*) table);
1315
1687
    error= 1;
1316
1688
  }
1317
1689
  *prev=0;
1318
1690
  if (tables != tables_ptr)                     // Should we get back old locks
1319
1691
  {
1320
 
    DrizzleLock *local_lock;
 
1692
    DRIZZLE_LOCK *local_lock;
1321
1693
    /*
1322
1694
      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
 
1695
      wait_for_tables() as it tries to acquire LOCK_open, which is
1324
1696
      already locked.
1325
1697
    */
1326
1698
    some_tables_deleted= false;
1327
1699
 
1328
 
    if ((local_lock= lockTables(tables, (uint32_t) (tables_ptr - tables),
1329
 
                                       flags, &not_used)))
 
1700
    if ((local_lock= mysql_lock_tables(this, tables, (uint32_t) (tables_ptr - tables),
 
1701
                                 flags, &not_used)))
1330
1702
    {
1331
1703
      /* unused */
1332
1704
    }
1345
1717
  if (get_locks && tables)
1346
1718
    delete [] tables;
1347
1719
 
1348
 
  locking::broadcast_refresh();
 
1720
  broadcast_refresh();
1349
1721
 
1350
1722
  return(error);
1351
1723
}
1392
1764
              lock on it. This will also give them a chance to close their
1393
1765
              instances of this table.
1394
1766
            */
1395
 
            abortLock(ulcktbl);
1396
 
            removeLock(ulcktbl);
 
1767
            mysql_lock_abort(this, ulcktbl);
 
1768
            mysql_lock_remove(this, ulcktbl);
1397
1769
            ulcktbl->lock_count= 0;
1398
1770
          }
1399
1771
          if ((ulcktbl != table) && ulcktbl->db_stat)
1433
1805
    }
1434
1806
  }
1435
1807
  if (found)
1436
 
    locking::broadcast_refresh();
 
1808
    broadcast_refresh();
 
1809
}
 
1810
 
 
1811
 
 
1812
/*
 
1813
  Wait until all threads has closed the tables in the list
 
1814
  We have also to wait if there is thread that has a lock on this table even
 
1815
  if the table is closed
 
1816
*/
 
1817
 
 
1818
bool table_is_used(Table *table, bool wait_for_name_lock)
 
1819
{
 
1820
  do
 
1821
  {
 
1822
    const TableIdentifier::Key &key(table->getShare()->getCacheKey());
 
1823
 
 
1824
    HASH_SEARCH_STATE state;
 
1825
    for (Table *search= (Table*) hash_first(&get_open_cache(), (unsigned char*) &key[0],
 
1826
                                            key.size(), &state);
 
1827
         search ;
 
1828
         search= (Table*) hash_next(&get_open_cache(), (unsigned char*) &key[0],
 
1829
                                    key.size(), &state))
 
1830
    {
 
1831
      if (search->in_use == table->in_use)
 
1832
        continue;                               // Name locked by this thread
 
1833
      /*
 
1834
        We can't use the table under any of the following conditions:
 
1835
        - There is an name lock on it (Table is to be deleted or altered)
 
1836
        - If we are in flush table and we didn't execute the flush
 
1837
        - If the table engine is open and it's an old version
 
1838
        (We must wait until all engines are shut down to use the table)
 
1839
      */
 
1840
      if ( (search->locked_by_name && wait_for_name_lock) ||
 
1841
           (search->is_name_opened() && search->needs_reopen_or_name_lock()))
 
1842
        return 1;
 
1843
    }
 
1844
  } while ((table=table->getNext()));
 
1845
  return 0;
1437
1846
}
1438
1847
 
1439
1848
 
1444
1853
  bool result;
1445
1854
 
1446
1855
  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
 
  }
 
1856
  pthread_mutex_lock(&LOCK_open); /* Lock for all tables to be refreshed */
 
1857
  while (!session->killed)
 
1858
  {
 
1859
    session->some_tables_deleted= false;
 
1860
    session->close_old_data_files(false, dropping_tables != 0);
 
1861
    if (!table_is_used(session->open_tables, 1))
 
1862
      break;
 
1863
    (void) pthread_cond_wait(&COND_refresh,&LOCK_open);
 
1864
  }
 
1865
  if (session->killed)
 
1866
    result= true;                                       // aborted
 
1867
  else
 
1868
  {
 
1869
    /* Now we can open all tables without any interference */
 
1870
    session->set_proc_info("Reopen tables");
 
1871
    session->version= refresh_version;
 
1872
    result= session->reopen_tables(false, false);
 
1873
  }
 
1874
  pthread_mutex_unlock(&LOCK_open);
1469
1875
  session->set_proc_info(0);
1470
1876
 
1471
1877
  return result;
1496
1902
*/
1497
1903
 
1498
1904
 
1499
 
Table *drop_locked_tables(Session *session, const drizzled::TableIdentifier &identifier)
 
1905
Table *drop_locked_tables(Session *session, const char *db, const char *table_name)
1500
1906
{
1501
1907
  Table *table,*next,**prev, *found= 0;
1502
1908
  prev= &session->open_tables;
1503
1909
 
1504
1910
  /*
1505
 
    Note that we need to hold table::Cache::singleton().mutex() while changing the
 
1911
    Note that we need to hold LOCK_open while changing the
1506
1912
    open_tables list. Another thread may work on it.
1507
 
    (See: table::Cache::singleton().removeTable(), mysql_wait_completed_table())
 
1913
    (See: remove_table_from_cache(), mysql_wait_completed_table())
1508
1914
    Closing a MERGE child before the parent would be fatal if the
1509
1915
    other thread tries to abort the MERGE lock in between.
1510
1916
  */
1511
1917
  for (table= session->open_tables; table ; table=next)
1512
1918
  {
1513
1919
    next=table->getNext();
1514
 
    if (table->getShare()->getCacheKey() == identifier.getKey())
 
1920
    if (!strcmp(table->getMutableShare()->getTableName(), table_name) &&
 
1921
        !strcasecmp(table->getMutableShare()->getSchemaName(), db))
1515
1922
    {
1516
 
      session->removeLock(table);
 
1923
      mysql_lock_remove(session, table);
1517
1924
 
1518
1925
      if (!found)
1519
1926
      {
1528
1935
      else
1529
1936
      {
1530
1937
        /* We already have a name lock, remove copy */
1531
 
        table::remove_table(static_cast<table::Concurrent *>(table));
 
1938
        hash_delete(&get_open_cache(),(unsigned char*) table);
1532
1939
      }
1533
1940
    }
1534
1941
    else
1539
1946
  }
1540
1947
  *prev=0;
1541
1948
  if (found)
1542
 
    locking::broadcast_refresh();
 
1949
    broadcast_refresh();
1543
1950
 
1544
1951
  return(found);
1545
1952
}
1551
1958
  other threads trying to get the lock.
1552
1959
*/
1553
1960
 
1554
 
void abort_locked_tables(Session *session, const drizzled::TableIdentifier &identifier)
 
1961
void abort_locked_tables(Session *session,const char *db, const char *table_name)
1555
1962
{
1556
1963
  Table *table;
1557
1964
  for (table= session->open_tables; table ; table= table->getNext())
1558
1965
  {
1559
 
    if (table->getShare()->getCacheKey() == identifier.getKey())
 
1966
    if (!strcmp(table->getMutableShare()->getTableName(), table_name) &&
 
1967
        !strcmp(table->getMutableShare()->getSchemaName(), db))
1560
1968
    {
1561
1969
      /* If MERGE child, forward lock handling to parent. */
1562
 
      session->abortLock(table);
 
1970
      mysql_lock_abort(session, table);
1563
1971
      break;
1564
1972
    }
1565
1973
  }
1566
1974
}
1567
1975
 
 
1976
/*
 
1977
  Load a table definition from cursor and open unireg table
 
1978
 
 
1979
  SYNOPSIS
 
1980
  open_unireg_entry()
 
1981
  session                       Thread handle
 
1982
  entry         Store open table definition here
 
1983
  table_list            TableList with db, table_name
 
1984
  alias         Alias name
 
1985
  cache_key             Key for share_cache
 
1986
  cache_key_length      length of cache_key
 
1987
 
 
1988
  NOTES
 
1989
  Extra argument for open is taken from session->open_options
 
1990
  One must have a lock on LOCK_open when calling this function
 
1991
 
 
1992
  RETURN
 
1993
  0     ok
 
1994
#       Error
 
1995
*/
 
1996
 
 
1997
static int open_unireg_entry(Session *session,
 
1998
                             Table *entry,
 
1999
                             const char *alias,
 
2000
                             TableIdentifier &identifier)
 
2001
{
 
2002
  int error;
 
2003
  TableShare *share;
 
2004
  uint32_t discover_retry_count= 0;
 
2005
 
 
2006
  safe_mutex_assert_owner(&LOCK_open);
 
2007
retry:
 
2008
  if (not (share= TableShare::getShareCreate(session,
 
2009
                                             identifier,
 
2010
                                             &error)))
 
2011
    return 1;
 
2012
 
 
2013
  while ((error= share->open_table_from_share(session,
 
2014
                                              identifier,
 
2015
                                              alias,
 
2016
                                              (uint32_t) (HA_OPEN_KEYFILE |
 
2017
                                                          HA_OPEN_RNDFILE |
 
2018
                                                          HA_GET_INDEX |
 
2019
                                                          HA_TRY_READ_ONLY),
 
2020
                                              session->open_options, *entry)))
 
2021
  {
 
2022
    if (error == 7)                             // Table def changed
 
2023
    {
 
2024
      share->resetVersion();                        // Mark share as old
 
2025
      if (discover_retry_count++)               // Retry once
 
2026
        goto err;
 
2027
 
 
2028
      /*
 
2029
        TODO->
 
2030
        Here we should wait until all threads has released the table.
 
2031
        For now we do one retry. This may cause a deadlock if there
 
2032
        is other threads waiting for other tables used by this thread.
 
2033
 
 
2034
        Proper fix would be to if the second retry failed:
 
2035
        - Mark that table def changed
 
2036
        - Return from open table
 
2037
        - Close all tables used by this thread
 
2038
        - Start waiting that the share is released
 
2039
        - Retry by opening all tables again
 
2040
      */
 
2041
 
 
2042
      /*
 
2043
        TO BE FIXED
 
2044
        To avoid deadlock, only wait for release if no one else is
 
2045
        using the share.
 
2046
      */
 
2047
      if (share->getTableCount() != 1)
 
2048
        goto err;
 
2049
      /* Free share and wait until it's released by all threads */
 
2050
      TableShare::release(share);
 
2051
 
 
2052
      if (!session->killed)
 
2053
      {
 
2054
        drizzle_reset_errors(session, 1);         // Clear warnings
 
2055
        session->clear_error();                 // Clear error message
 
2056
        goto retry;
 
2057
      }
 
2058
      return 1;
 
2059
    }
 
2060
 
 
2061
    goto err;
 
2062
  }
 
2063
 
 
2064
  return 0;
 
2065
 
 
2066
err:
 
2067
  TableShare::release(share);
 
2068
 
 
2069
  return 1;
 
2070
}
 
2071
 
1568
2072
 
1569
2073
/*
1570
2074
  Open all tables in list
1632
2136
     * to see if it exists so that an unauthorized user cannot phish for
1633
2137
     * table/schema information via error messages
1634
2138
     */
1635
 
    TableIdentifier the_table(tables->getSchemaName(), tables->getTableName());
 
2139
    TableIdentifier the_table(tables->db, tables->table_name);
1636
2140
    if (not plugin::Authorization::isAuthorized(getSecurityContext(),
1637
2141
                                                the_table))
1638
2142
    {
1742
2246
 
1743
2247
    assert(lock == 0);  // You must lock everything at once
1744
2248
    if ((table->reginfo.lock_type= lock_type) != TL_UNLOCK)
1745
 
      if (! (lock= lockTables(&table_list->table, 1, 0, &refresh)))
 
2249
      if (! (lock= mysql_lock_tables(this, &table_list->table, 1, 0, &refresh)))
1746
2250
        table= 0;
1747
2251
  }
1748
2252
 
1805
2309
      *(ptr++)= table->table;
1806
2310
  }
1807
2311
 
1808
 
  if (!(session->lock= session->lockTables(start, (uint32_t) (ptr - start), lock_flag, need_reopen)))
 
2312
  if (!(session->lock= mysql_lock_tables(session, start, (uint32_t) (ptr - start),
 
2313
                                         lock_flag, need_reopen)))
1809
2314
  {
1810
2315
    return -1;
1811
2316
  }
1834
2339
#  Table object
1835
2340
*/
1836
2341
 
1837
 
Table *Open_tables_state::open_temporary_table(const TableIdentifier &identifier,
1838
 
                                               bool link_in_list)
 
2342
Table *Session::open_temporary_table(TableIdentifier &identifier,
 
2343
                                     bool link_in_list)
1839
2344
{
 
2345
  Table *new_tmp_table;
 
2346
  TableShare *share;
 
2347
 
1840
2348
  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)
 
2349
  share= new TableShare(identifier.getType(),
 
2350
                        identifier,
 
2351
                        const_cast<char *>(identifier.getPath().c_str()), static_cast<uint32_t>(identifier.getPath().length()));
 
2352
 
 
2353
 
 
2354
  if (!(new_tmp_table= (Table*) malloc(sizeof(*new_tmp_table))))
1848
2355
    return NULL;
1849
2356
 
 
2357
  memset(new_tmp_table, 0, sizeof(*new_tmp_table));
 
2358
 
 
2359
 
1850
2360
  /*
1851
2361
    First open the share, and then open the table from the share we just opened.
1852
2362
  */
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))
 
2363
  if (share->open_table_def(*this, identifier) ||
 
2364
      share->open_table_from_share(this, identifier, identifier.getTableName().c_str(),
 
2365
                            (uint32_t) (HA_OPEN_KEYFILE | HA_OPEN_RNDFILE |
 
2366
                                        HA_GET_INDEX),
 
2367
                            ha_open_options,
 
2368
                            *new_tmp_table))
1859
2369
  {
1860
2370
    /* 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;
 
2371
    delete share;
 
2372
    free((char*) new_tmp_table);
1863
2373
 
1864
2374
    return 0;
1865
2375
  }
1900
2410
{
1901
2411
  if (session->mark_used_columns != MARK_COLUMNS_NONE)
1902
2412
  {
1903
 
    boost::dynamic_bitset<> *current_bitmap= NULL;
 
2413
    MyBitmap *current_bitmap, *other_bitmap;
1904
2414
 
1905
2415
    /*
1906
2416
      We always want to register the used keys, as the column bitmap may have
1913
2423
    if (session->mark_used_columns == MARK_COLUMNS_READ)
1914
2424
    {
1915
2425
      current_bitmap= table->read_set;
 
2426
      other_bitmap=   table->write_set;
1916
2427
    }
1917
2428
    else
1918
2429
    {
1919
2430
      current_bitmap= table->write_set;
 
2431
      other_bitmap=   table->read_set;
1920
2432
    }
1921
2433
 
1922
 
    //if (current_bitmap->testAndSet(field->position()))
1923
 
    if (current_bitmap->test(field->position()))
 
2434
    if (current_bitmap->testAndSet(field->field_index))
1924
2435
    {
1925
2436
      if (session->mark_used_columns == MARK_COLUMNS_WRITE)
1926
2437
        session->dup_field= field;
2032
2543
  {
2033
2544
    field_ptr= table->getFields() + cached_field_index;
2034
2545
  }
2035
 
  else if (table->getShare()->getNamedFieldSize())
 
2546
  else if (table->getShare()->name_hash.records)
2036
2547
  {
2037
 
    field_ptr= table->getMutableShare()->getNamedField(std::string(name, length));
 
2548
    field_ptr= (Field**) hash_search(&table->getShare()->name_hash, (unsigned char*) name,
 
2549
                                     length);
2038
2550
    if (field_ptr)
2039
2551
    {
2040
2552
      /*
2154
2666
      */
2155
2667
      table_name && table_name[0] &&
2156
2668
      (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()))))
 
2669
       (db_name && db_name[0] && table_list->db && table_list->db[0] &&
 
2670
        strcmp(db_name, table_list->db))))
2159
2671
    return 0;
2160
2672
 
2161
2673
  *actual_table= NULL;
2230
2742
      {
2231
2743
        Table *table= field_to_set->getTable();
2232
2744
        if (session->mark_used_columns == MARK_COLUMNS_READ)
2233
 
          table->setReadSet(field_to_set->position());
 
2745
          table->setReadSet(field_to_set->field_index);
2234
2746
        else
2235
 
          table->setWriteSet(field_to_set->position());
 
2747
          table->setWriteSet(field_to_set->field_index);
2236
2748
      }
2237
2749
    }
2238
2750
  }
2788
3300
    /* true if field_name_1 is a member of using_fields */
2789
3301
    bool is_using_column_1;
2790
3302
    if (!(nj_col_1= it_1.get_or_create_column_ref(leaf_1)))
2791
 
      return(result);
 
3303
      goto err;
2792
3304
    field_name_1= nj_col_1->name();
2793
3305
    is_using_column_1= using_fields &&
2794
3306
      test_if_string_in_list(field_name_1, using_fields);
2806
3318
      Natural_join_column *cur_nj_col_2;
2807
3319
      const char *cur_field_name_2;
2808
3320
      if (!(cur_nj_col_2= it_2.get_or_create_column_ref(leaf_2)))
2809
 
        return(result);
 
3321
        goto err;
2810
3322
      cur_field_name_2= cur_nj_col_2->name();
2811
3323
 
2812
3324
      /*
2826
3338
            (found && (!using_fields || is_using_column_1)))
2827
3339
        {
2828
3340
          my_error(ER_NON_UNIQ_ERROR, MYF(0), field_name_1, session->where);
2829
 
          return(result);
 
3341
          goto err;
2830
3342
        }
2831
3343
        nj_col_2= cur_nj_col_2;
2832
3344
        found= true;
2859
3371
      Item_func_eq *eq_cond;
2860
3372
 
2861
3373
      if (!item_1 || !item_2)
2862
 
        return(result); // out of memory
 
3374
        goto err;                               // out of memory
2863
3375
 
2864
3376
      /*
2865
3377
        In the case of no_wrap_view_item == 0, the created items must be
2884
3396
      */
2885
3397
      if (set_new_item_local_context(session, item_ident_1, nj_col_1->table_ref) ||
2886
3398
          set_new_item_local_context(session, item_ident_2, nj_col_2->table_ref))
2887
 
        return(result);
 
3399
        goto err;
2888
3400
 
2889
3401
      if (!(eq_cond= new Item_func_eq(item_ident_1, item_ident_2)))
2890
 
        return(result);                               /* Out of memory. */
 
3402
        goto err;                               /* Out of memory. */
2891
3403
 
2892
3404
      /*
2893
3405
        Add the new equi-join condition to the ON clause. Notice that
2904
3416
      {
2905
3417
        Table *table_1= nj_col_1->table_ref->table;
2906
3418
        /* Mark field_1 used for table cache. */
2907
 
        table_1->setReadSet(field_1->position());
 
3419
        table_1->setReadSet(field_1->field_index);
2908
3420
        table_1->covering_keys&= field_1->part_of_key;
2909
3421
        table_1->merge_keys|= field_1->part_of_key;
2910
3422
      }
2912
3424
      {
2913
3425
        Table *table_2= nj_col_2->table_ref->table;
2914
3426
        /* Mark field_2 used for table cache. */
2915
 
        table_2->setReadSet(field_2->position());
 
3427
        table_2->setReadSet(field_2->field_index);
2916
3428
        table_2->covering_keys&= field_2->part_of_key;
2917
3429
        table_2->merge_keys|= field_2->part_of_key;
2918
3430
      }
2933
3445
  */
2934
3446
  result= false;
2935
3447
 
 
3448
err:
2936
3449
  return(result);
2937
3450
}
2938
3451
 
2990
3503
 
2991
3504
  if (!(non_join_columns= new List<Natural_join_column>) ||
2992
3505
      !(natural_using_join->join_columns= new List<Natural_join_column>))
2993
 
  {
2994
 
    return(result);
2995
 
  }
 
3506
    goto err;
2996
3507
 
2997
3508
  /* Append the columns of the first join operand. */
2998
3509
  for (it_1.set(table_ref_1); !it_1.end_of_fields(); it_1.next())
3031
3542
        {
3032
3543
          my_error(ER_BAD_FIELD_ERROR, MYF(0), using_field_name_ptr,
3033
3544
                   session->where);
3034
 
          return(result);
 
3545
          goto err;
3035
3546
        }
3036
3547
        if (!my_strcasecmp(system_charset_info,
3037
3548
                           common_field->name(), using_field_name_ptr))
3059
3570
 
3060
3571
  result= false;
3061
3572
 
 
3573
err:
3062
3574
  return(result);
3063
3575
}
3064
3576
 
3144
3656
      if (cur_table_ref->getNestedJoin() &&
3145
3657
          store_top_level_join_columns(session, cur_table_ref,
3146
3658
                                       real_left_neighbor, real_right_neighbor))
3147
 
        return(result);
 
3659
        goto err;
3148
3660
      same_level_right_neighbor= cur_table_ref;
3149
3661
    }
3150
3662
  }
3176
3688
      std::swap(table_ref_1, table_ref_2);
3177
3689
    if (mark_common_columns(session, table_ref_1, table_ref_2,
3178
3690
                            using_fields, &found_using_fields))
3179
 
      return(result);
 
3691
      goto err;
3180
3692
 
3181
3693
    /*
3182
3694
      Swap the join operands back, so that we pick the columns of the second
3188
3700
    if (store_natural_using_join_columns(session, table_ref, table_ref_1,
3189
3701
                                         table_ref_2, using_fields,
3190
3702
                                         found_using_fields))
3191
 
      return(result);
 
3703
      goto err;
3192
3704
 
3193
3705
    /*
3194
3706
      Change NATURAL JOIN to JOIN ... ON. We do this for both operands
3221
3733
  }
3222
3734
  result= false; /* All is OK. */
3223
3735
 
 
3736
err:
3224
3737
  return(result);
3225
3738
}
3226
3739
 
3622
4135
    assert(tables->is_leaf_for_name_resolution());
3623
4136
 
3624
4137
    if ((table_name && my_strcasecmp(table_alias_charset, table_name, tables->alias)) ||
3625
 
        (db_name && strcasecmp(tables->getSchemaName(),db_name)))
 
4138
        (db_name && strcasecmp(tables->db,db_name)))
3626
4139
      continue;
3627
4140
 
3628
4141
    /*
3658
4171
      if ((field= field_iterator.field()))
3659
4172
      {
3660
4173
        /* Mark fields as used to allow storage engine to optimze access */
3661
 
        field->getTable()->setReadSet(field->position());
 
4174
        field->getTable()->setReadSet(field->field_index);
3662
4175
        if (table)
3663
4176
        {
3664
4177
          table->covering_keys&= field->part_of_key;
3865
4378
    if ((value->save_in_field(rfield, 0) < 0) && !ignore_errors)
3866
4379
    {
3867
4380
      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;
 
4381
      goto err;
3872
4382
    }
3873
4383
  }
3874
4384
 
3875
4385
  return session->is_error();
 
4386
 
 
4387
err:
 
4388
  if (table)
 
4389
    table->auto_increment_field_not_null= false;
 
4390
 
 
4391
  return true;
3876
4392
}
3877
4393
 
3878
4394
 
3922
4438
    if (field == table->next_number_field)
3923
4439
      table->auto_increment_field_not_null= true;
3924
4440
    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
 
    }
 
4441
      goto err;
3931
4442
  }
3932
4443
 
3933
4444
  return(session->is_error());
 
4445
 
 
4446
err:
 
4447
  if (table)
 
4448
    table->auto_increment_field_not_null= false;
 
4449
 
 
4450
  return true;
3934
4451
}
3935
4452
 
3936
4453
 
3958
4475
  unireg support functions
3959
4476
 *****************************************************************************/
3960
4477
 
3961
 
 
 
4478
/*
 
4479
  Invalidate any cache entries that are for some DB
 
4480
 
 
4481
  SYNOPSIS
 
4482
  remove_db_from_cache()
 
4483
  db            Database name. This will be in lower case if
 
4484
  lower_case_table_name is set
 
4485
 
 
4486
NOTE:
 
4487
We can't use hash_delete when looping hash_elements. We mark them first
 
4488
and afterwards delete those marked unused.
 
4489
*/
 
4490
 
 
4491
void remove_db_from_cache(const SchemaIdentifier &schema_identifier)
 
4492
{
 
4493
  safe_mutex_assert_owner(&LOCK_open);
 
4494
 
 
4495
  for (uint32_t idx=0 ; idx < get_open_cache().records ; idx++)
 
4496
  {
 
4497
    Table *table=(Table*) hash_element(&get_open_cache(),idx);
 
4498
    if (not schema_identifier.getPath().compare(table->getMutableShare()->getSchemaName()))
 
4499
    {
 
4500
      table->getMutableShare()->resetVersion();                 /* Free when thread is ready */
 
4501
      if (not table->in_use)
 
4502
        unused_tables.relink(table);
 
4503
    }
 
4504
  }
 
4505
 
 
4506
  unused_tables.cullByVersion();
 
4507
}
 
4508
 
 
4509
 
 
4510
/*
 
4511
  Mark all entries with the table as deleted to force an reopen of the table
 
4512
 
 
4513
  The table will be closed (not stored in cache) by the current thread when
 
4514
  close_thread_tables() is called.
 
4515
 
 
4516
  PREREQUISITES
 
4517
  Lock on LOCK_open()
 
4518
 
 
4519
  RETURN
 
4520
  0  This thread now have exclusive access to this table and no other thread
 
4521
  can access the table until close_thread_tables() is called.
 
4522
  1  Table is in use by another thread
 
4523
*/
 
4524
 
 
4525
bool remove_table_from_cache(Session *session, TableIdentifier &identifier, uint32_t flags)
 
4526
{
 
4527
  const TableIdentifier::Key &key(identifier.getKey());
 
4528
  bool result= false; 
 
4529
  bool signalled= false;
 
4530
 
 
4531
  uint32_t key_length= key.size();
 
4532
 
 
4533
  for (;;)
 
4534
  {
 
4535
    HASH_SEARCH_STATE state;
 
4536
    Table *table;
 
4537
    result= signalled= false;
 
4538
 
 
4539
    for (table= (Table*) hash_first(&get_open_cache(), (unsigned char*) &key[0], key_length,
 
4540
                                    &state);
 
4541
         table;
 
4542
         table= (Table*) hash_next(&get_open_cache(), (unsigned char*) &key[0], key_length,
 
4543
                                   &state))
 
4544
    {
 
4545
      Session *in_use;
 
4546
 
 
4547
      table->getMutableShare()->resetVersion();         /* Free when thread is ready */
 
4548
      if (!(in_use=table->in_use))
 
4549
      {
 
4550
        unused_tables.relink(table);
 
4551
      }
 
4552
      else if (in_use != session)
 
4553
      {
 
4554
        /*
 
4555
          Mark that table is going to be deleted from cache. This will
 
4556
          force threads that are in mysql_lock_tables() (but not yet
 
4557
          in thr_multi_lock()) to abort it's locks, close all tables and retry
 
4558
        */
 
4559
        in_use->some_tables_deleted= true;
 
4560
        if (table->is_name_opened())
 
4561
        {
 
4562
          result= true;
 
4563
        }
 
4564
        /*
 
4565
          Now we must abort all tables locks used by this thread
 
4566
          as the thread may be waiting to get a lock for another table.
 
4567
          Note that we need to hold LOCK_open while going through the
 
4568
          list. So that the other thread cannot change it. The other
 
4569
          thread must also hold LOCK_open whenever changing the
 
4570
          open_tables list. Aborting the MERGE lock after a child was
 
4571
          closed and before the parent is closed would be fatal.
 
4572
        */
 
4573
        for (Table *session_table= in_use->open_tables;
 
4574
             session_table ;
 
4575
             session_table= session_table->getNext())
 
4576
        {
 
4577
          /* Do not handle locks of MERGE children. */
 
4578
          if (session_table->db_stat)   // If table is open
 
4579
            signalled|= mysql_lock_abort_for_thread(session, session_table);
 
4580
        }
 
4581
      }
 
4582
      else
 
4583
        result= result || (flags & RTFC_OWNED_BY_Session_FLAG);
 
4584
    }
 
4585
 
 
4586
    unused_tables.cullByVersion();
 
4587
 
 
4588
    /* Remove table from table definition cache if it's not in use */
 
4589
    TableShare::release(identifier);
 
4590
 
 
4591
    if (result && (flags & RTFC_WAIT_OTHER_THREAD_FLAG))
 
4592
    {
 
4593
      /*
 
4594
        Signal any thread waiting for tables to be freed to
 
4595
        reopen their tables
 
4596
      */
 
4597
      broadcast_refresh();
 
4598
      if (!(flags & RTFC_CHECK_KILLED_FLAG) || !session->killed)
 
4599
      {
 
4600
        dropping_tables++;
 
4601
        if (likely(signalled))
 
4602
          (void) pthread_cond_wait(&COND_refresh, &LOCK_open);
 
4603
        else
 
4604
        {
 
4605
          struct timespec abstime;
 
4606
          /*
 
4607
            It can happen that another thread has opened the
 
4608
            table but has not yet locked any table at all. Since
 
4609
            it can be locked waiting for a table that our thread
 
4610
            has done LOCK Table x WRITE on previously, we need to
 
4611
            ensure that the thread actually hears our signal
 
4612
            before we go to sleep. Thus we wait for a short time
 
4613
            and then we retry another loop in the
 
4614
            remove_table_from_cache routine.
 
4615
          */
 
4616
          set_timespec(abstime, 10);
 
4617
          pthread_cond_timedwait(&COND_refresh, &LOCK_open, &abstime);
 
4618
        }
 
4619
        dropping_tables--;
 
4620
        continue;
 
4621
      }
 
4622
    }
 
4623
    break;
 
4624
  }
 
4625
 
 
4626
  return result;
 
4627
}
3962
4628
 
3963
4629
 
3964
4630
/**