~drizzle-trunk/drizzle/development

« back to all changes in this revision

Viewing changes to drizzled/sql_base.cc

  • Committer: Monty Taylor
  • Date: 2010-06-26 03:52:47 UTC
  • mfrom: (1637.1.5 staging)
  • Revision ID: mordred@inaugust.com-20100626035247-i0iq4sd6wqzfisyy
Merged in staging changes: Mark's syslog patch and vijay's program_options.

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>
45
44
#include <drizzled/lock.h>
46
45
#include <drizzled/plugin/listen.h>
47
46
#include "drizzled/cached_directory.h"
48
 
#include <drizzled/field/epoch.h>
 
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"
59
 
#include "drizzled/plugin/storage_engine.h"
60
 
 
61
 
#include <drizzled/refresh_version.h>
 
56
#include "drizzled/table_placeholder.h"
62
57
 
63
58
using namespace std;
64
59
 
67
62
 
68
63
extern bool volatile shutdown_in_progress;
69
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
 
70
99
bool table_cache_init(void)
71
100
{
72
 
  return false;
73
 
}
74
 
 
75
 
uint32_t cached_open_tables(void)
76
 
{
77
 
  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);
78
105
}
79
106
 
80
107
void table_cache_free(void)
81
108
{
82
109
  refresh_version++;                            // Force close of open tables
83
110
 
84
 
  table::getUnused().clear();
85
 
  table::getCache().clear();
86
 
}
 
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
 
87
123
 
88
124
/*
89
125
  Close cursor handle, but leave the table in the table cache
96
132
  By leaving the table in the table cache, it disallows any other thread
97
133
  to open the table
98
134
 
99
 
  session->getKilled() will be set if we run out of memory
 
135
  session->killed will be set if we run out of memory
100
136
 
101
137
  If closing a MERGE child, the calling function has to take care for
102
138
  closing the parent too, if necessary.
105
141
 
106
142
void close_handle_and_leave_table_as_lock(Table *table)
107
143
{
 
144
  TableShare *share, *old_share= table->getMutableShare();
108
145
  assert(table->db_stat);
109
146
  assert(table->getShare()->getType() == message::Table::STANDARD);
110
147
 
113
150
    This has to be done to ensure that the table share is removed from
114
151
    the table defintion cache as soon as the last instance is removed
115
152
  */
116
 
  identifier::Table identifier(table->getShare()->getSchemaName(), table->getShare()->getTableName(), message::Table::INTERNAL);
117
 
  const identifier::Table::Key &key(identifier.getKey());
118
 
  TableShare *share= new TableShare(identifier.getType(),
119
 
                                    identifier,
120
 
                                    const_cast<char *>(key.vector()),  static_cast<uint32_t>(table->getShare()->getCacheKeySize()));
 
153
  TableIdentifier identifier(table->getShare()->getSchemaName(), table->getShare()->getTableName(), message::Table::INTERNAL);
 
154
  const TableIdentifier::Key &key(identifier.getKey());
 
155
  share= new TableShare(identifier.getType(),
 
156
                        identifier,
 
157
                        const_cast<char *>(&key[0]),  static_cast<uint32_t>(old_share->getCacheKeySize()));
121
158
 
122
159
  table->cursor->close();
123
160
  table->db_stat= 0;                            // Mark cursor closed
124
 
  table::instance::release(table->getMutableShare());
 
161
  TableShare::release(table->getMutableShare());
125
162
  table->setShare(share);
 
163
  table->cursor->change_table_ptr(table, table->getMutableShare());
126
164
}
127
165
 
128
166
 
140
178
  }
141
179
}
142
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
 
143
219
/* Free resources allocated by filesort() and read_record() */
144
220
 
145
221
void Table::free_io_cache()
146
222
{
147
223
  if (sort.io_cache)
148
224
  {
149
 
    sort.io_cache->close_cached_file();
 
225
    close_cached_file(sort.io_cache);
150
226
    delete sort.io_cache;
151
227
    sort.io_cache= 0;
152
228
  }
158
234
 
159
235
  @param session Thread context (may be NULL)
160
236
  @param tables List of tables to remove from the cache
161
 
  @param have_lock If table::Cache::singleton().mutex() is locked
 
237
  @param have_lock If LOCK_open is locked
162
238
  @param wait_for_refresh Wait for a impending flush
163
239
  @param wait_for_placeholders Wait for tables being reopened so that the GRL
164
240
  won't proceed while write-locked tables are being reopened by other
173
249
  bool result= false;
174
250
  Session *session= this;
175
251
 
176
 
  {
177
 
    boost::mutex::scoped_lock scopedLock(table::Cache::singleton().mutex()); /* Optionally lock for remove tables from open_cahe if not in use */
178
 
 
179
 
    if (tables == NULL)
180
 
    {
181
 
      refresh_version++;                                // Force close of open tables
182
 
 
183
 
      table::getUnused().clear();
184
 
 
185
 
      if (wait_for_refresh)
186
 
      {
 
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;
187
348
        /*
188
 
          Other threads could wait in a loop in open_and_lock_tables(),
189
 
          trying to lock one or more of our tables.
190
 
 
191
 
          If they wait for the locks in thr_multi_lock(), their lock
192
 
          request is aborted. They loop in open_and_lock_tables() and
193
 
          enter open_table(). Here they notice the table is refreshed and
194
 
          wait for COND_refresh. Then they loop again in
195
 
          openTablesLock() and this time open_table() succeeds. At
196
 
          this moment, if we (the FLUSH TABLES thread) are scheduled and
197
 
          on another FLUSH TABLES enter close_cached_tables(), they could
198
 
          awake while we sleep below, waiting for others threads (us) to
199
 
          close their open tables. If this happens, the other threads
200
 
          would find the tables unlocked. They would get the locks, one
201
 
          after the other, and could do their destructive work. This is an
202
 
          issue if we have LOCK TABLES in effect.
203
 
 
204
 
          The problem is that the other threads passed all checks in
205
 
          open_table() before we refresh the table.
206
 
 
207
 
          The fix for this problem is to set some_tables_deleted for all
208
 
          threads with open tables. These threads can still get their
209
 
          locks, but will immediately release them again after checking
210
 
          this variable. They will then loop in openTablesLock()
211
 
          again. There they will wait until we update all tables version
212
 
          below.
213
 
 
214
 
          Setting some_tables_deleted is done by table::Cache::singleton().removeTable()
215
 
          in the other branch.
216
 
 
217
 
          In other words (reviewer suggestion): You need this setting of
218
 
          some_tables_deleted for the case when table was opened and all
219
 
          related checks were passed before incrementing refresh_version
220
 
          (which you already have) but attempt to lock the table happened
221
 
          after the call to Session::close_old_data_files() i.e. after removal of
222
 
          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.
223
361
        */
224
 
        for (table::CacheMap::const_iterator iter= table::getCache().begin();
225
 
             iter != table::getCache().end();
226
 
             iter++)
227
 
        {
228
 
          Table *table= (*iter).second;
229
 
          if (table->in_use)
230
 
            table->in_use->some_tables_deleted= false;
231
 
        }
232
 
      }
233
 
    }
234
 
    else
235
 
    {
236
 
      bool found= false;
237
 
      for (TableList *table= tables; table; table= table->next_local)
238
 
      {
239
 
        identifier::Table identifier(table->getSchemaName(), table->getTableName());
240
 
        if (table::Cache::singleton().removeTable(session, identifier,
241
 
                                    RTFC_OWNED_BY_Session_FLAG))
 
362
        if (table->needs_reopen_or_name_lock() && (table->db_stat ||
 
363
                                                   (table->open_placeholder && wait_for_placeholders)))
242
364
        {
243
365
          found= true;
 
366
          pthread_cond_wait(&COND_refresh,&LOCK_open);
 
367
          break;
244
368
        }
245
369
      }
246
 
      if (!found)
247
 
        wait_for_refresh= false;                        // Nothing to wait for
248
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);
249
377
 
250
 
    if (wait_for_refresh)
 
378
    /* Set version for table */
 
379
    for (Table *table= session->open_tables; table ; table= table->getNext())
251
380
    {
252
381
      /*
253
 
        If there is any table that has a lower refresh_version, wait until
254
 
        this is closed (or this thread is killed) before returning
255
 
      */
256
 
      session->mysys_var->current_mutex= &table::Cache::singleton().mutex();
257
 
      session->mysys_var->current_cond= &COND_refresh;
258
 
      session->set_proc_info("Flushing tables");
259
 
 
260
 
      session->close_old_data_files();
261
 
 
262
 
      bool found= true;
263
 
      /* Wait until all threads has closed all the tables we had locked */
264
 
      while (found && ! session->getKilled())
265
 
      {
266
 
        found= false;
267
 
        for (table::CacheMap::const_iterator iter= table::getCache().begin();
268
 
             iter != table::getCache().end();
269
 
             iter++)
270
 
        {
271
 
          Table *table= (*iter).second;
272
 
          /* Avoid a self-deadlock. */
273
 
          if (table->in_use == session)
274
 
            continue;
275
 
          /*
276
 
            Note that we wait here only for tables which are actually open, and
277
 
            not for placeholders with Table::open_placeholder set. Waiting for
278
 
            latter will cause deadlock in the following scenario, for example:
279
 
 
280
 
            conn1-> lock table t1 write;
281
 
            conn2-> lock table t2 write;
282
 
            conn1-> flush tables;
283
 
            conn2-> flush tables;
284
 
 
285
 
            It also does not make sense to wait for those of placeholders that
286
 
            are employed by CREATE TABLE as in this case table simply does not
287
 
            exist yet.
288
 
          */
289
 
          if (table->needs_reopen_or_name_lock() && (table->db_stat ||
290
 
                                                     (table->open_placeholder && wait_for_placeholders)))
291
 
          {
292
 
            found= true;
293
 
            COND_refresh.wait(scopedLock);
294
 
            break;
295
 
          }
296
 
        }
297
 
      }
298
 
      /*
299
 
        No other thread has the locked tables open; reopen them and get the
300
 
        old locks. This should always succeed (unless some external process
301
 
        has removed the tables)
302
 
      */
303
 
      result= session->reopen_tables();
304
 
 
305
 
      /* Set version for table */
306
 
      for (Table *table= session->open_tables; table ; table= table->getNext())
307
 
      {
308
 
        /*
309
 
          Preserve the version (0) of write locked tables so that a impending
310
 
          global read lock won't sneak in.
311
 
        */
312
 
        if (table->reginfo.lock_type < TL_WRITE_ALLOW_WRITE)
313
 
          table->getMutableShare()->refreshVersion();
314
 
      }
 
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();
315
387
    }
316
388
  }
317
389
 
 
390
  pthread_mutex_unlock(&LOCK_open);
 
391
 
318
392
  if (wait_for_refresh)
319
393
  {
320
 
    boost_unique_lock_t scopedLock(session->mysys_var->mutex);
 
394
    pthread_mutex_lock(&session->mysys_var->mutex);
321
395
    session->mysys_var->current_mutex= 0;
322
396
    session->mysys_var->current_cond= 0;
323
397
    session->set_proc_info(0);
 
398
    pthread_mutex_unlock(&session->mysys_var->mutex);
324
399
  }
325
400
 
326
401
  return result;
331
406
  move one table to free list 
332
407
*/
333
408
 
334
 
bool Session::free_cached_table(boost::mutex::scoped_lock &scopedLock)
 
409
bool Session::free_cached_table()
335
410
{
336
411
  bool found_old_table= false;
337
 
 
338
 
  (void)scopedLock;
339
 
 
340
 
  table::Concurrent *table= static_cast<table::Concurrent *>(open_tables);
341
 
 
342
 
  safe_mutex_assert_owner(table::Cache::singleton().mutex().native_handle());
 
412
  Table *table= open_tables;
 
413
 
 
414
  safe_mutex_assert_owner(&LOCK_open);
343
415
  assert(table->key_read == 0);
344
416
  assert(!table->cursor || table->cursor->inited == Cursor::NONE);
345
417
 
348
420
  if (table->needs_reopen_or_name_lock() ||
349
421
      version != refresh_version || !table->db_stat)
350
422
  {
351
 
    table::remove_table(table);
 
423
    hash_delete(&open_cache,(unsigned char*) table);
352
424
    found_old_table= true;
353
425
  }
354
426
  else
361
433
 
362
434
    /* Free memory and reset for next loop */
363
435
    table->cursor->ha_reset();
364
 
    table->in_use= NULL;
 
436
    table->in_use= false;
365
437
 
366
 
    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
    }
367
450
  }
