~drizzle-trunk/drizzle/development

« back to all changes in this revision

Viewing changes to drizzled/sql_base.cc

  • Committer: Monty Taylor
  • Date: 2010-06-19 16:36:52 UTC
  • mto: This revision was merged to the branch mainline in revision 1628.
  • Revision ID: mordred@inaugust.com-20100619163652-6fej38011wsop52k
Moved password parsing code into get_password.cc.

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
Table *unused_tables;                           /* Used by mysql_test */
 
70
HASH open_cache;                                /* Used by mysql_test */
 
71
static int open_unireg_entry(Session *session,
 
72
                             Table *entry,
 
73
                             const char *alias,
 
74
                             TableIdentifier &identifier);
 
75
void free_cache_entry(void *entry);
 
76
unsigned char *table_cache_key(const unsigned char *record,
 
77
                               size_t *length,
 
78
                               bool );
 
79
 
 
80
#if 0
 
81
static bool reopen_table(Table *table);
 
82
#endif
 
83
 
 
84
unsigned char *table_cache_key(const unsigned char *record,
 
85
                               size_t *length,
 
86
                               bool )
 
87
{
 
88
  Table *entry=(Table*) record;
 
89
  *length= entry->getShare()->getCacheKey().size();
 
90
  return (unsigned char*) &entry->getShare()->getCacheKey()[0];
 
91
}
 
92
 
 
93
HASH *get_open_cache()
 
94
{
 
95
  return &open_cache;
 
96
}
 
97
 
 
98
 
67
99
bool table_cache_init(void)
68
100
{
69
 
  return false;
70
 
}
71
 
 
72
 
uint32_t cached_open_tables(void)
73
 
{
74
 
  return table::getCache().size();
 
101
  return hash_init(&open_cache, &my_charset_bin,
 
102
                   (size_t) table_cache_size+16,
 
103
                   0, 0, table_cache_key,
 
104
                   free_cache_entry, 0);
75
105
}
76
106
 
77
107
void table_cache_free(void)
78
108
{
79
109
  refresh_version++;                            // Force close of open tables
80
110
 
81
 
  table::getUnused().clear();
82
 
  table::getCache().clear();
83
 
}
 
111
  while (unused_tables)
 
112
    hash_delete(&open_cache, (unsigned char*) unused_tables);
 
113
 
 
114
  if (not open_cache.records)                   // Safety first
 
115
    hash_free(&open_cache);
 
116
}
 
117
 
 
118
uint32_t cached_open_tables(void)
 
119
{
 
120
  return open_cache.records;
 
121
}
 
122
 
84
123
 
85
124
/*
86
125
  Close cursor handle, but leave the table in the table cache
93
132
  By leaving the table in the table cache, it disallows any other thread
94
133
  to open the table
95
134
 
96
 
  session->getKilled() will be set if we run out of memory
 
135
  session->killed will be set if we run out of memory
97
136
 
98
137
  If closing a MERGE child, the calling function has to take care for
99
138
  closing the parent too, if necessary.
102
141
 
103
142
void close_handle_and_leave_table_as_lock(Table *table)
104
143
{
 
144
  TableShare *share, *old_share= table->getMutableShare();
105
145
  assert(table->db_stat);
106
146
  assert(table->getShare()->getType() == message::Table::STANDARD);
107
147
 
112
152
  */
113
153
  TableIdentifier identifier(table->getShare()->getSchemaName(), table->getShare()->getTableName(), message::Table::INTERNAL);
114
154
  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()));
 
155
  share= new TableShare(identifier.getType(),
 
156
                        identifier,
 
157
                        const_cast<char *>(&key[0]),  static_cast<uint32_t>(old_share->getCacheKeySize()));
118
158
 
119
159
  table->cursor->close();
120
160
  table->db_stat= 0;                            // Mark cursor closed
121
161
  TableShare::release(table->getMutableShare());
122
162
  table->setShare(share);
 
163
  table->cursor->change_table_ptr(table, table->getMutableShare());
123
164
}
124
165
 
125
166
 
137
178
  }
138
179
}
139
180
 
 
181
/*
 
182
  Remove table from the open table cache
 
183
 
 
184
  SYNOPSIS
 
185
  free_cache_entry()
 
186
  entry         Table to remove
 
187
 
 
188
  NOTE
 
189
  We need to have a lock on LOCK_open when calling this
 
190
*/
 
191
 
 
192
void free_cache_entry(void *entry)
 
193
{
 
194
  Table *table= static_cast<Table *>(entry);
 
195
 
 
196
  table->intern_close_table();
 
197
  if (not table->in_use)
 
198
  {
 
199
    table->getNext()->setPrev(table->getPrev());                /* remove from used chain */
 
200
    table->getPrev()->setNext(table->getNext());
 
201
    if (table == unused_tables)
 
202
    {
 
203
      unused_tables= unused_tables->getNext();
 
204
      if (table == unused_tables)
 
205
        unused_tables= NULL;
 
206
    }
 
207
  }
 
208
 
 
209
  if (table->isPlaceHolder())
 
210
  {
 
211
    delete table;
 
212
  }
 
213
  else
 
214
  {
 
215
    free(table);
 
216
  }
 
217
}
 
218
 
140
219
/* Free resources allocated by filesort() and read_record() */
141
220
 
142
221
void Table::free_io_cache()
143
222
{
144
223
  if (sort.io_cache)
145
224
  {
146
 
    sort.io_cache->close_cached_file();
 
225
    close_cached_file(sort.io_cache);
147
226
    delete sort.io_cache;
148
227
    sort.io_cache= 0;
149
228
  }
155
234
 
156
235
  @param session Thread context (may be NULL)
157
236
  @param tables List of tables to remove from the cache
158
 
  @param have_lock If table::Cache::singleton().mutex() is locked
 
237
  @param have_lock If LOCK_open is locked
159
238
  @param wait_for_refresh Wait for a impending flush
160
239
  @param wait_for_placeholders Wait for tables being reopened so that the GRL
161
240
  won't proceed while write-locked tables are being reopened by other
170
249
  bool result= false;
171
250
  Session *session= this;
172
251
 
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
 
      {
 
252
  pthread_mutex_lock(&LOCK_open); /* Optionally lock for remove tables from open_cahe if not in use */
 
253
 
 
254
  if (tables == NULL)
 
255
  {
 
256
    refresh_version++;                          // Force close of open tables
 
257
    while (unused_tables)
 
258
    {
 
259
      hash_delete(&open_cache,(unsigned char*) unused_tables);
 
260
    }
 
261
 
 
262
    if (wait_for_refresh)
 
263
    {
 
264
      /*
 
265
        Other threads could wait in a loop in open_and_lock_tables(),
 
266
        trying to lock one or more of our tables.
 
267
 
 
268
        If they wait for the locks in thr_multi_lock(), their lock
 
269
        request is aborted. They loop in open_and_lock_tables() and
 
270
        enter open_table(). Here they notice the table is refreshed and
 
271
        wait for COND_refresh. Then they loop again in
 
272
        openTablesLock() and this time open_table() succeeds. At
 
273
        this moment, if we (the FLUSH TABLES thread) are scheduled and
 
274
        on another FLUSH TABLES enter close_cached_tables(), they could
 
275
        awake while we sleep below, waiting for others threads (us) to
 
276
        close their open tables. If this happens, the other threads
 
277
        would find the tables unlocked. They would get the locks, one
 
278
        after the other, and could do their destructive work. This is an
 
279
        issue if we have LOCK TABLES in effect.
 
280
 
 
281
        The problem is that the other threads passed all checks in
 
282
        open_table() before we refresh the table.
 
283
 
 
284
        The fix for this problem is to set some_tables_deleted for all
 
285
        threads with open tables. These threads can still get their
 
286
        locks, but will immediately release them again after checking
 
287
        this variable. They will then loop in openTablesLock()
 
288
        again. There they will wait until we update all tables version
 
289
        below.
 
290
 
 
291
        Setting some_tables_deleted is done by remove_table_from_cache()
 
292
        in the other branch.
 
293
 
 
294
        In other words (reviewer suggestion): You need this setting of
 
295
        some_tables_deleted for the case when table was opened and all
 
296
        related checks were passed before incrementing refresh_version
 
297
        (which you already have) but attempt to lock the table happened
 
298
        after the call to Session::close_old_data_files() i.e. after removal of
 
299
        current thread locks.
 
300
      */
 
301
      for (uint32_t idx=0 ; idx < open_cache.records ; idx++)
 
302
      {
 
303
        Table *table=(Table*) hash_element(&open_cache,idx);
 
304
        if (table->in_use)
 
305
          table->in_use->some_tables_deleted= false;
 
306
      }
 
307
    }
 
308
  }
 
309
  else
 
310
  {
 
311
    bool found= false;
 
312
    for (TableList *table= tables; table; table= table->next_local)
 
313
    {
 
314
      TableIdentifier identifier(table->db, table->table_name);
 
315
      if (remove_table_from_cache(session, identifier,
 
316
                                  RTFC_OWNED_BY_Session_FLAG))
 
317
      {
 
318
        found= true;
 
319
      }
 
320
    }
 
321
    if (!found)
 
322
      wait_for_refresh= false;                  // Nothing to wait for
 
323
  }
 
324
 
 
325
  if (wait_for_refresh)
 
326
  {
 
327
    /*
 
328
      If there is any table that has a lower refresh_version, wait until
 
329
      this is closed (or this thread is killed) before returning
 
330
    */
 
331
    session->mysys_var->current_mutex= &LOCK_open;
 
332
    session->mysys_var->current_cond= &COND_refresh;
 
333
    session->set_proc_info("Flushing tables");
 
334
 
 
335
    session->close_old_data_files();
 
336
 
 
337
    bool found= true;
 
338
    /* Wait until all threads has closed all the tables we had locked */
 
339
    while (found && ! session->killed)
 
340
    {
 
341
      found= false;
 
342
      for (uint32_t idx=0 ; idx < open_cache.records ; idx++)
 
343
      {
 
344
        Table *table=(Table*) hash_element(&open_cache,idx);
 
345
        /* Avoid a self-deadlock. */
 
346
        if (table->in_use == session)
 
347
          continue;
184
348
        /*
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.
 
349
          Note that we wait here only for tables which are actually open, and
 
350
          not for placeholders with Table::open_placeholder set. Waiting for
 
351
          latter will cause deadlock in the following scenario, for example:
 
352
 
 
353
conn1: lock table t1 write;
 
354
conn2: lock table t2 write;
 
355
conn1: flush tables;
 
356
conn2: flush tables;
 
357
 
 
358
It also does not make sense to wait for those of placeholders that
 
359
are employed by CREATE TABLE as in this case table simply does not
 
360
exist yet.
220
361
        */
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))
 
362
        if (table->needs_reopen_or_name_lock() && (table->db_stat ||
 
363
                                                   (table->open_placeholder && wait_for_placeholders)))
239
364
        {
240
365
          found= true;
 
366
          pthread_cond_wait(&COND_refresh,&LOCK_open);
 
367
          break;
241
368
        }
242
369
      }
243
 
      if (!found)
244
 
        wait_for_refresh= false;                        // Nothing to wait for
245
370
    }
 
371
    /*
 
372
      No other thread has the locked tables open; reopen them and get the
 
373
      old locks. This should always succeed (unless some external process
 
374
      has removed the tables)
 
375
    */
 
376
    result= session->reopen_tables(true, true);
246
377
 
247
 
    if (wait_for_refresh)
 
378
    /* Set version for table */
 
379
    for (Table *table= session->open_tables; table ; table= table->getNext())
248
380
    {
249
381
      /*
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
 
      }
 
382
        Preserve the version (0) of write locked tables so that a impending
 
383
        global read lock won't sneak in.
 
384
      */
 
385
      if (table->reginfo.lock_type < TL_WRITE_ALLOW_WRITE)
 
386
        table->getMutableShare()->refreshVersion();
314
387
    }
315
 
 
316
 
    table::Cache::singleton().mutex().unlock();
317
388
  }
