~drizzle-trunk/drizzle/development

« back to all changes in this revision

Viewing changes to drizzled/sql_base.cc

  • Committer: Stewart Smith
  • Date: 2010-03-02 06:41:59 UTC
  • mto: (1309.2.13 build)
  • mto: This revision was merged to the branch mainline in revision 1318.
  • Revision ID: stewart@flamingspork.com-20100302064159-gktw6hcbs3u0fflm
move Item_result out to its own header file and out of common.h

Show diffs side-by-side

added added

removed removed

Lines of Context:
11
11
 
12
12
  You should have received a copy of the GNU General Public License
13
13
  along with this program; if not, write to the Free Software
14
 
  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA */
 
14
  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA */
15
15
 
16
16
 
17
17
/* Basic functions needed by many modules */
31
31
# endif
32
32
#endif
33
33
#include "drizzled/internal/my_pthread.h"
34
 
#include "drizzled/internal/thread_var.h"
35
34
 
36
35
#include <drizzled/sql_select.h>
37
36
#include <drizzled/error.h>
47
46
#include "drizzled/cached_directory.h"
48
47
#include <drizzled/field/timestamp.h>
49
48
#include <drizzled/field/null.h>
 
49
#include "drizzled/memory/multi_malloc.h"
50
50
#include "drizzled/sql_table.h"
51
51
#include "drizzled/global_charset_info.h"
52
52
#include "drizzled/pthread_globals.h"
53
53
#include "drizzled/internal/iocache.h"
54
 
#include "drizzled/drizzled.h"
55
 
#include "drizzled/plugin/authorization.h"
56
 
#include "drizzled/table/temporary.h"
57
 
#include "drizzled/table/placeholder.h"
58
 
#include "drizzled/table/unused.h"
59
54
 
60
55
using namespace std;
61
56
 
64
59
 
65
60
extern bool volatile shutdown_in_progress;
66
61
 
 
62
bool drizzle_rm_tmp_tables();
 
63
 
 
64
/**
 
65
  @defgroup Data_Dictionary Data Dictionary
 
66
  @{
 
67
*/
 
68
Table *unused_tables;                           /* Used by mysql_test */
 
69
HASH open_cache;                                /* Used by mysql_test */
 
70
static int open_unireg_entry(Session *session, Table *entry, TableList *table_list,
 
71
                             const char *alias,
 
72
                             char *cache_key, uint32_t cache_key_length);
 
73
void free_cache_entry(void *entry);
 
74
unsigned char *table_cache_key(const unsigned char *record,
 
75
                               size_t *length,
 
76
                               bool );
 
77
 
 
78
 
 
79
unsigned char *table_cache_key(const unsigned char *record,
 
80
                               size_t *length,
 
81
                               bool )
 
82
{
 
83
  Table *entry=(Table*) record;
 
84
  *length= entry->s->table_cache_key.length;
 
85
  return (unsigned char*) entry->s->table_cache_key.str;
 
86
}
 
87
 
 
88
 
67
89
bool table_cache_init(void)
68
90
{
69
 
  return false;
70
 
}
71
 
 
72
 
uint32_t cached_open_tables(void)
73
 
{
74
 
  return table::getCache().size();
 
91
  return hash_init(&open_cache, &my_charset_bin,
 
92
                   (size_t) table_cache_size+16,
 
93
                   0, 0, table_cache_key,
 
94
                   free_cache_entry, 0);
75
95
}
76
96
 
77
97
void table_cache_free(void)
78
98
{
79
99
  refresh_version++;                            // Force close of open tables
80
100
 
81
 
  table::getUnused().clear();
82
 
  table::getCache().clear();
83
 
}
 
101
  while (unused_tables)
 
102
    hash_delete(&open_cache,(unsigned char*) unused_tables);
 
103
 
 
104
  if (!open_cache.records)                      // Safety first
 
105
    hash_free(&open_cache);
 
106
}
 
107
 
 
108
uint32_t cached_open_tables(void)
 
109
{
 
110
  return open_cache.records;
 
111
}
 
112
 
84
113
 
85
114
/*
86
115
  Close cursor handle, but leave the table in the table cache
93
122
  By leaving the table in the table cache, it disallows any other thread
94
123
  to open the table
95
124
 
96
 
  session->getKilled() will be set if we run out of memory
 
125
  session->killed will be set if we run out of memory
97
126
 
98
127
  If closing a MERGE child, the calling function has to take care for
99
128
  closing the parent too, if necessary.
102
131
 
103
132
void close_handle_and_leave_table_as_lock(Table *table)
104
133
{
 
134
  TableShare *share, *old_share= table->s;
 
135
  char *key_buff;
 
136
  memory::Root *mem_root= &table->mem_root;
 
137
 
105
138
  assert(table->db_stat);
106
 
  assert(table->getShare()->getType() == message::Table::STANDARD);
107
139
 
108
140
  /*
109
141
    Make a local copy of the table share and free the current one.
110
142
    This has to be done to ensure that the table share is removed from
111
143
    the table defintion cache as soon as the last instance is removed
112
144
  */
113
 
  TableIdentifier identifier(table->getShare()->getSchemaName(), table->getShare()->getTableName(), message::Table::INTERNAL);
114
 
  const TableIdentifier::Key &key(identifier.getKey());
115
 
  TableShare *share= new TableShare(identifier.getType(),
116
 
                                    identifier,
117
 
                                    const_cast<char *>(key.vector()),  static_cast<uint32_t>(table->getShare()->getCacheKeySize()));
 
145
  if (multi_alloc_root(mem_root,
 
146
                       &share, sizeof(*share),
 
147
                       &key_buff, old_share->table_cache_key.length,
 
148
                       NULL))
 
149
  {
 
150
    memset(share, 0, sizeof(*share));
 
151
    share->set_table_cache_key(key_buff, old_share->table_cache_key.str,
 
152
                               old_share->table_cache_key.length);
 
153
    share->tmp_table= INTERNAL_TMP_TABLE;       // for intern_close_table()
 
154
  }
118
155
 
119
156
  table->cursor->close();
120
157
  table->db_stat= 0;                            // Mark cursor closed
121
 
  TableShare::release(table->getMutableShare());
122
 
  table->setShare(share);
 
158
  TableShare::release(table->s);
 
159
  table->s= share;
 
160
  table->cursor->change_table_ptr(table, table->s);
123
161
}
124
162
 
125
163
 
132
170
{                                               // Free all structures
133
171
  free_io_cache();
134
172
  if (cursor)                              // Not true if name lock
 
173
    closefrm(true);                     // close cursor
 
174
}
 
175
 
 
176
/*
 
177
  Remove table from the open table cache
 
178
 
 
179
  SYNOPSIS
 
180
  free_cache_entry()
 
181
  entry         Table to remove
 
182
 
 
183
  NOTE
 
184
  We need to have a lock on LOCK_open when calling this
 
185
*/
 
186
 
 
187
void free_cache_entry(void *entry)
 
188
{
 
189
  Table *table= static_cast<Table *>(entry);
 
190
  table->intern_close_table();
 
191
  if (!table->in_use)
135
192
  {
136
 
    delete_table(true);                 // close cursor
 
193
    table->next->prev=table->prev;              /* remove from used chain */
 
194
    table->prev->next=table->next;
 
195
    if (table == unused_tables)
 
196
    {
 
197
      unused_tables=unused_tables->next;
 
198
      if (table == unused_tables)
 
199
        unused_tables= NULL;
 
200
    }
137
201
  }
 
202
  free(table);
138
203
}
139
204
 