368
451
 
369
452
  return found_old_table;
382
465
{
383
466
  bool found_old_table= false;
384
467
 
385
 
  safe_mutex_assert_not_owner(table::Cache::singleton().mutex().native_handle());
 
468
  safe_mutex_assert_not_owner(&LOCK_open);
386
469
 
387
 
  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 */
388
471
 
389
472
  while (open_tables)
390
473
  {
391
 
    found_old_table|= free_cached_table(scoped_lock);
 
474
    found_old_table|= free_cached_table();
392
475
  }
393
476
  some_tables_deleted= false;
394
477
 
395
478
  if (found_old_table)
396
479
  {
397
480
    /* Tell threads waiting for refresh that something has happened */
398
 
    locking::broadcast_refresh();
 
481
    broadcast_refresh();
399
482
  }
 
483
 
 
484
  pthread_mutex_unlock(&LOCK_open);
400
485
}
401
486
 
402
487
/*
424
509
{
425
510
  for (; table; table= table->*link )
426
511
  {
427
 
    if ((table->table == 0 || table->table->getShare()->getType() == message::Table::STANDARD) and
428
 
        my_strcasecmp(system_charset_info, table->getSchemaName(), db_name) == 0 and
429
 
        my_strcasecmp(system_charset_info, table->getTableName(), table_name) == 0)
430
 
    {
 
512
    if ((table->table == 0 || table->table->getShare()->getType() == message::Table::STANDARD) &&
 
513
        strcasecmp(table->db, db_name) == 0 &&
 
514
        strcasecmp(table->table_name, table_name) == 0)
431
515
      break;
432
 
    }
433
516
  }
434
517
  return table;
435
518
}
499
582
    */
500
583
    assert(table);
501
584
  }
502
 
  d_name= table->getSchemaName();
503
 
  t_name= table->getTableName();
 
585
  d_name= table->db;
 
586
  t_name= table->table_name;
504
587
  t_alias= table->alias;
505
588
 
506
589
  for (;;)
521
604
}
522
605
 
523
606
 
524
 
void Open_tables_state::doGetTableNames(const identifier::Schema &schema_identifier,
525
 
                                        std::set<std::string>& set_of_names)
 
607
void Session::doGetTableNames(SchemaIdentifier &schema_identifier,
 
608
                              std::set<std::string>& set_of_names)