318
389
 
 
390
  pthread_mutex_unlock(&LOCK_open);
 
391
 
319
392
  if (wait_for_refresh)
320
393
  {
321
 
    boost_unique_lock_t scopedLock(session->mysys_var->mutex);
 
394
    pthread_mutex_lock(&session->mysys_var->mutex);
322
395
    session->mysys_var->current_mutex= 0;
323
396
    session->mysys_var->current_cond= 0;
324
397
    session->set_proc_info(0);
 
398
    pthread_mutex_unlock(&session->mysys_var->mutex);
325
399
  }
326
400
 
327
401
  return result;
335
409
bool Session::free_cached_table()
336
410
{
337
411
  bool found_old_table= false;
338
 
  table::Concurrent *table= static_cast<table::Concurrent *>(open_tables);
 
412
  Table *table= open_tables;
339
413
 
340
 
  safe_mutex_assert_owner(table::Cache::singleton().mutex().native_handle());
 
414
  safe_mutex_assert_owner(&LOCK_open);
341
415
  assert(table->key_read == 0);
342
416
  assert(!table->cursor || table->cursor->inited == Cursor::NONE);
343
417
 
346
420
  if (table->needs_reopen_or_name_lock() ||
347
421
      version != refresh_version || !table->db_stat)
348
422
  {
349
 
    table::remove_table(table);
 
423
    hash_delete(&open_cache,(unsigned char*) table);
350
424
    found_old_table= true;
351
425
  }
352
426
  else
359
433
 
360
434
    /* Free memory and reset for next loop */
361
435
    table->cursor->ha_reset();
362
 
    table->in_use= NULL;
 
436
    table->in_use= false;
363
437
 
364
 
    table::getUnused().link(table);
 
438
    if (unused_tables)
 
439
    {
 
440
      table->setNext(unused_tables);            /* Link in last */
 
441
      table->setPrev(unused_tables->getPrev());
 
442
      unused_tables->setPrev(table);
 
443
      table->getPrev()->setNext(table);
 
444
    }
 
445
    else
 
446
    {
 
447
      table->setPrev(unused_tables= table);
 
448
      table->setNext(table->getPrev());
 
449
    }
365
450
  }
366
451
 
367
452
  return found_old_table;
380
465
{
381
466
  bool found_old_table= false;
382
467
 
383
 
  safe_mutex_assert_not_owner(table::Cache::singleton().mutex().native_handle());
 
468
  safe_mutex_assert_not_owner(&LOCK_open);
384
469
 
385
 
  boost_unique_lock_t scoped_lock(table::Cache::singleton().mutex()); /* Close all open tables on Session */
 
470
  pthread_mutex_lock(&LOCK_open); /* Close all open tables on Session */
386
471
 
387
472
  while (open_tables)
388
473
  {
393
478
  if (found_old_table)
394
479
  {
395
480
    /* Tell threads waiting for refresh that something has happened */
396
 
    locking::broadcast_refresh();
 
481
    broadcast_refresh();
397
482
  }
 
483
 
 
484
  pthread_mutex_unlock(&LOCK_open);
398
485
}
399
486
 
400
487
/*
423
510
  for (; table; table= table->*link )
424
511
  {
425
512
    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)
 
513
        strcasecmp(table->db, db_name) == 0 &&
 
514
        strcasecmp(table->table_name, table_name) == 0)
428
515
      break;
429
516
  }
430
517
  return table;
495
582
    */
496
583
    assert(table);
497
584
  }
498
 
  d_name= table->getSchemaName();
499
 
  t_name= table->getTableName();
 
585
  d_name= table->db;
 
586
  t_name= table->table_name;
500
587
  t_alias= table->alias;
501
588
 
502
589
  for (;;)
517
604
}
518
605
 
519
606
 
520
 
void Open_tables_state::doGetTableNames(const SchemaIdentifier &schema_identifier,
521
 
                                        std::set<std::string>& set_of_names)
 
607
void Session::doGetTableNames(SchemaIdentifier &schema_identifier,
 
608
                              std::set<std::string>& set_of_names)