140
205
/* Free resources allocated by filesort() and read_record() */
143
208
{
144
209
  if (sort.io_cache)
145
210
  {
146
 
    sort.io_cache->close_cached_file();
 
211
    close_cached_file(sort.io_cache);
147
212
    delete sort.io_cache;
148
213
    sort.io_cache= 0;
149
214
  }
155
220
 
156
221
  @param session Thread context (may be NULL)
157
222
  @param tables List of tables to remove from the cache
158
 
  @param have_lock If table::Cache::singleton().mutex() is locked
 
223
  @param have_lock If LOCK_open is locked
159
224
  @param wait_for_refresh Wait for a impending flush
160
225
  @param wait_for_placeholders Wait for tables being reopened so that the GRL
161
226
  won't proceed while write-locked tables are being reopened by other
170
235
  bool result= false;
171
236
  Session *session= this;
172
237
 
173
 
  {
174
 
    table::Cache::singleton().mutex().lock(); /* Optionally lock for remove tables from open_cahe if not in use */
175
 
 
176
 
    if (tables == NULL)
177
 
    {
178
 
      refresh_version++;                                // Force close of open tables
179
 
 
180
 
      table::getUnused().clear();
181
 
 
182
 
      if (wait_for_refresh)
183
 
      {
 
238
  pthread_mutex_lock(&LOCK_open); /* Optionally lock for remove tables from open_cahe if not in use */
 
239
 
 
240
  if (tables == NULL)
 
241
  {
 
242
    refresh_version++;                          // Force close of open tables
 
243
    while (unused_tables)
 
244
      hash_delete(&open_cache,(unsigned char*) unused_tables);
 
245
 
 
246
    if (wait_for_refresh)
 
247
    {
 
248
      /*
 
249
        Other threads could wait in a loop in open_and_lock_tables(),
 
250
        trying to lock one or more of our tables.
 
251
 
 
252
        If they wait for the locks in thr_multi_lock(), their lock
 
253
        request is aborted. They loop in open_and_lock_tables() and
 
254
        enter open_table(). Here they notice the table is refreshed and
 
255
        wait for COND_refresh. Then they loop again in
 
256
        openTablesLock() and this time open_table() succeeds. At
 
257
        this moment, if we (the FLUSH TABLES thread) are scheduled and
 
258
        on another FLUSH TABLES enter close_cached_tables(), they could
 
259
        awake while we sleep below, waiting for others threads (us) to
 
260
        close their open tables. If this happens, the other threads
 
261
        would find the tables unlocked. They would get the locks, one
 
262
        after the other, and could do their destructive work. This is an
 
263
        issue if we have LOCK TABLES in effect.
 
264
 
 
265
        The problem is that the other threads passed all checks in
 
266
        open_table() before we refresh the table.
 
267
 
 
268
        The fix for this problem is to set some_tables_deleted for all
 
269
        threads with open tables. These threads can still get their
 
270
        locks, but will immediately release them again after checking
 
271
        this variable. They will then loop in openTablesLock()
 
272
        again. There they will wait until we update all tables version
 
273
        below.
 
274
 
 
275
        Setting some_tables_deleted is done by remove_table_from_cache()
 
276
        in the other branch.
 
277
 
 
278
        In other words (reviewer suggestion): You need this setting of
 
279
        some_tables_deleted for the case when table was opened and all
 
280
        related checks were passed before incrementing refresh_version
 
281
        (which you already have) but attempt to lock the table happened
 
282
        after the call to Session::close_old_data_files() i.e. after removal of
 
283
        current thread locks.
 
284
      */
 
285
      for (uint32_t idx=0 ; idx < open_cache.records ; idx++)
 
286
      {
 
287
        Table *table=(Table*) hash_element(&open_cache,idx);
 
288
        if (table->in_use)
 
289
          table->in_use->some_tables_deleted= false;
 
290
      }
 
291
    }
 
292
  }
 
293
  else
 
294
  {
 
295
    bool found= false;
 
296
    for (TableList *table= tables; table; table= table->next_local)
 
297
    {
 
298
      if (remove_table_from_cache(session, table->db, table->table_name,
 
299
                                  RTFC_OWNED_BY_Session_FLAG))
 
300
        found= true;
 
301
    }
 
302
    if (!found)
 
303
      wait_for_refresh= false;                  // Nothing to wait for
 
304
  }
 
305
 
 
306
  if (wait_for_refresh)
 
307
  {
 
308
    /*
 
309
      If there is any table that has a lower refresh_version, wait until
 
310
      this is closed (or this thread is killed) before returning
 
311
    */
 
312
    session->mysys_var->current_mutex= &LOCK_open;
 
313
    session->mysys_var->current_cond= &COND_refresh;
 
314
    session->set_proc_info("Flushing tables");
 
315
 
 
316
    session->close_old_data_files();
 
317
 
 
318
    bool found= true;
 
319
    /* Wait until all threads has closed all the tables we had locked */
 
320
    while (found && ! session->killed)
 
321
    {
 
322
      found= false;
 
323
      for (uint32_t idx=0 ; idx < open_cache.records ; idx++)
 
324
      {
 
325
        Table *table=(Table*) hash_element(&open_cache,idx);
 
326
        /* Avoid a self-deadlock. */
 
327
        if (table->in_use == session)
 
328
          continue;
184
329
        /*
185
 
          Other threads could wait in a loop in open_and_lock_tables(),
186
 
          trying to lock one or more of our tables.
187
 
 
188
 
          If they wait for the locks in thr_multi_lock(), their lock
189
 
          request is aborted. They loop in open_and_lock_tables() and
190
 
          enter open_table(). Here they notice the table is refreshed and
191
 
          wait for COND_refresh. Then they loop again in
192
 
          openTablesLock() and this time open_table() succeeds. At
193
 
          this moment, if we (the FLUSH TABLES thread) are scheduled and
194
 
          on another FLUSH TABLES enter close_cached_tables(), they could
195
 
          awake while we sleep below, waiting for others threads (us) to
196
 
          close their open tables. If this happens, the other threads
197
 
          would find the tables unlocked. They would get the locks, one
198
 
          after the other, and could do their destructive work. This is an
199
 
          issue if we have LOCK TABLES in effect.
200
 
 
201
 
          The problem is that the other threads passed all checks in
202
 
          open_table() before we refresh the table.
203
 
 
204
 
          The fix for this problem is to set some_tables_deleted for all
205
 
          threads with open tables. These threads can still get their
206
 
          locks, but will immediately release them again after checking
207
 
          this variable. They will then loop in openTablesLock()
208
 
          again. There they will wait until we update all tables version
209
 
          below.
210
 
 
211
 
          Setting some_tables_deleted is done by table::Cache::singleton().removeTable()
212
 
          in the other branch.
213
 
 
214
 
          In other words (reviewer suggestion): You need this setting of
215
 
          some_tables_deleted for the case when table was opened and all
216
 
          related checks were passed before incrementing refresh_version
217
 
          (which you already have) but attempt to lock the table happened
218
 
          after the call to Session::close_old_data_files() i.e. after removal of
219
 
          current thread locks.
 
330
          Note that we wait here only for tables which are actually open, and
 
331
          not for placeholders with Table::open_placeholder set. Waiting for
 
332
          latter will cause deadlock in the following scenario, for example:
 
333
 
 
334
conn1: lock table t1 write;
 
335
conn2: lock table t2 write;
 
336
conn1: flush tables;
 
337
conn2: flush tables;
 
338
 
 
339
It also does not make sense to wait for those of placeholders that
 
340
are employed by CREATE TABLE as in this case table simply does not
 
341
exist yet.
220
342
        */
221
 
        for (table::CacheMap::const_iterator iter= table::getCache().begin();
222
 
             iter != table::getCache().end();
223
 
             iter++)
224
 
        {
225
 
          Table *table= (*iter).second;
226
 
          if (table->in_use)
227
 
            table->in_use->some_tables_deleted= false;
228
 
        }
229
 
      }
230
 
    }
231
 
    else
232
 
    {
233
 
      bool found= false;
234
 
      for (TableList *table= tables; table; table= table->next_local)
235
 
      {
236
 
        TableIdentifier identifier(table->getSchemaName(), table->getTableName());
237
 
        if (table::Cache::singleton().removeTable(session, identifier,
238
 
                                    RTFC_OWNED_BY_Session_FLAG))
 
343
        if (table->needs_reopen_or_name_lock() && (table->db_stat ||
 
344
                                                   (table->open_placeholder && wait_for_placeholders)))
239
345
        {
240
346
          found= true;
 
347
          pthread_cond_wait(&COND_refresh,&LOCK_open);
 
348
          break;
241
349
        }
242
350
      }
243
 
      if (!found)
244
 
        wait_for_refresh= false;                        // Nothing to wait for
245
351
    }
 
352
    /*
 
353
      No other thread has the locked tables open; reopen them and get the
 
354
      old locks. This should always succeed (unless some external process
 
355
      has removed the tables)
 
356
    */
 
357
    result= session->reopen_tables(true, true);
246
358
 
247
 
    if (wait_for_refresh)
 
359
    /* Set version for table */
 
360
    for (Table *table= session->open_tables; table ; table= table->next)
248
361
    {
249
362
      /*
250
 
        If there is any table that has a lower refresh_version, wait until
251
 
        this is closed (or this thread is killed) before returning
252
 
      */
253
 
      session->mysys_var->current_mutex= &table::Cache::singleton().mutex();
254
 
      session->mysys_var->current_cond= &COND_refresh;
255
 
      session->set_proc_info("Flushing tables");
256
 
 
257
 
      session->close_old_data_files();
258
 
 
259
 
      bool found= true;
260
 
      /* Wait until all threads has closed all the tables we had locked */
261
 
      while (found && ! session->getKilled())
262
 
      {
263
 
        found= false;
264
 
        for (table::CacheMap::const_iterator iter= table::getCache().begin();
265
 
             iter != table::getCache().end();
266
 
             iter++)
267
 
        {
268
 
          Table *table= (*iter).second;
269
 
          /* Avoid a self-deadlock. */
270
 
          if (table->in_use == session)
271
 
            continue;
272
 
          /*
273
 
            Note that we wait here only for tables which are actually open, and
274
 
            not for placeholders with Table::open_placeholder set. Waiting for
275
 
            latter will cause deadlock in the following scenario, for example:
276
 
 
277
 
            conn1-> lock table t1 write;
278
 
            conn2-> lock table t2 write;
279
 
            conn1-> flush tables;
280
 
            conn2-> flush tables;
281
 
 
282
 
            It also does not make sense to wait for those of placeholders that
283
 
            are employed by CREATE TABLE as in this case table simply does not
284
 
            exist yet.
285
 
          */
286
 
          if (table->needs_reopen_or_name_lock() && (table->db_stat ||
287
 
                                                     (table->open_placeholder && wait_for_placeholders)))
288
 
          {
289
 
            found= true;
290
 
            boost_unique_lock_t scoped(table::Cache::singleton().mutex(), boost::adopt_lock_t());
291
 
            COND_refresh.wait(scoped);
292
 
            scoped.release();
293
 
            break;
294
 
          }
295
 
        }
296
 
      }
297
 
      /*
298
 
        No other thread has the locked tables open; reopen them and get the
299
 
        old locks. This should always succeed (unless some external process
300
 
        has removed the tables)
301
 
      */
302
 
      result= session->reopen_tables(true, true);
303
 
 
304
 
      /* Set version for table */
305
 
      for (Table *table= session->open_tables; table ; table= table->getNext())
306
 
      {
307
 
        /*
308
 
          Preserve the version (0) of write locked tables so that a impending
309
 
          global read lock won't sneak in.
310
 
        */
311
 
        if (table->reginfo.lock_type < TL_WRITE_ALLOW_WRITE)
312
 
          table->getMutableShare()->refreshVersion();
313
 
      }
 
363
        Preserve the version (0) of write locked tables so that a impending
 
364
        global read lock won't sneak in.
 
365
      */
 
366
      if (table->reginfo.lock_type < TL_WRITE_ALLOW_WRITE)
 
367
        table->s->version= refresh_version;
314
368
    }
315
 
 
316
 
    table::Cache::singleton().mutex().unlock();
317
369
  }
318
370
 
 
371
  pthread_mutex_unlock(&LOCK_open);
 
372
 
319
373
  if (wait_for_refresh)
320
374
  {
321
 
    boost_unique_lock_t scopedLock(session->mysys_var->mutex);
 
375
    pthread_mutex_lock(&session->mysys_var->mutex);
322
376
    session->mysys_var->current_mutex= 0;
323
377
    session->mysys_var->current_cond= 0;
324
378
    session->set_proc_info(0);
 
379
    pthread_mutex_unlock(&session->mysys_var->mutex);
325
380
  }
326
381
 
327
382
  return result;
335
390
bool Session::free_cached_table()
336
391
{
337
392
  bool found_old_table= false;
338
 
  table::Concurrent *table= static_cast<table::Concurrent *>(open_tables);
 
393
  Table *table= open_tables;
339
394
 
340
 
  safe_mutex_assert_owner(table::Cache::singleton().mutex().native_handle());
 
395
  safe_mutex_assert_owner(&LOCK_open);
341
396
  assert(table->key_read == 0);
342
397
  assert(!table->cursor || table->cursor->inited == Cursor::NONE);
343
398
 
344
 
  open_tables= table->getNext();
 
399
  open_tables= table->next;
345
400
 
346
401
  if (table->needs_reopen_or_name_lock() ||
347
402
      version != refresh_version || !table->db_stat)
348
403
  {
349
 
    table::remove_table(table);
 
404
    hash_delete(&open_cache,(unsigned char*) table);
350
405
    found_old_table= true;
351
406
  }
352
407
  else
355
410
      Open placeholders have Table::db_stat set to 0, so they should be
356
411
      handled by the first alternative.
357
412
    */
358
 
    assert(not table->open_placeholder);
 
413
    assert(!table->open_placeholder);
359
414
 
360
415
    /* Free memory and reset for next loop */
361
416
    table->cursor->ha_reset();
362
 
    table->in_use= NULL;
 
417
    table->in_use= false;
363
418
 
364
 
    table::getUnused().link(table);
 
419
    if (unused_tables)
 
420
    {
 
421
      table->next= unused_tables;               /* Link in last */
 
422
      table->prev= unused_tables->prev;
 
423
      unused_tables->prev= table;
 
424
      table->prev->next= table;
 
425
    }
 
426
    else
 
427
      unused_tables= table->next=table->prev=table;
365
428
  }
366
429
 
367
430
  return found_old_table;
380
443
{
381
444
  bool found_old_table= false;
382
445
 
383
 
  safe_mutex_assert_not_owner(table::Cache::singleton().mutex().native_handle());
 
446
  safe_mutex_assert_not_owner(&LOCK_open);
384
447
 
385
 
  boost_unique_lock_t scoped_lock(table::Cache::singleton().mutex()); /* Close all open tables on Session */
 
448
  pthread_mutex_lock(&LOCK_open); /* Close all open tables on Session */
386
449
 
387
450
  while (open_tables)
388
 
  {
389
451
    found_old_table|= free_cached_table();
390
 
  }
391
452
  some_tables_deleted= false;
392
453
 
393
454
  if (found_old_table)
394
455
  {
395
456
    /* Tell threads waiting for refresh that something has happened */
396
 
    locking::broadcast_refresh();
 
457
    broadcast_refresh();
397
458
  }
 
459
 
 
460
  pthread_mutex_unlock(&LOCK_open);
398
461
}
399
462
 
400
463
/*
422
485
{
423
486
  for (; table; table= table->*link )
424
487
  {
425
 
    if ((table->table == 0 || table->table->getShare()->getType() == message::Table::STANDARD) &&
426
 
        strcasecmp(table->getSchemaName(), db_name) == 0 &&
427
 
        strcasecmp(table->getTableName(), table_name) == 0)
 
488
    if ((table->table == 0 || table->table->s->tmp_table == NO_TMP_TABLE) &&
 
489
        strcmp(table->db, db_name) == 0 &&
 
490
        strcmp(table->table_name, table_name) == 0)
428
491
      break;
429
492
  }
430
493
  return table;
486
549
  if (table->table)
487
550
  {
488
551
    /* temporary table is always unique */
489
 
    if (table->table && table->table->getShare()->getType() != message::Table::STANDARD)
 
552
    if (table->table && table->table->s->tmp_table != NO_TMP_TABLE)
490
553
      return 0;
491
554
    table= table->find_underlying_table(table->table);
492
555
    /*
495
558
    */
496
559
    assert(table);
497
560
  }
498
 
  d_name= table->getSchemaName();
499
 
  t_name= table->getTableName();
 
561
  d_name= table->db;
 
562
  t_name= table->table_name;
500
563
  t_alias= table->alias;
501
564
 
502
565
  for (;;)
517
580
}
518
581
 
519
582
 
520
 
void Open_tables_state::doGetTableNames(const SchemaIdentifier &schema_identifier,
521
 
                                        std::set<std::string>& set_of_names)
522
 
{
523
 
  for (Table *table= getTemporaryTables() ; table ; table= table->getNext())
524
 
  {
525
 
    if (schema_identifier.compare(table->getShare()->getSchemaName()))
526
 
    {
527
 
      set_of_names.insert(table->getShare()->getTableName());
528
 
    }
529
 
  }
530
 
}
531
 
 
532
 
void Open_tables_state::doGetTableNames(CachedDirectory &,
533
 
                                        const SchemaIdentifier &schema_identifier,
534
 
                                        std::set<std::string> &set_of_names)
535
 
{
536
 
  doGetTableNames(schema_identifier, set_of_names);
537
 
}
538
 
 
539
 
void Open_tables_state::doGetTableIdentifiers(const SchemaIdentifier &schema_identifier,
540
 
                                              TableIdentifier::vector &set_of_identifiers)
541
 
{
542
 
  for (Table *table= getTemporaryTables() ; table ; table= table->getNext())
543
 
  {
544
 
    if (schema_identifier.compare(table->getShare()->getSchemaName()))
545
 
    {
546
 
      set_of_identifiers.push_back(TableIdentifier(table->getShare()->getSchemaName(),
547
 
                                                   table->getShare()->getTableName(),
548
 
                                                   table->getShare()->getPath()));
549
 
    }
550
 
  }
551
 
}
552
 
 
553
 
void Open_tables_state::doGetTableIdentifiers(CachedDirectory &,
554
 
                                              const SchemaIdentifier &schema_identifier,
555
 
                                              TableIdentifier::vector &set_of_identifiers)
556
 
{
557
 
  doGetTableIdentifiers(schema_identifier, set_of_identifiers);
558
 
}
559
 
 
560
 
bool Open_tables_state::doDoesTableExist(const TableIdentifier &identifier)
561
 
{
562
 
  for (Table *table= getTemporaryTables() ; table ; table= table->getNext())
563
 
  {
564
 
    if (table->getShare()->getType() == message::Table::TEMPORARY)
565
 
    {
566
 
      if (identifier.getKey() == table->getShare()->getCacheKey())
567
 
      {
568
 
        return true;
569
 
      }
570
 
    }
571
 
  }
572
 
 
573
 
  return false;
574
 
}
575
 
 
576
 
int Open_tables_state::doGetTableDefinition(const TableIdentifier &identifier,
577
 
                                  message::Table &table_proto)
578
 
{
579
 
  for (Table *table= getTemporaryTables() ; table ; table= table->getNext())
580
 
  {
581
 
    if (table->getShare()->getType() == message::Table::TEMPORARY)
582
 
    {
583
 
      if (identifier.getKey() == table->getShare()->getCacheKey())
584
 
      {
585
 
        table_proto.CopyFrom(*(table->getShare()->getTableProto()));
586
 
 
587
 
        return EEXIST;
 
583
void Session::doGetTableNames(CachedDirectory &,
 
584
                              const std::string& db_name,
 
585
                              std::set<std::string>& set_of_names)
 
586
{
 
587
  for (Table *table= temporary_tables ; table ; table= table->next)
 
588
  {
 
589
    if (not db_name.compare(table->s->db.str))
 
590
    {
 
591
      set_of_names.insert(table->s->table_name.str);
 
592
    }
 
593
  }
 
594
}
 
595
 
 
596
int Session::doGetTableDefinition(const char *,
 
597
                                  const char *db_arg,
 
598
                                  const char *table_name_arg,
 
599
                                  const bool ,
 
600
                                  message::Table *table_proto)
 
601
{
 
602
  for (Table *table= temporary_tables ; table ; table= table->next)
 
603
  {
 
604
    if (table->s->tmp_table == TEMP_TABLE)
 
605
    {
 
606
      if (not strcmp(db_arg, table->s->db.str))
 
607
      {
 
608
        if (not strcmp(table_name_arg, table->s->table_name.str))
 
609
        {
 
610
          if (table_proto)
 
611
            table_proto->CopyFrom(*(table->s->getTableProto()));
 
612
 
 
613
          return EEXIST;
 
614
        }
588
615
      }
589
616
    }
590
617
  }
592
619
  return ENOENT;
593
620
}
594
621
 
595
 
Table *Open_tables_state::find_temporary_table(const TableIdentifier &identifier)
 
622
Table *Session::find_temporary_table(const char *new_db, const char *table_name)
596
623
{
597
 
  for (Table *table= temporary_tables ; table ; table= table->getNext())
 
624
  char  key[MAX_DBKEY_LENGTH];
 
625
  uint  key_length;
 
626
  Table *table;
 
627
 
 
628
  key_length= TableShare::createKey(key, new_db, table_name);
 
629
 
 
630
  for (table= temporary_tables ; table ; table= table->next)
598
631
  {
599
 
    if (identifier.getKey() == table->getShare()->getCacheKey())
 
632
    if (table->s->table_cache_key.length == key_length &&
 
633
        !memcmp(table->s->table_cache_key.str, key, key_length))
600
634
      return table;
601
635
  }
602
 
 
603
636
  return NULL;                               // Not a temporary table
604
637
}
605
638
 
 
639
Table *Session::find_temporary_table(TableList *table_list)
 
640
{
 
641
  return find_temporary_table(table_list->db, table_list->table_name);
 
642
}
 
643
 
606
644
 
607
645
/**
608
646
  Drop a temporary table.
630
668
  @retval -1  the table is in use by a outer query
631
669
*/
632
670
 
633
 
int Open_tables_state::drop_temporary_table(const drizzled::TableIdentifier &identifier)
 
671
int Session::drop_temporary_table(TableList *table_list)
634
672
{
635
673
  Table *table;
636
674
 
637
 
  if (not (table= find_temporary_table(identifier)))
 
675
  if (!(table= find_temporary_table(table_list)))
638
676
    return 1;
639
677
 
640
678
  /* Table might be in use by some outer statement. */
641
 
  if (table->query_id && table->query_id != getQueryId())
 
679
  if (table->query_id && table->query_id != query_id)
642
680
  {
643
 
    my_error(ER_CANT_REOPEN_TABLE, MYF(0), table->getAlias());
 
681
    my_error(ER_CANT_REOPEN_TABLE, MYF(0), table->alias);
644
682
    return -1;
645
683
  }
646
684
 
650
688
}
651
689
 
652
690
 
 
691
/* move table first in unused links */
 
692
 
 
693
static void relink_unused(Table *table)
 
694
{
 
695
  if (table != unused_tables)
 
696
  {
 
697
    table->prev->next=table->next;              /* Remove from unused list */
 
698
    table->next->prev=table->prev;
 
699
    table->next=unused_tables;                  /* Link in unused tables */
 
700
    table->prev=unused_tables->prev;
 
701
    unused_tables->prev->next=table;
 
702
    unused_tables->prev=table;
 
703
    unused_tables=table;
 
704
  }
 
705
}
 
706
 
 
707
 
653
708
/**
654
709
  Remove all instances of table from thread's open list and
655
710
  table cache.
656
711
 
657
712
  @param  session     Thread context
658
713
  @param  find    Table to remove
659
 
 
660
 
  @note because we risk the chance of deleting the share, we can't assume that it will exist past, this should be modified once we can use a TableShare::shared_ptr here.
661
714
*/
662
715
 
663
716
void Session::unlink_open_table(Table *find)
664
717
{
665
 
  const TableIdentifier::Key find_key(find->getShare()->getCacheKey());
666
 
  Table **prev;
667
 
  safe_mutex_assert_owner(table::Cache::singleton().mutex().native_handle());
668
 
 
 
718
  char key[MAX_DBKEY_LENGTH];
 
719
  uint32_t key_length= find->s->table_cache_key.length;
 
720
  Table *list, **prev;
 
721
 
 
722
  safe_mutex_assert_owner(&LOCK_open);
 
723
 
 
724
  memcpy(key, find->s->table_cache_key.str, key_length);
669
725
  /*
670
 
    Note that we need to hold table::Cache::singleton().mutex() while changing the
 
726
    Note that we need to hold LOCK_open while changing the
671
727
    open_tables list. Another thread may work on it.
672
 
    (See: table::Cache::singleton().removeTable(), mysql_wait_completed_table())
 
728
    (See: remove_table_from_cache(), mysql_wait_completed_table())
673
729
    Closing a MERGE child before the parent would be fatal if the
674
730
    other thread tries to abort the MERGE lock in between.
675
731
  */
676
732
  for (prev= &open_tables; *prev; )
677
733
  {
678
 
    Table *list= *prev;
 
734
    list= *prev;
679
735
 
680
 
    if (list->getShare()->getCacheKey() == find_key)
 
736
    if (list->s->table_cache_key.length == key_length &&
 
737
        !memcmp(list->s->table_cache_key.str, key, key_length))
681
738
    {
682
739
      /* Remove table from open_tables list. */
683
 
      *prev= list->getNext();
684
 
 
 
740
      *prev= list->next;
685
741
      /* Close table. */
686
 
      table::remove_table(static_cast<table::Concurrent *>(list));
 
742
      hash_delete(&open_cache,(unsigned char*) list); // Close table
687
743
    }
688
744
    else
689
745
    {
690
746
      /* Step to next entry in open_tables list. */
691
 
      prev= list->getNextPtr();
 
747
      prev= &list->next;
692
748
    }
693
749
  }
694
750
 
695
751
  // Notify any 'refresh' threads
696
 
  locking::broadcast_refresh();
 
752
  broadcast_refresh();
697
753
}
698
754
 
699
755
 
716
772
  table that was locked with LOCK TABLES.
717
773
*/
718
774
 
719
 
void Session::drop_open_table(Table *table, const TableIdentifier &identifier)
 
775
void Session::drop_open_table(Table *table, const char *db_name,
 
776
                              const char *table_name)
720
777
{
721
 
  if (table->getShare()->getType())
 
778
  if (table->s->tmp_table)
722
779
  {
723
780
    close_temporary_table(table);
724
781
  }
725
782
  else
726
783
  {
727
 
    boost_unique_lock_t scoped_lock(table::Cache::singleton().mutex()); /* Close and drop a table (AUX routine) */
 
784
    pthread_mutex_lock(&LOCK_open); /* Close and drop a table (AUX routine) */
728
785
    /*
729
786
      unlink_open_table() also tells threads waiting for refresh or close
730
787
      that something has happened.
731
788
    */
732
789
    unlink_open_table(table);
733
 
    plugin::StorageEngine::dropTable(*this, identifier);
 
790
    TableIdentifier identifier(db_name, table_name, NO_TMP_TABLE);
 
791
    quick_rm_table(*this, identifier);
 
792
    pthread_mutex_unlock(&LOCK_open);
734
793
  }
735
794
}
736
795
 
746
805
  cond  Condition to wait for
747
806
*/
748
807
 
749
 
void Session::wait_for_condition(boost::mutex &mutex, boost::condition_variable_any &cond)
 
808
void Session::wait_for_condition(pthread_mutex_t *mutex, pthread_cond_t *cond)
750
809
{
751
810
  /* Wait until the current table is up to date */
752
811
  const char *saved_proc_info;
753
 
  mysys_var->current_mutex= &mutex;
754
 
  mysys_var->current_cond= &cond;
 
812
  mysys_var->current_mutex= mutex;
 
813
  mysys_var->current_cond= cond;
755
814
  saved_proc_info= get_proc_info();
756
815
  set_proc_info("Waiting for table");
757
 
  {
758
 
    /*
759
 
      We must unlock mutex first to avoid deadlock becasue conditions are
760
 
      sent to this thread by doing locks in the following order:
761
 
      lock(mysys_var->mutex)
762
 
      lock(mysys_var->current_mutex)
763
 
 
764
 
      One by effect of this that one can only use wait_for_condition with
765
 
      condition variables that are guranteed to not disapper (freed) even if this
766
 
      mutex is unlocked
767
 
    */
768
 
    boost_unique_lock_t scopedLock(mutex, boost::adopt_lock_t());
769
 
    if (not getKilled())
770
 
    {
771
 
      cond.wait(scopedLock);
772
 
    }
773
 
  }
774
 
  boost_unique_lock_t mysys_scopedLock(mysys_var->mutex);
 
816
  if (!killed)
 
817
    (void) pthread_cond_wait(cond, mutex);
 
818
 
 
819
  /*
 
820
    We must unlock mutex first to avoid deadlock becasue conditions are
 
821
    sent to this thread by doing locks in the following order:
 
822
    lock(mysys_var->mutex)
 
823
    lock(mysys_var->current_mutex)
 
824
 
 
825
    One by effect of this that one can only use wait_for_condition with
 
826
    condition variables that are guranteed to not disapper (freed) even if this
 
827
    mutex is unlocked
 
828
  */
 
829
 
 
830
  pthread_mutex_unlock(mutex);
 
831
  pthread_mutex_lock(&mysys_var->mutex);
775
832
  mysys_var->current_mutex= 0;
776
833
  mysys_var->current_cond= 0;
777
834
  set_proc_info(saved_proc_info);
 
835
  pthread_mutex_unlock(&mysys_var->mutex);
 
836
}
 
837
 
 
838
 
 
839
/*
 
840
  Open table which is already name-locked by this thread.
 
841
 
 
842
  SYNOPSIS
 
843
  reopen_name_locked_table()
 
844
  session         Thread handle
 
845
  table_list  TableList object for table to be open, TableList::table
 
846
  member should point to Table object which was used for
 
847
  name-locking.
 
848
  link_in     true  - if Table object for table to be opened should be
 
849
  linked into Session::open_tables list.
 
850
  false - placeholder used for name-locking is already in
 
851
  this list so we only need to preserve Table::next
 
852
  pointer.
 
853
 
 
854
  NOTE
 
855
  This function assumes that its caller already acquired LOCK_open mutex.
 
856
 
 
857
  RETURN VALUE
 
858
  false - Success
 
859
  true  - Error
 
860
*/
 
861
 
 
862
bool Session::reopen_name_locked_table(TableList* table_list, bool link_in)
 
863
{
 
864
  Table *table= table_list->table;
 
865
  TableShare *share;
 
866
  char *table_name= table_list->table_name;
 
867
  Table orig_table;
 
868
 
 
869
  safe_mutex_assert_owner(&LOCK_open);
 
870
 
 
871
  if (killed || !table)
 
872
    return true;
 
873
 
 
874
  orig_table= *table;
 
875
 
 
876
  if (open_unireg_entry(this, table, table_list, table_name,
 
877
                        table->s->table_cache_key.str,
 
878
                        table->s->table_cache_key.length))
 
879
  {
 
880
    table->intern_close_table();
 
881
    /*
 
882
      If there was an error during opening of table (for example if it
 
883
      does not exist) '*table' object can be wiped out. To be able
 
884
      properly release name-lock in this case we should restore this
 
885
      object to its original state.
 
886
    */
 
887
    *table= orig_table;
 
888
    return true;
 
889
  }
 
890
 
 
891
  share= table->s;
 
892
  /*
 
893
    We want to prevent other connections from opening this table until end
 
894
    of statement as it is likely that modifications of table's metadata are
 
895
    not yet finished (for example CREATE TRIGGER have to change .TRG cursor,
 
896
    or we might want to drop table if CREATE TABLE ... SELECT fails).
 
897
    This also allows us to assume that no other connection will sneak in
 
898
    before we will get table-level lock on this table.
 
899
  */
 
900
  share->version=0;
 
901
  table->in_use = this;
 
902
 
 
903
  if (link_in)
 
904
  {
 
905
    table->next= open_tables;
 
906
    open_tables= table;
 
907
  }
 
908
  else
 
909
  {
 
910
    /*
 
911
      Table object should be already in Session::open_tables list so we just
 
912
      need to set Table::next correctly.
 
913
    */
 
914
    table->next= orig_table.next;
 
915
  }
 
916
 
 
917
  table->tablenr= current_tablenr++;
 
918
  table->used_fields= 0;
 
919
  table->const_table= 0;
 
920
  table->null_row= false;
 
921
  table->maybe_null= false;
 
922
  table->force_index= false;
 
923
  table->status= STATUS_NO_RECORD;
 
924
 
 
925
  return false;
778
926
}
779
927
 
780
928
 
791
939
  case of failure.
792
940
*/
793
941
 
794
 
table::Placeholder *Session::table_cache_insert_placeholder(const drizzled::TableIdentifier &arg)
 
942
Table *Session::table_cache_insert_placeholder(const char *key, uint32_t key_length)
795
943
{
796
 
  safe_mutex_assert_owner(table::Cache::singleton().mutex().native_handle());
 
944
  Table *table;
 
945
  TableShare *share;
 
946
  char *key_buff;
 
947
 
 
948
  safe_mutex_assert_owner(&LOCK_open);
797
949
 
798
950
  /*
799
951
    Create a table entry with the right key and with an old refresh version
 
952
    Note that we must use multi_malloc() here as this is freed by the
 
953
    table cache
800
954
  */
801
 
  TableIdentifier identifier(arg.getSchemaName(), arg.getTableName(), message::Table::INTERNAL);
802
 
  table::Placeholder *table= new table::Placeholder(this, identifier);
803
 
 
804
 
  if (not table::Cache::singleton().insert(table))
 
955
  if (! memory::multi_malloc(true,
 
956
                             &table, sizeof(*table),
 
957
                             &share, sizeof(*share),
 
958
                             &key_buff, key_length,
 
959
                             NULL))
 
960
    return NULL;
 
961
 
 
962
  table->s= share;
 
963
  share->set_table_cache_key(key_buff, key, key_length);
 
964
  share->tmp_table= INTERNAL_TMP_TABLE;  // for intern_close_table
 
965
  table->in_use= this;
 
966
  table->locked_by_name=1;
 
967
 
 
968
  if (my_hash_insert(&open_cache, (unsigned char*)table))
805
969
  {
806
 
    delete table;
807
 
 
 
970
    free((unsigned char*) table);
808
971
    return NULL;
809
972
  }
810
973
 
833
996
  @retval  true   Error occured (OOM)
834
997
  @retval  false  Success. 'table' parameter set according to above rules.
835
998
*/
836
 
bool Session::lock_table_name_if_not_cached(const TableIdentifier &identifier, Table **table)
 
999
 
 
1000
bool Session::lock_table_name_if_not_cached(const char *new_db,
 
1001
                                            const char *table_name, Table **table)
837
1002
{
838
 
  const TableIdentifier::Key &key(identifier.getKey());
839
 
 
840
 
  boost_unique_lock_t scope_lock(table::Cache::singleton().mutex()); /* Obtain a name lock even though table is not in cache (like for create table)  */
841
 
 
842
 
  table::CacheMap::iterator iter;
843
 
 
844
 
  iter= table::getCache().find(key);
845
 
 
846
 
  if (iter != table::getCache().end())
 
1003
  char key[MAX_DBKEY_LENGTH];
 
1004
  char *key_pos= key;
 
1005
  uint32_t key_length;
 
1006
 
 
1007
  key_pos= strcpy(key_pos, new_db) + strlen(new_db);
 
1008
  key_pos= strcpy(key_pos+1, table_name) + strlen(table_name);
 
1009
  key_length= (uint32_t) (key_pos-key)+1;
 
1010
 
 
1011
  pthread_mutex_lock(&LOCK_open); /* Obtain a name lock even though table is not in cache (like for create table)  */
 
1012
 
 
1013
  if (hash_search(&open_cache, (unsigned char *)key, key_length))
847
1014
  {
 
1015
    pthread_mutex_unlock(&LOCK_open);
848
1016
    *table= 0;
849
1017
    return false;
850
1018
  }
851
 
 
852
 
  if (not (*table= table_cache_insert_placeholder(identifier)))
 
1019
  if (!(*table= table_cache_insert_placeholder(key, key_length)))
853
1020
  {
 
1021
    pthread_mutex_unlock(&LOCK_open);
854
1022
    return true;
855
1023
  }
856
1024
  (*table)->open_placeholder= true;
857
 
  (*table)->setNext(open_tables);
 
1025
  (*table)->next= open_tables;
858
1026
  open_tables= *table;
 
1027
  pthread_mutex_unlock(&LOCK_open);
859
1028
 
860
1029
  return false;
861
1030
}
896
1065
Table *Session::openTable(TableList *table_list, bool *refresh, uint32_t flags)
897
1066
{
898
1067
  Table *table;
 
1068
  char key[MAX_DBKEY_LENGTH];
 
1069
  unsigned int key_length;
899
1070
  const char *alias= table_list->alias;
 
1071
  HASH_SEARCH_STATE state;
900
1072
 
901
1073
  /* Parsing of partitioning information from .frm needs session->lex set up. */
902
1074
  assert(lex->is_lex_started);
909
1081
  if (check_stack_overrun(this, STACK_MIN_SIZE_FOR_OPEN, (unsigned char *)&alias))
910
1082
    return NULL;
911
1083
 
912
 
  if (getKilled())
 
1084
  if (killed)
913
1085
    return NULL;
914
1086
 
915
 
  TableIdentifier identifier(table_list->getSchemaName(), table_list->getTableName());
916
 
  const TableIdentifier::Key &key(identifier.getKey());
917
 
  table::CacheRange ppp;
 
1087
  key_length= table_list->create_table_def_key(key);
918
1088
 
919
1089
  /*
920
1090
    Unless requested otherwise, try to resolve this table in the list
923
1093
    same name. This block implements the behaviour.
924
1094
    TODO -> move this block into a separate function.
925
1095
  */
926
 
  bool reset= false;
927
 
  for (table= getTemporaryTables(); table ; table=table->getNext())
 
1096
  for (table= temporary_tables; table ; table=table->next)
928
1097
  {
929
 
    if (table->getShare()->getCacheKey() == key)
 
1098
    if (table->s->table_cache_key.length == key_length && !memcmp(table->s->table_cache_key.str, key, key_length))
930
1099
    {
931
1100
      /*
932
1101
        We're trying to use the same temporary table twice in a query.
936
1105
      */
937
1106
      if (table->query_id)
938
1107
      {
939
 
        my_error(ER_CANT_REOPEN_TABLE, MYF(0), table->getAlias());
 
1108
        my_error(ER_CANT_REOPEN_TABLE, MYF(0), table->alias);
940
1109
        return NULL;
941
1110
      }
942
1111
      table->query_id= getQueryId();
943
 
      reset= true;
944
 
      break;
945
 
    }
946
 
  }
947
 
 
948
 
  if (not reset)
949
 
  {
950
 
    if (flags & DRIZZLE_OPEN_TEMPORARY_ONLY)
951
 
    {
952
 
      my_error(ER_NO_SUCH_TABLE, MYF(0), table_list->getSchemaName(), table_list->getTableName());
953
 
      return NULL;
954
 
    }
955
 
 
 
1112
      goto reset;
 
1113
    }
 
1114
  }
 
1115
 
 
1116
  if (flags & DRIZZLE_OPEN_TEMPORARY_ONLY)
 
1117
  {
 
1118
    my_error(ER_NO_SUCH_TABLE, MYF(0), table_list->db, table_list->table_name);
 
1119
    return NULL;
 
1120
  }
 
1121
 
 
1122
  /*
 
1123
    If it's the first table from a list of tables used in a query,
 
1124
    remember refresh_version (the version of open_cache state).
 
1125
    If the version changes while we're opening the remaining tables,
 
1126
    we will have to back off, close all the tables opened-so-far,
 
1127
    and try to reopen them.
 
1128
 
 
1129
    Note-> refresh_version is currently changed only during FLUSH TABLES.
 
1130
  */
 
1131
  if (!open_tables)
 
1132
    version= refresh_version;
 
1133
  else if ((version != refresh_version) &&
 
1134
           ! (flags & DRIZZLE_LOCK_IGNORE_FLUSH))
 
1135
  {
 
1136
    /* Someone did a refresh while thread was opening tables */
 
1137
    if (refresh)
 
1138
      *refresh= true;
 
1139
 
 
1140
    return NULL;
 
1141
  }
 
1142
 
 
1143
  /*
 
1144
    Before we test the global cache, we test our local session cache.
 
1145
  */
 
1146
  if (cached_table)
 
1147
  {
 
1148
    assert(false); /* Not implemented yet */
 
1149
  }
 
1150
 
 
1151
  /*
 
1152
    Non pre-locked/LOCK TABLES mode, and the table is not temporary:
 
1153
    this is the normal use case.
 
1154
    Now we should:
 
1155
    - try to find the table in the table cache.
 
1156
    - if one of the discovered Table instances is name-locked
 
1157
    (table->s->version == 0) back off -- we have to wait
 
1158
    until no one holds a name lock on the table.
 
1159
    - if there is no such Table in the name cache, read the table definition
 
1160
    and insert it into the cache.
 
1161
    We perform all of the above under LOCK_open which currently protects
 
1162
    the open cache (also known as table cache) and table definitions stored
 
1163
    on disk.
 
1164
  */
 
1165
 
 
1166
  pthread_mutex_lock(&LOCK_open); /* Lock for FLUSH TABLES for open table */
 
1167
 
 
1168
  /*
 
1169
    Actually try to find the table in the open_cache.
 
1170
    The cache may contain several "Table" instances for the same
 
1171
    physical table. The instances that are currently "in use" by
 
1172
    some thread have their "in_use" member != NULL.
 
1173
    There is no good reason for having more than one entry in the
 
1174
    hash for the same physical table, except that we use this as
 
1175
    an implicit "pending locks queue" - see
 
1176
    wait_for_locked_table_names for details.
 
1177
  */
 
1178
  for (table= (Table*) hash_first(&open_cache, (unsigned char*) key, key_length,
 
1179
                                  &state);
 
1180
       table && table->in_use ;
 
1181
       table= (Table*) hash_next(&open_cache, (unsigned char*) key, key_length,
 
1182
                                 &state))
 
1183
  {
956
1184
    /*
957
 
      If it's the first table from a list of tables used in a query,
958
 
      remember refresh_version (the version of open_cache state).
959
 
      If the version changes while we're opening the remaining tables,
960
 
      we will have to back off, close all the tables opened-so-far,
961
 
      and try to reopen them.
962
 
 
963
 
      Note-> refresh_version is currently changed only during FLUSH TABLES.
 
1185
      Here we flush tables marked for flush.
 
1186
      Normally, table->s->version contains the value of
 
1187
      refresh_version from the moment when this table was
 
1188
      (re-)opened and added to the cache.
 
1189
      If since then we did (or just started) FLUSH TABLES
 
1190
      statement, refresh_version has been increased.
 
1191
      For "name-locked" Table instances, table->s->version is set
 
1192
      to 0 (see lock_table_name for details).
 
1193
      In case there is a pending FLUSH TABLES or a name lock, we
 
1194
      need to back off and re-start opening tables.
 
1195
      If we do not back off now, we may dead lock in case of lock
 
1196
      order mismatch with some other thread:
 
1197
c1: name lock t1; -- sort of exclusive lock
 
1198
c2: open t2;      -- sort of shared lock
 
1199
c1: name lock t2; -- blocks
 
1200
c2: open t1; -- blocks
964
1201
    */
965
 
    if (!open_tables)
966
 
    {
967
 
      version= refresh_version;
968
 
    }
969
 
    else if ((version != refresh_version) &&
970
 
             ! (flags & DRIZZLE_LOCK_IGNORE_FLUSH))
971
 
    {
972
 
      /* Someone did a refresh while thread was opening tables */
 
1202
    if (table->needs_reopen_or_name_lock())
 
1203
    {
 
1204
      if (flags & DRIZZLE_LOCK_IGNORE_FLUSH)
 
1205
      {
 
1206
        /* Force close at once after usage */
 
1207
        version= table->s->version;
 
1208
        continue;
 
1209
      }
 
1210
 
 
1211
      /* Avoid self-deadlocks by detecting self-dependencies. */
 
1212
      if (table->open_placeholder && table->in_use == this)
 
1213
      {
 
1214
        pthread_mutex_unlock(&LOCK_open);
 
1215
        my_error(ER_UPDATE_TABLE_USED, MYF(0), table->s->table_name.str);
 
1216
        return NULL;
 
1217
      }
 
1218
 
 
1219
      /*
 
1220
        Back off, part 1: mark the table as "unused" for the
 
1221
        purpose of name-locking by setting table->db_stat to 0. Do
 
1222
        that only for the tables in this thread that have an old
 
1223
        table->s->version (this is an optimization (?)).
 
1224
        table->db_stat == 0 signals wait_for_locked_table_names
 
1225
        that the tables in question are not used any more. See
 
1226
        table_is_used call for details.
 
1227
      */
 
1228
      close_old_data_files(false, false);
 
1229
 
 
1230
      /*
 
1231
        Back-off part 2: try to avoid "busy waiting" on the table:
 
1232
        if the table is in use by some other thread, we suspend
 
1233
        and wait till the operation is complete: when any
 
1234
        operation that juggles with table->s->version completes,
 
1235
        it broadcasts COND_refresh condition variable.
 
1236
        If 'old' table we met is in use by current thread we return
 
1237
        without waiting since in this situation it's this thread
 
1238
        which is responsible for broadcasting on COND_refresh
 
1239
        (and this was done already in Session::close_old_data_files()).
 
1240
        Good example of such situation is when we have statement
 
1241
        that needs two instances of table and FLUSH TABLES comes
 
1242
        after we open first instance but before we open second
 
1243
        instance.
 
1244
      */
 
1245
      if (table->in_use != this)
 
1246
      {
 
1247
        /* wait_for_conditionwill unlock LOCK_open for us */
 
1248
        wait_for_condition(&LOCK_open, &COND_refresh);
 
1249
      }
 
1250
      else
 
1251
      {
 
1252
        pthread_mutex_unlock(&LOCK_open);
 
1253
      }
 
1254
      /*
 
1255
        There is a refresh in progress for this table.
 
1256
        Signal the caller that it has to try again.
 
1257
      */
973
1258
      if (refresh)
974
1259
        *refresh= true;
975
 
 
976
1260
      return NULL;
977
1261
    }
978
 
 
979
 
    /*
980
 
      Before we test the global cache, we test our local session cache.
981
 
    */
982
 
    if (cached_table)
983
 
    {
984
 
      assert(false); /* Not implemented yet */
 
1262
  }
 
1263
  if (table)
 
1264
  {
 
1265
    /* Unlink the table from "unused_tables" list. */
 
1266
    if (table == unused_tables)
 
1267
    {  // First unused
 
1268
      unused_tables=unused_tables->next; // Remove from link
 
1269
      if (table == unused_tables)
 
1270
        unused_tables= NULL;
985
1271
    }
986
 
 
987
 
    /*
988
 
      Non pre-locked/LOCK TABLES mode, and the table is not temporary:
989
 
      this is the normal use case.
990
 
      Now we should:
991
 
      - try to find the table in the table cache.
992
 
      - if one of the discovered Table instances is name-locked
993
 
      (table->getShare()->version == 0) back off -- we have to wait
994
 
      until no one holds a name lock on the table.
995
 
      - if there is no such Table in the name cache, read the table definition
996
 
      and insert it into the cache.
997
 
      We perform all of the above under table::Cache::singleton().mutex() which currently protects
998
 
      the open cache (also known as table cache) and table definitions stored
999
 
      on disk.
1000
 
    */
1001
 
 
 
1272
    table->prev->next=table->next; /* Remove from unused list */
 
1273
    table->next->prev=table->prev;
 
1274
    table->in_use= this;
 
1275
  }
 
1276
  else
 
1277
  {
 
1278
    /* Insert a new Table instance into the open cache */
 
1279
    int error;
 
1280
    /* Free cache if too big */
 
1281
    while (open_cache.records > table_cache_size && unused_tables)
 
1282
      hash_delete(&open_cache,(unsigned char*) unused_tables);
 
1283
 
 
1284
    if (table_list->create)
1002
1285
    {
1003
 
      table::Cache::singleton().mutex().lock(); /* Lock for FLUSH TABLES for open table */
1004
 
 
1005
 
      /*
1006
 
        Actually try to find the table in the open_cache.
1007
 
        The cache may contain several "Table" instances for the same
1008
 
        physical table. The instances that are currently "in use" by
1009
 
        some thread have their "in_use" member != NULL.
1010
 
        There is no good reason for having more than one entry in the
1011
 
        hash for the same physical table, except that we use this as
1012
 
        an implicit "pending locks queue" - see
1013
 
        wait_for_locked_table_names for details.
1014
 
      */
1015
 
      ppp= table::getCache().equal_range(key);
1016
 
 
1017
 
      table= NULL;
1018
 
      for (table::CacheMap::const_iterator iter= ppp.first;
1019
 
           iter != ppp.second; ++iter, table= NULL)
 
1286
      TableIdentifier  lock_table_identifier(table_list->db, table_list->table_name, NO_TMP_TABLE);
 
1287
 
 
1288
      if (plugin::StorageEngine::getTableDefinition(*this, lock_table_identifier) != EEXIST)
1020
1289
      {
1021
 
        table= (*iter).second;
1022
 
 
1023
 
        if (not table->in_use)
1024
 
          break;
1025
1290
        /*
1026
 
          Here we flush tables marked for flush.
1027
 
          Normally, table->getShare()->version contains the value of
1028
 
          refresh_version from the moment when this table was
1029
 
          (re-)opened and added to the cache.
1030
 
          If since then we did (or just started) FLUSH TABLES
1031
 
          statement, refresh_version has been increased.
1032
 
          For "name-locked" Table instances, table->getShare()->version is set
1033
 
          to 0 (see lock_table_name for details).
1034
 
          In case there is a pending FLUSH TABLES or a name lock, we
1035
 
          need to back off and re-start opening tables.
1036
 
          If we do not back off now, we may dead lock in case of lock
1037
 
          order mismatch with some other thread:
1038
 
          c1-> name lock t1; -- sort of exclusive lock
1039
 
          c2-> open t2;      -- sort of shared lock
1040
 
          c1-> name lock t2; -- blocks
1041
 
          c2-> open t1; -- blocks
 
1291
          Table to be created, so we need to create placeholder in table-cache.
1042
1292
        */
1043
 
        if (table->needs_reopen_or_name_lock())
 
1293
        if (!(table= table_cache_insert_placeholder(key, key_length)))
1044
1294
        {
1045
 
          if (flags & DRIZZLE_LOCK_IGNORE_FLUSH)
1046
 
          {
1047
 
            /* Force close at once after usage */
1048
 
            version= table->getShare()->getVersion();
1049
 
            continue;
1050
 
          }
1051
 
 
1052
 
          /* Avoid self-deadlocks by detecting self-dependencies. */
1053
 
          if (table->open_placeholder && table->in_use == this)
1054
 
          {
1055
 
            table::Cache::singleton().mutex().unlock();
1056
 
            my_error(ER_UPDATE_TABLE_USED, MYF(0), table->getShare()->getTableName());
1057
 
            return NULL;
1058
 
          }
1059
 
 
1060
 
          /*
1061
 
            Back off, part 1: mark the table as "unused" for the
1062
 
            purpose of name-locking by setting table->db_stat to 0. Do
1063
 
            that only for the tables in this thread that have an old
1064
 
            table->getShare()->version (this is an optimization (?)).
1065
 
            table->db_stat == 0 signals wait_for_locked_table_names
1066
 
            that the tables in question are not used any more. See
1067
 
            table_is_used call for details.
1068
 
          */
1069
 
          close_old_data_files(false, false);
1070
 
 
1071
 
          /*
1072
 
            Back-off part 2: try to avoid "busy waiting" on the table:
1073
 
            if the table is in use by some other thread, we suspend
1074
 
            and wait till the operation is complete: when any
1075
 
            operation that juggles with table->getShare()->version completes,
1076
 
            it broadcasts COND_refresh condition variable.
1077
 
            If 'old' table we met is in use by current thread we return
1078
 
            without waiting since in this situation it's this thread
1079
 
            which is responsible for broadcasting on COND_refresh
1080
 
            (and this was done already in Session::close_old_data_files()).
1081
 
            Good example of such situation is when we have statement
1082
 
            that needs two instances of table and FLUSH TABLES comes
1083
 
            after we open first instance but before we open second
1084
 
            instance.
1085
 
          */
1086
 
          if (table->in_use != this)
1087
 
          {
1088
 
            /* wait_for_conditionwill unlock table::Cache::singleton().mutex() for us */
1089
 
            wait_for_condition(table::Cache::singleton().mutex(), COND_refresh);
1090
 
          }
1091
 
          else
1092
 
          {
1093
 
            table::Cache::singleton().mutex().unlock();
1094
 
          }
1095
 
          /*
1096
 
            There is a refresh in progress for this table.
1097
 
            Signal the caller that it has to try again.
1098
 
          */
1099
 
          if (refresh)
1100
 
            *refresh= true;
 
1295
          pthread_mutex_unlock(&LOCK_open);
1101
1296
          return NULL;
1102
1297
        }
1103
 
      }
1104
 
      if (table)
1105
 
      {
1106
 
        table::getUnused().unlink(static_cast<table::Concurrent *>(table));
1107
 
        table->in_use= this;
1108
 
      }
1109
 
      else
1110
 
      {
1111
 
        /* Insert a new Table instance into the open cache */
1112
 
        int error;
1113
 
        /* Free cache if too big */
1114
 
        table::getUnused().cull();
1115
 
 
1116
 
        if (table_list->isCreate())
1117
 
        {
1118
 
          TableIdentifier  lock_table_identifier(table_list->getSchemaName(), table_list->getTableName(), message::Table::STANDARD);
1119
 
 
1120
 
          if (not plugin::StorageEngine::doesTableExist(*this, lock_table_identifier))
1121
 
          {
1122
 
            /*
1123
 
              Table to be created, so we need to create placeholder in table-cache.
1124
 
            */
1125
 
            if (!(table= table_cache_insert_placeholder(lock_table_identifier)))
1126
 
            {
1127
 
              table::Cache::singleton().mutex().unlock();
1128
 
              return NULL;
1129
 
            }
1130
 
            /*
1131
 
              Link placeholder to the open tables list so it will be automatically
1132
 
              removed once tables are closed. Also mark it so it won't be ignored
1133
 
              by other trying to take name-lock.
1134
 
            */
1135
 
            table->open_placeholder= true;
1136
 
            table->setNext(open_tables);
1137
 
            open_tables= table;
1138
 
            table::Cache::singleton().mutex().unlock();
1139
 
 
1140
 
            return table ;
1141
 
          }
1142
 
          /* Table exists. Let us try to open it. */
1143
 
        }
1144
 
 
1145
 
        /* make a new table */
1146
 
        {
1147
 
          table::Concurrent *new_table= new table::Concurrent;
1148
 
          table= new_table;
1149
 
          if (new_table == NULL)
1150
 
          {
1151
 
            table::Cache::singleton().mutex().unlock();
1152
 
            return NULL;
1153
 
          }
1154
 
 
1155
 
          error= new_table->open_unireg_entry(this, alias, identifier);
1156
 
          if (error != 0)
1157
 
          {
1158
 
            delete new_table;
1159
 
            table::Cache::singleton().mutex().unlock();
1160
 
            return NULL;
1161
 
          }
1162
 
          (void)table::Cache::singleton().insert(new_table);
1163
 
        }
1164
 
      }
1165
 
 
1166
 
      table::Cache::singleton().mutex().unlock();
1167
 
    }
1168
 
    if (refresh)
1169
 
    {
1170
 
      table->setNext(open_tables); /* Link into simple list */
1171
 
      open_tables= table;
1172
 
    }
1173
 
    table->reginfo.lock_type= TL_READ; /* Assume read */
1174
 
 
1175
 
  }
1176
 
  assert(table->getShare()->getTableCount() > 0 || table->getShare()->getType() != message::Table::STANDARD);
1177
 
 
 
1298
        /*
 
1299
          Link placeholder to the open tables list so it will be automatically
 
1300
          removed once tables are closed. Also mark it so it won't be ignored
 
1301
          by other trying to take name-lock.
 
1302
        */
 
1303
        table->open_placeholder= true;
 
1304
        table->next= open_tables;
 
1305
        open_tables= table;
 
1306
        pthread_mutex_unlock(&LOCK_open);
 
1307
 
 
1308
        return table ;
 
1309
      }
 
1310
      /* Table exists. Let us try to open it. */
 
1311
    }
 
1312
 
 
1313
    /* make a new table */
 
1314
    table= (Table *)malloc(sizeof(Table));
 
1315
    if (table == NULL)
 
1316
    {
 
1317
      pthread_mutex_unlock(&LOCK_open);
 
1318
      return NULL;
 
1319
    }
 
1320
 
 
1321
    error= open_unireg_entry(this, table, table_list, alias, key, key_length);
 
1322
    if (error != 0)
 
1323
    {
 
1324
      free(table);
 
1325
      pthread_mutex_unlock(&LOCK_open);
 
1326
      return NULL;
 
1327
    }
 
1328
    my_hash_insert(&open_cache, (unsigned char*) table);
 
1329
  }
 
1330
 
 
1331
  pthread_mutex_unlock(&LOCK_open);
 
1332
  if (refresh)
 
1333
  {
 
1334
    table->next= open_tables; /* Link into simple list */
 
1335
    open_tables=table;
 
1336
  }
 
1337
  table->reginfo.lock_type= TL_READ; /* Assume read */
 
1338
 
 
1339
reset:
 
1340
  assert(table->s->ref_count > 0 || table->s->tmp_table != NO_TMP_TABLE);
 
1341
 
 
1342
  if (lex->need_correct_ident())
 
1343
    table->alias_name_used= my_strcasecmp(table_alias_charset,
 
1344
                                          table->s->table_name.str, alias);
1178
1345
  /* Fix alias if table name changes */
1179
 
  if (strcmp(table->getAlias(), alias))
 
1346
  if (strcmp(table->alias, alias))
1180
1347
  {
1181
 
    table->setAlias(alias);
 
1348
    uint32_t length=(uint32_t) strlen(alias)+1;
 
1349
    table->alias= (char*) realloc((char*) table->alias, length);
 
1350
    memcpy((void*) table->alias, alias, length);
1182
1351
  }
1183
1352
 
1184
1353
  /* These variables are also set in reopen_table() */
1189
1358
  table->maybe_null= false;
1190
1359
  table->force_index= false;
1191
1360
  table->status=STATUS_NO_RECORD;
1192
 
  table->insert_values.clear();
 
1361
  table->insert_values= 0;
1193
1362
  /* Catch wrong handling of the auto_increment_field_not_null. */
1194
1363
  assert(!table->auto_increment_field_not_null);
1195
1364
  table->auto_increment_field_not_null= false;
1196
1365
  if (table->timestamp_field)
1197
 
  {
1198
1366
    table->timestamp_field_type= table->timestamp_field->get_auto_set_type();
1199
 
  }
1200
1367
  table->pos_in_table_list= table_list;
1201
1368
  table->clear_column_bitmaps();
1202
1369
  assert(table->key_read == 0);
1205
1372
}
1206
1373
 
1207
1374
 
 
1375
/*
 
1376
  Reopen an table because the definition has changed.
 
1377
 
 
1378
  SYNOPSIS
 
1379
  reopen_table()
 
1380
  table Table object
 
1381
 
 
1382
  NOTES
 
1383
  The data cursor for the table is already closed and the share is released
 
1384
  The table has a 'dummy' share that mainly contains database and table name.
 
1385
 
 
1386
  RETURN
 
1387
  0  ok
 
1388
  1  error. The old table object is not changed.
 
1389
*/
 
1390
 
 
1391
bool reopen_table(Table *table)
 
1392
{
 
1393
  Table tmp;
 
1394
  bool error= 1;
 
1395
  Field **field;
 
1396
  uint32_t key,part;
 
1397
  TableList table_list;
 
1398
  Session *session= table->in_use;
 
1399
 
 
1400
  assert(table->s->ref_count == 0);
 
1401
  assert(!table->sort.io_cache);
 
1402
 
 
1403
#ifdef EXTRA_DEBUG
 
1404
  if (table->db_stat)
 
1405
    errmsg_printf(ERRMSG_LVL_ERROR, _("Table %s had a open data Cursor in reopen_table"),
 
1406
                  table->alias);
 
1407
#endif
 
1408
  table_list.db=         table->s->db.str;
 
1409
  table_list.table_name= table->s->table_name.str;
 
1410
  table_list.table=      table;
 
1411
 
 
1412
  if (wait_for_locked_table_names(session, &table_list))
 
1413
    return true;                             // Thread was killed
 
1414
 
 
1415
  if (open_unireg_entry(session, &tmp, &table_list,
 
1416
                        table->alias,
 
1417
                        table->s->table_cache_key.str,
 
1418
                        table->s->table_cache_key.length))
 
1419
    goto end;
 
1420
 
 
1421
  /* This list copies variables set by open_table */
 
1422
  tmp.tablenr=          table->tablenr;
 
1423
  tmp.used_fields=      table->used_fields;
 
1424
  tmp.const_table=      table->const_table;
 
1425
  tmp.null_row=         table->null_row;
 
1426
  tmp.maybe_null=       table->maybe_null;
 
1427
  tmp.status=           table->status;
 
1428
 
 
1429
  /* Get state */
 
1430
  tmp.in_use=           session;
 
1431
  tmp.reginfo.lock_type=table->reginfo.lock_type;
 
1432
 
 
1433
  /* Replace table in open list */
 
1434
  tmp.next=             table->next;
 
1435
  tmp.prev=             table->prev;
 
1436
 
 
1437
  if (table->cursor)
 
1438
    table->closefrm(true);              // close cursor, free everything
 
1439
 
 
1440
  *table= tmp;
 
1441
  table->default_column_bitmaps();
 
1442
  table->cursor->change_table_ptr(table, table->s);
 
1443
 
 
1444
  assert(table->alias != 0);
 
1445
  for (field=table->field ; *field ; field++)
 
1446
  {
 
1447
    (*field)->table= (*field)->orig_table= table;
 
1448
    (*field)->table_name= &table->alias;
 
1449
  }
 
1450
  for (key=0 ; key < table->s->keys ; key++)
 
1451
  {
 
1452
    for (part=0 ; part < table->key_info[key].usable_key_parts ; part++)
 
1453
      table->key_info[key].key_part[part].field->table= table;
 
1454
  }
 
1455
 
 
1456
  broadcast_refresh();
 
1457
  error= false;
 
1458
 
 
1459
end:
 
1460
  return(error);
 
1461
}
 
1462
 
 
1463
 
1208
1464
/**
1209
1465
  Close all instances of a table open by this thread and replace
1210
1466
  them with exclusive name-locks.
1222
1478
  the strings are used in a loop even after the share may be freed.
1223
1479
*/
1224
1480
 
1225
 
void Session::close_data_files_and_morph_locks(const TableIdentifier &identifier)
 
1481
void Session::close_data_files_and_morph_locks(const char *new_db, const char *new_table_name)
1226
1482
{
1227
 
  safe_mutex_assert_owner(table::Cache::singleton().mutex().native_handle()); /* Adjust locks at the end of ALTER TABLEL */
 
1483
  Table *table;
 
1484
 
 
1485
  safe_mutex_assert_owner(&LOCK_open); /* Adjust locks at the end of ALTER TABLEL */
1228
1486
 
1229
1487
  if (lock)
1230
1488
  {
1232
1490
      If we are not under LOCK TABLES we should have only one table
1233
1491
      open and locked so it makes sense to remove the lock at once.
1234
1492
    */
1235
 
    unlockTables(lock);
 
1493
    mysql_unlock_tables(this, lock);
1236
1494
    lock= 0;
1237
1495
  }
1238
1496
 
1241
1499
    for target table name if we process ALTER Table ... RENAME.
1242
1500
    So loop below makes sense even if we are not under LOCK TABLES.
1243
1501
  */
1244
 
  for (Table *table= open_tables; table ; table=table->getNext())
 
1502
  for (table= open_tables; table ; table=table->next)
1245
1503
  {
1246
 
    if (table->getShare()->getCacheKey() == identifier.getKey())
 
1504
    if (!strcmp(table->s->table_name.str, new_table_name) &&
 
1505
        !strcmp(table->s->db.str, new_db))
1247
1506
    {
1248
1507
      table->open_placeholder= true;
1249
1508
      close_handle_and_leave_table_as_lock(table);
1267
1526
  combination when one needs tables to be reopened (for
1268
1527
  example see openTablesLock()).
1269
1528
 
1270
 
  @note One should have lock on table::Cache::singleton().mutex() when calling this.
 
1529
  @note One should have lock on LOCK_open when calling this.
1271
1530
 
1272
1531
  @return false in case of success, true - otherwise.
1273
1532
*/
1274
1533
 
1275
 
bool Session::reopen_tables(bool get_locks, bool)
 
1534
bool Session::reopen_tables(bool get_locks, bool mark_share_as_old)
1276
1535
{
1277
1536
  Table *table,*next,**prev;
1278
1537
  Table **tables,**tables_ptr;                  // For locks
1284
1543
  if (open_tables == NULL)
1285
1544
    return false;
1286
1545
 
1287
 
  safe_mutex_assert_owner(table::Cache::singleton().mutex().native_handle());
 
1546
  safe_mutex_assert_owner(&LOCK_open);
1288
1547
  if (get_locks)
1289
1548
  {
1290
1549
    /*
1293
1552
    */
1294
1553
    uint32_t opens= 0;
1295
1554
 
1296
 
    for (table= open_tables; table ; table=table->getNext())
1297
 
    {
 
1555
    for (table= open_tables; table ; table=table->next)
1298
1556
      opens++;
1299
 
    }
1300
1557
    tables= new Table *[opens];
1301
1558
  }
1302
1559
  else
1303
 
  {
1304
1560
    tables= &open_tables;
1305
 
  }
1306
1561
  tables_ptr =tables;
1307
1562
 
1308
1563
  prev= &open_tables;
1309
1564
  for (table= open_tables; table ; table=next)
1310
1565
  {
1311
 
    next= table->getNext();
1312
 
 
1313
 
    my_error(ER_CANT_REOPEN_TABLE, MYF(0), table->getAlias());
1314
 
    table::remove_table(static_cast<table::Concurrent *>(table));
1315
 
    error= 1;
 
1566
    uint32_t db_stat= table->db_stat;
 
1567
    next= table->next;
 
1568
    if (!tables || (!db_stat && reopen_table(table)))
 
1569
    {
 
1570
      my_error(ER_CANT_REOPEN_TABLE, MYF(0), table->alias);
 
1571
      hash_delete(&open_cache,(unsigned char*) table);
 
1572
      error= 1;
 
1573
    }
 
1574
    else
 
1575
    {
 
1576
      *prev= table;
 
1577
      prev= &table->next;
 
1578
      /* Do not handle locks of MERGE children. */
 
1579
      if (get_locks && !db_stat)
 
1580
        *tables_ptr++= table;                   // need new lock on this
 
1581
      if (mark_share_as_old)
 
1582
      {
 
1583
        table->s->version= 0;
 
1584
        table->open_placeholder= false;
 
1585
      }
 
1586
    }
1316
1587
  }
1317
1588
  *prev=0;
1318
1589
  if (tables != tables_ptr)                     // Should we get back old locks
1319
1590
  {
1320
 
    DrizzleLock *local_lock;
 
1591
    DRIZZLE_LOCK *local_lock;
1321
1592
    /*
1322
1593
      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
 
1594
      wait_for_tables() as it tries to acquire LOCK_open, which is
1324
1595
      already locked.
1325
1596
    */
1326
1597
    some_tables_deleted= false;
1327
1598
 
1328
 
    if ((local_lock= lockTables(tables, (uint32_t) (tables_ptr - tables),
1329
 
                                       flags, &not_used)))
 
1599
    if ((local_lock= mysql_lock_tables(this, tables, (uint32_t) (tables_ptr - tables),
 
1600
                                 flags, &not_used)))
1330
1601
    {
1331
1602
      /* unused */
1332
1603
    }
1345
1616
  if (get_locks && tables)
1346
1617
    delete [] tables;
1347
1618
 
1348
 
  locking::broadcast_refresh();
 
1619
  broadcast_refresh();
1349
1620
 
1350
1621
  return(error);
1351
1622
}
1371
1642
 
1372
1643
  Table *table= open_tables;
1373
1644
 
1374
 
  for (; table ; table=table->getNext())
 
1645
  for (; table ; table=table->next)
1375
1646
  {
1376
1647
    /*
1377
1648
      Reopen marked for flush.
1392
1663
              lock on it. This will also give them a chance to close their
1393
1664
              instances of this table.
1394
1665
            */
1395
 
            abortLock(ulcktbl);
1396
 
            removeLock(ulcktbl);
 
1666
            mysql_lock_abort(this, ulcktbl);
 
1667
            mysql_lock_remove(this, ulcktbl);
1397
1668
            ulcktbl->lock_count= 0;
1398
1669
          }
1399
1670
          if ((ulcktbl != table) && ulcktbl->db_stat)
1433
1704
    }
1434
1705
  }
1435
1706
  if (found)
1436
 
    locking::broadcast_refresh();
 
1707
    broadcast_refresh();
 
1708
}
 
1709
 
 
1710
 
 
1711
/*
 
1712
  Wait until all threads has closed the tables in the list
 
1713
  We have also to wait if there is thread that has a lock on this table even
 
1714
  if the table is closed
 
1715
*/
 
1716
 
 
1717
bool table_is_used(Table *table, bool wait_for_name_lock)
 
1718
{
 
1719
  do
 
1720
  {
 
1721
    char *key= table->s->table_cache_key.str;
 
1722
    uint32_t key_length= table->s->table_cache_key.length;
 
1723
 
 
1724
    HASH_SEARCH_STATE state;
 
1725
    for (Table *search= (Table*) hash_first(&open_cache, (unsigned char*) key,
 
1726
                                            key_length, &state);
 
1727
         search ;
 
1728
         search= (Table*) hash_next(&open_cache, (unsigned char*) key,
 
1729
                                    key_length, &state))
 
1730
    {
 
1731
      if (search->in_use == table->in_use)
 
1732
        continue;                               // Name locked by this thread
 
1733
      /*
 
1734
        We can't use the table under any of the following conditions:
 
1735
        - There is an name lock on it (Table is to be deleted or altered)
 
1736
        - If we are in flush table and we didn't execute the flush
 
1737
        - If the table engine is open and it's an old version
 
1738
        (We must wait until all engines are shut down to use the table)
 
1739
      */
 
1740
      if ( (search->locked_by_name && wait_for_name_lock) ||
 
1741
           (search->is_name_opened() && search->needs_reopen_or_name_lock()))
 
1742
        return 1;
 
1743
    }
 
1744
  } while ((table=table->next));
 
1745
  return 0;
1437
1746
}
1438
1747
 
1439
1748
 
1444
1753
  bool result;
1445
1754
 
1446
1755
  session->set_proc_info("Waiting for tables");
1447
 
  {
1448
 
    boost_unique_lock_t lock(table::Cache::singleton().mutex());
1449
 
    while (not session->getKilled())
1450
 
    {
1451
 
      session->some_tables_deleted= false;
1452
 
      session->close_old_data_files(false, dropping_tables != 0);
1453
 
      if (not table::Cache::singleton().areTablesUsed(session->open_tables, 1))
1454
 
      {
1455
 
        break;
1456
 
      }
1457
 
      COND_refresh.wait(lock);
1458
 
    }
1459
 
    if (session->getKilled())
1460
 
      result= true;                                     // aborted
1461
 
    else
1462
 
    {
1463
 
      /* Now we can open all tables without any interference */
1464
 
      session->set_proc_info("Reopen tables");
1465
 
      session->version= refresh_version;
1466
 
      result= session->reopen_tables(false, false);
1467
 
    }
1468
 
  }
 
1756
  pthread_mutex_lock(&LOCK_open); /* Lock for all tables to be refreshed */
 
1757
  while (!session->killed)
 
1758
  {
 
1759
    session->some_tables_deleted= false;
 
1760
    session->close_old_data_files(false, dropping_tables != 0);
 
1761
    if (!table_is_used(session->open_tables, 1))
 
1762
      break;
 
1763
    (void) pthread_cond_wait(&COND_refresh,&LOCK_open);
 
1764
  }
 
1765
  if (session->killed)
 
1766
    result= true;                                       // aborted
 
1767
  else
 
1768
  {
 
1769
    /* Now we can open all tables without any interference */
 
1770
    session->set_proc_info("Reopen tables");
 
1771
    session->version= refresh_version;
 
1772
    result= session->reopen_tables(false, false);
 
1773
  }
 
1774
  pthread_mutex_unlock(&LOCK_open);
1469
1775
  session->set_proc_info(0);
1470
1776
 
1471
1777
  return result;
1496
1802
*/
1497
1803
 
1498
1804
 
1499
 
Table *drop_locked_tables(Session *session, const drizzled::TableIdentifier &identifier)
 
1805
Table *drop_locked_tables(Session *session,const char *db, const char *table_name)
1500
1806
{
1501
1807
  Table *table,*next,**prev, *found= 0;
1502
1808
  prev= &session->open_tables;
1503
1809
 
1504
1810
  /*
1505
 
    Note that we need to hold table::Cache::singleton().mutex() while changing the
 
1811
    Note that we need to hold LOCK_open while changing the
1506
1812
    open_tables list. Another thread may work on it.
1507
 
    (See: table::Cache::singleton().removeTable(), mysql_wait_completed_table())
 
1813
    (See: remove_table_from_cache(), mysql_wait_completed_table())
1508
1814
    Closing a MERGE child before the parent would be fatal if the
1509
1815
    other thread tries to abort the MERGE lock in between.
1510
1816
  */
1511
1817
  for (table= session->open_tables; table ; table=next)
1512
1818
  {
1513
 
    next=table->getNext();
1514
 
    if (table->getShare()->getCacheKey() == identifier.getKey())
 
1819
    next=table->next;
 
1820
    if (!strcmp(table->s->table_name.str, table_name) &&
 
1821
        !strcmp(table->s->db.str, db))
1515
1822
    {
1516
 
      session->removeLock(table);
 
1823
      mysql_lock_remove(session, table);
1517
1824
 
1518
1825
      if (!found)
1519
1826
      {
1528
1835
      else
1529
1836
      {
1530
1837
        /* We already have a name lock, remove copy */
1531
 
        table::remove_table(static_cast<table::Concurrent *>(table));
 
1838
        hash_delete(&open_cache,(unsigned char*) table);
1532
1839
      }
1533
1840
    }
1534
1841
    else
1535
1842
    {
1536
1843
      *prev=table;
1537
 
      prev= table->getNextPtr();
 
1844
      prev= &table->next;
1538
1845
    }
1539
1846
  }
1540
1847
  *prev=0;
1541
1848
  if (found)
1542
 
    locking::broadcast_refresh();
 
1849
    broadcast_refresh();
1543
1850
 
1544
1851
  return(found);
1545
1852
}
1551
1858
  other threads trying to get the lock.
1552
1859
*/
1553
1860
 
1554
 
void abort_locked_tables(Session *session, const drizzled::TableIdentifier &identifier)
 
1861
void abort_locked_tables(Session *session,const char *db, const char *table_name)
1555
1862
{
1556
1863
  Table *table;
1557
 
  for (table= session->open_tables; table ; table= table->getNext())
 
1864
  for (table= session->open_tables; table ; table= table->next)
1558
1865
  {
1559
 
    if (table->getShare()->getCacheKey() == identifier.getKey())
 
1866
    if (!strcmp(table->s->table_name.str, table_name) &&
 
1867
        !strcmp(table->s->db.str, db))
1560
1868
    {
1561
1869
      /* If MERGE child, forward lock handling to parent. */
1562
 
      session->abortLock(table);
 
1870
      mysql_lock_abort(session, table);
1563
1871
      break;
1564
1872
    }
1565
1873
  }
1566
1874
}
1567
1875
 
 
1876
/*
 
1877
  Load a table definition from cursor and open unireg table
 
1878
 
 
1879
  SYNOPSIS
 
1880
  open_unireg_entry()
 
1881
  session                       Thread handle
 
1882
  entry         Store open table definition here
 
1883
  table_list            TableList with db, table_name
 
1884
  alias         Alias name
 
1885
  cache_key             Key for share_cache
 
1886
  cache_key_length      length of cache_key
 
1887
 
 
1888
  NOTES
 
1889
  Extra argument for open is taken from session->open_options
 
1890
  One must have a lock on LOCK_open when calling this function
 
1891
 
 
1892
  RETURN
 
1893
  0     ok
 
1894
#       Error
 
1895
*/
 
1896
 
 
1897
static int open_unireg_entry(Session *session, Table *entry, TableList *table_list,
 
1898
                             const char *alias,
 
1899
                             char *cache_key, uint32_t cache_key_length)
 
1900
{
 
1901
  int error;
 
1902
  TableShare *share;
 
1903
  uint32_t discover_retry_count= 0;
 
1904
 
 
1905
  safe_mutex_assert_owner(&LOCK_open);
 
1906
retry:
 
1907
  if (!(share= TableShare::getShare(session, table_list, cache_key,
 
1908
                                    cache_key_length,
 
1909
                                    table_list->i_s_requested_object,
 
1910
                                    &error)))
 
1911
    return 1;
 
1912
 
 
1913
  while ((error= open_table_from_share(session, share, alias,
 
1914
                                       (uint32_t) (HA_OPEN_KEYFILE |
 
1915
                                                   HA_OPEN_RNDFILE |
 
1916
                                                   HA_GET_INDEX |
 
1917
                                                   HA_TRY_READ_ONLY),
 
1918
                                       session->open_options, entry)))
 
1919
  {
 
1920
    if (error == 7)                             // Table def changed
 
1921
    {
 
1922
      share->version= 0;                        // Mark share as old
 
1923
      if (discover_retry_count++)               // Retry once
 
1924
        goto err;
 
1925
 
 
1926
      /*
 
1927
        TODO->
 
1928
        Here we should wait until all threads has released the table.
 
1929
        For now we do one retry. This may cause a deadlock if there
 
1930
        is other threads waiting for other tables used by this thread.
 
1931
 
 
1932
        Proper fix would be to if the second retry failed:
 
1933
        - Mark that table def changed
 
1934
        - Return from open table
 
1935
        - Close all tables used by this thread
 
1936
        - Start waiting that the share is released
 
1937
        - Retry by opening all tables again
 
1938
      */
 
1939
 
 
1940
      /*
 
1941
        TO BE FIXED
 
1942
        To avoid deadlock, only wait for release if no one else is
 
1943
        using the share.
 
1944
      */
 
1945
      if (share->ref_count != 1)
 
1946
        goto err;
 
1947
      /* Free share and wait until it's released by all threads */
 
1948
      TableShare::release(share);
 
1949
 
 
1950
      if (!session->killed)
 
1951
      {
 
1952
        drizzle_reset_errors(session, 1);         // Clear warnings
 
1953
        session->clear_error();                 // Clear error message
 
1954
        goto retry;
 
1955
      }
 
1956
      return 1;
 
1957
    }
 
1958
 
 
1959
    goto err;
 
1960
  }
 
1961
 
 
1962
  return 0;
 
1963
 
 
1964
err:
 
1965
  TableShare::release(share);
 
1966
 
 
1967
  return 1;
 
1968
}
 
1969
 
1568
1970
 
1569
1971
/*
1570
1972
  Open all tables in list
1628
2030
    (*counter)++;
1629
2031
 
1630
2032
    /*
1631
 
     * Is the user authorized to see this table? Do this before we check
1632
 
     * to see if it exists so that an unauthorized user cannot phish for
1633
 
     * table/schema information via error messages
1634
 
     */
1635
 
    TableIdentifier the_table(tables->getSchemaName(), tables->getTableName());
1636
 
    if (not plugin::Authorization::isAuthorized(getSecurityContext(),
1637
 
                                                the_table))
1638
 
    {
1639
 
      result= -1;                               // Fatal error
1640
 
      break;
1641
 
    }
1642
 
 
1643
 
 
1644
 
    /*
1645
2033
      Not a placeholder: must be a base table or a view, and the table is
1646
2034
      not opened yet. Try to open the table.
1647
2035
    */
1680
2068
    {
1681
2069
      if (tables->lock_type == TL_WRITE_DEFAULT)
1682
2070
        tables->table->reginfo.lock_type= update_lock_default;
1683
 
      else if (tables->table->getShare()->getType() == message::Table::STANDARD)
 
2071
      else if (tables->table->s->tmp_table == NO_TMP_TABLE)
1684
2072
        tables->table->reginfo.lock_type= tables->lock_type;
1685
2073
    }
1686
2074
  }
1742
2130
 
1743
2131
    assert(lock == 0);  // You must lock everything at once
1744
2132
    if ((table->reginfo.lock_type= lock_type) != TL_UNLOCK)
1745
 
      if (! (lock= lockTables(&table_list->table, 1, 0, &refresh)))
 
2133
      if (! (lock= mysql_lock_tables(this, &table_list->table, 1, 0, &refresh)))
1746
2134
        table= 0;
1747
2135
  }
1748
2136
 
1805
2193
      *(ptr++)= table->table;
1806
2194
  }
1807
2195
 
1808
 
  if (!(session->lock= session->lockTables(start, (uint32_t) (ptr - start), lock_flag, need_reopen)))
 
2196
  if (!(session->lock= mysql_lock_tables(session, start, (uint32_t) (ptr - start),
 
2197
                                         lock_flag, need_reopen)))
1809
2198
  {
1810
2199
    return -1;
1811
2200
  }
1834
2223
#  Table object
1835
2224
*/
1836
2225
 
1837
 
Table *Open_tables_state::open_temporary_table(const TableIdentifier &identifier,
1838
 
                                               bool link_in_list)
 
2226
Table *Session::open_temporary_table(TableIdentifier &identifier,
 
2227
                                     bool link_in_list)
1839
2228
{
1840
 
  assert(identifier.isTmp());
1841
 
 
1842
 
 
1843
 
  table::Temporary *new_tmp_table= new table::Temporary(identifier.getType(),
1844
 
                                                        identifier,
1845
 
                                                        const_cast<char *>(const_cast<TableIdentifier&>(identifier).getPath().c_str()),
1846
 
                                                        static_cast<uint32_t>(identifier.getPath().length()));
1847
 
  if (not new_tmp_table)
 
2229
  Table *new_tmp_table;
 
2230
  TableShare *share;
 
2231
  char cache_key[MAX_DBKEY_LENGTH], *saved_cache_key, *tmp_path;
 
2232
  uint32_t key_length, path_length;
 
2233
  TableList table_list;
 
2234
 
 
2235
  table_list.db=         (char*) identifier.getDBName();
 
2236
  table_list.table_name= (char*) identifier.getTableName();
 
2237
  /* Create the cache_key for temporary tables */
 
2238
  key_length= table_list.create_table_def_key(cache_key);
 
2239
  path_length= strlen(identifier.getPath());
 
2240
 
 
2241
  if (!(new_tmp_table= (Table*) malloc(sizeof(*new_tmp_table) + sizeof(*share) +
 
2242
                                       path_length + 1 + key_length)))
1848
2243
    return NULL;
1849
2244
 
 
2245
  share= (TableShare*) (new_tmp_table+1);
 
2246
  tmp_path= (char*) (share+1);
 
2247
  saved_cache_key= strcpy(tmp_path, identifier.getPath())+path_length+1;
 
2248
  memcpy(saved_cache_key, cache_key, key_length);
 
2249
 
 
2250
  share->init(saved_cache_key, key_length, strchr(saved_cache_key, '\0')+1, tmp_path);
 
2251
 
1850
2252
  /*
1851
2253
    First open the share, and then open the table from the share we just opened.
1852
2254
  */
1853
 
  if (new_tmp_table->getMutableShare()->open_table_def(*static_cast<Session *>(this), identifier) ||
1854
 
      new_tmp_table->getMutableShare()->open_table_from_share(static_cast<Session *>(this), identifier, identifier.getTableName().c_str(),
1855
 
                                                              (uint32_t) (HA_OPEN_KEYFILE | HA_OPEN_RNDFILE |
1856
 
                                                                          HA_GET_INDEX),
1857
 
                                                              ha_open_options,
1858
 
                                                              *new_tmp_table))
 
2255
  if (open_table_def(*this, share) ||
 
2256
      open_table_from_share(this, share, identifier.getTableName(),
 
2257
                            (uint32_t) (HA_OPEN_KEYFILE | HA_OPEN_RNDFILE |
 
2258
                                        HA_GET_INDEX),
 
2259
                            ha_open_options,
 
2260
                            new_tmp_table))
1859
2261
  {
1860
2262
    /* No need to lock share->mutex as this is not needed for tmp tables */
1861
 
    delete new_tmp_table->getMutableShare();
1862
 
    delete new_tmp_table;
1863
 
 
 
2263
    share->free_table_share();
 
2264
    free((char*) new_tmp_table);
1864
2265
    return 0;
1865
2266
  }
1866
2267
 
1867
2268
  new_tmp_table->reginfo.lock_type= TL_WRITE;    // Simulate locked
 
2269
  share->tmp_table= TEMP_TABLE;
1868
2270
 
1869
2271
  if (link_in_list)
1870
2272
  {
1871
2273
    /* growing temp list at the head */
1872
 
    new_tmp_table->setNext(this->temporary_tables);
1873
 
    if (new_tmp_table->getNext())
1874
 
    {
1875
 
      new_tmp_table->getNext()->setPrev(new_tmp_table);
1876
 
    }
 
2274
    new_tmp_table->next= this->temporary_tables;
 
2275
    if (new_tmp_table->next)
 
2276
      new_tmp_table->next->prev= new_tmp_table;
1877
2277
    this->temporary_tables= new_tmp_table;
1878
 
    this->temporary_tables->setPrev(0);
 
2278
    this->temporary_tables->prev= 0;
1879
2279
  }
1880
2280
  new_tmp_table->pos_in_table_list= 0;
1881
2281
 
1900
2300
{
1901
2301
  if (session->mark_used_columns != MARK_COLUMNS_NONE)
1902
2302
  {
1903
 
    boost::dynamic_bitset<> *current_bitmap= NULL;
 
2303
    MyBitmap *current_bitmap, *other_bitmap;
1904
2304
 
1905
2305
    /*
1906
2306
      We always want to register the used keys, as the column bitmap may have
1913
2313
    if (session->mark_used_columns == MARK_COLUMNS_READ)
1914
2314
    {
1915
2315
      current_bitmap= table->read_set;
 
2316
      other_bitmap=   table->write_set;
1916
2317
    }
1917
2318
    else
1918
2319
    {
1919
2320
      current_bitmap= table->write_set;
 
2321
      other_bitmap=   table->read_set;
1920
2322
    }
1921
2323
 
1922
 
    //if (current_bitmap->testAndSet(field->position()))
1923
 
    if (current_bitmap->test(field->position()))
 
2324
    if (current_bitmap->testAndSet(field->field_index))
1924
2325
    {
1925
2326
      if (session->mark_used_columns == MARK_COLUMNS_WRITE)
1926
2327
        session->dup_field= field;
1989
2390
    return NULL;
1990
2391
  {
1991
2392
    /* This is a base table. */
1992
 
    assert(nj_col->table_ref->table == nj_col->table_field->getTable());
 
2393
    assert(nj_col->table_ref->table == nj_col->table_field->table);
1993
2394
    found_field= nj_col->table_field;
1994
2395
    update_field_dependencies(session, found_field, nj_col->table_ref->table);
1995
2396
  }
2026
2427
  uint32_t cached_field_index= *cached_field_index_ptr;
2027
2428
 
2028
2429
  /* We assume here that table->field < NO_CACHED_FIELD_INDEX = UINT_MAX */
2029
 
  if (cached_field_index < table->getShare()->sizeFields() &&
 
2430
  if (cached_field_index < table->s->fields &&
2030
2431
      !my_strcasecmp(system_charset_info,
2031
 
                     table->getField(cached_field_index)->field_name, name))
2032
 
  {
2033
 
    field_ptr= table->getFields() + cached_field_index;
2034
 
  }
2035
 
  else if (table->getShare()->getNamedFieldSize())
2036
 
  {
2037
 
    field_ptr= table->getMutableShare()->getNamedField(std::string(name, length));
 
2432
                     table->field[cached_field_index]->field_name, name))
 
2433
    field_ptr= table->field + cached_field_index;
 
2434
  else if (table->s->name_hash.records)
 
2435
  {
 
2436
    field_ptr= (Field**) hash_search(&table->s->name_hash, (unsigned char*) name,
 
2437
                                     length);
2038
2438
    if (field_ptr)
2039
2439
    {
2040
2440
      /*
2041
2441
        field_ptr points to field in TableShare. Convert it to the matching
2042
2442
        field in table
2043
2443
      */
2044
 
      field_ptr= (table->getFields() + table->getShare()->positionFields(field_ptr));
 
2444
      field_ptr= (table->field + (field_ptr - table->s->field));
2045
2445
    }
2046
2446
  }
2047
2447
  else
2048
2448
  {
2049
 
    if (!(field_ptr= table->getFields()))
 
2449
    if (!(field_ptr= table->field))
2050
2450
      return((Field *)0);
2051
2451
    for (; *field_ptr; ++field_ptr)
2052
2452
      if (!my_strcasecmp(system_charset_info, (*field_ptr)->field_name, name))
2055
2455
 
2056
2456
  if (field_ptr && *field_ptr)
2057
2457
  {
2058
 
    *cached_field_index_ptr= field_ptr - table->getFields();
 
2458
    *cached_field_index_ptr= field_ptr - table->field;
2059
2459
    field= *field_ptr;
2060
2460
  }
2061
2461
  else
2062
2462
  {
2063
2463
    if (!allow_rowid ||
2064
2464
        my_strcasecmp(system_charset_info, name, "_rowid") ||
2065
 
        table->getShare()->rowid_field_offset == 0)
 
2465
        table->s->rowid_field_offset == 0)
2066
2466
      return((Field*) 0);
2067
 
    field= table->getField(table->getShare()->rowid_field_offset-1);
 
2467
    field= table->field[table->s->rowid_field_offset-1];
2068
2468
  }
2069
2469
 
2070
2470
  update_field_dependencies(session, field, table);
2143
2543
    inside the view, but we want to search directly in the view columns
2144
2544
    which are represented as a 'field_translation'.
2145
2545
 
2146
 
    TODO-> Ensure that table_name, db_name and tables->db always points to something !
 
2546
TODO: Ensure that table_name, db_name and tables->db always points to
 
2547
something !
2147
2548
  */
2148
2549
  if (/* Exclude nested joins. */
2149
 
      (!table_list->getNestedJoin()) &&
 
2550
      (!table_list->nested_join) &&
2150
2551
      /* Include merge views and information schema tables. */
2151
2552
      /*
2152
2553
        Test if the field qualifiers match the table reference we plan
2154
2555
      */
2155
2556
      table_name && table_name[0] &&
2156
2557
      (my_strcasecmp(table_alias_charset, table_list->alias, table_name) ||
2157
 
       (db_name && db_name[0] && table_list->getSchemaName() && table_list->getSchemaName()[0] &&
2158
 
        strcmp(db_name, table_list->getSchemaName()))))
 
2558
       (db_name && db_name[0] && table_list->db && table_list->db[0] &&
 
2559
        strcmp(db_name, table_list->db))))
2159
2560
    return 0;
2160
2561
 
2161
2562
  *actual_table= NULL;
2162
2563
 
2163
 
  if (!table_list->getNestedJoin())
 
2564
  if (!table_list->nested_join)
2164
2565
  {
2165
2566
    /* 'table_list' is a stored table. */
2166
2567
    assert(table_list->table);
2180
2581
    */
2181
2582
    if (table_name && table_name[0])
2182
2583
    {
2183
 
      List_iterator<TableList> it(table_list->getNestedJoin()->join_list);
 
2584
      List_iterator<TableList> it(table_list->nested_join->join_list);
2184
2585
      TableList *table;
2185
2586
      while ((table= it++))
2186
2587
      {
2228
2629
        field_to_set= fld;
2229
2630
      if (field_to_set)
2230
2631
      {
2231
 
        Table *table= field_to_set->getTable();
 
2632
        Table *table= field_to_set->table;
2232
2633
        if (session->mark_used_columns == MARK_COLUMNS_READ)
2233
 
          table->setReadSet(field_to_set->position());
 
2634
          table->setReadSet(field_to_set->field_index);
2234
2635
        else
2235
 
          table->setWriteSet(field_to_set->position());
 
2636
          table->setWriteSet(field_to_set->field_index);
2236
2637
      }
2237
2638
    }
2238
2639
  }
2474
2875
 
2475
2876
 
2476
2877
Item **
2477
 
find_item_in_list(Session *session,
2478
 
                  Item *find, List<Item> &items, uint32_t *counter,
 
2878
find_item_in_list(Item *find, List<Item> &items, uint32_t *counter,
2479
2879
                  find_item_error_report_type report_error,
2480
2880
                  enum_resolution_type *resolution)
2481
2881
{
2555
2955
            */
2556
2956
            if (report_error != IGNORE_ERRORS)
2557
2957
              my_error(ER_NON_UNIQ_ERROR, MYF(0),
2558
 
                       find->full_name(), session->where);
 
2958
                       find->full_name(), current_session->where);
2559
2959
            return (Item**) 0;
2560
2960
          }
2561
2961
          found_unaliased= li.ref();
2586
2986
              continue;                           // Same field twice
2587
2987
            if (report_error != IGNORE_ERRORS)
2588
2988
              my_error(ER_NON_UNIQ_ERROR, MYF(0),
2589
 
                       find->full_name(), session->where);
 
2989
                       find->full_name(), current_session->where);
2590
2990
            return (Item**) 0;
2591
2991
          }
2592
2992
          found= li.ref();
2638
3038
    {
2639
3039
      if (report_error != IGNORE_ERRORS)
2640
3040
        my_error(ER_NON_UNIQ_ERROR, MYF(0),
2641
 
                 find->full_name(), session->where);
 
3041
                 find->full_name(), current_session->where);
2642
3042
      return (Item **) 0;
2643
3043
    }
2644
3044
    if (found_unaliased)
2654
3054
  {
2655
3055
    if (report_error == REPORT_ALL_ERRORS)
2656
3056
      my_error(ER_BAD_FIELD_ERROR, MYF(0),
2657
 
               find->full_name(), session->where);
 
3057
               find->full_name(), current_session->where);
2658
3058
    return (Item **) 0;
2659
3059
  }
2660
3060
  else
2772
3172
    Leaf table references to which new natural join columns are added
2773
3173
    if the leaves are != NULL.
2774
3174
  */
2775
 
  TableList *leaf_1= (table_ref_1->getNestedJoin() &&
2776
 
                      ! table_ref_1->is_natural_join) ?
 
3175
  TableList *leaf_1= (table_ref_1->nested_join &&
 
3176
                      !table_ref_1->is_natural_join) ?
2777
3177
    NULL : table_ref_1;
2778
 
  TableList *leaf_2= (table_ref_2->getNestedJoin() &&
2779
 
                      ! table_ref_2->is_natural_join) ?
 
3178
  TableList *leaf_2= (table_ref_2->nested_join &&
 
3179
                      !table_ref_2->is_natural_join) ?
2780
3180
    NULL : table_ref_2;
2781
3181
 
2782
3182
  *found_using_fields= 0;
2788
3188
    /* true if field_name_1 is a member of using_fields */
2789
3189
    bool is_using_column_1;
2790
3190
    if (!(nj_col_1= it_1.get_or_create_column_ref(leaf_1)))
2791
 
      return(result);
 
3191
      goto err;
2792
3192
    field_name_1= nj_col_1->name();
2793
3193
    is_using_column_1= using_fields &&
2794
3194
      test_if_string_in_list(field_name_1, using_fields);
2806
3206
      Natural_join_column *cur_nj_col_2;
2807
3207
      const char *cur_field_name_2;
2808
3208
      if (!(cur_nj_col_2= it_2.get_or_create_column_ref(leaf_2)))
2809
 
        return(result);
 
3209
        goto err;
2810
3210
      cur_field_name_2= cur_nj_col_2->name();
2811
3211
 
2812
3212
      /*
2826
3226
            (found && (!using_fields || is_using_column_1)))
2827
3227
        {
2828
3228
          my_error(ER_NON_UNIQ_ERROR, MYF(0), field_name_1, session->where);
2829
 
          return(result);
 
3229
          goto err;
2830
3230
        }
2831
3231
        nj_col_2= cur_nj_col_2;
2832
3232
        found= true;
2859
3259
      Item_func_eq *eq_cond;
2860
3260
 
2861
3261
      if (!item_1 || !item_2)
2862
 
        return(result); // out of memory
 
3262
        goto err;                               // out of memory
2863
3263
 
2864
3264
      /*
2865
3265
        In the case of no_wrap_view_item == 0, the created items must be
2884
3284
      */
2885
3285
      if (set_new_item_local_context(session, item_ident_1, nj_col_1->table_ref) ||
2886
3286
          set_new_item_local_context(session, item_ident_2, nj_col_2->table_ref))
2887
 
        return(result);
 
3287
        goto err;
2888
3288
 
2889
3289
      if (!(eq_cond= new Item_func_eq(item_ident_1, item_ident_2)))
2890
 
        return(result);                               /* Out of memory. */
 
3290
        goto err;                               /* Out of memory. */
2891
3291
 
2892
3292
      /*
2893
3293
        Add the new equi-join condition to the ON clause. Notice that
2904
3304
      {
2905
3305
        Table *table_1= nj_col_1->table_ref->table;
2906
3306
        /* Mark field_1 used for table cache. */
2907
 
        table_1->setReadSet(field_1->position());
 
3307
        table_1->setReadSet(field_1->field_index);
2908
3308
        table_1->covering_keys&= field_1->part_of_key;
2909
3309
        table_1->merge_keys|= field_1->part_of_key;
2910
3310
      }