526
609
{
527
 
  for (Table *table= getTemporaryTables() ; table ; table= table->getNext())
 
610
  for (Table *table= temporary_tables ; table ; table= table->getNext())
528
611
  {
529
612
    if (schema_identifier.compare(table->getShare()->getSchemaName()))
530
613
    {
533
616
  }
534
617
}
535
618
 
536
 
void Open_tables_state::doGetTableNames(CachedDirectory &,
537
 
                                        const identifier::Schema &schema_identifier,
538
 
                                        std::set<std::string> &set_of_names)
 
619
void Session::doGetTableNames(CachedDirectory &,
 
620
                              SchemaIdentifier &schema_identifier,
 
621
                              std::set<std::string> &set_of_names)
539
622
{
540
623
  doGetTableNames(schema_identifier, set_of_names);
541
624
}
542
625
 
543
 
void Open_tables_state::doGetTableIdentifiers(const identifier::Schema &schema_identifier,
544
 
                                              identifier::Table::vector &set_of_identifiers)
 
626
void Session::doGetTableIdentifiers(SchemaIdentifier &schema_identifier,
 
627
                                    TableIdentifiers &set_of_identifiers)
545
628
{
546
 
  for (Table *table= getTemporaryTables() ; table ; table= table->getNext())
 
629
  for (Table *table= temporary_tables ; table ; table= table->getNext())
547
630
  {
548
631
    if (schema_identifier.compare(table->getShare()->getSchemaName()))
549
632
    {
550
 
      set_of_identifiers.push_back(identifier::Table(table->getShare()->getSchemaName(),
 
633
      set_of_identifiers.push_back(TableIdentifier(table->getShare()->getSchemaName(),
551
634
                                                   table->getShare()->getTableName(),
552
635
                                                   table->getShare()->getPath()));
553
636
    }
554
637
  }
555
638
}
556
639
 
557
 
void Open_tables_state::doGetTableIdentifiers(CachedDirectory &,
558
 
                                              const identifier::Schema &schema_identifier,
559
 
                                              identifier::Table::vector &set_of_identifiers)
 
640
void Session::doGetTableIdentifiers(CachedDirectory &,
 
641
                                    SchemaIdentifier &schema_identifier,
 
642
                                    TableIdentifiers &set_of_identifiers)
560
643
{
561
644
  doGetTableIdentifiers(schema_identifier, set_of_identifiers);
562
645
}
563
646
 
564
 
bool Open_tables_state::doDoesTableExist(const identifier::Table &identifier)
 
647
bool Session::doDoesTableExist(const TableIdentifier &identifier)
565
648
{
566
 
  for (Table *table= getTemporaryTables() ; table ; table= table->getNext())
 
649
  for (Table *table= temporary_tables ; table ; table= table->getNext())
567
650
  {
568
651
    if (table->getShare()->getType() == message::Table::TEMPORARY)
569
652
    {
570
 
      if (identifier.getKey() == table->getShare()->getCacheKey())
 
653
      if (identifier.compare(table->getShare()->getSchemaName(), table->getShare()->getTableName()))
571
654
      {
572
655
        return true;
573
656
      }
577
660
  return false;
578
661
}
579
662
 
580
 
int Open_tables_state::doGetTableDefinition(const identifier::Table &identifier,
581
 
                                            message::Table &table_proto)
 
663
int Session::doGetTableDefinition(const TableIdentifier &identifier,
 
664
                                  message::Table &table_proto)
582
665
{
583
 
  for (Table *table= getTemporaryTables() ; table ; table= table->getNext())
 
666
  for (Table *table= temporary_tables ; table ; table= table->getNext())
584
667
  {
585
668
    if (table->getShare()->getType() == message::Table::TEMPORARY)
586
669
    {
587
 
      if (identifier.getKey() == table->getShare()->getCacheKey())
 
670
      if (identifier.compare(table->getShare()->getSchemaName(), table->getShare()->getTableName()))
588
671
      {
589
 
        table_proto.CopyFrom(*(table->getShare()->getTableMessage()));
 
672
        table_proto.CopyFrom(*(table->getShare()->getTableProto()));
590
673
 
591
674
        return EEXIST;
592
675
      }
596
679
  return ENOENT;
597
680
}
598
681
 
599
 
Table *Open_tables_state::find_temporary_table(const identifier::Table &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)
600
707
{
601
708
  for (Table *table= temporary_tables ; table ; table= table->getNext())
602
709
  {
634
741
  @retval -1  the table is in use by a outer query
635
742
*/
636
743
 
637
 
int Open_tables_state::drop_temporary_table(const drizzled::identifier::Table &identifier)
 
744
int Session::drop_temporary_table(TableList *table_list)
638
745
{
639
746
  Table *table;
640
747
 
641
 
  if (not (table= find_temporary_table(identifier)))
 
748
  if (not (table= find_temporary_table(table_list)))
642
749
    return 1;
643
750
 
644
751
  /* Table might be in use by some outer statement. */
645
 
  if (table->query_id && table->query_id != getQueryId())
 
752
  if (table->query_id && table->query_id != query_id)
646
753
  {
647
 
    my_error(ER_CANT_REOPEN_TABLE, MYF(0), table->getAlias());
 
754
    my_error(ER_CANT_REOPEN_TABLE, MYF(0), table->alias);
648
755
    return -1;
649
756
  }
650
757
 
654
761
}
655
762
 
656
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
 
657
781
/**
658
782
  Remove all instances of table from thread's open list and
659
783
  table cache.
660
784
 
661
785
  @param  session     Thread context
662
786
  @param  find    Table to remove
663
 
 
664
 
  @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.
665
787
*/
666
788
 
667
789
void Session::unlink_open_table(Table *find)
668
790
{
669
 
  const identifier::Table::Key find_key(find->getShare()->getCacheKey());
670
 
  Table **prev;
671
 
  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);
672
795
 
 
796
  memcpy(key, &find->getMutableShare()->getCacheKey()[0], key_length);
673
797
  /*
674
 
    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
675
799
    open_tables list. Another thread may work on it.
676
 
    (See: table::Cache::singleton().removeTable(), wait_completed_table())
 
800
    (See: remove_table_from_cache(), mysql_wait_completed_table())
677
801
    Closing a MERGE child before the parent would be fatal if the
678
802
    other thread tries to abort the MERGE lock in between.
679
803
  */
680
804
  for (prev= &open_tables; *prev; )
681
805
  {
682
 
    Table *list= *prev;
 
806
    list= *prev;
683
807
 
684
 
    if (list->getShare()->getCacheKey() == find_key)
 
808
    if (list->getShare()->getCacheKeySize() == key_length &&
 
809
        not memcmp(&list->getShare()->getCacheKey()[0], key, key_length))
685
810
    {
686
811
      /* Remove table from open_tables list. */
687
812
      *prev= list->getNext();
688
813
 
689
814
      /* Close table. */
690
 
      table::remove_table(static_cast<table::Concurrent *>(list));
 
815
      hash_delete(&open_cache,(unsigned char*) list); // Close table
691
816
    }
692
817
    else
693
818
    {
697
822
  }
698
823
 
699
824
  // Notify any 'refresh' threads
700
 
  locking::broadcast_refresh();
 
825
  broadcast_refresh();
701
826
}
702
827
 
703
828
 
720
845
  table that was locked with LOCK TABLES.
721
846
*/
722
847
 
723
 
void Session::drop_open_table(Table *table, const identifier::Table &identifier)
 
848
void Session::drop_open_table(Table *table, TableIdentifier &identifier)
724
849
{
725
850
  if (table->getShare()->getType())
726
851
  {
728
853
  }
729
854
  else
730
855
  {
731
 
    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) */
732
857
    /*
733
858
      unlink_open_table() also tells threads waiting for refresh or close
734
859
      that something has happened.
735
860
    */
736
861
    unlink_open_table(table);
737
 
    (void)plugin::StorageEngine::dropTable(*this, identifier);
 
862
    quick_rm_table(*this, identifier);
 
863
    pthread_mutex_unlock(&LOCK_open);
738
864
  }
739
865
}
740
866
 
750
876
  cond  Condition to wait for
751
877
*/
752
878
 
753
 
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)
754
880
{
755
881
  /* Wait until the current table is up to date */
756
882
  const char *saved_proc_info;
757
 
  mysys_var->current_mutex= &mutex;
758
 
  mysys_var->current_cond= &cond;
 
883
  mysys_var->current_mutex= mutex;
 
884
  mysys_var->current_cond= cond;
759
885
  saved_proc_info= get_proc_info();
760
886
  set_proc_info("Waiting for table");
761
 
  {
762
 
    /*
763
 
      We must unlock mutex first to avoid deadlock becasue conditions are
764
 
      sent to this thread by doing locks in the following order:
765
 
      lock(mysys_var->mutex)
766
 
      lock(mysys_var->current_mutex)
767
 
 
768
 
      One by effect of this that one can only use wait_for_condition with
769
 
      condition variables that are guranteed to not disapper (freed) even if this
770
 
      mutex is unlocked
771
 
    */
772
 
    boost_unique_lock_t scopedLock(mutex, boost::adopt_lock_t());
773
 
    if (not getKilled())
774
 
    {
775
 
      cond.wait(scopedLock);
776
 
    }
777
 
  }
778
 
  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);
779
903
  mysys_var->current_mutex= 0;
780
904
  mysys_var->current_cond= 0;
781
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;
782
996
}
783
997
 
784
998
 
795
1009
  case of failure.
796
1010
*/
797
1011
 
798
 
table::Placeholder *Session::table_cache_insert_placeholder(const drizzled::identifier::Table &arg)
 
1012
Table *Session::table_cache_insert_placeholder(const char *db_name, const char *table_name, const char *, uint32_t)
799
1013
{
800
 
  safe_mutex_assert_owner(table::Cache::singleton().mutex().native_handle());
 
1014
  safe_mutex_assert_owner(&LOCK_open);
801
1015
 
802
1016
  /*
803
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
804
1020
  */
805
 
  identifier::Table identifier(arg.getSchemaName(), arg.getTableName(), message::Table::INTERNAL);
806
 
  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);
807
1023
 
808
 
  if (not table::Cache::singleton().insert(table))
 
1024
  if (my_hash_insert(&open_cache, (unsigned char*)table))
809
1025
  {
810
1026
    delete table;
811
1027
 
837
1053
  @retval  true   Error occured (OOM)
838
1054
  @retval  false  Success. 'table' parameter set according to above rules.
839
1055
*/
840
 
bool Session::lock_table_name_if_not_cached(const identifier::Table &identifier, Table **table)
841
 
{
842
 
  const identifier::Table::Key &key(identifier.getKey());
843
 
 
844
 
  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)  */
845
 
 
846
 
  table::CacheMap::iterator iter;
847
 
 
848
 
  iter= table::getCache().find(key);
849
 
 
850
 
  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))
851
1072
  {
 
1073
    pthread_mutex_unlock(&LOCK_open);
852
1074
    *table= 0;
853
1075
    return false;
854
1076
  }
855
1077
 
856
 
  if (not (*table= table_cache_insert_placeholder(identifier)))
 
1078
  if (not (*table= table_cache_insert_placeholder(new_db, table_name, key, key_length)))
857
1079
  {
 
1080
    pthread_mutex_unlock(&LOCK_open);
858
1081
    return true;
859
1082
  }
860
1083
  (*table)->open_placeholder= true;
861
1084
  (*table)->setNext(open_tables);
862
1085
  open_tables= *table;
 
1086
  pthread_mutex_unlock(&LOCK_open);
863
1087
 
864
1088
  return false;
865
1089
}
900
1124
Table *Session::openTable(TableList *table_list, bool *refresh, uint32_t flags)
901
1125
{
902
1126
  Table *table;
 
1127
  unsigned int key_length;
903
1128
  const char *alias= table_list->alias;
 
1129
  HASH_SEARCH_STATE state;
904
1130
 
905
1131
  /* Parsing of partitioning information from .frm needs session->lex set up. */
906
1132
  assert(lex->is_lex_started);
913
1139
  if (check_stack_overrun(this, STACK_MIN_SIZE_FOR_OPEN, (unsigned char *)&alias))
914
1140
    return NULL;
915
1141
 
916
 
  if (getKilled())
 
1142
  if (killed)
917
1143
    return NULL;
918
1144
 
919
 
  identifier::Table identifier(table_list->getSchemaName(), table_list->getTableName());
920
 
  const identifier::Table::Key &key(identifier.getKey());
921
 
  table::CacheRange ppp;
 
1145
  TableIdentifier identifier(table_list->db, table_list->table_name);
 
1146
  const TableIdentifier::Key &key(identifier.getKey());
 
1147
  key_length= key.size();
922
1148
 
923
1149
  /*
924
1150
    Unless requested otherwise, try to resolve this table in the list
927
1153
    same name. This block implements the behaviour.
928
1154
    TODO -> move this block into a separate function.
929
1155
  */
930
 
  bool reset= false;
931
 
  for (table= getTemporaryTables(); table ; table=table->getNext())
 
1156
  for (table= temporary_tables; table ; table=table->getNext())
932
1157
  {
933
1158
    if (table->getShare()->getCacheKey() == key)
934
1159
    {
940
1165
      */
941
1166
      if (table->query_id)
942
1167
      {
943
 
        my_error(ER_CANT_REOPEN_TABLE, MYF(0), table->getAlias());
 
1168
        my_error(ER_CANT_REOPEN_TABLE, MYF(0), table->alias);
944
1169
        return NULL;
945
1170
      }
946
1171
      table->query_id= getQueryId();
947
 
      reset= true;
948
 
      break;
949
 
    }
950
 
  }
951
 
 
952
 
  if (not reset)
953
 
  {
954
 
    if (flags & DRIZZLE_OPEN_TEMPORARY_ONLY)
955
 
    {
956
 
      my_error(ER_TABLE_UNKNOWN, identifier);
957
 
      return NULL;
958
 
    }
959
 
 
 
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
  {
960
1246
    /*
961
 
      If it's the first table from a list of tables used in a query,
962
 
      remember refresh_version (the version of open_cache state).
963
 
      If the version changes while we're opening the remaining tables,
964
 
      we will have to back off, close all the tables opened-so-far,
965
 
      and try to reopen them.
966
 
 
967
 
      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
968
1263
    */
969
 
    if (!open_tables)
970
 
    {
971
 
      version= refresh_version;
972
 
    }
973
 
    else if ((version != refresh_version) &&
974
 
             ! (flags & DRIZZLE_LOCK_IGNORE_FLUSH))
975
 
    {
976
 
      /* 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
      */
977
1320
      if (refresh)
978
1321
        *refresh= true;
979
 
 
980
1322
      return NULL;
981
1323
    }
982
 
 
983
 
    /*
984
 
      Before we test the global cache, we test our local session cache.
985
 
    */
986
 
    if (cached_table)
987
 
    {
988
 
      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;
989
1333
    }
990
 
 
991
 
    /*
992
 
      Non pre-locked/LOCK TABLES mode, and the table is not temporary:
993
 
      this is the normal use case.
994
 
      Now we should:
995
 
      - try to find the table in the table cache.
996
 
      - if one of the discovered Table instances is name-locked
997
 
      (table->getShare()->version == 0) back off -- we have to wait
998
 
      until no one holds a name lock on the table.
999
 
      - if there is no such Table in the name cache, read the table definition
1000
 
      and insert it into the cache.
1001
 
      We perform all of the above under table::Cache::singleton().mutex() which currently protects
1002
 
      the open cache (also known as table cache) and table definitions stored
1003
 
      on disk.
1004
 
    */
1005
 
 
 
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)
1006
1347
    {
1007
 
      boost::mutex::scoped_lock scopedLock(table::Cache::singleton().mutex());
1008
 
 
1009
 
      /*
1010
 
        Actually try to find the table in the open_cache.
1011
 
        The cache may contain several "Table" instances for the same
1012
 
        physical table. The instances that are currently "in use" by
1013
 
        some thread have their "in_use" member != NULL.
1014
 
        There is no good reason for having more than one entry in the
1015
 
        hash for the same physical table, except that we use this as
1016
 
        an implicit "pending locks queue" - see
1017
 
        wait_for_locked_table_names for details.
1018
 
      */
1019
 
      ppp= table::getCache().equal_range(key);
1020
 
 
1021
 
      table= NULL;
1022
 
      for (table::CacheMap::const_iterator iter= ppp.first;
1023
 
           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))
1024
1351
      {
1025
 
        table= (*iter).second;
1026
 
 
1027
 
        if (not table->in_use)
1028
 
          break;
1029
1352
        /*
1030
 
          Here we flush tables marked for flush.
1031
 
          Normally, table->getShare()->version contains the value of
1032
 
          refresh_version from the moment when this table was
1033
 
          (re-)opened and added to the cache.
1034
 
          If since then we did (or just started) FLUSH TABLES
1035
 
          statement, refresh_version has been increased.
1036
 
          For "name-locked" Table instances, table->getShare()->version is set
1037
 
          to 0 (see lock_table_name for details).
1038
 
          In case there is a pending FLUSH TABLES or a name lock, we
1039
 
          need to back off and re-start opening tables.
1040
 
          If we do not back off now, we may dead lock in case of lock
1041
 
          order mismatch with some other thread:
1042
 
          c1-> name lock t1; -- sort of exclusive lock
1043
 
          c2-> open t2;      -- sort of shared lock
1044
 
          c1-> name lock t2; -- blocks
1045
 
          c2-> open t1; -- blocks
 
1353
          Table to be created, so we need to create placeholder in table-cache.
1046
1354
        */
1047
 
        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)))
1048
1356
        {
1049
 
          if (flags & DRIZZLE_LOCK_IGNORE_FLUSH)
1050
 
          {
1051
 
            /* Force close at once after usage */
1052
 
            version= table->getShare()->getVersion();
1053
 
            continue;
1054
 
          }
1055
 
 
1056
 
          /* Avoid self-deadlocks by detecting self-dependencies. */
1057
 
          if (table->open_placeholder && table->in_use == this)
1058
 
          {
1059
 
            my_error(ER_UPDATE_TABLE_USED, MYF(0), table->getShare()->getTableName());
1060
 
            return NULL;
1061
 
          }
1062
 
 
1063
 
          /*
1064
 
            Back off, part 1: mark the table as "unused" for the
1065
 
            purpose of name-locking by setting table->db_stat to 0. Do
1066
 
            that only for the tables in this thread that have an old
1067
 
            table->getShare()->version (this is an optimization (?)).
1068
 
            table->db_stat == 0 signals wait_for_locked_table_names
1069
 
            that the tables in question are not used any more. See
1070
 
            table_is_used call for details.
1071
 
          */
1072
 
          close_old_data_files(false, false);
1073
 
 
1074
 
          /*
1075
 
            Back-off part 2: try to avoid "busy waiting" on the table:
1076
 
            if the table is in use by some other thread, we suspend
1077
 
            and wait till the operation is complete: when any
1078
 
            operation that juggles with table->getShare()->version completes,
1079
 
            it broadcasts COND_refresh condition variable.
1080
 
            If 'old' table we met is in use by current thread we return
1081
 
            without waiting since in this situation it's this thread
1082
 
            which is responsible for broadcasting on COND_refresh
1083
 
            (and this was done already in Session::close_old_data_files()).
1084
 
            Good example of such situation is when we have statement
1085
 
            that needs two instances of table and FLUSH TABLES comes
1086
 
            after we open first instance but before we open second
1087
 
            instance.
1088
 
          */
1089
 
          if (table->in_use != this)
1090
 
          {
1091
 
            /* wait_for_conditionwill unlock table::Cache::singleton().mutex() for us */
1092
 
            wait_for_condition(table::Cache::singleton().mutex(), COND_refresh);
1093
 
            scopedLock.release();
1094
 
          }
1095
 
          else
1096
 
          {
1097
 
            scopedLock.unlock();
1098
 
          }
1099
 
 
1100
 
          /*
1101
 
            There is a refresh in progress for this table.
1102
 
            Signal the caller that it has to try again.
1103
 
          */
1104
 
          if (refresh)
1105
 
            *refresh= true;
1106
 
 
 
1357
          pthread_mutex_unlock(&LOCK_open);
1107
1358
          return NULL;
1108
1359
        }
1109
 
      }
1110
 
 
1111
 
      if (table)
1112
 
      {
1113
 
        table::getUnused().unlink(static_cast<table::Concurrent *>(table));
1114
 
        table->in_use= this;
1115
 
      }
1116
 
      else
1117
 
      {
1118
 
        /* Insert a new Table instance into the open cache */
1119
 
        int error;
1120
 
        /* Free cache if too big */
1121
 
        table::getUnused().cull();
1122
 
 
1123
 
        if (table_list->isCreate())
1124
 
        {
1125
 
          identifier::Table  lock_table_identifier(table_list->getSchemaName(), table_list->getTableName(), message::Table::STANDARD);
1126
 
 
1127
 
          if (not plugin::StorageEngine::doesTableExist(*this, lock_table_identifier))
1128
 
          {
1129
 
            /*
1130
 
              Table to be created, so we need to create placeholder in table-cache.
1131
 
            */
1132
 
            if (!(table= table_cache_insert_placeholder(lock_table_identifier)))
1133
 
            {
1134
 
              return NULL;
1135
 
            }
1136
 
            /*
1137
 
              Link placeholder to the open tables list so it will be automatically
1138
 
              removed once tables are closed. Also mark it so it won't be ignored
1139
 
              by other trying to take name-lock.
1140
 
            */
1141
 
            table->open_placeholder= true;
1142
 
            table->setNext(open_tables);
1143
 
            open_tables= table;
1144
 
 
1145
 
            return table ;
1146
 
          }
1147
 
          /* Table exists. Let us try to open it. */
1148
 
        }
1149
 
 
1150
 
        /* make a new table */
1151
 
        {
1152
 
          table::Concurrent *new_table= new table::Concurrent;
1153
 
          table= new_table;
1154
 
          if (new_table == NULL)
1155
 
          {
1156
 
            return NULL;
1157
 
          }
1158
 
 
1159
 
          error= new_table->open_unireg_entry(this, alias, identifier);
1160
 
          if (error != 0)
1161
 
          {
1162
 
            delete new_table;
1163
 
            return NULL;
1164
 
          }
1165
 
          (void)table::Cache::singleton().insert(new_table);
1166
 
        }
1167
 
      }
1168
 
    }
1169
 
 
1170
 
    if (refresh)
1171
 
    {
1172
 
      table->setNext(open_tables); /* Link into simple list */
1173
 
      open_tables= table;
1174
 
    }
1175
 
    table->reginfo.lock_type= TL_READ; /* Assume read */
1176
 
 
1177
 
  }
 
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:
1178
1403
  assert(table->getShare()->getTableCount() > 0 || table->getShare()->getType() != message::Table::STANDARD);
1179
1404
 
 
1405
  if (lex->need_correct_ident())
 
1406
    table->alias_name_used= my_strcasecmp(table_alias_charset,
 
1407
                                          table->getMutableShare()->getTableName(), alias);
1180
1408
  /* Fix alias if table name changes */
1181
 
  if (strcmp(table->getAlias(), alias))
 
1409
  if (strcmp(table->alias, alias))
1182
1410
  {
1183
 
    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);
1184
1414
  }