522
609
{
523
 
  for (Table *table= getTemporaryTables() ; table ; table= table->getNext())
 
610
  for (Table *table= temporary_tables ; table ; table= table->getNext())
524
611
  {
525
612
    if (schema_identifier.compare(table->getShare()->getSchemaName()))
526
613
    {
529
616
  }
530
617
}
531
618
 
532
 
void Open_tables_state::doGetTableNames(CachedDirectory &,
533
 
                                        const SchemaIdentifier &schema_identifier,
534
 
                                        std::set<std::string> &set_of_names)
 
619
void Session::doGetTableNames(CachedDirectory &,
 
620
                              SchemaIdentifier &schema_identifier,
 
621
                              std::set<std::string> &set_of_names)
535
622
{
536
623
  doGetTableNames(schema_identifier, set_of_names);
537
624
}
538
625
 
539
 
void Open_tables_state::doGetTableIdentifiers(const SchemaIdentifier &schema_identifier,
540
 
                                              TableIdentifier::vector &set_of_identifiers)
 
626
void Session::doGetTableIdentifiers(SchemaIdentifier &schema_identifier,
 
627
                                    TableIdentifiers &set_of_identifiers)
541
628
{
542
 
  for (Table *table= getTemporaryTables() ; table ; table= table->getNext())
 
629
  for (Table *table= temporary_tables ; table ; table= table->getNext())
543
630
  {
544
631
    if (schema_identifier.compare(table->getShare()->getSchemaName()))
545
632
    {
550
637
  }
551
638
}
552
639
 
553
 
void Open_tables_state::doGetTableIdentifiers(CachedDirectory &,
554
 
                                              const SchemaIdentifier &schema_identifier,
555
 
                                              TableIdentifier::vector &set_of_identifiers)
 
640
void Session::doGetTableIdentifiers(CachedDirectory &,
 
641
                                    SchemaIdentifier &schema_identifier,
 
642
                                    TableIdentifiers &set_of_identifiers)
556
643
{
557
644
  doGetTableIdentifiers(schema_identifier, set_of_identifiers);
558
645
}
559
646
 
560
 
bool Open_tables_state::doDoesTableExist(const TableIdentifier &identifier)
 
647
bool Session::doDoesTableExist(TableIdentifier &identifier)
561
648
{
562
 
  for (Table *table= getTemporaryTables() ; table ; table= table->getNext())
 
649
  for (Table *table= temporary_tables ; table ; table= table->getNext())
563
650
  {
564
651
    if (table->getShare()->getType() == message::Table::TEMPORARY)
565
652
    {
566
 
      if (identifier.getKey() == table->getShare()->getCacheKey())
 
653
      if (identifier.compare(table->getShare()->getSchemaName(), table->getShare()->getTableName()))
567
654
      {
568
655
        return true;
569
656
      }
573
660
  return false;
574
661
}
575
662
 
576
 
int Open_tables_state::doGetTableDefinition(const TableIdentifier &identifier,
 
663
int Session::doGetTableDefinition(TableIdentifier &identifier,
577
664
                                  message::Table &table_proto)
578
665
{
579
 
  for (Table *table= getTemporaryTables() ; table ; table= table->getNext())
 
666
  for (Table *table= temporary_tables ; table ; table= table->getNext())
580
667
  {
581
668
    if (table->getShare()->getType() == message::Table::TEMPORARY)
582
669
    {
583
 
      if (identifier.getKey() == table->getShare()->getCacheKey())
 
670
      if (identifier.compare(table->getShare()->getSchemaName(), table->getShare()->getTableName()))
584
671
      {
585
672
        table_proto.CopyFrom(*(table->getShare()->getTableProto()));
586
673
 
592
679
  return ENOENT;
593
680
}
594
681
 
595
 
Table *Open_tables_state::find_temporary_table(const TableIdentifier &identifier)
 
682
Table *Session::find_temporary_table(const char *new_db, const char *table_name)
 
683
{
 
684
  char  key[MAX_DBKEY_LENGTH];
 
685
  uint  key_length;
 
686
 
 
687
  key_length= TableIdentifier::createKey(key, new_db, table_name);
 
688
 
 
689
  for (Table *table= temporary_tables ; table ; table= table->getNext())
 
690
  {
 
691
    const TableIdentifier::Key &share_key(table->getShare()->getCacheKey());
 
692
    if (share_key.size() == key_length &&
 
693
        not memcmp(&share_key[0], key, key_length))
 
694
    {
 
695
      return table;
 
696
    }
 
697
  }
 
698
  return NULL;                               // Not a temporary table
 
699
}
 
700
 
 
701
Table *Session::find_temporary_table(TableList *table_list)
 
702
{
 
703
  return find_temporary_table(table_list->db, table_list->table_name);
 
704
}
 
705
 
 
706
Table *Session::find_temporary_table(TableIdentifier &identifier)
596
707
{
597
708
  for (Table *table= temporary_tables ; table ; table= table->getNext())
598
709
  {
630
741
  @retval -1  the table is in use by a outer query
631
742
*/
632
743
 
633
 
int Open_tables_state::drop_temporary_table(const drizzled::TableIdentifier &identifier)
 
744
int Session::drop_temporary_table(TableList *table_list)
634
745
{
635
746
  Table *table;
636
747
 
637
 
  if (not (table= find_temporary_table(identifier)))
 
748
  if (not (table= find_temporary_table(table_list)))
638
749
    return 1;
639
750
 
640
751
  /* Table might be in use by some outer statement. */
641
 
  if (table->query_id && table->query_id != getQueryId())
 
752
  if (table->query_id && table->query_id != query_id)
642
753
  {
643
 
    my_error(ER_CANT_REOPEN_TABLE, MYF(0), table->getAlias());
 
754
    my_error(ER_CANT_REOPEN_TABLE, MYF(0), table->alias);
644
755
    return -1;
645
756
  }
646
757
 
650
761
}
651
762
 
652
763
 
 
764
/* move table first in unused links */
 
765
 
 
766
static void relink_unused(Table *table)
 
767
{
 
768
  if (table != unused_tables)
 
769
  {
 
770
    table->getPrev()->setNext(table->getNext());                /* Remove from unused list */
 
771
    table->getNext()->setPrev(table->getPrev());
 
772
    table->setNext(unused_tables);                      /* Link in unused tables */
 
773
    table->setPrev(unused_tables->getPrev());
 
774
    unused_tables->getPrev()->setNext(table);
 
775
    unused_tables->setPrev(table);
 
776
    unused_tables= table;
 
777
  }
 
778
}
 
779
 
 
780
 
653
781
/**
654
782
  Remove all instances of table from thread's open list and
655
783
  table cache.
656
784
 
657
785
  @param  session     Thread context
658
786
  @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
787
*/
662
788
 
663
789
void Session::unlink_open_table(Table *find)
664
790
{
665
 
  const TableIdentifier::Key find_key(find->getShare()->getCacheKey());
666
 
  Table **prev;
667
 
  safe_mutex_assert_owner(table::Cache::singleton().mutex().native_handle());
 
791
  char key[MAX_DBKEY_LENGTH];
 
792
  uint32_t key_length= find->getShare()->getCacheKeySize();
 
793
  Table *list, **prev;
 
794
  safe_mutex_assert_owner(&LOCK_open);
668
795
 
 
796
  memcpy(key, &find->getMutableShare()->getCacheKey()[0], key_length);
669
797
  /*
670
 
    Note that we need to hold table::Cache::singleton().mutex() while changing the
 
798
    Note that we need to hold LOCK_open while changing the
671
799
    open_tables list. Another thread may work on it.
672
 
    (See: table::Cache::singleton().removeTable(), mysql_wait_completed_table())
 
800
    (See: remove_table_from_cache(), mysql_wait_completed_table())
673
801
    Closing a MERGE child before the parent would be fatal if the
674
802
    other thread tries to abort the MERGE lock in between.
675
803
  */
676
804
  for (prev= &open_tables; *prev; )
677
805
  {
678
 
    Table *list= *prev;
 
806
    list= *prev;
679
807
 
680
 
    if (list->getShare()->getCacheKey() == find_key)
 
808
    if (list->getShare()->getCacheKeySize() == key_length &&
 
809
        not memcmp(&list->getShare()->getCacheKey()[0], key, key_length))
681
810
    {
682
811
      /* Remove table from open_tables list. */
683
812
      *prev= list->getNext();
684
813
 
685
814
      /* Close table. */
686
 
      table::remove_table(static_cast<table::Concurrent *>(list));
 
815
      hash_delete(&open_cache,(unsigned char*) list); // Close table
687
816
    }
688
817
    else
689
818
    {
693
822
  }
694
823
 
695
824
  // Notify any 'refresh' threads
696
 
  locking::broadcast_refresh();
 
825
  broadcast_refresh();
697
826
}
698
827
 
699
828
 
716
845
  table that was locked with LOCK TABLES.
717
846
*/
718
847
 
719
 
void Session::drop_open_table(Table *table, const TableIdentifier &identifier)
 
848
void Session::drop_open_table(Table *table, TableIdentifier &identifier)
720
849
{
721
850
  if (table->getShare()->getType())
722
851
  {
724
853
  }
725
854
  else
726
855
  {
727
 
    boost_unique_lock_t scoped_lock(table::Cache::singleton().mutex()); /* Close and drop a table (AUX routine) */
 
856
    pthread_mutex_lock(&LOCK_open); /* Close and drop a table (AUX routine) */
728
857
    /*
729
858
      unlink_open_table() also tells threads waiting for refresh or close
730
859
      that something has happened.
731
860
    */
732
861
    unlink_open_table(table);
733
 
    plugin::StorageEngine::dropTable(*this, identifier);
 
862
    quick_rm_table(*this, identifier);
 
863
    pthread_mutex_unlock(&LOCK_open);
734
864
  }
735
865
}
736
866
 
746
876
  cond  Condition to wait for
747
877
*/
748
878
 
749
 
void Session::wait_for_condition(boost::mutex &mutex, boost::condition_variable_any &cond)
 
879
void Session::wait_for_condition(pthread_mutex_t *mutex, pthread_cond_t *cond)
750
880
{
751
881
  /* Wait until the current table is up to date */
752
882
  const char *saved_proc_info;
753
 
  mysys_var->current_mutex= &mutex;
754
 
  mysys_var->current_cond= &cond;
 
883
  mysys_var->current_mutex= mutex;
 
884
  mysys_var->current_cond= cond;
755
885
  saved_proc_info= get_proc_info();
756
886
  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);
 
887
  if (!killed)
 
888
    (void) pthread_cond_wait(cond, mutex);
 
889
 
 
890
  /*
 
891
    We must unlock mutex first to avoid deadlock becasue conditions are
 
892
    sent to this thread by doing locks in the following order:
 
893
    lock(mysys_var->mutex)
 
894
    lock(mysys_var->current_mutex)
 
895
 
 
896
    One by effect of this that one can only use wait_for_condition with
 
897
    condition variables that are guranteed to not disapper (freed) even if this
 
898
    mutex is unlocked
 
899
  */
 
900
 
 
901
  pthread_mutex_unlock(mutex);
 
902
  pthread_mutex_lock(&mysys_var->mutex);
775
903
  mysys_var->current_mutex= 0;
776
904
  mysys_var->current_cond= 0;
777
905
  set_proc_info(saved_proc_info);
 
906
  pthread_mutex_unlock(&mysys_var->mutex);
 
907
}
 
908
 
 
909
 
 
910
/*
 
911
  Open table which is already name-locked by this thread.
 
912
 
 
913
  SYNOPSIS
 
914
  reopen_name_locked_table()
 
915
  session         Thread handle
 
916
  table_list  TableList object for table to be open, TableList::table
 
917
  member should point to Table object which was used for
 
918
  name-locking.
 
919
  link_in     true  - if Table object for table to be opened should be
 
920
  linked into Session::open_tables list.
 
921
  false - placeholder used for name-locking is already in
 
922
  this list so we only need to preserve Table::next
 
923
  pointer.
 
924
 
 
925
  NOTE
 
926
  This function assumes that its caller already acquired LOCK_open mutex.
 
927
 
 
928
  RETURN VALUE
 
929
  false - Success
 
930
  true  - Error
 
931
*/
 
932
 
 
933
bool Session::reopen_name_locked_table(TableList* table_list, bool link_in)
 
934
{
 
935
  Table *table= table_list->table;
 
936
  TableShare *share;
 
937
  char *table_name= table_list->table_name;
 
938
  Table orig_table;
 
939
 
 
940
  safe_mutex_assert_owner(&LOCK_open);
 
941
 
 
942
  if (killed || !table)
 
943
    return true;
 
944
 
 
945
  orig_table= *table;
 
946
 
 
947
  TableIdentifier identifier(table_list->db, table_list->table_name);
 
948
  if (open_unireg_entry(this, table, table_name, identifier))
 
949
  {
 
950
    table->intern_close_table();
 
951
    /*
 
952
      If there was an error during opening of table (for example if it
 
953
      does not exist) '*table' object can be wiped out. To be able
 
954
      properly release name-lock in this case we should restore this
 
955
      object to its original state.
 
956
    */
 
957
    *table= orig_table;
 
958
    return true;
 
959
  }
 
960
 
 
961
  share= table->getMutableShare();
 
962
  /*
 
963
    We want to prevent other connections from opening this table until end
 
964
    of statement as it is likely that modifications of table's metadata are
 
965
    not yet finished (for example CREATE TRIGGER have to change .TRG cursor,
 
966
    or we might want to drop table if CREATE TABLE ... SELECT fails).
 
967
    This also allows us to assume that no other connection will sneak in
 
968
    before we will get table-level lock on this table.
 
969
  */
 
970
  share->resetVersion();
 
971
  table->in_use = this;
 
972
 
 
973
  if (link_in)
 
974
  {
 
975
    table->setNext(open_tables);
 
976
    open_tables= table;
 
977
  }
 
978
  else
 
979
  {
 
980
    /*
 
981
      Table object should be already in Session::open_tables list so we just
 
982
      need to set Table::next correctly.
 
983
    */
 
984
    table->setNext(orig_table.getNext());
 
985
  }
 
986
 
 
987
  table->tablenr= current_tablenr++;
 
988
  table->used_fields= 0;
 
989
  table->const_table= 0;
 
990
  table->null_row= false;
 
991
  table->maybe_null= false;
 
992
  table->force_index= false;
 
993
  table->status= STATUS_NO_RECORD;
 
994
 
 
995
  return false;
778
996
}
779
997
 
780
998
 
791
1009
  case of failure.
792
1010
*/
793
1011
 
794
 
table::Placeholder *Session::table_cache_insert_placeholder(const drizzled::TableIdentifier &arg)
 
1012
Table *Session::table_cache_insert_placeholder(const char *db_name, const char *table_name, const char *, uint32_t)
795
1013
{
796
 
  safe_mutex_assert_owner(table::Cache::singleton().mutex().native_handle());
 
1014
  safe_mutex_assert_owner(&LOCK_open);
797
1015
 
798
1016
  /*
799
1017
    Create a table entry with the right key and with an old refresh version
 
1018
    Note that we must use multi_malloc() here as this is freed by the
 
1019
    table cache
800
1020
  */
801
 
  TableIdentifier identifier(arg.getSchemaName(), arg.getTableName(), message::Table::INTERNAL);
802
 
  table::Placeholder *table= new table::Placeholder(this, identifier);
 
1021
  TableIdentifier identifier(db_name, table_name, message::Table::INTERNAL);
 
1022
  TablePlaceholder *table= new TablePlaceholder(this, identifier);
803
1023
 
804
 
  if (not table::Cache::singleton().insert(table))
 
1024
  if (my_hash_insert(&open_cache, (unsigned char*)table))
805
1025
  {
806
1026
    delete table;
807
1027
 
833
1053
  @retval  true   Error occured (OOM)
834
1054
  @retval  false  Success. 'table' parameter set according to above rules.
835
1055
*/
836
 
bool Session::lock_table_name_if_not_cached(const TableIdentifier &identifier, Table **table)
837
 
{
838
 
  const TableIdentifier::Key &key(identifier.getKey());
839
 
 
840
 
  boost_unique_lock_t scope_lock(table::Cache::singleton().mutex()); /* Obtain a name lock even though table is not in cache (like for create table)  */
841
 
 
842
 
  table::CacheMap::iterator iter;
843
 
 
844
 
  iter= table::getCache().find(key);
845
 
 
846
 
  if (iter != table::getCache().end())
 
1056
bool Session::lock_table_name_if_not_cached(TableIdentifier &identifier, Table **table)
 
1057
{
 
1058
  return lock_table_name_if_not_cached(identifier.getSchemaName().c_str(), identifier.getTableName().c_str(), table);
 
1059
}
 
1060
 
 
1061
bool Session::lock_table_name_if_not_cached(const char *new_db,
 
1062
                                            const char *table_name, Table **table)
 
1063
{
 
1064
  char key[MAX_DBKEY_LENGTH];
 
1065
  uint32_t key_length;
 
1066
 
 
1067
  key_length= TableIdentifier::createKey(key, new_db, table_name);
 
1068
 
 
1069
  pthread_mutex_lock(&LOCK_open); /* Obtain a name lock even though table is not in cache (like for create table)  */
 
1070
 
 
1071
  if (hash_search(&open_cache, (unsigned char *)key, key_length))
847
1072
  {
 
1073
    pthread_mutex_unlock(&LOCK_open);
848
1074
    *table= 0;
849
1075
    return false;
850
1076
  }
851
1077
 
852
 
  if (not (*table= table_cache_insert_placeholder(identifier)))
 
1078
  if (not (*table= table_cache_insert_placeholder(new_db, table_name, key, key_length)))
853
1079
  {
 
1080
    pthread_mutex_unlock(&LOCK_open);
854
1081
    return true;
855
1082
  }
856
1083
  (*table)->open_placeholder= true;
857
1084
  (*table)->setNext(open_tables);
858
1085
  open_tables= *table;
 
1086
  pthread_mutex_unlock(&LOCK_open);
859
1087
 
860
1088
  return false;
861
1089
}
896
1124
Table *Session::openTable(TableList *table_list, bool *refresh, uint32_t flags)
897
1125
{
898
1126
  Table *table;
 
1127
  unsigned int key_length;
899
1128
  const char *alias= table_list->alias;
 
1129
  HASH_SEARCH_STATE state;
900
1130
 
901
1131
  /* Parsing of partitioning information from .frm needs session->lex set up. */
902
1132
  assert(lex->is_lex_started);
909
1139
  if (check_stack_overrun(this, STACK_MIN_SIZE_FOR_OPEN, (unsigned char *)&alias))
910
1140
    return NULL;
911
1141
 
912
 
  if (getKilled())
 
1142
  if (killed)
913
1143
    return NULL;
914
1144
 
915
 
  TableIdentifier identifier(table_list->getSchemaName(), table_list->getTableName());
 
1145
  TableIdentifier identifier(table_list->db, table_list->table_name);
916
1146
  const TableIdentifier::Key &key(identifier.getKey());
917
 
  table::CacheRange ppp;
 
1147
  key_length= key.size();
918
1148
 
919
1149
  /*
920
1150
    Unless requested otherwise, try to resolve this table in the list
923
1153
    same name. This block implements the behaviour.
924
1154
    TODO -> move this block into a separate function.
925
1155
  */
926
 
  bool reset= false;
927
 
  for (table= getTemporaryTables(); table ; table=table->getNext())
 
1156
  for (table= temporary_tables; table ; table=table->getNext())
928
1157
  {
929
1158
    if (table->getShare()->getCacheKey() == key)
930
1159
    {
936
1165
      */
937
1166
      if (table->query_id)
938
1167
      {
939
 
        my_error(ER_CANT_REOPEN_TABLE, MYF(0), table->getAlias());
 
1168
        my_error(ER_CANT_REOPEN_TABLE, MYF(0), table->alias);
940
1169
        return NULL;
941
1170
      }
942
1171
      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
 
 
 
1172
      goto reset;
 
1173
    }
 
1174
  }
 
1175
 
 
1176
  if (flags & DRIZZLE_OPEN_TEMPORARY_ONLY)
 
1177
  {
 
1178
    my_error(ER_NO_SUCH_TABLE, MYF(0), table_list->db, table_list->table_name);
 
1179
    return NULL;
 
1180
  }
 
1181
 
 
1182
  /*
 
1183
    If it's the first table from a list of tables used in a query,
 
1184
    remember refresh_version (the version of open_cache state).
 
1185
    If the version changes while we're opening the remaining tables,
 
1186
    we will have to back off, close all the tables opened-so-far,
 
1187
    and try to reopen them.
 
1188
 
 
1189
    Note-> refresh_version is currently changed only during FLUSH TABLES.
 
1190
  */
 
1191
  if (!open_tables)
 
1192
  {
 
1193
    version= refresh_version;
 
1194
  }
 
1195
  else if ((version != refresh_version) &&
 
1196
           ! (flags & DRIZZLE_LOCK_IGNORE_FLUSH))
 
1197
  {
 
1198
    /* Someone did a refresh while thread was opening tables */
 
1199
    if (refresh)
 
1200
      *refresh= true;
 
1201
 
 
1202
    return NULL;
 
1203
  }
 
1204
 
 
1205
  /*
 
1206
    Before we test the global cache, we test our local session cache.
 
1207
  */
 
1208
  if (cached_table)
 
1209
  {
 
1210
    assert(false); /* Not implemented yet */
 
1211
  }
 
1212
 
 
1213
  /*
 
1214
    Non pre-locked/LOCK TABLES mode, and the table is not temporary:
 
1215
    this is the normal use case.
 
1216
    Now we should:
 
1217
    - try to find the table in the table cache.
 
1218
    - if one of the discovered Table instances is name-locked
 
1219
    (table->getShare()->version == 0) back off -- we have to wait
 
1220
    until no one holds a name lock on the table.
 
1221
    - if there is no such Table in the name cache, read the table definition
 
1222
    and insert it into the cache.
 
1223
    We perform all of the above under LOCK_open which currently protects
 
1224
    the open cache (also known as table cache) and table definitions stored
 
1225
    on disk.
 
1226
  */
 
1227
 
 
1228
  pthread_mutex_lock(&LOCK_open); /* Lock for FLUSH TABLES for open table */
 
1229
 
 
1230
  /*
 
1231
    Actually try to find the table in the open_cache.
 
1232
    The cache may contain several "Table" instances for the same
 
1233
    physical table. The instances that are currently "in use" by
 
1234
    some thread have their "in_use" member != NULL.
 
1235
    There is no good reason for having more than one entry in the
 
1236
    hash for the same physical table, except that we use this as
 
1237
    an implicit "pending locks queue" - see
 
1238
    wait_for_locked_table_names for details.
 
1239
  */
 
1240
  for (table= (Table*) hash_first(&open_cache, (unsigned char*) &key[0], key_length,
 
1241
                                  &state);
 
1242
       table && table->in_use ;
 
1243
       table= (Table*) hash_next(&open_cache, (unsigned char*) &key[0], key_length,
 
1244
                                 &state))
 
1245
  {
956
1246
    /*
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.
 
1247
      Here we flush tables marked for flush.
 
1248
      Normally, table->getShare()->version contains the value of
 
1249
      refresh_version from the moment when this table was
 
1250
      (re-)opened and added to the cache.
 
1251
      If since then we did (or just started) FLUSH TABLES
 
1252
      statement, refresh_version has been increased.
 
1253
      For "name-locked" Table instances, table->getShare()->version is set
 
1254
      to 0 (see lock_table_name for details).
 
1255
      In case there is a pending FLUSH TABLES or a name lock, we
 
1256
      need to back off and re-start opening tables.
 
1257
      If we do not back off now, we may dead lock in case of lock
 
1258
      order mismatch with some other thread:
 
1259
c1: name lock t1; -- sort of exclusive lock
 
1260
c2: open t2;      -- sort of shared lock
 
1261
c1: name lock t2; -- blocks
 
1262
c2: open t1; -- blocks
964
1263
    */
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 */
 
1264
    if (table->needs_reopen_or_name_lock())
 
1265
    {
 
1266
      if (flags & DRIZZLE_LOCK_IGNORE_FLUSH)
 
1267
      {
 
1268
        /* Force close at once after usage */
 
1269
        version= table->getShare()->getVersion();
 
1270
        continue;
 
1271
      }
 
1272
 
 
1273
      /* Avoid self-deadlocks by detecting self-dependencies. */
 
1274
      if (table->open_placeholder && table->in_use == this)
 
1275
      {
 
1276
        pthread_mutex_unlock(&LOCK_open);
 
1277
        my_error(ER_UPDATE_TABLE_USED, MYF(0), table->getMutableShare()->getTableName());
 
1278
        return NULL;
 
1279
      }
 
1280
 
 
1281
      /*
 
1282
        Back off, part 1: mark the table as "unused" for the
 
1283
        purpose of name-locking by setting table->db_stat to 0. Do
 
1284
        that only for the tables in this thread that have an old
 
1285
        table->getShare()->version (this is an optimization (?)).
 
1286
        table->db_stat == 0 signals wait_for_locked_table_names
 
1287
        that the tables in question are not used any more. See
 
1288
        table_is_used call for details.
 
1289
      */
 
1290
      close_old_data_files(false, false);
 
1291
 
 
1292
      /*
 
1293
        Back-off part 2: try to avoid "busy waiting" on the table:
 
1294
        if the table is in use by some other thread, we suspend
 
1295
        and wait till the operation is complete: when any
 
1296
        operation that juggles with table->getShare()->version completes,
 
1297
        it broadcasts COND_refresh condition variable.
 
1298
        If 'old' table we met is in use by current thread we return
 
1299
        without waiting since in this situation it's this thread
 
1300
        which is responsible for broadcasting on COND_refresh
 
1301
        (and this was done already in Session::close_old_data_files()).
 
1302
        Good example of such situation is when we have statement
 
1303
        that needs two instances of table and FLUSH TABLES comes
 
1304
        after we open first instance but before we open second
 
1305
        instance.
 
1306
      */
 
1307
      if (table->in_use != this)
 
1308
      {
 
1309
        /* wait_for_conditionwill unlock LOCK_open for us */
 
1310
        wait_for_condition(&LOCK_open, &COND_refresh);
 
1311
      }
 
1312
      else
 
1313
      {
 
1314
        pthread_mutex_unlock(&LOCK_open);
 
1315
      }
 
1316
      /*
 
1317
        There is a refresh in progress for this table.
 
1318
        Signal the caller that it has to try again.
 
1319
      */
973
1320
      if (refresh)
974
1321
        *refresh= true;
975
 
 
976
1322
      return NULL;
977
1323
    }
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 */
 
1324
  }
 
1325
  if (table)
 
1326
  {
 
1327
    /* Unlink the table from "unused_tables" list. */
 
1328
    if (table == unused_tables)
 
1329
    {  // First unused
 
1330
      unused_tables= unused_tables->getNext(); // Remove from link
 
1331
      if (table == unused_tables)
 
1332
        unused_tables= NULL;
985
1333
    }
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
 
 
 
1334
    table->getPrev()->setNext(table->getNext()); /* Remove from unused list */
 
1335
    table->getNext()->setPrev(table->getPrev());
 
1336
    table->in_use= this;
 
1337
  }
 
1338
  else
 
1339
  {
 
1340
    /* Insert a new Table instance into the open cache */
 
1341
    int error;
 
1342
    /* Free cache if too big */
 
1343
    while (open_cache.records > table_cache_size && unused_tables)
 
1344
      hash_delete(&open_cache,(unsigned char*) unused_tables);
 
1345
 
 
1346
    if (table_list->create)
1002
1347
    {
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)
 
1348
      TableIdentifier  lock_table_identifier(table_list->db, table_list->table_name, message::Table::STANDARD);
 
1349
 
 
1350
      if (not plugin::StorageEngine::doesTableExist(*this, lock_table_identifier))
1020
1351
      {
1021
 
        table= (*iter).second;
1022
 
 
1023
 
        if (not table->in_use)
1024
 
          break;
1025
1352
        /*
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
 
1353
          Table to be created, so we need to create placeholder in table-cache.
1042
1354
        */
1043
 
        if (table->needs_reopen_or_name_lock())
 
1355
        if (!(table= table_cache_insert_placeholder(table_list->db, table_list->table_name, &key[0], key_length)))
1044
1356
        {
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;
 
1357
          pthread_mutex_unlock(&LOCK_open);
1101
1358
          return NULL;
1102
1359
        }
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
 
  }
 
1360
        /*
 
1361
          Link placeholder to the open tables list so it will be automatically
 
1362
          removed once tables are closed. Also mark it so it won't be ignored
 
1363
          by other trying to take name-lock.
 
1364
        */
 
1365
        table->open_placeholder= true;
 
1366
        table->setNext(open_tables);
 
1367
        open_tables= table;
 
1368
        pthread_mutex_unlock(&LOCK_open);
 
1369
 
 
1370
        return table ;
 
1371
      }
 
1372
      /* Table exists. Let us try to open it. */
 
1373
    }
 
1374
 
 
1375
    /* make a new table */
 
1376
    table= (Table *)malloc(sizeof(Table));
 
1377
    memset(table, 0, sizeof(Table));
 
1378
    if (table == NULL)
 
1379
    {
 
1380
      pthread_mutex_unlock(&LOCK_open);
 
1381
      return NULL;
 
1382
    }
 
1383
 
 
1384
    error= open_unireg_entry(this, table, alias, identifier);
 
1385
    if (error != 0)
 
1386
    {
 
1387
      free(table);
 
1388
      pthread_mutex_unlock(&LOCK_open);
 
1389
      return NULL;
 
1390
    }
 
1391
    my_hash_insert(&open_cache, (unsigned char*) table);
 
1392
  }
 
1393
 
 
1394
  pthread_mutex_unlock(&LOCK_open);
 
1395
  if (refresh)
 
1396
  {
 
1397
    table->setNext(open_tables); /* Link into simple list */
 
1398
    open_tables= table;
 
1399
  }
 
1400
  table->reginfo.lock_type= TL_READ; /* Assume read */
 
1401
 
 
1402
reset:
1176
1403
  assert(table->getShare()->getTableCount() > 0 || table->getShare()->getType() != message::Table::STANDARD);
1177
1404
 
 
1405
  if (lex->need_correct_ident())
 
1406
    table->alias_name_used= my_strcasecmp(table_alias_charset,
 
1407
                                          table->getMutableShare()->getTableName(), alias);
1178
1408
  /* Fix alias if table name changes */
1179
 
  if (strcmp(table->getAlias(), alias))
 
1409
  if (strcmp(table->alias, alias))
1180
1410
  {
1181
 
    table->setAlias(alias);
 
1411
    uint32_t length=(uint32_t) strlen(alias)+1;
 
1412
    table->alias= (char*) realloc((char*) table->alias, length);
 
1413
    memcpy((void*) table->alias, alias, length);
1182
1414
  }
1183
1415
 
1184
1416
  /* These variables are also set in reopen_table() */
1189
1421
  table->maybe_null= false;
1190
1422
  table->force_index= false;
1191
1423
  table->status=STATUS_NO_RECORD;
1192
 
  table->insert_values.clear();
 
1424
  table->insert_values= 0;
1193
1425
  /* Catch wrong handling of the auto_increment_field_not_null. */
1194
1426
  assert(!table->auto_increment_field_not_null);
1195
1427
  table->auto_increment_field_not_null= false;
1205
1437
}
1206
1438
 
1207
1439
 
 
1440
#if 0
 
1441
/*
 
1442
  Reopen an table because the definition has changed.
 
1443
 
 
1444
  SYNOPSIS
 
1445
  reopen_table()
 
1446
  table Table object
 
1447
 
 
1448
  NOTES
 
1449
  The data cursor for the table is already closed and the share is released
 
1450
  The table has a 'dummy' share that mainly contains database and table name.
 
1451
 
 
1452
  RETURN
 
1453
  0  ok
 
1454
  1  error. The old table object is not changed.
 
1455
*/
 
1456
 
 
1457
bool reopen_table(Table *table)
 
1458
{
 
1459
  Table tmp;
 
1460
  bool error= 1;
 
1461
  Field **field;
 
1462
  uint32_t key,part;
 
1463
  TableList table_list;
 
1464
  Session *session= table->in_use;
 
1465
 
 
1466
  assert(table->getShare()->ref_count == 0);
 
1467
  assert(!table->sort.io_cache);
 
1468
 
 
1469
#ifdef EXTRA_DEBUG
 
1470
  if (table->db_stat)
 
1471
    errmsg_printf(ERRMSG_LVL_ERROR, _("Table %s had a open data Cursor in reopen_table"),
 
1472
                  table->alias);
 
1473
#endif
 
1474
  table_list.db=         const_cast<char *>(table->getShare()->getSchemaName());
 
1475
  table_list.table_name= table->getShare()->getTableName();
 
1476
  table_list.table=      table;
 
1477
 
 
1478
  if (wait_for_locked_table_names(session, &table_list))
 
1479
    return true;                             // Thread was killed
 
1480
 
 
1481
  if (open_unireg_entry(session, &tmp, &table_list,
 
1482
                        table->alias,
 
1483
                        table->getShare()->getCacheKey(),
 
1484
                        table->getShare()->getCacheKeySize()))
 
1485
    goto end;
 
1486
 
 
1487
  /* This list copies variables set by open_table */
 
1488
  tmp.tablenr=          table->tablenr;
 
1489
  tmp.used_fields=      table->used_fields;
 
1490
  tmp.const_table=      table->const_table;
 
1491
  tmp.null_row=         table->null_row;
 
1492
  tmp.maybe_null=       table->maybe_null;
 
1493
  tmp.status=           table->status;
 
1494
 
 
1495
  /* Get state */
 
1496
  tmp.in_use=           session;
 
1497
  tmp.reginfo.lock_type=table->reginfo.lock_type;
 
1498
 
 
1499
  /* Replace table in open list */
 
1500
  tmp.next=             table->next;
 
1501
  tmp.prev=             table->prev;
 
1502
 
 
1503
  if (table->cursor)
 
1504
    table->delete_table(true);          // close cursor, free everything
 
1505
 
 
1506
  *table= tmp;
 
1507
  table->default_column_bitmaps();
 
1508
  table->cursor->change_table_ptr(table, table->s);
 
1509
 
 
1510
  assert(table->alias != 0);
 
1511
  for (field=table->field ; *field ; field++)
 
1512
  {
 
1513
    (*field)->table= (*field)->orig_table= table;
 
1514
    (*field)->table_name= &table->alias;
 
1515
  }
 
1516
  for (key=0 ; key < table->getShare()->keys ; key++)
 
1517
  {
 
1518
    for (part=0 ; part < table->key_info[key].usable_key_parts ; part++)
 
1519
      table->key_info[key].key_part[part].field->table= table;
 
1520
  }
 
1521
 
 
1522
  broadcast_refresh();
 
1523
  error= false;
 
1524
 
 
1525
end:
 
1526
  return(error);
 
1527
}
 
1528
#endif
 
1529
 
 
1530
 
1208
1531
/**
1209
1532
  Close all instances of a table open by this thread and replace
1210
1533
  them with exclusive name-locks.
1222
1545
  the strings are used in a loop even after the share may be freed.
1223
1546
*/
1224
1547
 
1225
 
void Session::close_data_files_and_morph_locks(const TableIdentifier &identifier)
 
1548
void Session::close_data_files_and_morph_locks(TableIdentifier &identifier)
1226
1549
{
1227
 
  safe_mutex_assert_owner(table::Cache::singleton().mutex().native_handle()); /* Adjust locks at the end of ALTER TABLEL */
 
1550
  Table *table;
 
1551
 
 
1552
  safe_mutex_assert_owner(&LOCK_open); /* Adjust locks at the end of ALTER TABLEL */
1228
1553
 
1229
1554
  if (lock)
1230
1555
  {
1232
1557
      If we are not under LOCK TABLES we should have only one table
1233
1558
      open and locked so it makes sense to remove the lock at once.
1234
1559
    */
1235
 
    unlockTables(lock);
 
1560
    mysql_unlock_tables(this, lock);
1236
1561
    lock= 0;
1237
1562
  }
1238
1563
 
1241
1566
    for target table name if we process ALTER Table ... RENAME.
1242
1567
    So loop below makes sense even if we are not under LOCK TABLES.
1243
1568
  */
1244
 
  for (Table *table= open_tables; table ; table=table->getNext())
 
1569
  for (table= open_tables; table ; table=table->getNext())
1245
1570
  {
1246
 
    if (table->getShare()->getCacheKey() == identifier.getKey())
 
1571
    if (!strcmp(table->getMutableShare()->getTableName(), identifier.getTableName().c_str()) &&
 
1572
        !strcasecmp(table->getMutableShare()->getSchemaName(), identifier.getSchemaName().c_str()))
1247
1573
    {
1248
1574
      table->open_placeholder= true;
1249
1575
      close_handle_and_leave_table_as_lock(table);
1267
1593
  combination when one needs tables to be reopened (for
1268
1594
  example see openTablesLock()).
1269
1595
 
1270
 
  @note One should have lock on table::Cache::singleton().mutex() when calling this.
 
1596
  @note One should have lock on LOCK_open when calling this.
1271
1597
 
1272
1598
  @return false in case of success, true - otherwise.
1273
1599
*/
1284
1610
  if (open_tables == NULL)
1285
1611
    return false;
1286
1612
 
1287
 
  safe_mutex_assert_owner(table::Cache::singleton().mutex().native_handle());
 
1613
  safe_mutex_assert_owner(&LOCK_open);
1288
1614
  if (get_locks)
1289
1615
  {
1290
1616
    /*
1310
1636
  {
1311
1637
    next= table->getNext();
1312
1638
 
1313
 
    my_error(ER_CANT_REOPEN_TABLE, MYF(0), table->getAlias());
1314
 
    table::remove_table(static_cast<table::Concurrent *>(table));
 
1639
    my_error(ER_CANT_REOPEN_TABLE, MYF(0), table->alias);
 
1640
    hash_delete(&open_cache,(unsigned char*) table);
1315
1641
    error= 1;
1316
1642
  }
1317
1643
  *prev=0;
1318
1644
  if (tables != tables_ptr)                     // Should we get back old locks
1319
1645
  {
1320
 
    DrizzleLock *local_lock;
 
1646
    DRIZZLE_LOCK *local_lock;
1321
1647
    /*
1322
1648
      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
 
1649
      wait_for_tables() as it tries to acquire LOCK_open, which is
1324
1650
      already locked.
1325
1651
    */
1326
1652
    some_tables_deleted= false;
1327
1653
 
1328
 
    if ((local_lock= lockTables(tables, (uint32_t) (tables_ptr - tables),
1329
 
                                       flags, &not_used)))
 
1654
    if ((local_lock= mysql_lock_tables(this, tables, (uint32_t) (tables_ptr - tables),
 
1655
                                 flags, &not_used)))
1330
1656
    {
1331
1657
      /* unused */
1332
1658
    }
1345
1671
  if (get_locks && tables)
1346
1672
    delete [] tables;
1347
1673
 
1348
 
  locking::broadcast_refresh();
 
1674
  broadcast_refresh();
1349
1675
 
1350
1676
  return(error);
1351
1677
}
1392
1718
              lock on it. This will also give them a chance to close their
1393
1719
              instances of this table.
1394
1720
            */
1395
 
            abortLock(ulcktbl);
1396
 
            removeLock(ulcktbl);
 
1721
            mysql_lock_abort(this, ulcktbl);
 
1722
            mysql_lock_remove(this, ulcktbl);
1397
1723
            ulcktbl->lock_count= 0;
1398
1724
          }
1399
1725
          if ((ulcktbl != table) && ulcktbl->db_stat)
1433
1759
    }
1434
1760
  }
1435
1761
  if (found)
1436
 
    locking::broadcast_refresh();
 
1762
    broadcast_refresh();
 
1763
}
 
1764
 
 
1765
 
 
1766
/*
 
1767
  Wait until all threads has closed the tables in the list
 
1768
  We have also to wait if there is thread that has a lock on this table even
 
1769
  if the table is closed
 
1770
*/
 
1771
 
 
1772
bool table_is_used(Table *table, bool wait_for_name_lock)
 
1773
{
 
1774
  do
 
1775
  {
 
1776
    const TableIdentifier::Key &key(table->getShare()->getCacheKey());
 
1777
 
 
1778
    HASH_SEARCH_STATE state;
 
1779
    for (Table *search= (Table*) hash_first(&open_cache, (unsigned char*) &key[0],
 
1780
                                            key.size(), &state);
 
1781
         search ;
 
1782
         search= (Table*) hash_next(&open_cache, (unsigned char*) &key[0],
 
1783
                                    key.size(), &state))
 
1784
    {
 
1785
      if (search->in_use == table->in_use)
 
1786
        continue;                               // Name locked by this thread
 
1787
      /*
 
1788
        We can't use the table under any of the following conditions:
 
1789
        - There is an name lock on it (Table is to be deleted or altered)
 
1790
        - If we are in flush table and we didn't execute the flush
 
1791
        - If the table engine is open and it's an old version
 
1792
        (We must wait until all engines are shut down to use the table)
 
1793
      */
 
1794
      if ( (search->locked_by_name && wait_for_name_lock) ||
 
1795
           (search->is_name_opened() && search->needs_reopen_or_name_lock()))
 
1796
        return 1;
 
1797
    }
 
1798
  } while ((table=table->getNext()));
 
1799
  return 0;
1437
1800
}
1438
1801
 
1439
1802
 
1444
1807
  bool result;
1445
1808
 
1446
1809
  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
 
  }
 
1810
  pthread_mutex_lock(&LOCK_open); /* Lock for all tables to be refreshed */
 
1811
  while (!session->killed)
 
1812
  {
 
1813
    session->some_tables_deleted= false;
 
1814
    session->close_old_data_files(false, dropping_tables != 0);
 
1815
    if (!table_is_used(session->open_tables, 1))
 
1816
      break;
 
1817
    (void) pthread_cond_wait(&COND_refresh,&LOCK_open);
 
1818
  }
 
1819
  if (session->killed)
 
1820
    result= true;                                       // aborted
 
1821
  else
 
1822
  {
 
1823
    /* Now we can open all tables without any interference */
 
1824
    session->set_proc_info("Reopen tables");
 
1825
    session->version= refresh_version;
 
1826
    result= session->reopen_tables(false, false);
 
1827
  }
 
1828
  pthread_mutex_unlock(&LOCK_open);
1469
1829
  session->set_proc_info(0);
1470
1830
 
1471
1831
  return result;
1496
1856
*/
1497
1857
 
1498
1858
 
1499
 
Table *drop_locked_tables(Session *session, const drizzled::TableIdentifier &identifier)
 
1859
Table *drop_locked_tables(Session *session, const char *db, const char *table_name)
1500
1860
{
1501
1861
  Table *table,*next,**prev, *found= 0;
1502
1862
  prev= &session->open_tables;
1503
1863
 
1504
1864
  /*
1505
 
    Note that we need to hold table::Cache::singleton().mutex() while changing the
 
1865
    Note that we need to hold LOCK_open while changing the
1506
1866
    open_tables list. Another thread may work on it.
1507
 
    (See: table::Cache::singleton().removeTable(), mysql_wait_completed_table())
 
1867
    (See: remove_table_from_cache(), mysql_wait_completed_table())
1508
1868
    Closing a MERGE child before the parent would be fatal if the
1509
1869
    other thread tries to abort the MERGE lock in between.
1510
1870
  */
1511
1871
  for (table= session->open_tables; table ; table=next)
1512
1872
  {
1513
1873
    next=table->getNext();
1514
 
    if (table->getShare()->getCacheKey() == identifier.getKey())
 
1874
    if (!strcmp(table->getMutableShare()->getTableName(), table_name) &&
 
1875
        !strcasecmp(table->getMutableShare()->getSchemaName(), db))
1515
1876
    {
1516
 
      session->removeLock(table);
 
1877
      mysql_lock_remove(session, table);
1517
1878
 
1518
1879
      if (!found)
1519
1880
      {
1528
1889
      else
1529
1890
      {
1530
1891
        /* We already have a name lock, remove copy */
1531
 
        table::remove_table(static_cast<table::Concurrent *>(table));
 
1892
        hash_delete(&open_cache,(unsigned char*) table);
1532
1893
      }
1533
1894
    }
1534
1895
    else
1539
1900
  }
1540
1901
  *prev=0;
1541
1902
  if (found)
1542
 
    locking::broadcast_refresh();
 
1903
    broadcast_refresh();
1543
1904
 
1544
1905
  return(found);
1545
1906
}
1551
1912
  other threads trying to get the lock.
1552
1913
*/
1553
1914
 
1554
 
void abort_locked_tables(Session *session, const drizzled::TableIdentifier &identifier)
 
1915
void abort_locked_tables(Session *session,const char *db, const char *table_name)
1555
1916
{
1556
1917
  Table *table;
1557
1918
  for (table= session->open_tables; table ; table= table->getNext())
1558
1919
  {
1559
 
    if (table->getShare()->getCacheKey() == identifier.getKey())
 
1920
    if (!strcmp(table->getMutableShare()->getTableName(), table_name) &&
 
1921
        !strcmp(table->getMutableShare()->getSchemaName(), db))
1560
1922
    {
1561
1923
      /* If MERGE child, forward lock handling to parent. */
1562
 
      session->abortLock(table);
 
1924
      mysql_lock_abort(session, table);
1563
1925
      break;
1564
1926
    }
1565
1927
  }
1566
1928
}
1567
1929
 
 
1930
/*
 
1931
  Load a table definition from cursor and open unireg table
 
1932
 
 
1933
  SYNOPSIS
 
1934
  open_unireg_entry()
 
1935
  session                       Thread handle
 
1936
  entry         Store open table definition here
 
1937
  table_list            TableList with db, table_name
 
1938
  alias         Alias name
 
1939
  cache_key             Key for share_cache
 
1940
  cache_key_length      length of cache_key
 
1941
 
 
1942
  NOTES
 
1943
  Extra argument for open is taken from session->open_options
 
1944
  One must have a lock on LOCK_open when calling this function
 
1945
 
 
1946
  RETURN
 
1947
  0     ok
 
1948
#       Error
 
1949
*/
 
1950
 
 
1951
static int open_unireg_entry(Session *session,
 
1952
                             Table *entry,
 
1953
                             const char *alias,
 
1954
                             TableIdentifier &identifier)
 
1955
{
 
1956
  int error;
 
1957
  TableShare *share;
 
1958
  uint32_t discover_retry_count= 0;
 
1959
 
 
1960
  safe_mutex_assert_owner(&LOCK_open);
 
1961
retry:
 
1962
  if (not (share= TableShare::getShareCreate(session,
 
1963
                                             identifier,
 
1964
                                             &error)))
 
1965
    return 1;
 
1966
 
 
1967
  while ((error= share->open_table_from_share(session, alias,
 
1968
                                              (uint32_t) (HA_OPEN_KEYFILE |
 
1969
                                                          HA_OPEN_RNDFILE |
 
1970
                                                          HA_GET_INDEX |
 
1971
                                                          HA_TRY_READ_ONLY),
 
1972
                                              session->open_options, *entry)))
 
1973
  {
 
1974
    if (error == 7)                             // Table def changed
 
1975
    {
 
1976
      share->resetVersion();                        // Mark share as old
 
1977
      if (discover_retry_count++)               // Retry once
 
1978
        goto err;
 
1979
 
 
1980
      /*
 
1981
        TODO->
 
1982
        Here we should wait until all threads has released the table.
 
1983
        For now we do one retry. This may cause a deadlock if there
 
1984
        is other threads waiting for other tables used by this thread.
 
1985
 
 
1986
        Proper fix would be to if the second retry failed:
 
1987
        - Mark that table def changed
 
1988
        - Return from open table
 
1989
        - Close all tables used by this thread
 
1990
        - Start waiting that the share is released
 
1991
        - Retry by opening all tables again
 
1992
      */
 
1993
 
 
1994
      /*
 
1995
        TO BE FIXED
 
1996
        To avoid deadlock, only wait for release if no one else is
 
1997
        using the share.
 
1998
      */
 
1999
      if (share->getTableCount() != 1)
 
2000
        goto err;
 
2001
      /* Free share and wait until it's released by all threads */
 
2002
      TableShare::release(share);
 
2003
 
 
2004
      if (!session->killed)
 
2005
      {
 
2006
        drizzle_reset_errors(session, 1);         // Clear warnings
 
2007
        session->clear_error();                 // Clear error message
 
2008
        goto retry;
 
2009
      }
 
2010
      return 1;
 
2011
    }
 
2012
 
 
2013
    goto err;
 
2014
  }
 
2015
 
 
2016
  return 0;
 
2017
 
 
2018
err:
 
2019
  TableShare::release(share);
 
2020
 
 
2021
  return 1;
 
2022
}
 
2023
 
1568
2024
 
1569
2025
/*
1570
2026
  Open all tables in list
1632
2088
     * to see if it exists so that an unauthorized user cannot phish for
1633
2089
     * table/schema information via error messages
1634
2090
     */
1635
 
    TableIdentifier the_table(tables->getSchemaName(), tables->getTableName());
1636
 
    if (not plugin::Authorization::isAuthorized(user(), the_table))
 
2091
    TableIdentifier the_table(tables->db, tables->table_name);
 
2092
    if (not plugin::Authorization::isAuthorized(getSecurityContext(),
 
2093
                                                the_table))
1637
2094
    {
1638
2095
      result= -1;                               // Fatal error
1639
2096
      break;
1741
2198
 
1742
2199
    assert(lock == 0);  // You must lock everything at once
1743
2200
    if ((table->reginfo.lock_type= lock_type) != TL_UNLOCK)
1744
 
      if (! (lock= lockTables(&table_list->table, 1, 0, &refresh)))
 
2201
      if (! (lock= mysql_lock_tables(this, &table_list->table, 1, 0, &refresh)))
1745
2202
        table= 0;
1746
2203
  }
1747
2204
 
1804
2261
      *(ptr++)= table->table;
1805
2262
  }
1806
2263
 
1807
 
  if (!(session->lock= session->lockTables(start, (uint32_t) (ptr - start), lock_flag, need_reopen)))
 
2264
  if (!(session->lock= mysql_lock_tables(session, start, (uint32_t) (ptr - start),
 
2265
                                         lock_flag, need_reopen)))
1808
2266
  {
1809
2267
    return -1;
1810
2268
  }
1833
2291
#  Table object
1834
2292
*/
1835
2293
 
1836
 
Table *Open_tables_state::open_temporary_table(const TableIdentifier &identifier,
1837
 
                                               bool link_in_list)
 
2294
Table *Session::open_temporary_table(TableIdentifier &identifier,
 
2295
                                     bool link_in_list)
1838
2296
{
 
2297
  Table *new_tmp_table;
 
2298
  TableShare *share;
 
2299
 
1839
2300
  assert(identifier.isTmp());
1840
 
 
1841
 
 
1842
 
  table::Temporary *new_tmp_table= new table::Temporary(identifier.getType(),
1843
 
                                                        identifier,
1844
 
                                                        const_cast<char *>(const_cast<TableIdentifier&>(identifier).getPath().c_str()),
1845
 
                                                        static_cast<uint32_t>(identifier.getPath().length()));
1846
 
  if (not new_tmp_table)
 
2301
  share= new TableShare(identifier.getType(),
 
2302
                        identifier,
 
2303
                        const_cast<char *>(identifier.getPath().c_str()), static_cast<uint32_t>(identifier.getPath().length()));
 
2304
 
 
2305
 
 
2306
  if (!(new_tmp_table= (Table*) malloc(sizeof(*new_tmp_table))))
1847
2307
    return NULL;
1848
2308
 
 
2309
  memset(new_tmp_table, 0, sizeof(*new_tmp_table));
 
2310
 
 
2311
 
1849
2312
  /*
1850
2313
    First open the share, and then open the table from the share we just opened.
1851
2314
  */
1852
 
  if (new_tmp_table->getMutableShare()->open_table_def(*static_cast<Session *>(this), identifier) ||
1853
 
      new_tmp_table->getMutableShare()->open_table_from_share(static_cast<Session *>(this), identifier, identifier.getTableName().c_str(),
1854
 
                                                              (uint32_t) (HA_OPEN_KEYFILE | HA_OPEN_RNDFILE |
1855
 
                                                                          HA_GET_INDEX),
1856
 
                                                              ha_open_options,
1857
 
                                                              *new_tmp_table))
 
2315
  if (share->open_table_def(*this, identifier) ||
 
2316
      share->open_table_from_share(this, identifier.getTableName().c_str(),
 
2317
                            (uint32_t) (HA_OPEN_KEYFILE | HA_OPEN_RNDFILE |
 
2318
                                        HA_GET_INDEX),
 
2319
                            ha_open_options,
 
2320
                            *new_tmp_table))
1858
2321
  {
1859
2322
    /* No need to lock share->mutex as this is not needed for tmp tables */
1860
 
    delete new_tmp_table->getMutableShare();
1861
 
    delete new_tmp_table;
 
2323
    delete share;
 
2324
    free((char*) new_tmp_table);
1862
2325
 
1863
2326
    return 0;
1864
2327
  }
1899
2362
{
1900
2363
  if (session->mark_used_columns != MARK_COLUMNS_NONE)
1901
2364
  {
1902
 
    boost::dynamic_bitset<> *current_bitmap= NULL;
 
2365
    MyBitmap *current_bitmap, *other_bitmap;
1903
2366
 
1904
2367
    /*
1905
2368
      We always want to register the used keys, as the column bitmap may have
1912
2375
    if (session->mark_used_columns == MARK_COLUMNS_READ)
1913
2376
    {
1914
2377
      current_bitmap= table->read_set;
 
2378
      other_bitmap=   table->write_set;
1915
2379
    }
1916
2380
    else
1917
2381
    {
1918
2382
      current_bitmap= table->write_set;
 
2383
      other_bitmap=   table->read_set;
1919
2384
    }
1920
2385
 
1921
 
    //if (current_bitmap->testAndSet(field->position()))
1922
 
    if (current_bitmap->test(field->position()))
 
2386
    if (current_bitmap->testAndSet(field->field_index))
1923
2387
    {
1924
2388
      if (session->mark_used_columns == MARK_COLUMNS_WRITE)
1925
2389
        session->dup_field= field;
1988
2452
    return NULL;
1989
2453
  {
1990
2454
    /* This is a base table. */
1991
 
    assert(nj_col->table_ref->table == nj_col->table_field->getTable());
 
2455
    assert(nj_col->table_ref->table == nj_col->table_field->table);
1992
2456
    found_field= nj_col->table_field;
1993
2457
    update_field_dependencies(session, found_field, nj_col->table_ref->table);
1994
2458
  }
2031
2495
  {
2032
2496
    field_ptr= table->getFields() + cached_field_index;
2033
2497
  }
2034
 
  else if (table->getShare()->getNamedFieldSize())
 
2498
  else if (table->getShare()->name_hash.records)
2035
2499
  {
2036
 
    field_ptr= table->getMutableShare()->getNamedField(std::string(name, length));
 
2500
    field_ptr= (Field**) hash_search(&table->getShare()->name_hash, (unsigned char*) name,
 
2501
                                     length);
2037
2502
    if (field_ptr)
2038
2503
    {
2039
2504
      /*
2145
2610
    TODO-> Ensure that table_name, db_name and tables->db always points to something !
2146
2611
  */
2147
2612
  if (/* Exclude nested joins. */
2148
 
      (!table_list->getNestedJoin()) &&
 
2613
      (!table_list->nested_join) &&
2149
2614
      /* Include merge views and information schema tables. */
2150
2615
      /*
2151
2616
        Test if the field qualifiers match the table reference we plan
2153
2618
      */
2154
2619
      table_name && table_name[0] &&
2155
2620
      (my_strcasecmp(table_alias_charset, table_list->alias, table_name) ||
2156
 
       (db_name && db_name[0] && table_list->getSchemaName() && table_list->getSchemaName()[0] &&
2157
 
        strcmp(db_name, table_list->getSchemaName()))))
 
2621
       (db_name && db_name[0] && table_list->db && table_list->db[0] &&
 
2622
        strcmp(db_name, table_list->db))))
2158
2623
    return 0;
2159
2624
 
2160
2625
  *actual_table= NULL;
2161
2626
 
2162
 
  if (!table_list->getNestedJoin())
 
2627
  if (!table_list->nested_join)
2163
2628
  {
2164
2629
    /* 'table_list' is a stored table. */
2165
2630
    assert(table_list->table);
2179
2644
    */
2180
2645
    if (table_name && table_name[0])
2181
2646
    {
2182
 
      List_iterator<TableList> it(table_list->getNestedJoin()->join_list);
 
2647
      List_iterator<TableList> it(table_list->nested_join->join_list);
2183
2648
      TableList *table;
2184
2649
      while ((table= it++))
2185
2650
      {
2227
2692
        field_to_set= fld;
2228
2693
      if (field_to_set)
2229
2694
      {
2230
 
        Table *table= field_to_set->getTable();
 
2695
        Table *table= field_to_set->table;
2231
2696
        if (session->mark_used_columns == MARK_COLUMNS_READ)
2232
 
          table->setReadSet(field_to_set->position());
 
2697
          table->setReadSet(field_to_set->field_index);
2233
2698
        else
2234
 
          table->setWriteSet(field_to_set->position());
 
2699
          table->setWriteSet(field_to_set->field_index);
2235
2700
      }
2236
2701
    }
2237
2702
  }
2771
3236
    Leaf table references to which new natural join columns are added
2772
3237
    if the leaves are != NULL.
2773
3238
  */
2774
 
  TableList *leaf_1= (table_ref_1->getNestedJoin() &&
2775
 
                      ! table_ref_1->is_natural_join) ?
 
3239
  TableList *leaf_1= (table_ref_1->nested_join &&
 
3240
                      !table_ref_1->is_natural_join) ?
2776
3241
    NULL : table_ref_1;
2777
 
  TableList *leaf_2= (table_ref_2->getNestedJoin() &&
2778
 
                      ! table_ref_2->is_natural_join) ?
 
3242
  TableList *leaf_2= (table_ref_2->nested_join &&
 
3243
                      !table_ref_2->is_natural_join) ?
2779
3244
    NULL : table_ref_2;
2780
3245
 
2781
3246
  *found_using_fields= 0;
2787
3252
    /* true if field_name_1 is a member of using_fields */
2788
3253
    bool is_using_column_1;
2789
3254
    if (!(nj_col_1= it_1.get_or_create_column_ref(leaf_1)))
2790
 
      return(result);
 
3255
      goto err;
2791
3256
    field_name_1= nj_col_1->name();
2792
3257
    is_using_column_1= using_fields &&
2793
3258
      test_if_string_in_list(field_name_1, using_fields);
2805
3270
      Natural_join_column *cur_nj_col_2;
2806
3271
      const char *cur_field_name_2;
2807
3272
      if (!(cur_nj_col_2= it_2.get_or_create_column_ref(leaf_2)))
2808
 
        return(result);
 
3273
        goto err;
2809
3274
      cur_field_name_2= cur_nj_col_2->name();
2810
3275
 
2811
3276
      /*
2825
3290
            (found && (!using_fields || is_using_column_1)))
2826
3291
        {
2827
3292
          my_error(ER_NON_UNIQ_ERROR, MYF(0), field_name_1, session->where);
2828
 
          return(result);
 
3293
          goto err;
2829
3294
        }
2830
3295
        nj_col_2= cur_nj_col_2;
2831
3296
        found= true;
2858
3323
      Item_func_eq *eq_cond;
2859
3324
 
2860
3325
      if (!item_1 || !item_2)
2861
 
        return(result); // out of memory
 
3326
        goto err;                               // out of memory
2862
3327
 
2863
3328
      /*
2864
3329
        In the case of no_wrap_view_item == 0, the created items must be
2883
3348
      */
2884
3349
      if (set_new_item_local_context(session, item_ident_1, nj_col_1->table_ref) ||
2885
3350
          set_new_item_local_context(session, item_ident_2, nj_col_2->table_ref))
2886
 
        return(result);
 
3351
        goto err;
2887
3352
 
2888
3353
      if (!(eq_cond= new Item_func_eq(item_ident_1, item_ident_2)))
2889
 
        return(result);                               /* Out of memory. */
 
3354
        goto err;                               /* Out of memory. */
2890
3355
 
2891
3356
      /*
2892
3357
        Add the new equi-join condition to the ON clause. Notice that
2903
3368
      {
2904
3369
        Table *table_1= nj_col_1->table_ref->table;
2905
3370
        /* Mark field_1 used for table cache. */
2906
 
        table_1->setReadSet(field_1->position());
 
3371
        table_1->setReadSet(field_1->field_index);
2907
3372
        table_1->covering_keys&= field_1->part_of_key;
2908
3373
        table_1->merge_keys|= field_1->part_of_key;
2909
3374
      }
2911
3376
      {
2912
3377
        Table *table_2= nj_col_2->table_ref->table;
2913
3378
        /* Mark field_2 used for table cache. */
2914
 
        table_2->setReadSet(field_2->position());
 
3379
        table_2->setReadSet(field_2->field_index);
2915
3380
        table_2->covering_keys&= field_2->part_of_key;
2916
3381
        table_2->merge_keys|= field_2->part_of_key;
2917
3382
      }
2932
3397
  */
2933
3398
  result= false;
2934
3399
 
 
3400
err:
2935
3401
  return(result);
2936
3402
}
2937
3403
 
2989
3455
 
2990
3456
  if (!(non_join_columns= new List<Natural_join_column>) ||
2991
3457
      !(natural_using_join->join_columns= new List<Natural_join_column>))
2992
 
  {
2993
 
    return(result);
2994
 
  }
 
3458
    goto err;
2995
3459
 
2996
3460
  /* Append the columns of the first join operand. */
2997
3461
  for (it_1.set(table_ref_1); !it_1.end_of_fields(); it_1.next())
3030
3494
        {
3031
3495
          my_error(ER_BAD_FIELD_ERROR, MYF(0), using_field_name_ptr,
3032
3496
                   session->where);
3033
 
          return(result);
 
3497
          goto err;
3034
3498
        }
3035
3499
        if (!my_strcasecmp(system_charset_info,
3036
3500
                           common_field->name(), using_field_name_ptr))
3058
3522
 
3059
3523
  result= false;
3060
3524
 
 
3525
err:
3061
3526
  return(result);
3062
3527
}
3063
3528
 
3100
3565
  bool result= true;
3101
3566
 
3102
3567
  /* Call the procedure recursively for each nested table reference. */
3103
 
  if (table_ref->getNestedJoin())
 
3568
  if (table_ref->nested_join)
3104
3569
  {
3105
 
    List_iterator_fast<TableList> nested_it(table_ref->getNestedJoin()->join_list);
 
3570
    List_iterator_fast<TableList> nested_it(table_ref->nested_join->join_list);
3106
3571
    TableList *same_level_left_neighbor= nested_it++;
3107
3572
    TableList *same_level_right_neighbor= NULL;
3108
3573
    /* Left/right-most neighbors, possibly at higher levels in the join tree. */
3127
3592
          cur_table_ref->outer_join & JOIN_TYPE_RIGHT)
3128
3593
      {
3129
3594
        /* This can happen only for JOIN ... ON. */
3130
 
        assert(table_ref->getNestedJoin()->join_list.elements == 2);
 
3595
        assert(table_ref->nested_join->join_list.elements == 2);
3131
3596
        std::swap(same_level_left_neighbor, cur_table_ref);
3132
3597
      }
3133
3598
 
3140
3605
      real_right_neighbor= (same_level_right_neighbor) ?
3141
3606
        same_level_right_neighbor : right_neighbor;
3142
3607
 
3143
 
      if (cur_table_ref->getNestedJoin() &&
 
3608
      if (cur_table_ref->nested_join &&
3144
3609
          store_top_level_join_columns(session, cur_table_ref,
3145
3610
                                       real_left_neighbor, real_right_neighbor))
3146
 
        return(result);
 
3611
        goto err;
3147
3612
      same_level_right_neighbor= cur_table_ref;
3148
3613
    }
3149
3614
  }
3154
3619
  */
3155
3620
  if (table_ref->is_natural_join)
3156
3621
  {
3157
 
    assert(table_ref->getNestedJoin() &&
3158
 
           table_ref->getNestedJoin()->join_list.elements == 2);
3159
 
    List_iterator_fast<TableList> operand_it(table_ref->getNestedJoin()->join_list);
 
3622
    assert(table_ref->nested_join &&
 
3623
           table_ref->nested_join->join_list.elements == 2);
 
3624
    List_iterator_fast<TableList> operand_it(table_ref->nested_join->join_list);
3160
3625
    /*
3161
3626
      Notice that the order of join operands depends on whether table_ref
3162
3627
      represents a LEFT or a RIGHT join. In a RIGHT join, the operands are
3175
3640
      std::swap(table_ref_1, table_ref_2);
3176
3641
    if (mark_common_columns(session, table_ref_1, table_ref_2,
3177
3642
                            using_fields, &found_using_fields))
3178
 
      return(result);
 
3643
      goto err;
3179
3644
 
3180
3645
    /*
3181
3646
      Swap the join operands back, so that we pick the columns of the second
3187
3652
    if (store_natural_using_join_columns(session, table_ref, table_ref_1,
3188
3653
                                         table_ref_2, using_fields,
3189
3654
                                         found_using_fields))
3190
 
      return(result);
 
3655
      goto err;
3191
3656
 
3192
3657
    /*
3193
3658
      Change NATURAL JOIN to JOIN ... ON. We do this for both operands
3220
3685
  }
3221
3686
  result= false; /* All is OK. */
3222
3687
 
 
3688
err:
3223
3689
  return(result);
3224
3690
}
3225
3691
 
3621
4087
    assert(tables->is_leaf_for_name_resolution());
3622
4088
 
3623
4089
    if ((table_name && my_strcasecmp(table_alias_charset, table_name, tables->alias)) ||
3624
 
        (db_name && strcasecmp(tables->getSchemaName(),db_name)))
 
4090
        (db_name && strcasecmp(tables->db,db_name)))
3625
4091
      continue;
3626
4092
 
3627
4093
    /*
3657
4123
      if ((field= field_iterator.field()))
3658
4124
      {
3659
4125
        /* Mark fields as used to allow storage engine to optimze access */
3660
 
        field->getTable()->setReadSet(field->position());
 
4126
        field->table->setReadSet(field->field_index);
3661
4127
        if (table)
3662
4128
        {
3663
4129
          table->covering_keys&= field->part_of_key;
3785
4251
          goto err_no_arena;
3786
4252
        select_lex->cond_count++;
3787
4253
      }
3788
 
      embedding= embedded->getEmbedding();
 
4254
      embedding= embedded->embedding;
3789
4255
    }
3790
4256
    while (embedding &&
3791
 
           embedding->getNestedJoin()->join_list.head() == embedded);
 
4257
           embedding->nested_join->join_list.head() == embedded);
3792
4258
 
3793
4259
  }
3794
4260
  session->session_marker= save_session_marker;
3847
4313
      thus we safely can take table from the first field.
3848
4314
    */
3849
4315
    field= static_cast<Item_field *>(f++);
3850
 
    table= field->field->getTable();
 
4316
    table= field->field->table;
3851
4317
    table->auto_increment_field_not_null= false;
3852
4318
    f.rewind();
3853
4319
  }
3857
4323
    value= v++;
3858
4324
 
3859
4325
    Field *rfield= field->field;
3860
 
    table= rfield->getTable();
 
4326
    table= rfield->table;
3861
4327
 
3862
4328
    if (rfield == table->next_number_field)
3863
4329
      table->auto_increment_field_not_null= true;
3864
4330
    if ((value->save_in_field(rfield, 0) < 0) && !ignore_errors)
3865
4331
    {
3866
4332
      my_message(ER_UNKNOWN_ERROR, ER(ER_UNKNOWN_ERROR), MYF(0));
3867
 
      if (table)
3868
 
        table->auto_increment_field_not_null= false;
3869
 
 
3870
 
      return true;
 
4333
      goto err;
3871
4334
    }
3872
4335
  }
3873
4336
 
3874
4337
  return session->is_error();
 
4338
 
 
4339
err:
 
4340
  if (table)
 
4341
    table->auto_increment_field_not_null= false;
 
4342
 
 
4343
  return true;
3875
4344
}
3876
4345
 
3877
4346
 
3911
4380
      On INSERT or UPDATE fields are checked to be from the same table,
3912
4381
      thus we safely can take table from the first field.
3913
4382
    */
3914
 
    table= (*ptr)->getTable();
 
4383
    table= (*ptr)->table;
3915
4384
    table->auto_increment_field_not_null= false;
3916
4385
  }