2912
3312
      {
2913
3313
        Table *table_2= nj_col_2->table_ref->table;
2914
3314
        /* Mark field_2 used for table cache. */
2915
 
        table_2->setReadSet(field_2->position());
 
3315
        table_2->setReadSet(field_2->field_index);
2916
3316
        table_2->covering_keys&= field_2->part_of_key;
2917
3317
        table_2->merge_keys|= field_2->part_of_key;
2918
3318
      }
2933
3333
  */
2934
3334
  result= false;
2935
3335
 
 
3336
err:
2936
3337
  return(result);
2937
3338
}
2938
3339
 
2974
3375
*/
2975
3376
 
2976
3377
static bool
2977
 
store_natural_using_join_columns(Session *session,
 
3378
store_natural_using_join_columns(Session *,
2978
3379
                                 TableList *natural_using_join,
2979
3380
                                 TableList *table_ref_1,
2980
3381
                                 TableList *table_ref_2,
2990
3391
 
2991
3392
  if (!(non_join_columns= new List<Natural_join_column>) ||
2992
3393
      !(natural_using_join->join_columns= new List<Natural_join_column>))
2993
 
  {
2994
 
    return(result);
2995
 
  }
 
3394
    goto err;
2996
3395
 
2997
3396
  /* Append the columns of the first join operand. */
2998
3397
  for (it_1.set(table_ref_1); !it_1.end_of_fields(); it_1.next())
3030
3429
        if (!(common_field= it++))
3031
3430
        {
3032
3431
          my_error(ER_BAD_FIELD_ERROR, MYF(0), using_field_name_ptr,
3033
 
                   session->where);
3034
 
          return(result);
 
3432
                   current_session->where);
 
3433
          goto err;
3035
3434
        }
3036
3435
        if (!my_strcasecmp(system_charset_info,
3037
3436
                           common_field->name(), using_field_name_ptr))
3059
3458
 
3060
3459
  result= false;
3061
3460
 
 
3461
err:
3062
3462
  return(result);
3063
3463
}
3064
3464
 