1185
1415
 
1186
1416
  /* These variables are also set in reopen_table() */
1191
1421
  table->maybe_null= false;
1192
1422
  table->force_index= false;
1193
1423
  table->status=STATUS_NO_RECORD;
1194
 
  table->insert_values.clear();
 
1424
  table->insert_values= 0;
1195
1425
  /* Catch wrong handling of the auto_increment_field_not_null. */
1196
1426
  assert(!table->auto_increment_field_not_null);
1197
1427
  table->auto_increment_field_not_null= false;
1207
1437
}
1208
1438
 
1209
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
 
1210
1531
/**
1211
1532
  Close all instances of a table open by this thread and replace
1212
1533
  them with exclusive name-locks.
1224
1545
  the strings are used in a loop even after the share may be freed.
1225
1546
*/
1226
1547
 
1227
 
void Session::close_data_files_and_morph_locks(const identifier::Table &identifier)
 
1548
void Session::close_data_files_and_morph_locks(TableIdentifier &identifier)
1228
1549
{
1229
 
  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 */
1230
1553
 
1231
1554
  if (lock)
1232
1555
  {
1234
1557
      If we are not under LOCK TABLES we should have only one table
1235
1558
      open and locked so it makes sense to remove the lock at once.
1236
1559
    */
1237
 
    unlockTables(lock);
 
1560
    mysql_unlock_tables(this, lock);
1238
1561
    lock= 0;
1239
1562
  }
1240
1563
 
1243
1566
    for target table name if we process ALTER Table ... RENAME.
1244
1567
    So loop below makes sense even if we are not under LOCK TABLES.
1245
1568
  */
1246
 
  for (Table *table= open_tables; table ; table=table->getNext())
 
1569
  for (table= open_tables; table ; table=table->getNext())
1247
1570
  {
1248
 
    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()))
1249
1573
    {
1250
1574
      table->open_placeholder= true;
1251
1575
      close_handle_and_leave_table_as_lock(table);
1269
1593
  combination when one needs tables to be reopened (for
1270
1594
  example see openTablesLock()).
1271
1595
 
1272
 
  @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.
1273
1597
 
1274
1598
  @return false in case of success, true - otherwise.
1275
1599
*/
1276
1600
 
1277
 
bool Session::reopen_tables()
 
1601
bool Session::reopen_tables(bool get_locks, bool)
1278
1602
{
1279
1603
  Table *table,*next,**prev;
1280
 
  Table **tables= 0;                    // For locks
1281
 
  Table **tables_ptr= 0;                        // For locks
1282
 
  bool error= false;
 
1604
  Table **tables,**tables_ptr;                  // For locks
 
1605
  bool error=0, not_used;
1283
1606
  const uint32_t flags= DRIZZLE_LOCK_NOTIFY_IF_NEED_REOPEN |
1284
1607
    DRIZZLE_LOCK_IGNORE_GLOBAL_READ_LOCK |
1285
1608
    DRIZZLE_LOCK_IGNORE_FLUSH;
1287
1610
  if (open_tables == NULL)
1288
1611
    return false;
1289
1612
 
1290
 
  safe_mutex_assert_owner(table::Cache::singleton().mutex().native_handle());
 
1613
  safe_mutex_assert_owner(&LOCK_open);
 
1614
  if (get_locks)
1291
1615
  {
1292
1616
    /*
1293
1617
      The ptr is checked later
1301
1625
    }
1302
1626
    tables= new Table *[opens];
1303
1627
  }
1304
 
 
 
1628
  else
 
1629
  {
 
1630
    tables= &open_tables;
 
1631
  }
1305
1632
  tables_ptr =tables;
1306
1633
 
1307
1634
  prev= &open_tables;
1309
1636
  {
1310
1637
    next= table->getNext();
1311
1638
 
1312
 
    my_error(ER_CANT_REOPEN_TABLE, MYF(0), table->getAlias());
1313
 
    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);
1314
1641
    error= 1;
1315
1642
  }
1316
1643
  *prev=0;
1317
 
 
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), flags)))
 
1654
    if ((local_lock= mysql_lock_tables(this, tables, (uint32_t) (tables_ptr - tables),
 
1655
                                 flags, &not_used)))
1329
1656
    {
1330
1657
      /* unused */
1331
1658
    }
1341
1668
    }
1342
1669
  }
1343
1670
 
1344
 
  delete [] tables;
1345
 
 
1346
 
  locking::broadcast_refresh();
1347
 
 
1348
 
  return error;
 
1671
  if (get_locks && tables)
 
1672
    delete [] tables;
 
1673
 
 
1674
  broadcast_refresh();
 
1675
 
 
1676
  return(error);
1349
1677
}
1350
1678
 
1351
1679
 
1376
1704
    */
1377
1705
    if (table->needs_reopen_or_name_lock())