3917
4386
  while ((field = *ptr++) && ! session->is_error())
3918
4387
  {
3919
4388
    value=v++;
3920
 
    table= field->getTable();
 
4389
    table= field->table;
3921
4390
    if (field == table->next_number_field)
3922
4391
      table->auto_increment_field_not_null= true;
3923
4392
    if (value->save_in_field(field, 0) < 0)
3924
 
    {
3925
 
      if (table)
3926
 
        table->auto_increment_field_not_null= false;
3927
 
 
3928
 
      return true;
3929
 
    }
 
4393
      goto err;
3930
4394
  }
3931
4395
 
3932
4396
  return(session->is_error());
 
4397
 
 
4398
err:
 
4399
  if (table)
 
4400
    table->auto_increment_field_not_null= false;
 
4401
 
 
4402
  return true;
3933
4403
}
3934
4404
 
3935
4405
 
3957
4427
  unireg support functions
3958
4428
 *****************************************************************************/
3959
4429
 
3960
 
 
 
4430
/*
 
4431
  Invalidate any cache entries that are for some DB
 
4432
 
 
4433
  SYNOPSIS
 
4434
  remove_db_from_cache()
 
4435
  db            Database name. This will be in lower case if
 
4436
  lower_case_table_name is set
 
4437
 
 
4438
NOTE:
 
4439
We can't use hash_delete when looping hash_elements. We mark them first
 
4440
and afterwards delete those marked unused.
 
4441
*/
 