3101
3501
  bool result= true;
3102
3502
 
3103
3503
  /* Call the procedure recursively for each nested table reference. */
3104
 
  if (table_ref->getNestedJoin())
 
3504
  if (table_ref->nested_join)
3105
3505
  {
3106
 
    List_iterator_fast<TableList> nested_it(table_ref->getNestedJoin()->join_list);
 
3506
    List_iterator_fast<TableList> nested_it(table_ref->nested_join->join_list);
3107
3507
    TableList *same_level_left_neighbor= nested_it++;
3108
3508
    TableList *same_level_right_neighbor= NULL;
3109
3509
    /* Left/right-most neighbors, possibly at higher levels in the join tree. */
3128
3528
          cur_table_ref->outer_join & JOIN_TYPE_RIGHT)
3129
3529
      {
3130
3530
        /* This can happen only for JOIN ... ON. */
3131
 
        assert(table_ref->getNestedJoin()->join_list.elements == 2);
 
3531
        assert(table_ref->nested_join->join_list.elements == 2);
3132
3532
        std::swap(same_level_left_neighbor, cur_table_ref);
3133
3533
      }
3134
3534
 
3141
3541
      real_right_neighbor= (same_level_right_neighbor) ?
3142
3542
        same_level_right_neighbor : right_neighbor;