1378
1706
    {
1379
 
      found= true;
 
1707
      found=1;
1380
1708
      if (table->db_stat)
1381
1709
      {
1382
1710
        if (morph_locks)
1390
1718
              lock on it. This will also give them a chance to close their
1391
1719
              instances of this table.
1392
1720
            */
1393
 
            abortLock(ulcktbl);
1394
 
            removeLock(ulcktbl);
 
1721
            mysql_lock_abort(this, ulcktbl);
 
1722
            mysql_lock_remove(this, ulcktbl);
1395
1723
            ulcktbl->lock_count= 0;
1396
1724
          }
1397
1725
          if ((ulcktbl != table) && ulcktbl->db_stat)
1431
1759
    }
1432
1760
  }
1433
1761
  if (found)
1434
 
    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;
 
1800
}
 
1801
 
 
1802
 
 
1803
/* Wait until all used tables are refreshed */
 
1804
 
 
1805
bool wait_for_tables(Session *session)
 
1806
{
 
1807
  bool result;
 
1808
 
 
1809
  session->set_proc_info("Waiting for tables");
 
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);
 
1829
  session->set_proc_info(0);
 
1830
 
 
1831
  return result;
1435
1832
}
1436
1833
 
1437
1834
 
1459
1856
*/
1460
1857
 
1461
1858
 
1462
 
Table *drop_locked_tables(Session *session, const drizzled::identifier::Table &identifier)
 
1859
Table *drop_locked_tables(Session *session, const char *db, const char *table_name)
1463
1860
{
1464
1861
  Table *table,*next,**prev, *found= 0;
1465
1862
  prev= &session->open_tables;
1466
1863
 
1467
1864
  /*
1468
 
    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
1469
1866
    open_tables list. Another thread may work on it.
1470
 
    (See: table::Cache::singleton().removeTable(), wait_completed_table())
 
1867
    (See: remove_table_from_cache(), mysql_wait_completed_table())
1471
1868
    Closing a MERGE child before the parent would be fatal if the
1472
1869
    other thread tries to abort the MERGE lock in between.
1473
1870
  */
1474
1871
  for (table= session->open_tables; table ; table=next)
1475
1872
  {
1476
1873
    next=table->getNext();
1477
 
    if (table->getShare()->getCacheKey() == identifier.getKey())
 
1874
    if (!strcmp(table->getMutableShare()->getTableName(), table_name) &&
 
1875
        !strcasecmp(table->getMutableShare()->getSchemaName(), db))
1478
1876
    {
1479
 
      session->removeLock(table);
 
1877
      mysql_lock_remove(session, table);
1480
1878
 
1481
1879
      if (!found)
1482
1880
      {
1491
1889
      else
1492
1890
      {
1493
1891
        /* We already have a name lock, remove copy */
1494
 
        table::remove_table(static_cast<table::Concurrent *>(table));
 
1892
        hash_delete(&open_cache,(unsigned char*) table);
1495
1893
      }
1496
1894
    }
1497
1895
    else
1501
1899
    }
1502
1900
  }
1503
1901
  *prev=0;
1504
 
 
1505
1902
  if (found)
1506
 
    locking::broadcast_refresh();
 
1903
    broadcast_refresh();
1507
1904
 
1508
 
  return found;
 
1905
  return(found);
1509
1906
}
1510
1907
 
1511
1908
 
1515
1912
  other threads trying to get the lock.
1516
1913
*/
1517
1914
 
1518
 
void abort_locked_tables(Session *session, const drizzled::identifier::Table &identifier)
 
1915
void abort_locked_tables(Session *session,const char *db, const char *table_name)
1519
1916
{
1520
1917
  Table *table;
1521
1918
  for (table= session->open_tables; table ; table= table->getNext())
1522
1919
  {
1523
 
    if (table->getShare()->getCacheKey() == identifier.getKey())
 
1920
    if (!strcmp(table->getMutableShare()->getTableName(), table_name) &&
 
1921
        !strcmp(table->getMutableShare()->getSchemaName(), db))
1524
1922
    {
1525
1923
      /* If MERGE child, forward lock handling to parent. */
1526
 
      session->abortLock(table);
1527
 
      assert(0);
 
1924
      mysql_lock_abort(session, table);
1528
1925
      break;
1529
1926
    }
1530
1927
  }
1531
1928
}
1532
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,
 
1968
                                              identifier,
 
1969
                                              alias,
 
1970
                                              (uint32_t) (HA_OPEN_KEYFILE |
 
1971
                                                          HA_OPEN_RNDFILE |
 
1972
                                                          HA_GET_INDEX |
 
1973
                                                          HA_TRY_READ_ONLY),
 
1974
                                              session->open_options, *entry)))
 
1975
  {
 
1976
    if (error == 7)                             // Table def changed
 
1977
    {
 
1978
      share->resetVersion();                        // Mark share as old
 
1979
      if (discover_retry_count++)               // Retry once
 
1980
        goto err;
 
1981
 
 
1982
      /*
 
1983
        TODO->
 
1984
        Here we should wait until all threads has released the table.
 
1985
        For now we do one retry. This may cause a deadlock if there
 
1986
        is other threads waiting for other tables used by this thread.
 
1987
 
 
1988
        Proper fix would be to if the second retry failed:
 
1989
        - Mark that table def changed
 
1990
        - Return from open table
 
1991
        - Close all tables used by this thread
 
1992
        - Start waiting that the share is released
 
1993
        - Retry by opening all tables again
 
1994
      */
 
1995
 
 
1996
      /*
 
1997
        TO BE FIXED
 
1998
        To avoid deadlock, only wait for release if no one else is
 
1999
        using the share.
 
2000
      */
 
2001
      if (share->getTableCount() != 1)
 
2002
        goto err;
 
2003
      /* Free share and wait until it's released by all threads */
 
2004
      TableShare::release(share);
 
2005
 
 
2006
      if (!session->killed)
 
2007
      {
 
2008
        drizzle_reset_errors(session, 1);         // Clear warnings
 
2009
        session->clear_error();                 // Clear error message
 
2010
        goto retry;
 
2011
      }
 
2012
      return 1;
 
2013
    }
 
2014
 
 
2015
    goto err;
 
2016
  }
 
2017
 
 
2018
  return 0;
 
2019
 
 
2020
err:
 
2021
  TableShare::release(share);
 
2022
 
 
2023
  return 1;
 
2024
}
 
2025
 
1533
2026
 
1534
2027
/*
1535
2028
  Open all tables in list
1597
2090
     * to see if it exists so that an unauthorized user cannot phish for
1598
2091
     * table/schema information via error messages
1599
2092
     */
1600
 
    identifier::Table the_table(tables->getSchemaName(), tables->getTableName());
1601
 
    if (not plugin::Authorization::isAuthorized(user(), the_table))
 
2093
    TableIdentifier the_table(tables->db, tables->table_name);
 
2094
    if (not plugin::Authorization::isAuthorized(getSecurityContext(),
 
2095
                                                the_table))