4442
 
 
4443
void remove_db_from_cache(SchemaIdentifier &schema_identifier)
 
4444
{
 
4445
  safe_mutex_assert_owner(&LOCK_open);
 
4446
 
 
4447
  for (uint32_t idx=0 ; idx < open_cache.records ; idx++)
 
4448
  {
 
4449
    Table *table=(Table*) hash_element(&open_cache,idx);
 
4450
    if (not schema_identifier.getPath().compare(table->getMutableShare()->getSchemaName()))
 
4451
    {
 
4452
      table->getMutableShare()->resetVersion();                 /* Free when thread is ready */
 
4453
      if (not table->in_use)
 
4454
        relink_unused(table);
 
4455
    }
 
4456
  }
 
4457
  while (unused_tables && !unused_tables->getShare()->getVersion())
 
4458
    hash_delete(&open_cache,(unsigned char*) unused_tables);
 
4459
}
 
4460
 
 
4461
 
 
4462
/*
 
4463
  Mark all entries with the table as deleted to force an reopen of the table
 
4464
 
 
4465
  The table will be closed (not stored in cache) by the current thread when
 
4466
  close_thread_tables() is called.
 
4467
 
 
4468
  PREREQUISITES
 
4469
  Lock on LOCK_open()
 
4470
 
 
4471
  RETURN
 
4472
  0  This thread now have exclusive access to this table and no other thread
 
4473
  can access the table until close_thread_tables() is called.
 
4474
  1  Table is in use by another thread
 
4475
*/
 