3143
3543
 
3144
 
      if (cur_table_ref->getNestedJoin() &&
 
3544
      if (cur_table_ref->nested_join &&
3145
3545
          store_top_level_join_columns(session, cur_table_ref,
3146
3546
                                       real_left_neighbor, real_right_neighbor))
3147
 
        return(result);
 
3547
        goto err;
3148
3548
      same_level_right_neighbor= cur_table_ref;
3149
3549
    }
3150
3550
  }
3155
3555
  */
3156
3556
  if (table_ref->is_natural_join)
3157
3557
  {
3158
 
    assert(table_ref->getNestedJoin() &&
3159
 
           table_ref->getNestedJoin()->join_list.elements == 2);
3160
 
    List_iterator_fast<TableList> operand_it(table_ref->getNestedJoin()->join_list);
 
3558
    assert(table_ref->nested_join &&
 
3559
           table_ref->nested_join->join_list.elements == 2);
 
3560
    List_iterator_fast<TableList> operand_it(table_ref->nested_join->join_list);
3161
3561
    /*
3162
3562
      Notice that the order of join operands depends on whether table_ref
3163
3563
      represents a LEFT or a RIGHT join. In a RIGHT join, the operands are
3176
3576
      std::swap(table_ref_1, table_ref_2);
3177
3577
    if (mark_common_columns(session, table_ref_1, table_ref_2,
3178
3578
                            using_fields, &found_using_fields))
3179
 
      return(result);
 
3579
      goto err;
3180
3580
 
3181
3581
    /*
3182
3582
      Swap the join operands back, so that we pick the columns of the second
3188
3588
    if (store_natural_using_join_columns(session, table_ref, table_ref_1,
3189
3589
                                         table_ref_2, using_fields,
3190
3590
                                         found_using_fields))
3191
 
      return(result);
 
3591
      goto err;
3192
3592
 
3193
3593
    /*
3194
3594
      Change NATURAL JOIN to JOIN ... ON. We do this for both operands
3221
3621
  }
3222
3622
  result= false; /* All is OK. */
3223
3623
 
 
3624
err:
3224
3625
  return(result);
3225
3626
}
3226
3627
 