1602
2096
    {
1603
2097
      result= -1;                               // Fatal error
1604
2098
      break;
1695
2189
 
1696
2190
  set_proc_info("Opening table");
1697
2191
  current_tablenr= 0;
1698
 
  while (!(table= openTable(table_list, &refresh)) && refresh) ;
 
2192
  while (!(table= openTable(table_list, &refresh)) &&
 
2193
         refresh)
 
2194
    ;
1699
2195
 
1700
2196
  if (table)
1701
2197
  {
1704
2200
 
1705
2201
    assert(lock == 0);  // You must lock everything at once
1706
2202
    if ((table->reginfo.lock_type= lock_type) != TL_UNLOCK)
1707
 
    {
1708
 
      if (not (lock= lockTables(&table_list->table, 1, 0)))
1709
 
        table= NULL;
1710
 
    }
 
2203
      if (! (lock= mysql_lock_tables(this, &table_list->table, 1, 0, &refresh)))
 
2204
        table= 0;
1711
2205
  }
1712
2206
 
1713
2207
  set_proc_info(0);
1761
2255
  Table **start,**ptr;
1762
2256
  uint32_t lock_flag= DRIZZLE_LOCK_NOTIFY_IF_NEED_REOPEN;
1763
2257
 
1764
 
  if (!(ptr=start=(Table**) session->getMemRoot()->allocate(sizeof(Table*)*count)))
 
2258
  if (!(ptr=start=(Table**) session->alloc(sizeof(Table*)*count)))
1765
2259
    return -1;
1766
 
 
1767
2260
  for (table= tables; table; table= table->next_global)
1768
2261
  {
1769
2262
    if (!table->placeholder())
1770
2263
      *(ptr++)= table->table;
1771
2264
  }
1772
2265
 
1773
 
  if (not (session->lock= session->lockTables(start, (uint32_t) (ptr - start), lock_flag)))
 
2266
  if (!(session->lock= mysql_lock_tables(session, start, (uint32_t) (ptr - start),
 
2267
                                         lock_flag, need_reopen)))
1774
2268
  {
1775
2269
    return -1;
1776
2270
  }
1799
2293
#  Table object
1800
2294
*/
1801
2295
 
1802
 
Table *Open_tables_state::open_temporary_table(const identifier::Table &identifier,
1803
 
                                               bool link_in_list)
 
2296
Table *Session::open_temporary_table(TableIdentifier &identifier,
 
2297
                                     bool link_in_list)
1804
2298
{
 
2299
  Table *new_tmp_table;
 
2300
  TableShare *share;
 
2301
 
1805
2302
  assert(identifier.isTmp());
1806
 
 
1807
 
 
1808
 
  table::Temporary *new_tmp_table= new table::Temporary(identifier.getType(),
1809
 
                                                        identifier,
1810
 
                                                        const_cast<char *>(const_cast<identifier::Table&>(identifier).getPath().c_str()),
1811
 
                                                        static_cast<uint32_t>(identifier.getPath().length()));
1812
 
  if (not new_tmp_table)
 
2303
  share= new TableShare(identifier.getType(),
 
2304
                        identifier,
 
2305
                        const_cast<char *>(identifier.getPath().c_str()), static_cast<uint32_t>(identifier.getPath().length()));
 
2306
 
 
2307
 
 
2308
  if (!(new_tmp_table= (Table*) malloc(sizeof(*new_tmp_table))))
1813
2309
    return NULL;
1814
2310
 
 
2311
  memset(new_tmp_table, 0, sizeof(*new_tmp_table));
 
2312
 
 
2313
 
1815
2314
  /*
1816
2315
    First open the share, and then open the table from the share we just opened.
1817
2316
  */
1818
 
  if (new_tmp_table->getMutableShare()->open_table_def(*static_cast<Session *>(this), identifier) ||
1819
 
      new_tmp_table->getMutableShare()->open_table_from_share(static_cast<Session *>(this), identifier, identifier.getTableName().c_str(),
1820
 
                                                              (uint32_t) (HA_OPEN_KEYFILE | HA_OPEN_RNDFILE |
1821
 
                                                                          HA_GET_INDEX),
1822
 
                                                              ha_open_options,
1823
 
                                                              *new_tmp_table))
 
2317
  if (share->open_table_def(*this, identifier) ||
 
2318
      share->open_table_from_share(this, identifier, identifier.getTableName().c_str(),
 
2319
                            (uint32_t) (HA_OPEN_KEYFILE | HA_OPEN_RNDFILE |
 
2320
                                        HA_GET_INDEX),
 
2321
                            ha_open_options,
 
2322
                            *new_tmp_table))
1824
2323
  {
1825
2324
    /* No need to lock share->mutex as this is not needed for tmp tables */
1826
 
    delete new_tmp_table->getMutableShare();
1827
 
    delete new_tmp_table;
 
2325
    delete share;
 
2326
    free((char*) new_tmp_table);
1828
2327
 
1829
2328
    return 0;
1830
2329
  }
1865
2364
{
1866
2365
  if (session->mark_used_columns != MARK_COLUMNS_NONE)
1867
2366
  {
1868
 
    boost::dynamic_bitset<> *current_bitmap= NULL;
 
2367
    MyBitmap *current_bitmap, *other_bitmap;
1869
2368
 
1870
2369
    /*
1871
2370
      We always want to register the used keys, as the column bitmap may have
1878
2377
    if (session->mark_used_columns == MARK_COLUMNS_READ)
1879
2378
    {
1880
2379
      current_bitmap= table->read_set;
 
2380
      other_bitmap=   table->write_set;
1881
2381
    }
1882
2382
    else
1883
2383
    {
1884
2384
      current_bitmap= table->write_set;
 
2385
      other_bitmap=   table->read_set;
1885
2386
    }
1886
2387
 
1887
 
    //if (current_bitmap->testAndSet(field->position()))
1888
 
    if (current_bitmap->test(field->position()))
 
2388
    if (current_bitmap->testAndSet(field->field_index))
1889
2389
    {
1890
2390
      if (session->mark_used_columns == MARK_COLUMNS_WRITE)
1891
2391
        session->dup_field= field;
1944
2444
    {
1945
2445
      if (nj_col)
1946
2446
      {
1947
 
        my_error(ER_NON_UNIQ_ERROR, MYF(0), name, session->where());
 
2447
        my_error(ER_NON_UNIQ_ERROR, MYF(0), name, session->where);
1948
2448
        return NULL;
1949
2449
      }
1950
2450
      nj_col= curr_nj_col;
1954
2454
    return NULL;
1955
2455
  {
1956
2456
    /* This is a base table. */
1957
 
    assert(nj_col->table_ref->table == nj_col->table_field->getTable());
 
2457
    assert(nj_col->table_ref->table == nj_col->table_field->table);
1958
2458
    found_field= nj_col->table_field;
1959
2459
    update_field_dependencies(session, found_field, nj_col->table_ref->table);
1960
2460
  }
1997
2497
  {
1998
2498
    field_ptr= table->getFields() + cached_field_index;
1999
2499
  }
2000
 
  else if (table->getShare()->getNamedFieldSize())
 
2500
  else if (table->getShare()->name_hash.records)
2001
2501
  {
2002
 
    field_ptr= table->getMutableShare()->getNamedField(std::string(name, length));
 
2502
    field_ptr= (Field**) hash_search(&table->getShare()->name_hash, (unsigned char*) name,
 
2503
                                     length);
2003
2504
    if (field_ptr)
2004
2505
    {
2005
2506
      /*
2111
2612
    TODO-> Ensure that table_name, db_name and tables->db always points to something !
2112
2613
  */
2113
2614
  if (/* Exclude nested joins. */
2114
 
      (!table_list->getNestedJoin()) &&
 
2615
      (!table_list->nested_join) &&
2115
2616
      /* Include merge views and information schema tables. */
2116
2617
      /*
2117
2618
        Test if the field qualifiers match the table reference we plan
2119
2620
      */
2120
2621
      table_name && table_name[0] &&
2121
2622
      (my_strcasecmp(table_alias_charset, table_list->alias, table_name) ||
2122
 
       (db_name && db_name[0] && table_list->getSchemaName() && table_list->getSchemaName()[0] &&
2123
 
        strcmp(db_name, table_list->getSchemaName()))))
 
2623
       (db_name && db_name[0] && table_list->db && table_list->db[0] &&
 
2624
        strcmp(db_name, table_list->db))))
2124
2625
    return 0;
2125
2626
 
2126
2627
  *actual_table= NULL;
2127
2628
 
2128
 
  if (!table_list->getNestedJoin())
 
2629
  if (!table_list->nested_join)
2129
2630
  {
2130
2631
    /* 'table_list' is a stored table. */
2131
2632
    assert(table_list->table);
2145
2646
    */
2146
2647
    if (table_name && table_name[0])
2147
2648
    {
2148
 
      List_iterator<TableList> it(table_list->getNestedJoin()->join_list);
 
2649
      List_iterator<TableList> it(table_list->nested_join->join_list);
2149
2650
      TableList *table;
2150
2651
      while ((table= it++))
2151
2652
      {
2193
2694
        field_to_set= fld;
2194
2695
      if (field_to_set)
2195
2696
      {
2196
 
        Table *table= field_to_set->getTable();
 
2697
        Table *table= field_to_set->table;
2197
2698
        if (session->mark_used_columns == MARK_COLUMNS_READ)
2198
 
          table->setReadSet(field_to_set->position());
 
2699
          table->setReadSet(field_to_set->field_index);
2199
2700
        else
2200
 
          table->setWriteSet(field_to_set->position());
 
2701
          table->setWriteSet(field_to_set->field_index);
2201
2702
      }
2202
2703
    }
2203
2704
  }
2341
2842
      */
2342
2843
      item->cached_table= found ?  0 : actual_table;
2343
2844
 
2344
 
      assert(session->where());
 
2845
      assert(session->where);
2345
2846
      /*
2346
2847
        If we found a fully qualified field we return it directly as it can't
2347
2848
        have duplicates.
2354
2855
        if (report_error == REPORT_ALL_ERRORS ||
2355
2856
            report_error == IGNORE_EXCEPT_NON_UNIQUE)
2356
2857
          my_error(ER_NON_UNIQ_ERROR, MYF(0),
2357
 
                   table_name ? item->full_name() : name, session->where());
 
2858
                   table_name ? item->full_name() : name, session->where);
2358
2859
        return (Field*) 0;
2359
2860
      }
2360
2861
      found= cur_field;
2387
2888
      strcat(buff, table_name);
2388
2889
      table_name=buff;
2389
2890
    }
2390
 
    my_error(ER_UNKNOWN_TABLE, MYF(0), table_name, session->where());
 
2891
    my_error(ER_UNKNOWN_TABLE, MYF(0), table_name, session->where);
2391
2892
  }
2392
2893
  else
2393
2894
  {
2394
2895
    if (report_error == REPORT_ALL_ERRORS ||
2395
2896
        report_error == REPORT_EXCEPT_NON_UNIQUE)
2396
 
      my_error(ER_BAD_FIELD_ERROR, MYF(0), item->full_name(), session->where());
 
2897
      my_error(ER_BAD_FIELD_ERROR, MYF(0), item->full_name(), session->where);
2397
2898
    else
2398
2899
      found= not_found_field;
2399
2900
  }
2520
3021
            */
2521
3022
            if (report_error != IGNORE_ERRORS)
2522
3023
              my_error(ER_NON_UNIQ_ERROR, MYF(0),
2523
 
                       find->full_name(), session->where());
 
3024
                       find->full_name(), session->where);
2524
3025
            return (Item**) 0;
2525
3026
          }
2526
3027
          found_unaliased= li.ref();
2551
3052
              continue;                           // Same field twice
2552
3053
            if (report_error != IGNORE_ERRORS)
2553
3054
              my_error(ER_NON_UNIQ_ERROR, MYF(0),
2554
 
                       find->full_name(), session->where());
 
3055
                       find->full_name(), session->where);
2555
3056
            return (Item**) 0;
2556
3057
          }
2557
3058
          found= li.ref();
2603
3104
    {
2604
3105
      if (report_error != IGNORE_ERRORS)
2605
3106
        my_error(ER_NON_UNIQ_ERROR, MYF(0),
2606
 
                 find->full_name(), session->where());
 
3107
                 find->full_name(), session->where);
2607
3108
      return (Item **) 0;
2608
3109
    }
2609
3110
    if (found_unaliased)
2619
3120
  {
2620
3121
    if (report_error == REPORT_ALL_ERRORS)
2621
3122
      my_error(ER_BAD_FIELD_ERROR, MYF(0),
2622
 
               find->full_name(), session->where());
 
3123
               find->full_name(), session->where);
2623
3124
    return (Item **) 0;
2624
3125
  }
2625
3126
  else
2737
3238
    Leaf table references to which new natural join columns are added
2738
3239
    if the leaves are != NULL.
2739
3240
  */
2740
 
  TableList *leaf_1= (table_ref_1->getNestedJoin() &&
2741
 
                      ! table_ref_1->is_natural_join) ?
 
3241
  TableList *leaf_1= (table_ref_1->nested_join &&
 
3242
                      !table_ref_1->is_natural_join) ?
2742
3243
    NULL : table_ref_1;
2743
 
  TableList *leaf_2= (table_ref_2->getNestedJoin() &&
2744
 
                      ! table_ref_2->is_natural_join) ?
 
3244
  TableList *leaf_2= (table_ref_2->nested_join &&
 
3245
                      !table_ref_2->is_natural_join) ?
2745
3246
    NULL : table_ref_2;
2746
3247
 
2747
3248
  *found_using_fields= 0;
2753
3254
    /* true if field_name_1 is a member of using_fields */
2754
3255
    bool is_using_column_1;
2755
3256
    if (!(nj_col_1= it_1.get_or_create_column_ref(leaf_1)))
2756
 
      return(result);
 
3257
      goto err;
2757
3258
    field_name_1= nj_col_1->name();
2758
3259
    is_using_column_1= using_fields &&
2759
3260
      test_if_string_in_list(field_name_1, using_fields);
2771
3272
      Natural_join_column *cur_nj_col_2;
2772
3273
      const char *cur_field_name_2;
2773
3274
      if (!(cur_nj_col_2= it_2.get_or_create_column_ref(leaf_2)))
2774
 
        return(result);
 
3275
        goto err;
2775
3276
      cur_field_name_2= cur_nj_col_2->name();
2776
3277
 