4476
 
 
4477
bool remove_table_from_cache(Session *session, TableIdentifier &identifier, uint32_t flags)
 
4478
{
 
4479
  const TableIdentifier::Key &key(identifier.getKey());
 
4480
  bool result= false; 
 
4481
  bool signalled= false;
 
4482
 
 
4483
  uint32_t key_length= key.size();
 
4484
 
 
4485
  for (;;)
 
4486
  {
 
4487
    HASH_SEARCH_STATE state;
 
4488
    Table *table;
 
4489
    result= signalled= false;
 
4490
 
 
4491
    for (table= (Table*) hash_first(&open_cache, (unsigned char*) &key[0], key_length,
 
4492
                                    &state);
 
4493
         table;
 
4494
         table= (Table*) hash_next(&open_cache, (unsigned char*) &key[0], key_length,
 
4495
                                   &state))
 
4496
    {
 
4497
      Session *in_use;
 
4498
 
 
4499
      table->getMutableShare()->resetVersion();         /* Free when thread is ready */
 
4500
      if (!(in_use=table->in_use))
 
4501
      {
 
4502
        relink_unused(table);
 
4503
      }
 
4504
      else if (in_use != session)
 
4505
      {
 
4506
        /*
 
4507
          Mark that table is going to be deleted from cache. This will
 
4508
          force threads that are in mysql_lock_tables() (but not yet
 
4509
          in thr_multi_lock()) to abort it's locks, close all tables and retry
 
4510
        */
 
4511
        in_use->some_tables_deleted= true;
 
4512
        if (table->is_name_opened())
 
4513
        {
 
4514
          result= true;
 
4515
        }
 
4516
        /*
 
4517
          Now we must abort all tables locks used by this thread
 
4518
          as the thread may be waiting to get a lock for another table.
 
4519
          Note that we need to hold LOCK_open while going through the
 
4520
          list. So that the other thread cannot change it. The other
 
4521
          thread must also hold LOCK_open whenever changing the
 
4522
          open_tables list. Aborting the MERGE lock after a child was
 
4523
          closed and before the parent is closed would be fatal.
 
4524
        */
 
4525
        for (Table *session_table= in_use->open_tables;
 
4526
             session_table ;
 
4527
             session_table= session_table->getNext())
 
4528
        {
 
4529
          /* Do not handle locks of MERGE children. */
 
4530
          if (session_table->db_stat)   // If table is open
 
4531
            signalled|= mysql_lock_abort_for_thread(session, session_table);
 
4532
        }
 
4533
      }
 
4534
      else
 
4535
        result= result || (flags & RTFC_OWNED_BY_Session_FLAG);
 
4536
    }
 
4537
    while (unused_tables && !unused_tables->getShare()->getVersion())
 
4538
      hash_delete(&open_cache,(unsigned char*) unused_tables);
 
4539
 
 
4540
    /* Remove table from table definition cache if it's not in use */
 
4541
    TableShare::release(identifier);
 
4542
 
 
4543
    if (result && (flags & RTFC_WAIT_OTHER_THREAD_FLAG))
 
4544
    {
 
4545
      /*
 
4546
        Signal any thread waiting for tables to be freed to
 
4547
        reopen their tables
 
4548
      */
 
4549
      broadcast_refresh();
 
4550
      if (!(flags & RTFC_CHECK_KILLED_FLAG) || !session->killed)
 
4551
      {
 
4552
        dropping_tables++;
 
4553
        if (likely(signalled))
 
4554
          (void) pthread_cond_wait(&COND_refresh, &LOCK_open);
 
4555
        else
 
4556
        {
 
4557
          struct timespec abstime;
 
4558
          /*
 
4559
            It can happen that another thread has opened the
 
4560
            table but has not yet locked any table at all. Since
 
4561
            it can be locked waiting for a table that our thread
 
4562
            has done LOCK Table x WRITE on previously, we need to
 
4563
            ensure that the thread actually hears our signal
 
4564
            before we go to sleep. Thus we wait for a short time
 
4565
            and then we retry another loop in the
 
4566
            remove_table_from_cache routine.
 
4567
          */
 
4568
          set_timespec(abstime, 10);
 
4569
          pthread_cond_timedwait(&COND_refresh, &LOCK_open, &abstime);
 
4570
        }
 
4571
        dropping_tables--;
 
4572
        continue;
 
4573
      }
 
4574
    }
 
4575
    break;
 
4576
  }
 
4577
 
 
4578
  return result;
 
4579
}
3961
4580
 
3962
4581
 
3963
4582
/**