3622
4023
    assert(tables->is_leaf_for_name_resolution());
3623
4024
 
3624
4025
    if ((table_name && my_strcasecmp(table_alias_charset, table_name, tables->alias)) ||
3625
 
        (db_name && strcasecmp(tables->getSchemaName(),db_name)))
 
4026
        (db_name && strcmp(tables->db,db_name)))
3626
4027
      continue;
3627
4028
 
3628
4029
    /*
3658
4059
      if ((field= field_iterator.field()))
3659
4060
      {
3660
4061
        /* Mark fields as used to allow storage engine to optimze access */
3661
 
        field->getTable()->setReadSet(field->position());
 
4062
        field->table->setReadSet(field->field_index);
3662
4063
        if (table)
3663
4064
        {
3664
4065
          table->covering_keys&= field->part_of_key;
3696
4097
      For NATURAL joins, used_tables is updated in the IF above.
3697
4098
    */
3698
4099
    if (table)
3699
 
      table->used_fields= table->getShare()->sizeFields();
 
4100
      table->used_fields= table->s->fields;
3700
4101
  }
3701
4102
  if (found)
3702
4103
    return false;
3786
4187
          goto err_no_arena;
3787
4188
        select_lex->cond_count++;
3788
4189
      }
3789
 
      embedding= embedded->getEmbedding();
 