2777
3278
      /*
2790
3291
        if (cur_nj_col_2->is_common ||
2791
3292
            (found && (!using_fields || is_using_column_1)))
2792
3293
        {
2793
 
          my_error(ER_NON_UNIQ_ERROR, MYF(0), field_name_1, session->where());
2794
 
          return(result);
 
3294
          my_error(ER_NON_UNIQ_ERROR, MYF(0), field_name_1, session->where);
 
3295
          goto err;
2795
3296
        }
2796
3297
        nj_col_2= cur_nj_col_2;
2797
3298
        found= true;
2824
3325
      Item_func_eq *eq_cond;
2825
3326
 
2826
3327
      if (!item_1 || !item_2)
2827
 
        return(result); // out of memory
 
3328
        goto err;                               // out of memory
2828
3329
 
2829
3330
      /*
2830
3331
        In the case of no_wrap_view_item == 0, the created items must be
2849
3350
      */
2850
3351
      if (set_new_item_local_context(session, item_ident_1, nj_col_1->table_ref) ||
2851
3352
          set_new_item_local_context(session, item_ident_2, nj_col_2->table_ref))
2852
 
        return(result);
 
3353
        goto err;
2853
3354
 
2854
3355
      if (!(eq_cond= new Item_func_eq(item_ident_1, item_ident_2)))
2855
 
        return(result);                               /* Out of memory. */
 
3356
        goto err;                               /* Out of memory. */
2856
3357
 
2857
3358
      /*
2858
3359
        Add the new equi-join condition to the ON clause. Notice that
2869
3370
      {
2870
3371
        Table *table_1= nj_col_1->table_ref->table;
2871
3372
        /* Mark field_1 used for table cache. */
2872
 
        table_1->setReadSet(field_1->position());
 
3373
        table_1->setReadSet(field_1->field_index);
2873
3374
        table_1->covering_keys&= field_1->part_of_key;
2874
3375
        table_1->merge_keys|= field_1->part_of_key;
2875
3376
      }
2877
3378
      {
2878
3379
        Table *table_2= nj_col_2->table_ref->table;
2879
3380
        /* Mark field_2 used for table cache. */
2880
 
        table_2->setReadSet(field_2->position());
 
3381
        table_2->setReadSet(field_2->field_index);
2881
3382
        table_2->covering_keys&= field_2->part_of_key;
2882
3383
        table_2->merge_keys|= field_2->part_of_key;
2883
3384
      }
2898
3399
  */
2899
3400
  result= false;
2900
3401
 
 
3402
err:
2901
3403
  return(result);
2902
3404
}
2903
3405
 
2955
3457
 
2956
3458
  if (!(non_join_columns= new List<Natural_join_column>) ||
2957
3459
      !(natural_using_join->join_columns= new List<Natural_join_column>))
2958
 
  {
2959
 
    return(result);
2960
 
  }
 
3460
    goto err;
2961
3461
 
2962
3462
  /* Append the columns of the first join operand. */
2963
3463
  for (it_1.set(table_ref_1); !it_1.end_of_fields(); it_1.next())
2995
3495
        if (!(common_field= it++))
2996
3496
        {
2997
3497
          my_error(ER_BAD_FIELD_ERROR, MYF(0), using_field_name_ptr,
2998
 
                   session->where());
2999
 
          return(result);
 
3498
                   session->where);
 
3499
          goto err;
3000
3500
        }
3001
3501
        if (!my_strcasecmp(system_charset_info,
3002
3502
                           common_field->name(), using_field_name_ptr))
3024
3524
 
3025
3525
  result= false;
3026
3526
 
 
3527
err:
3027
3528
  return(result);
3028
3529
}
3029
3530
 
3066
3567
  bool result= true;
3067
3568
 
3068
3569
  /* Call the procedure recursively for each nested table reference. */
3069
 
  if (table_ref->getNestedJoin())
 
3570
  if (table_ref->nested_join)
3070
3571
  {
3071
 
    List_iterator_fast<TableList> nested_it(table_ref->getNestedJoin()->join_list);
 
3572
    List_iterator_fast<TableList> nested_it(table_ref->nested_join->join_list);
3072
3573
    TableList *same_level_left_neighbor= nested_it++;
3073
3574
    TableList *same_level_right_neighbor= NULL;
3074
3575
    /* Left/right-most neighbors, possibly at higher levels in the join tree. */
3093
3594
          cur_table_ref->outer_join & JOIN_TYPE_RIGHT)
3094
3595
      {
3095
3596
        /* This can happen only for JOIN ... ON. */
3096
 
        assert(table_ref->getNestedJoin()->join_list.elements == 2);
 
3597
        assert(table_ref->nested_join->join_list.elements == 2);
3097
3598
        std::swap(same_level_left_neighbor, cur_table_ref);
3098
3599
      }
3099
3600
 
3106
3607
      real_right_neighbor= (same_level_right_neighbor) ?
3107
3608
        same_level_right_neighbor : right_neighbor;
3108
3609
 
3109
 
      if (cur_table_ref->getNestedJoin() &&
 
3610
      if (cur_table_ref->nested_join &&
3110
3611
          store_top_level_join_columns(session, cur_table_ref,
3111
3612
                                       real_left_neighbor, real_right_neighbor))
3112
 
        return(result);
 
3613
        goto err;
3113
3614
      same_level_right_neighbor= cur_table_ref;
3114
3615
    }
3115
3616
  }
3120
3621
  */
3121
3622
  if (table_ref->is_natural_join)
3122
3623
  {
3123
 
    assert(table_ref->getNestedJoin() &&
3124
 
           table_ref->getNestedJoin()->join_list.elements == 2);
3125
 
    List_iterator_fast<TableList> operand_it(table_ref->getNestedJoin()->join_list);
 
3624
    assert(table_ref->nested_join &&
 
3625
           table_ref->nested_join->join_list.elements == 2);
 
3626
    List_iterator_fast<TableList> operand_it(table_ref->nested_join->join_list);
3126
3627
    /*
3127
3628
      Notice that the order of join operands depends on whether table_ref
3128
3629
      represents a LEFT or a RIGHT join. In a RIGHT join, the operands are
3141
3642
      std::swap(table_ref_1, table_ref_2);
3142
3643
    if (mark_common_columns(session, table_ref_1, table_ref_2,
3143
3644
                            using_fields, &found_using_fields))
3144
 
      return(result);
 
3645
      goto err;
3145
3646
 
3146
3647
    /*
3147
3648
      Swap the join operands back, so that we pick the columns of the second
3153
3654
    if (store_natural_using_join_columns(session, table_ref, table_ref_1,
3154
3655
                                         table_ref_2, using_fields,
3155
3656
                                         found_using_fields))
3156
 
      return(result);
 
3657
      goto err;
3157
3658
 
3158
3659
    /*
3159
3660
      Change NATURAL JOIN to JOIN ... ON. We do this for both operands
3186
3687
  }
3187
3688
  result= false; /* All is OK. */
3188
3689
 
 
3690
err:
3189
3691
  return(result);
3190
3692
}
3191
3693
 
3218
3720
                                         List<TableList> *from_clause,
3219
3721
                                         Name_resolution_context *context)
3220
3722
{
3221
 
  session->setWhere("from clause");
 
3723
  session->where= "from clause";
3222
3724
  if (from_clause->elements == 0)
3223
3725
    return false; /* We come here in the case of UNIONs. */
3224
3726
 
3339
3841
  session->mark_used_columns= mark_used_columns;
3340
3842
  if (allow_sum_func)
3341
3843
    session->lex->allow_sum_func|= 1 << session->lex->current_select->nest_level;
3342
 
  session->setWhere(Session::DEFAULT_WHERE);
 
3844
  session->where= Session::DEFAULT_WHERE;
3343
3845
  save_is_item_list_lookup= session->lex->current_select->is_item_list_lookup;
3344
3846
  session->lex->current_select->is_item_list_lookup= 0;
3345
3847
 
3351
3853
    There is other way to solve problem: fill array with pointers to list,
3352
3854
    but it will be slower.
3353
3855
 
3354
 
    TODO-> remove it when (if) we made one list for allfields and ref_pointer_array
 
3856
TODO: remove it when (if) we made one list for allfields and
 
3857
ref_pointer_array
3355
3858
  */
3356
3859
  if (ref_pointer_array)
3357
 
  {
3358
3860
    memset(ref_pointer_array, 0, sizeof(Item *) * fields.elements);
3359
 
  }
3360
3861
 
3361
3862
  Item **ref= ref_pointer_array;
3362
3863
  session->lex->current_select->cur_pos_in_select_list= 0;
3588
4089
    assert(tables->is_leaf_for_name_resolution());
3589
4090
 
3590
4091
    if ((table_name && my_strcasecmp(table_alias_charset, table_name, tables->alias)) ||
3591
 
        (db_name && my_strcasecmp(system_charset_info, tables->getSchemaName(),db_name)))
 
4092
        (db_name && strcasecmp(tables->db,db_name)))
3592
4093
      continue;
3593
4094
 
3594
4095
    /*
3624
4125
      if ((field= field_iterator.field()))
3625
4126
      {
3626
4127
        /* Mark fields as used to allow storage engine to optimze access */
3627
 
        field->getTable()->setReadSet(field->position());
 
4128
        field->table->setReadSet(field->field_index);
3628
4129
        if (table)
3629
4130
        {
3630
4131
          table->covering_keys&= field->part_of_key;
3652
4153
        }
3653
4154
      }
3654
4155
      else
3655
 
      {
3656
4156
        session->used_tables|= item->used_tables();
3657
 
      }
3658
 
 
3659
4157
      session->lex->current_select->cur_pos_in_select_list++;
3660
4158
    }
3661
4159
    /*
3675
4173
    qualified '*', and all columns were coalesced, we have to give a more
3676
4174
    meaningful message than ER_BAD_TABLE_ERROR.
3677
4175
  */
3678
 
  if (not table_name)
3679
 
  {
 
4176
  if (!table_name)
3680
4177
    my_message(ER_NO_TABLES_USED, ER(ER_NO_TABLES_USED), MYF(0));
3681
 
  }
3682
4178
  else
3683
 
  {
3684
4179
    my_error(ER_BAD_TABLE_ERROR, MYF(0), table_name);
3685
 
  }
3686
4180
 
3687
4181
  return true;
3688
4182
}
3731
4225
  session->session_marker= (void*)1;
3732
4226
  if (*conds)
3733
4227
  {
3734
 
    session->setWhere("where clause");
 
4228
    session->where="where clause";
3735
4229
    if ((!(*conds)->fixed && (*conds)->fix_fields(session, conds)) ||
3736
4230
        (*conds)->check_cols(1))
3737
4231
      goto err_no_arena;
3753
4247
      {
3754
4248
        /* Make a join an a expression */
3755
4249
        session->session_marker= (void*)embedded;
3756
 
        session->setWhere("on clause");
 
4250
        session->where="on clause";
3757
4251
        if ((!embedded->on_expr->fixed && embedded->on_expr->fix_fields(session, &embedded->on_expr)) ||
3758
4252
            embedded->on_expr->check_cols(1))
3759
4253
          goto err_no_arena;
3760
4254
        select_lex->cond_count++;
3761
4255
      }
3762
 
      embedding= embedded->getEmbedding();
 
4256
      embedding= embedded->embedding;
3763
4257
    }
3764
4258
    while (embedding &&
3765
 
           embedding->getNestedJoin()->join_list.head() == embedded);
 
4259
           embedding->nested_join->join_list.head() == embedded);
3766
4260
 
3767
4261
  }
3768
4262
  session->session_marker= save_session_marker;
3821
4315
      thus we safely can take table from the first field.
3822
4316
    */
3823
4317
    field= static_cast<Item_field *>(f++);
3824
 
    table= field->field->getTable();
 
4318
    table= field->field->table;
3825
4319
    table->auto_increment_field_not_null= false;
3826
4320
    f.rewind();
3827
4321
  }
3831
4325
    value= v++;
3832
4326
 
3833
4327
    Field *rfield= field->field;
3834
 
    table= rfield->getTable();
 
4328
    table= rfield->table;
3835
4329
 
3836
4330
    if (rfield == table->next_number_field)
3837
4331
      table->auto_increment_field_not_null= true;
3838
4332
    if ((value->save_in_field(rfield, 0) < 0) && !ignore_errors)
3839
4333
    {
3840
4334
      my_message(ER_UNKNOWN_ERROR, ER(ER_UNKNOWN_ERROR), MYF(0));
3841
 
      if (table)
3842
 
        table->auto_increment_field_not_null= false;
3843
 
 
3844
 
      return true;
 
4335
      goto err;
3845
4336
    }
3846
4337
  }
3847
4338
 
3848
4339
  return session->is_error();
 
4340
 
 
4341
err:
 
4342
  if (table)
 
4343
    table->auto_increment_field_not_null= false;
 
4344
 
 
4345
  return true;
3849
4346
}
3850
4347
 
3851
4348
 
3885
4382
      On INSERT or UPDATE fields are checked to be from the same table,
3886
4383
      thus we safely can take table from the first field.
3887
4384
    */
3888
 
    table= (*ptr)->getTable();
 
4385
    table= (*ptr)->table;
3889
4386
    table->auto_increment_field_not_null= false;
3890
4387
  }
3891
 
 
3892
4388
  while ((field = *ptr++) && ! session->is_error())
3893
4389
  {
3894
4390
    value=v++;
3895
 
    table= field->getTable();
3896
 
 
 
4391
    table= field->table;
3897
4392
    if (field == table->next_number_field)
3898
4393
      table->auto_increment_field_not_null= true;
3899
 
 
3900
4394
    if (value->save_in_field(field, 0) < 0)
3901
 
    {
3902
 
      if (table)
3903
 
        table->auto_increment_field_not_null= false;
3904
 
 
3905
 
      return true;
3906
 
    }
 
4395
      goto err;
3907
4396
  }
3908
4397
 
3909
4398
  return(session->is_error());
 
4399
 
 
4400
err:
 
4401
  if (table)
 
4402
    table->auto_increment_field_not_null= false;
 
4403
 
 
4404
  return true;
3910
4405
}
3911
4406
 
3912
4407
 
3913
4408
bool drizzle_rm_tmp_tables()
3914
4409
{
 
4410
  Session *session;
3915
4411
 
3916
4412
  assert(drizzle_tmpdir.size());
3917
 
  Session::shared_ptr session= Session::make_shared(plugin::Listen::getNullClient(), catalog::local());
3918
4413
 
3919
 
  if (not session)
 
4414
  if (!(session= new Session(plugin::Listen::getNullClient())))
3920
4415
    return true;
3921
 
  session->thread_stack= (char*) session.get();
 
4416
  session->thread_stack= (char*) &session;
3922
4417
  session->storeGlobals();
3923
4418
 
3924
4419
  plugin::StorageEngine::removeLostTemporaryTables(*session, drizzle_tmpdir.c_str());
3925
4420
 
 
4421
  delete session;
 
4422
 
3926
4423
  return false;
3927
4424
}
3928
4425
 
3932
4429
  unireg support functions
3933
4430
 *****************************************************************************/
3934
4431
 
3935
 
 
 
4432
/*
 
4433
  Invalidate any cache entries that are for some DB
 
4434
 
 
4435
  SYNOPSIS
 
4436
  remove_db_from_cache()
 
4437
  db            Database name. This will be in lower case if
 
4438
  lower_case_table_name is set
 
4439
 
 
4440
NOTE:
 
4441
We can't use hash_delete when looping hash_elements. We mark them first
 
4442
and afterwards delete those marked unused.
 
4443
*/
 
4444
 
 
4445
void remove_db_from_cache(SchemaIdentifier &schema_identifier)
 
4446
{
 
4447
  safe_mutex_assert_owner(&LOCK_open);
 
4448
 
 
4449
  for (uint32_t idx=0 ; idx < open_cache.records ; idx++)
 
4450
  {
 
4451
    Table *table=(Table*) hash_element(&open_cache,idx);
 
4452
    if (not schema_identifier.getPath().compare(table->getMutableShare()->getSchemaName()))
 
4453
    {
 
4454
      table->getMutableShare()->resetVersion();                 /* Free when thread is ready */
 
4455
      if (not table->in_use)
 
4456
        relink_unused(table);
 
4457
    }
 
4458
  }
 
4459
  while (unused_tables && !unused_tables->getShare()->getVersion())
 
4460
    hash_delete(&open_cache,(unsigned char*) unused_tables);
 
4461
}
 
4462
 
 
4463
 
 
4464
/*
 
4465
  Mark all entries with the table as deleted to force an reopen of the table
 
4466
 
 
4467
  The table will be closed (not stored in cache) by the current thread when
 
4468
  close_thread_tables() is called.
 
4469
 
 
4470
  PREREQUISITES
 
4471
  Lock on LOCK_open()
 
4472
 
 
4473
  RETURN
 
4474
  0  This thread now have exclusive access to this table and no other thread
 
4475
  can access the table until close_thread_tables() is called.
 
4476
  1  Table is in use by another thread
 
4477
*/
 
4478
 
 
4479
bool remove_table_from_cache(Session *session, TableIdentifier &identifier, uint32_t flags)
 
4480
{
 
4481
  const TableIdentifier::Key &key(identifier.getKey());
 
4482
  bool result= false; 
 
4483
  bool signalled= false;
 
4484
 
 
4485
  uint32_t key_length= key.size();
 
4486
 
 
4487
  for (;;)
 
4488
  {
 
4489
    HASH_SEARCH_STATE state;
 
4490
    Table *table;
 
4491
    result= signalled= false;
 
4492
 
 
4493
    for (table= (Table*) hash_first(&open_cache, (unsigned char*) &key[0], key_length,
 
4494
                                    &state);
 
4495
         table;
 
4496
         table= (Table*) hash_next(&open_cache, (unsigned char*) &key[0], key_length,
 
4497
                                   &state))
 
4498
    {
 
4499
      Session *in_use;
 
4500
 
 
4501
      table->getMutableShare()->resetVersion();         /* Free when thread is ready */
 
4502
      if (!(in_use=table->in_use))
 
4503
      {
 
4504
        relink_unused(table);
 
4505
      }
 
4506
      else if (in_use != session)
 
4507
      {
 
4508
        /*
 
4509
          Mark that table is going to be deleted from cache. This will
 
4510
          force threads that are in mysql_lock_tables() (but not yet
 
4511
          in thr_multi_lock()) to abort it's locks, close all tables and retry
 
4512
        */
 
4513
        in_use->some_tables_deleted= true;
 
4514
        if (table->is_name_opened())
 
4515
        {
 
4516
          result= true;
 
4517
        }
 
4518
        /*
 
4519
          Now we must abort all tables locks used by this thread
 
4520
          as the thread may be waiting to get a lock for another table.
 
4521
          Note that we need to hold LOCK_open while going through the
 
4522
          list. So that the other thread cannot change it. The other
 
4523
          thread must also hold LOCK_open whenever changing the
 
4524
          open_tables list. Aborting the MERGE lock after a child was
 
4525
          closed and before the parent is closed would be fatal.
 
4526
        */
 
4527
        for (Table *session_table= in_use->open_tables;
 
4528
             session_table ;
 
4529
             session_table= session_table->getNext())
 
4530
        {
 
4531
          /* Do not handle locks of MERGE children. */
 
4532
          if (session_table->db_stat)   // If table is open
 
4533
            signalled|= mysql_lock_abort_for_thread(session, session_table);
 
4534
        }
 
4535
      }
 
4536
      else
 
4537
        result= result || (flags & RTFC_OWNED_BY_Session_FLAG);
 
4538
    }
 
4539
    while (unused_tables && !unused_tables->getShare()->getVersion())
 
4540
      hash_delete(&open_cache,(unsigned char*) unused_tables);
 
4541
 
 
4542
    /* Remove table from table definition cache if it's not in use */
 
4543
    TableShare::release(identifier);
 
4544
 
 
4545
    if (result && (flags & RTFC_WAIT_OTHER_THREAD_FLAG))
 
4546
    {
 
4547
      /*
 
4548
        Signal any thread waiting for tables to be freed to
 
4549
        reopen their tables
 
4550
      */
 
4551
      broadcast_refresh();
 
4552
      if (!(flags & RTFC_CHECK_KILLED_FLAG) || !session->killed)
 
4553
      {
 
4554
        dropping_tables++;
 
4555
        if (likely(signalled))
 
4556
          (void) pthread_cond_wait(&COND_refresh, &LOCK_open);
 
4557
        else
 
4558
        {
 
4559
          struct timespec abstime;
 
4560
          /*
 
4561
            It can happen that another thread has opened the
 
4562
            table but has not yet locked any table at all. Since
 
4563
            it can be locked waiting for a table that our thread
 
4564
            has done LOCK Table x WRITE on previously, we need to
 
4565
            ensure that the thread actually hears our signal
 
4566
            before we go to sleep. Thus we wait for a short time
 
4567
            and then we retry another loop in the
 
4568
            remove_table_from_cache routine.
 
4569
          */
 
4570
          set_timespec(abstime, 10);
 
4571
          pthread_cond_timedwait(&COND_refresh, &LOCK_open, &abstime);
 
4572
        }
 
4573
        dropping_tables--;
 
4574
        continue;
 
4575
      }
 
4576
    }
 
4577
    break;
 
4578
  }
 
4579
 
 
4580
  return result;
 
4581
}
3936
4582
 
3937
4583
 
3938
4584
/**