4190
      embedding= embedded->embedding;
3790
4191
    }
3791
4192
    while (embedding &&
3792
 
           embedding->getNestedJoin()->join_list.head() == embedded);
 
4193
           embedding->nested_join->join_list.head() == embedded);
3793
4194
 
3794
4195
  }
3795
4196
  session->session_marker= save_session_marker;
3848
4249
      thus we safely can take table from the first field.
3849
4250
    */
3850
4251
    field= static_cast<Item_field *>(f++);
3851
 
    table= field->field->getTable();
 
4252
    table= field->field->table;
3852
4253
    table->auto_increment_field_not_null= false;
3853
4254
    f.rewind();
3854
4255
  }
3858
4259
    value= v++;
3859
4260
 
3860
4261
    Field *rfield= field->field;
3861
 
    table= rfield->getTable();
 
4262
    table= rfield->table;
3862
4263
 
3863
4264
    if (rfield == table->next_number_field)
3864
4265
      table->auto_increment_field_not_null= true;
3865
4266
    if ((value->save_in_field(rfield, 0) < 0) && !ignore_errors)
3866
4267
    {
3867
4268
      my_message(ER_UNKNOWN_ERROR, ER(ER_UNKNOWN_ERROR), MYF(0));
3868
 
      if (table)
3869
 
        table->auto_increment_field_not_null= false;
3870
 
 
3871
 
      return true;
 
4269
      goto err;
3872
4270
    }
3873
4271
  }
3874
4272
 
3875
4273
  return session->is_error();
 
4274
 
 
4275
err:
 
4276
  if (table)
 
4277
    table->auto_increment_field_not_null= false;
 
4278
 
 
4279
  return true;
3876
4280
}
3877
4281
 
3878
4282
 
3912
4316
      On INSERT or UPDATE fields are checked to be from the same table,
3913
4317
      thus we safely can take table from the first field.
3914
4318
    */
3915
 
    table= (*ptr)->getTable();
 
4319
    table= (*ptr)->table;
3916
4320
    table->auto_increment_field_not_null= false;
3917
4321
  }
3918
4322
  while ((field = *ptr++) && ! session->is_error())
3919
4323
  {
3920
4324
    value=v++;
3921
 
    table= field->getTable();
 
4325
    table= field->table;
3922
4326
    if (field == table->next_number_field)
3923
4327
      table->auto_increment_field_not_null= true;
3924
4328
    if (value->save_in_field(field, 0) < 0)
3925
 
    {
3926
 
      if (table)
3927
 
        table->auto_increment_field_not_null= false;
3928
 
 
3929
 
      return true;
3930
 
    }
 
4329
      goto err;
3931
4330
  }
3932
4331
 
3933
4332
  return(session->is_error());
 
4333
 
 
4334
err:
 
4335
  if (table)
 
4336
    table->auto_increment_field_not_null= false;
 
4337
 
 
4338
  return true;
3934
4339
}
3935
4340
 
3936
4341
 
3938
4343
{
3939
4344
  Session *session;
3940
4345
 
3941
 
  assert(drizzle_tmpdir.size());
 
4346
  assert(drizzle_tmpdir);
3942
4347
 
3943
4348
  if (!(session= new Session(plugin::Listen::getNullClient())))
3944
4349
    return true;
3945
4350
  session->thread_stack= (char*) &session;
3946
4351
  session->storeGlobals();
3947
4352
 
3948
 
  plugin::StorageEngine::removeLostTemporaryTables(*session, drizzle_tmpdir.c_str());
 
4353
  plugin::StorageEngine::removeLostTemporaryTables(*session, drizzle_tmpdir);
3949
4354
 
3950
4355
  delete session;
3951
4356
 
3958
4363
  unireg support functions
3959
4364
 *****************************************************************************/
3960
4365
 
3961
 
 
 
4366
/*
 
4367
  Invalidate any cache entries that are for some DB
 
4368
 
 
4369
  SYNOPSIS
 
4370
  remove_db_from_cache()
 
4371
  db            Database name. This will be in lower case if
 
4372
  lower_case_table_name is set
 
4373
 
 
4374
NOTE:
 
4375
We can't use hash_delete when looping hash_elements. We mark them first
 
4376
and afterwards delete those marked unused.
 
4377
*/
 
4378
 
 
4379
void remove_db_from_cache(const std::string schema_name)
 
4380
{
 
4381
  safe_mutex_assert_owner(&LOCK_open);
 
4382
 
 
4383
  for (uint32_t idx=0 ; idx < open_cache.records ; idx++)
 
4384
  {
 
4385
    Table *table=(Table*) hash_element(&open_cache,idx);
 
4386
    if (not strcmp(table->s->db.str, schema_name.c_str()))
 
4387
    {
 
4388
      table->s->version= 0L;                    /* Free when thread is ready */
 
4389
      if (not table->in_use)
 
4390
        relink_unused(table);
 
4391
    }
 
4392
  }
 
4393
  while (unused_tables && !unused_tables->s->version)
 
4394
    hash_delete(&open_cache,(unsigned char*) unused_tables);
 
4395
}
 
4396
 
 
4397
 
 
4398
/*
 
4399
  Mark all entries with the table as deleted to force an reopen of the table
 
4400
 
 
4401
  The table will be closed (not stored in cache) by the current thread when
 
4402
  close_thread_tables() is called.
 
4403
 
 
4404
  PREREQUISITES
 
4405
  Lock on LOCK_open()
 
4406
 
 
4407
  RETURN
 
4408
  0  This thread now have exclusive access to this table and no other thread
 
4409
  can access the table until close_thread_tables() is called.
 
4410
  1  Table is in use by another thread
 
4411
*/
 
4412
 
 
4413
bool remove_table_from_cache(Session *session, const char *db, const char *table_name,
 
4414
                             uint32_t flags)
 
4415
{
 
4416
  char key[MAX_DBKEY_LENGTH];
 
4417
  char *key_pos= key;
 
4418
  uint32_t key_length;
 
4419
  Table *table;
 
4420
  bool result= false; 
 
4421
  bool signalled= false;
 
4422
 
 
4423
  key_pos= strcpy(key_pos, db) + strlen(db);
 
4424
  key_pos= strcpy(key_pos+1, table_name) + strlen(table_name);
 
4425
  key_length= (uint32_t) (key_pos-key)+1;
 
4426
 
 
4427
  for (;;)
 
4428
  {
 
4429
    HASH_SEARCH_STATE state;
 
4430
    result= signalled= false;
 
4431
 
 
4432
    for (table= (Table*) hash_first(&open_cache, (unsigned char*) key, key_length,
 
4433
                                    &state);
 
4434
         table;
 
4435
         table= (Table*) hash_next(&open_cache, (unsigned char*) key, key_length,
 
4436
                                   &state))
 
4437
    {
 
4438
      Session *in_use;
 
4439
 
 
4440
      table->s->version=0L;             /* Free when thread is ready */
 
4441
      if (!(in_use=table->in_use))
 
4442
      {
 
4443
        relink_unused(table);
 
4444
      }
 
4445
      else if (in_use != session)
 
4446
      {
 
4447
        /*
 
4448
          Mark that table is going to be deleted from cache. This will
 
4449
          force threads that are in mysql_lock_tables() (but not yet
 
4450
          in thr_multi_lock()) to abort it's locks, close all tables and retry
 
4451
        */
 
4452
        in_use->some_tables_deleted= true;
 
4453
        if (table->is_name_opened())
 
4454
        {
 
4455
          result= true;
 
4456
        }
 
4457
        /*
 
4458
          Now we must abort all tables locks used by this thread
 
4459
          as the thread may be waiting to get a lock for another table.
 
4460
          Note that we need to hold LOCK_open while going through the
 
4461
          list. So that the other thread cannot change it. The other
 
4462
          thread must also hold LOCK_open whenever changing the
 
4463
          open_tables list. Aborting the MERGE lock after a child was
 
4464
          closed and before the parent is closed would be fatal.
 
4465
        */
 
4466
        for (Table *session_table= in_use->open_tables;
 
4467
             session_table ;
 
4468
             session_table= session_table->next)
 
4469
        {
 
4470
          /* Do not handle locks of MERGE children. */
 
4471
          if (session_table->db_stat)   // If table is open
 
4472
            signalled|= mysql_lock_abort_for_thread(session, session_table);
 
4473
        }
 
4474
      }
 
4475
      else
 
4476
        result= result || (flags & RTFC_OWNED_BY_Session_FLAG);
 
4477
    }
 
4478
    while (unused_tables && !unused_tables->s->version)
 
4479
      hash_delete(&open_cache,(unsigned char*) unused_tables);
 
4480
 
 
4481
    /* Remove table from table definition cache if it's not in use */
 
4482
    TableShare::release(key, key_length);
 
4483
 
 
4484
    if (result && (flags & RTFC_WAIT_OTHER_THREAD_FLAG))
 
4485
    {
 
4486
      /*
 
4487
        Signal any thread waiting for tables to be freed to
 
4488
        reopen their tables
 
4489
      */
 
4490
      broadcast_refresh();
 
4491
      if (!(flags & RTFC_CHECK_KILLED_FLAG) || !session->killed)
 
4492
      {
 
4493
        dropping_tables++;
 
4494
        if (likely(signalled))
 
4495
          (void) pthread_cond_wait(&COND_refresh, &LOCK_open);
 
4496
        else
 
4497
        {
 
4498
          struct timespec abstime;
 
4499
          /*
 
4500
            It can happen that another thread has opened the
 
4501
            table but has not yet locked any table at all. Since
 
4502
            it can be locked waiting for a table that our thread
 
4503
            has done LOCK Table x WRITE on previously, we need to
 
4504
            ensure that the thread actually hears our signal
 
4505
            before we go to sleep. Thus we wait for a short time
 
4506
            and then we retry another loop in the
 
4507
            remove_table_from_cache routine.
 
4508
          */
 
4509
          set_timespec(abstime, 10);
 
4510
          pthread_cond_timedwait(&COND_refresh, &LOCK_open, &abstime);
 
4511
        }
 
4512
        dropping_tables--;
 
4513
        continue;
 
4514
      }
 
4515
    }
 
4516
    break;
 
4517
  }
 
4518
  return result;
 
4519
}
3962
4520
 
3963
4521
 
3964
4522
/**