~drizzle-trunk/drizzle/development

« back to all changes in this revision

Viewing changes to drizzled/sql_base.cc

  • Committer: Olaf van der Spek
  • Date: 2011-02-12 18:24:24 UTC
  • mto: (2167.1.2 build) (2172.1.4 build)
  • mto: This revision was merged to the branch mainline in revision 2168.
  • Revision ID: olafvdspek@gmail.com-20110212182424-kgnm9osi7qo97at2
casts

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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA */
 
14
  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  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"
34
35
 
35
36
#include <drizzled/sql_select.h>
36
37
#include <drizzled/error.h>
44
45
#include <drizzled/lock.h>
45
46
#include <drizzled/plugin/listen.h>
46
47
#include "drizzled/cached_directory.h"
47
 
#include <drizzled/field/timestamp.h>
 
48
#include <drizzled/field/epoch.h>
48
49
#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"
54
55
#include "drizzled/plugin/authorization.h"
 
56
#include "drizzled/table/temporary.h"
 
57
#include "drizzled/table/placeholder.h"
 
58
#include "drizzled/table/unused.h"
55
59
 
56
60
using namespace std;
57
61
 
60
64
 
61
65
extern bool volatile shutdown_in_progress;
62
66
 
63
 
bool drizzle_rm_tmp_tables();
64
 
 
65
 
/**
66
 
  @defgroup Data_Dictionary Data Dictionary
67
 
  @{
68
 
*/
69
 
Table *unused_tables;                           /* Used by mysql_test */
70
 
HASH open_cache;                                /* Used by mysql_test */
71
 
static int open_unireg_entry(Session *session, Table *entry, TableList *table_list,
72
 
                             const char *alias,
73
 
                             char *cache_key, uint32_t cache_key_length);
74
 
void free_cache_entry(void *entry);
75
 
unsigned char *table_cache_key(const unsigned char *record,
76
 
                               size_t *length,
77
 
                               bool );
78
 
 
79
 
 
80
 
unsigned char *table_cache_key(const unsigned char *record,
81
 
                               size_t *length,
82
 
                               bool )
83
 
{
84
 
  Table *entry=(Table*) record;
85
 
  *length= entry->s->table_cache_key.length;
86
 
  return (unsigned char*) entry->s->table_cache_key.str;
87
 
}
88
 
 
89
 
HASH *get_open_cache()
90
 
{
91
 
  return &open_cache;
92
 
}
93
 
 
94
 
 
95
67
bool table_cache_init(void)
96
68
{
97
 
  return hash_init(&open_cache, &my_charset_bin,
98
 
                   (size_t) table_cache_size+16,
99
 
                   0, 0, table_cache_key,
100
 
                   free_cache_entry, 0);
 
69
  return false;
 
70
}
 
71
 
 
72
uint32_t cached_open_tables(void)
 
73
{
 
74
  return table::getCache().size();
101
75
}
102
76
 
103
77
void table_cache_free(void)
104
78
{
105
79
  refresh_version++;                            // Force close of open tables
106
80
 
107
 
  while (unused_tables)
108
 
    hash_delete(&open_cache, (unsigned char*) unused_tables);
109
 
 
110
 
  if (not open_cache.records)                   // Safety first
111
 
    hash_free(&open_cache);
112
 
}
113
 
 
114
 
uint32_t cached_open_tables(void)
115
 
{
116
 
  return open_cache.records;
117
 
}
118
 
 
 
81
  table::getUnused().clear();
 
82
  table::getCache().clear();
 
83
}
119
84
 
120
85
/*
121
86
  Close cursor handle, but leave the table in the table cache
128
93
  By leaving the table in the table cache, it disallows any other thread
129
94
  to open the table
130
95
 
131
 
  session->killed will be set if we run out of memory
 
96
  session->getKilled() will be set if we run out of memory
132
97
 
133
98
  If closing a MERGE child, the calling function has to take care for
134
99
  closing the parent too, if necessary.
137
102
 
138
103
void close_handle_and_leave_table_as_lock(Table *table)
139
104
{
140
 
  TableShare *share, *old_share= table->s;
141
 
  char *key_buff;
142
 
  memory::Root *mem_root= &table->mem_root;
143
 
 
144
105
  assert(table->db_stat);
 
106
  assert(table->getShare()->getType() == message::Table::STANDARD);
145
107
 
146
108
  /*
147
109
    Make a local copy of the table share and free the current one.
148
110
    This has to be done to ensure that the table share is removed from
149
111
    the table defintion cache as soon as the last instance is removed
150
112
  */
151
 
  if (multi_alloc_root(mem_root,
152
 
                       &share, sizeof(*share),
153
 
                       &key_buff, old_share->table_cache_key.length,
154
 
                       NULL))
155
 
  {
156
 
    memset(share, 0, sizeof(*share));
157
 
    share->set_table_cache_key(key_buff, old_share->table_cache_key.str,
158
 
                               old_share->table_cache_key.length);
159
 
    share->tmp_table= message::Table::INTERNAL;       // for intern_close_table()
160
 
  }
 
113
  identifier::Table identifier(table->getShare()->getSchemaName(), table->getShare()->getTableName(), message::Table::INTERNAL);
 
114
  const identifier::Table::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()));
161
118
 
162
119
  table->cursor->close();
163
120
  table->db_stat= 0;                            // Mark cursor closed
164
 
  TableShare::release(table->s);
165
 
  table->s= share;
166
 
  table->cursor->change_table_ptr(table, table->s);
 
121
  table::instance::release(table->getMutableShare());
 
122
  table->setShare(share);
167
123
}
168
124
 
169
125
 
176
132
{                                               // Free all structures
177
133
  free_io_cache();
178
134
  if (cursor)                              // Not true if name lock
179
 
    closefrm(true);                     // close cursor
180
 
}
181
 
 
182
 
/*
183
 
  Remove table from the open table cache
184
 
 
185
 
  SYNOPSIS
186
 
  free_cache_entry()
187
 
  entry         Table to remove
188
 
 
189
 
  NOTE
190
 
  We need to have a lock on LOCK_open when calling this
191
 
*/
192
 
 
193
 
void free_cache_entry(void *entry)
194
 
{
195
 
  Table *table= static_cast<Table *>(entry);
196
 
  table->intern_close_table();
197
 
  if (not table->in_use)
198
135
  {
199
 
    table->next->prev=table->prev;              /* remove from used chain */
200
 
    table->prev->next=table->next;
201
 
    if (table == unused_tables)
202
 
    {
203
 
      unused_tables=unused_tables->next;
204
 
      if (table == unused_tables)
205
 
        unused_tables= NULL;
206
 
    }
 
136
    delete_table(true);                 // close cursor
207
137
  }
208
 
  free(table);
209
138
}
210
139
 
211
140
/* Free resources allocated by filesort() and read_record() */
214
143
{
215
144
  if (sort.io_cache)
216
145
  {
217
 
    close_cached_file(sort.io_cache);
 
146
    sort.io_cache->close_cached_file();
218
147
    delete sort.io_cache;
219
148
    sort.io_cache= 0;
220
149
  }
226
155
 
227
156
  @param session Thread context (may be NULL)
228
157
  @param tables List of tables to remove from the cache
229
 
  @param have_lock If LOCK_open is locked
 
158
  @param have_lock If table::Cache::singleton().mutex() is locked
230
159
  @param wait_for_refresh Wait for a impending flush
231
160
  @param wait_for_placeholders Wait for tables being reopened so that the GRL
232
161
  won't proceed while write-locked tables are being reopened by other
241
170
  bool result= false;
242
171
  Session *session= this;
243
172
 
244
 
  pthread_mutex_lock(&LOCK_open); /* Optionally lock for remove tables from open_cahe if not in use */
245
 
 
246
 
  if (tables == NULL)
247
173
  {
248
 
    refresh_version++;                          // Force close of open tables
249
 
    while (unused_tables)
250
 
      hash_delete(&open_cache,(unsigned char*) unused_tables);
 
174
    boost::mutex::scoped_lock scopedLock(table::Cache::singleton().mutex()); /* 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
      {
 
184
        /*
 
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.
 
220
        */
 
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
        identifier::Table identifier(table->getSchemaName(), table->getTableName());
 
237
        if (table::Cache::singleton().removeTable(session, identifier,
 
238
                                    RTFC_OWNED_BY_Session_FLAG))
 
239
        {
 
240
          found= true;
 
241
        }
 
242
      }
 
243
      if (!found)
 
244
        wait_for_refresh= false;                        // Nothing to wait for
 
245
    }
251
246
 
252
247
    if (wait_for_refresh)
253
248
    {
254
249
      /*
255
 
        Other threads could wait in a loop in open_and_lock_tables(),
256
 
        trying to lock one or more of our tables.
257
 
 
258
 
        If they wait for the locks in thr_multi_lock(), their lock
259
 
        request is aborted. They loop in open_and_lock_tables() and
260
 
        enter open_table(). Here they notice the table is refreshed and
261
 
        wait for COND_refresh. Then they loop again in
262
 
        openTablesLock() and this time open_table() succeeds. At
263
 
        this moment, if we (the FLUSH TABLES thread) are scheduled and
264
 
        on another FLUSH TABLES enter close_cached_tables(), they could
265
 
        awake while we sleep below, waiting for others threads (us) to
266
 
        close their open tables. If this happens, the other threads
267
 
        would find the tables unlocked. They would get the locks, one
268
 
        after the other, and could do their destructive work. This is an
269
 
        issue if we have LOCK TABLES in effect.
270
 
 
271
 
        The problem is that the other threads passed all checks in
272
 
        open_table() before we refresh the table.
273
 
 
274
 
        The fix for this problem is to set some_tables_deleted for all
275
 
        threads with open tables. These threads can still get their
276
 
        locks, but will immediately release them again after checking
277
 
        this variable. They will then loop in openTablesLock()
278
 
        again. There they will wait until we update all tables version
279
 
        below.
280
 
 
281
 
        Setting some_tables_deleted is done by remove_table_from_cache()
282
 
        in the other branch.
283
 
 
284
 
        In other words (reviewer suggestion): You need this setting of
285
 
        some_tables_deleted for the case when table was opened and all
286
 
        related checks were passed before incrementing refresh_version
287
 
        (which you already have) but attempt to lock the table happened
288
 
        after the call to Session::close_old_data_files() i.e. after removal of
289
 
        current thread locks.
 
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
290
252
      */
291
 
      for (uint32_t idx=0 ; idx < open_cache.records ; idx++)
 
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())
292
262
      {
293
 
        Table *table=(Table*) hash_element(&open_cache,idx);
294
 
        if (table->in_use)
295
 
          table->in_use->some_tables_deleted= false;
 
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
            COND_refresh.wait(scopedLock);
 
291
            break;
 
292
          }
 
293
        }
296
294
      }
297
 
    }
298
 
  }
299
 
  else
300
 
  {
301
 
    bool found= false;
302
 
    for (TableList *table= tables; table; table= table->next_local)
303
 
    {
304
 
      if (remove_table_from_cache(session, table->db, table->table_name,
305
 
                                  RTFC_OWNED_BY_Session_FLAG))
306
 
        found= true;
307
 
    }
308
 
    if (!found)
309
 
      wait_for_refresh= false;                  // Nothing to wait for
310
 
  }
311
 
 
312
 
  if (wait_for_refresh)
313
 
  {
314
 
    /*
315
 
      If there is any table that has a lower refresh_version, wait until
316
 
      this is closed (or this thread is killed) before returning
317
 
    */
318
 
    session->mysys_var->current_mutex= &LOCK_open;
319
 
    session->mysys_var->current_cond= &COND_refresh;
320
 
    session->set_proc_info("Flushing tables");
321
 
 
322
 
    session->close_old_data_files();
323
 
 
324
 
    bool found= true;
325
 
    /* Wait until all threads has closed all the tables we had locked */
326
 
    while (found && ! session->killed)
327
 
    {
328
 
      found= false;
329
 
      for (uint32_t idx=0 ; idx < open_cache.records ; idx++)
 
295
      /*
 
296
        No other thread has the locked tables open; reopen them and get the
 
297
        old locks. This should always succeed (unless some external process
 
298
        has removed the tables)
 
299
      */
 
300
      result= session->reopen_tables();
 
301
 
 
302
      /* Set version for table */
 
303
      for (Table *table= session->open_tables; table ; table= table->getNext())
330
304
      {
331
 
        Table *table=(Table*) hash_element(&open_cache,idx);
332
 
        /* Avoid a self-deadlock. */
333
 
        if (table->in_use == session)
334
 
          continue;
335
305
        /*
336
 
          Note that we wait here only for tables which are actually open, and
337
 
          not for placeholders with Table::open_placeholder set. Waiting for
338
 
          latter will cause deadlock in the following scenario, for example:
339
 
 
340
 
conn1: lock table t1 write;
341
 
conn2: lock table t2 write;
342
 
conn1: flush tables;
343
 
conn2: flush tables;
344
 
 
345
 
It also does not make sense to wait for those of placeholders that
346
 
are employed by CREATE TABLE as in this case table simply does not
347
 
exist yet.
 
306
          Preserve the version (0) of write locked tables so that a impending
 
307
          global read lock won't sneak in.
348
308
        */
349
 
        if (table->needs_reopen_or_name_lock() && (table->db_stat ||
350
 
                                                   (table->open_placeholder && wait_for_placeholders)))
351
 
        {
352
 
          found= true;
353
 
          pthread_cond_wait(&COND_refresh,&LOCK_open);
354
 
          break;
355
 
        }
 
309
        if (table->reginfo.lock_type < TL_WRITE_ALLOW_WRITE)
 
310
          table->getMutableShare()->refreshVersion();
356
311
      }
357
312
    }
358
 
    /*
359
 
      No other thread has the locked tables open; reopen them and get the
360
 
      old locks. This should always succeed (unless some external process
361
 
      has removed the tables)
362
 
    */
363
 
    result= session->reopen_tables(true, true);
364
 
 
365
 
    /* Set version for table */
366
 
    for (Table *table= session->open_tables; table ; table= table->next)
367
 
    {
368
 
      /*
369
 
        Preserve the version (0) of write locked tables so that a impending
370
 
        global read lock won't sneak in.
371
 
      */
372
 
      if (table->reginfo.lock_type < TL_WRITE_ALLOW_WRITE)
373
 
        table->s->version= refresh_version;
374
 
    }
375
313
  }
376
314
 
377
 
  pthread_mutex_unlock(&LOCK_open);
378
 
 
379
315
  if (wait_for_refresh)
380
316
  {
381
 
    pthread_mutex_lock(&session->mysys_var->mutex);
 
317
    boost_unique_lock_t scopedLock(session->mysys_var->mutex);
382
318
    session->mysys_var->current_mutex= 0;
383
319
    session->mysys_var->current_cond= 0;
384
320
    session->set_proc_info(0);
385
 
    pthread_mutex_unlock(&session->mysys_var->mutex);
386
321
  }
387
322
 
388
323
  return result;
393
328
  move one table to free list 
394
329
*/
395
330
 
396
 
bool Session::free_cached_table()
 
331
bool Session::free_cached_table(boost::mutex::scoped_lock &scopedLock)
397
332
{
398
333
  bool found_old_table= false;
399
 
  Table *table= open_tables;
400
 
 
401
 
  safe_mutex_assert_owner(&LOCK_open);
 
334
 
 
335
  (void)scopedLock;
 
336
 
 
337
  table::Concurrent *table= static_cast<table::Concurrent *>(open_tables);
 
338
 
 
339
  safe_mutex_assert_owner(table::Cache::singleton().mutex().native_handle());
402
340
  assert(table->key_read == 0);
403
341
  assert(!table->cursor || table->cursor->inited == Cursor::NONE);
404
342
 
405
 
  open_tables= table->next;
 
343
  open_tables= table->getNext();
406
344
 
407
345
  if (table->needs_reopen_or_name_lock() ||
408
346
      version != refresh_version || !table->db_stat)
409
347
  {
410
 
    hash_delete(&open_cache,(unsigned char*) table);
 
348
    table::remove_table(table);
411
349
    found_old_table= true;
412
350
  }
413
351
  else
420
358
 
421
359
    /* Free memory and reset for next loop */
422
360
    table->cursor->ha_reset();
423
 
    table->in_use= false;
 
361
    table->in_use= NULL;
424
362
 
425
 
    if (unused_tables)
426
 
    {
427
 
      table->next= unused_tables;               /* Link in last */
428
 
      table->prev= unused_tables->prev;
429
 
      unused_tables->prev= table;
430
 
      table->prev->next= table;
431
 
    }
432
 
    else
433
 
      unused_tables= table->next=table->prev=table;
 
363
    table::getUnused().link(table);
434
364
  }
435
365
 
436
366
  return found_old_table;
449
379
{
450
380
  bool found_old_table= false;
451
381
 
452
 
  safe_mutex_assert_not_owner(&LOCK_open);
 
382
  safe_mutex_assert_not_owner(table::Cache::singleton().mutex().native_handle());
453
383
 
454
 
  pthread_mutex_lock(&LOCK_open); /* Close all open tables on Session */
 
384
  boost_unique_lock_t scoped_lock(table::Cache::singleton().mutex()); /* Close all open tables on Session */
455
385
 
456
386
  while (open_tables)
457
 
    found_old_table|= free_cached_table();
 
387
  {
 
388
    found_old_table|= free_cached_table(scoped_lock);
 
389
  }
458
390
  some_tables_deleted= false;
459
391
 
460
392
  if (found_old_table)
461
393
  {
462
394
    /* Tell threads waiting for refresh that something has happened */
463
 
    broadcast_refresh();
 
395
    locking::broadcast_refresh();
464
396
  }
465
 
 
466
 
  pthread_mutex_unlock(&LOCK_open);
467
397
}
468
398
 
469
399
/*
491
421
{
492
422
  for (; table; table= table->*link )
493
423
  {
494
 
    if ((table->table == 0 || table->table->s->tmp_table == message::Table::STANDARD) &&
495
 
        strcasecmp(table->db, db_name) == 0 &&
496
 
        strcasecmp(table->table_name, table_name) == 0)
 
424
    if ((table->table == 0 || table->table->getShare()->getType() == message::Table::STANDARD) and
 
425
        my_strcasecmp(system_charset_info, table->getSchemaName(), db_name) == 0 and
 
426
        my_strcasecmp(system_charset_info, table->getTableName(), table_name) == 0)
 
427
    {
497
428
      break;
 
429
    }
498
430
  }
499
431
  return table;
500
432
}
555
487
  if (table->table)
556
488
  {
557
489
    /* temporary table is always unique */
558
 
    if (table->table && table->table->s->tmp_table != message::Table::STANDARD)
 
490
    if (table->table && table->table->getShare()->getType() != message::Table::STANDARD)
559
491
      return 0;
560
492
    table= table->find_underlying_table(table->table);
561
493
    /*
564
496
    */
565
497
    assert(table);
566
498
  }
567
 
  d_name= table->db;
568
 
  t_name= table->table_name;
 
499
  d_name= table->getSchemaName();
 
500
  t_name= table->getTableName();
569
501
  t_alias= table->alias;
570
502
 
571
503
  for (;;)
586
518
}
587
519
 
588
520
 
589
 
void Session::doGetTableNames(SchemaIdentifier &schema_identifier,
590
 
                              std::set<std::string>& set_of_names)
 
521
void Open_tables_state::doGetTableNames(const identifier::Schema &schema_identifier,
 
522
                                        std::set<std::string>& set_of_names)
591
523
{
592
 
  for (Table *table= temporary_tables ; table ; table= table->next)
 
524
  for (Table *table= getTemporaryTables() ; table ; table= table->getNext())
593
525
  {
594
 
    if (schema_identifier.compare(table->s->getSchemaName()))
 
526
    if (schema_identifier.compare(table->getShare()->getSchemaName()))
595
527
    {
596
 
      set_of_names.insert(table->s->table_name.str);
 
528
      set_of_names.insert(table->getShare()->getTableName());
597
529
    }
598
530
  }
599
531
}
600
532
 
601
 
void Session::doGetTableNames(CachedDirectory &,
602
 
                              SchemaIdentifier &schema_identifier,
603
 
                              std::set<std::string> &set_of_names)
 
533
void Open_tables_state::doGetTableNames(CachedDirectory &,
 
534
                                        const identifier::Schema &schema_identifier,
 
535
                                        std::set<std::string> &set_of_names)
604
536
{
605
537
  doGetTableNames(schema_identifier, set_of_names);
606
538
}
607
539
 
608
 
void Session::doGetTableIdentifiers(SchemaIdentifier &schema_identifier,
609
 
                                    TableIdentifiers &set_of_identifiers)
 
540
void Open_tables_state::doGetTableIdentifiers(const identifier::Schema &schema_identifier,
 
541
                                              identifier::Table::vector &set_of_identifiers)
610
542
{
611
 
  for (Table *table= temporary_tables ; table ; table= table->next)
 
543
  for (Table *table= getTemporaryTables() ; table ; table= table->getNext())
612
544
  {
613
 
    if (schema_identifier.compare(table->s->getSchemaName()))
 
545
    if (schema_identifier.compare(table->getShare()->getSchemaName()))
614
546
    {
615
 
      set_of_identifiers.push_back(TableIdentifier(table->getShare()->getSchemaName(),
 
547
      set_of_identifiers.push_back(identifier::Table(table->getShare()->getSchemaName(),
616
548
                                                   table->getShare()->getTableName(),
617
549
                                                   table->getShare()->getPath()));
618
550
    }
619
551
  }
620
552
}
621
553
 
622
 
void Session::doGetTableIdentifiers(CachedDirectory &,
623
 
                                    SchemaIdentifier &schema_identifier,
624
 
                                    TableIdentifiers &set_of_identifiers)
 
554
void Open_tables_state::doGetTableIdentifiers(CachedDirectory &,
 
555
                                              const identifier::Schema &schema_identifier,
 
556
                                              identifier::Table::vector &set_of_identifiers)
625
557
{
626
558
  doGetTableIdentifiers(schema_identifier, set_of_identifiers);
627
559
}
628
560
 
629
 
bool Session::doDoesTableExist(TableIdentifier &identifier)
 
561
bool Open_tables_state::doDoesTableExist(const identifier::Table &identifier)
630
562
{
631
 
  for (Table *table= temporary_tables ; table ; table= table->next)
 
563
  for (Table *table= getTemporaryTables() ; table ; table= table->getNext())
632
564
  {
633
 
    if (table->s->tmp_table == message::Table::TEMPORARY)
 
565
    if (table->getShare()->getType() == message::Table::TEMPORARY)
634
566
    {
635
 
      if (identifier.compare(table->s->getSchemaName(), table->s->table_name.str))
 
567
      if (identifier.getKey() == table->getShare()->getCacheKey())
636
568
      {
637
569
        return true;
638
570
      }
642
574
  return false;
643
575
}
644
576
 
645
 
int Session::doGetTableDefinition(TableIdentifier &identifier,
646
 
                                  message::Table &table_proto)
 
577
int Open_tables_state::doGetTableDefinition(const identifier::Table &identifier,
 
578
                                            message::Table &table_proto)
647
579
{
648
 
  for (Table *table= temporary_tables ; table ; table= table->next)
 
580
  for (Table *table= getTemporaryTables() ; table ; table= table->getNext())
649
581
  {
650
 
    if (table->s->tmp_table == message::Table::TEMPORARY)
 
582
    if (table->getShare()->getType() == message::Table::TEMPORARY)
651
583
    {
652
 
      if (identifier.compare(table->s->getSchemaName(), table->s->table_name.str))
 
584
      if (identifier.getKey() == table->getShare()->getCacheKey())
653
585
      {
654
 
        table_proto.CopyFrom(*(table->s->getTableProto()));
 
586
        table_proto.CopyFrom(*(table->getShare()->getTableMessage()));
655
587
 
656
588
        return EEXIST;
657
589
      }
661
593
  return ENOENT;
662
594
}
663
595
 
664
 
Table *Session::find_temporary_table(const char *new_db, const char *table_name)
665
 
{
666
 
  char  key[MAX_DBKEY_LENGTH];
667
 
  uint  key_length;
668
 
 
669
 
  key_length= TableShare::createKey(key, new_db, table_name);
670
 
 
671
 
  for (Table *table= temporary_tables ; table ; table= table->next)
672
 
  {
673
 
    if (table->s->table_cache_key.length == key_length &&
674
 
        not memcmp(table->s->table_cache_key.str, key, key_length))
675
 
    {
676
 
      return table;
677
 
    }
678
 
  }
679
 
  return NULL;                               // Not a temporary table
680
 
}
681
 
 
682
 
Table *Session::find_temporary_table(TableList *table_list)
683
 
{
684
 
  return find_temporary_table(table_list->db, table_list->table_name);
685
 
}
686
 
 
687
 
Table *Session::find_temporary_table(TableIdentifier &identifier)
688
 
{
689
 
  char  key[MAX_DBKEY_LENGTH];
690
 
  uint  key_length;
691
 
 
692
 
  key_length= TableShare::createKey(key, identifier);
693
 
 
694
 
  for (Table *table= temporary_tables ; table ; table= table->next)
695
 
  {
696
 
    if (table->s->table_cache_key.length == key_length &&
697
 
        not memcmp(table->s->table_cache_key.str, key, key_length))
698
 
 
 
596
Table *Open_tables_state::find_temporary_table(const identifier::Table &identifier)
 
597
{
 
598
  for (Table *table= temporary_tables ; table ; table= table->getNext())
 
599
  {
 
600
    if (identifier.getKey() == table->getShare()->getCacheKey())
699
601
      return table;
700
602
  }
701
603
 
729
631
  @retval -1  the table is in use by a outer query
730
632
*/
731
633
 
732
 
int Session::drop_temporary_table(TableList *table_list)
 
634
int Open_tables_state::drop_temporary_table(const drizzled::identifier::Table &identifier)
733
635
{
734
636
  Table *table;
735
637
 
736
 
  if (not (table= find_temporary_table(table_list)))
 
638
  if (not (table= find_temporary_table(identifier)))
737
639
    return 1;
738
640
 
739
641
  /* Table might be in use by some outer statement. */
740
 
  if (table->query_id && table->query_id != query_id)
 
642
  if (table->query_id && table->query_id != getQueryId())
741
643
  {
742
 
    my_error(ER_CANT_REOPEN_TABLE, MYF(0), table->alias);
 
644
    my_error(ER_CANT_REOPEN_TABLE, MYF(0), table->getAlias());
743
645
    return -1;
744
646
  }
745
647
 
749
651
}
750
652
 
751
653
 
752
 
/* move table first in unused links */
753
 
 
754
 
static void relink_unused(Table *table)
755
 
{
756
 
  if (table != unused_tables)
757
 
  {
758
 
    table->prev->next=table->next;              /* Remove from unused list */
759
 
    table->next->prev=table->prev;
760
 
    table->next=unused_tables;                  /* Link in unused tables */
761
 
    table->prev=unused_tables->prev;
762
 
    unused_tables->prev->next=table;
763
 
    unused_tables->prev=table;
764
 
    unused_tables=table;
765
 
  }
766
 
}
767
 
 
768
 
 
769
654
/**
770
655
  Remove all instances of table from thread's open list and
771
656
  table cache.
772
657
 
773
658
  @param  session     Thread context
774
659
  @param  find    Table to remove
 
660
 
 
661
  @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.
775
662
*/
776
663
 
777
664
void Session::unlink_open_table(Table *find)
778
665
{
779
 
  char key[MAX_DBKEY_LENGTH];
780
 
  uint32_t key_length= find->s->table_cache_key.length;
781
 
  Table *list, **prev;
782
 
 
783
 
  safe_mutex_assert_owner(&LOCK_open);
784
 
 
785
 
  memcpy(key, find->s->table_cache_key.str, key_length);
 
666
  const identifier::Table::Key find_key(find->getShare()->getCacheKey());
 
667
  Table **prev;
 
668
  safe_mutex_assert_owner(table::Cache::singleton().mutex().native_handle());
 
669
 
786
670
  /*
787
 
    Note that we need to hold LOCK_open while changing the
 
671
    Note that we need to hold table::Cache::singleton().mutex() while changing the
788
672
    open_tables list. Another thread may work on it.
789
 
    (See: remove_table_from_cache(), mysql_wait_completed_table())
 
673
    (See: table::Cache::singleton().removeTable(), wait_completed_table())
790
674
    Closing a MERGE child before the parent would be fatal if the
791
675
    other thread tries to abort the MERGE lock in between.
792
676
  */
793
677
  for (prev= &open_tables; *prev; )
794
678
  {
795
 
    list= *prev;
 
679
    Table *list= *prev;
796
680
 
797
 
    if (list->s->table_cache_key.length == key_length &&
798
 
        not memcmp(list->s->table_cache_key.str, key, key_length))
 
681
    if (list->getShare()->getCacheKey() == find_key)
799
682
    {
800
683
      /* Remove table from open_tables list. */
801
 
      *prev= list->next;
 
684
      *prev= list->getNext();
 
685
 
802
686
      /* Close table. */
803
 
      hash_delete(&open_cache,(unsigned char*) list); // Close table
 
687
      table::remove_table(static_cast<table::Concurrent *>(list));
804
688
    }
805
689
    else
806
690
    {
807
691
      /* Step to next entry in open_tables list. */
808
 
      prev= &list->next;
 
692
      prev= list->getNextPtr();
809
693
    }
810
694
  }
811
695
 
812
696
  // Notify any 'refresh' threads
813
 
  broadcast_refresh();
 
697
  locking::broadcast_refresh();
814
698
}
815
699
 
816
700
 
833
717
  table that was locked with LOCK TABLES.
834
718
*/
835
719
 
836
 
void Session::drop_open_table(Table *table, TableIdentifier &identifier)
 
720
void Session::drop_open_table(Table *table, const identifier::Table &identifier)
837
721
{
838
 
  if (table->s->tmp_table)
 
722
  if (table->getShare()->getType())
839
723
  {
840
724
    close_temporary_table(table);
841
725
  }
842
726
  else
843
727
  {
844
 
    pthread_mutex_lock(&LOCK_open); /* Close and drop a table (AUX routine) */
 
728
    boost_unique_lock_t scoped_lock(table::Cache::singleton().mutex()); /* Close and drop a table (AUX routine) */
845
729
    /*
846
730
      unlink_open_table() also tells threads waiting for refresh or close
847
731
      that something has happened.
848
732
    */
849
733
    unlink_open_table(table);
850
 
    quick_rm_table(*this, identifier);
851
 
    pthread_mutex_unlock(&LOCK_open);
 
734
    (void)plugin::StorageEngine::dropTable(*this, identifier);
852
735
  }
853
736
}
854
737
 
864
747
  cond  Condition to wait for
865
748
*/
866
749
 
867
 
void Session::wait_for_condition(pthread_mutex_t *mutex, pthread_cond_t *cond)
 
750
void Session::wait_for_condition(boost::mutex &mutex, boost::condition_variable_any &cond)
868
751
{
869
752
  /* Wait until the current table is up to date */
870
753
  const char *saved_proc_info;
871
 
  mysys_var->current_mutex= mutex;
872
 
  mysys_var->current_cond= cond;
 
754
  mysys_var->current_mutex= &mutex;
 
755
  mysys_var->current_cond= &cond;
873
756
  saved_proc_info= get_proc_info();
874
757
  set_proc_info("Waiting for table");
875
 
  if (!killed)
876
 
    (void) pthread_cond_wait(cond, mutex);
877
 
 
878
 
  /*
879
 
    We must unlock mutex first to avoid deadlock becasue conditions are
880
 
    sent to this thread by doing locks in the following order:
881
 
    lock(mysys_var->mutex)
882
 
    lock(mysys_var->current_mutex)
883
 
 
884
 
    One by effect of this that one can only use wait_for_condition with
885
 
    condition variables that are guranteed to not disapper (freed) even if this
886
 
    mutex is unlocked
887
 
  */
888
 
 
889
 
  pthread_mutex_unlock(mutex);
890
 
  pthread_mutex_lock(&mysys_var->mutex);
 
758
  {
 
759
    /*
 
760
      We must unlock mutex first to avoid deadlock becasue conditions are
 
761
      sent to this thread by doing locks in the following order:
 
762
      lock(mysys_var->mutex)
 
763
      lock(mysys_var->current_mutex)
 
764
 
 
765
      One by effect of this that one can only use wait_for_condition with
 
766
      condition variables that are guranteed to not disapper (freed) even if this
 
767
      mutex is unlocked
 
768
    */
 
769
    boost_unique_lock_t scopedLock(mutex, boost::adopt_lock_t());
 
770
    if (not getKilled())
 
771
    {
 
772
      cond.wait(scopedLock);
 
773
    }
 
774
  }
 
775
  boost_unique_lock_t mysys_scopedLock(mysys_var->mutex);
891
776
  mysys_var->current_mutex= 0;
892
777
  mysys_var->current_cond= 0;
893
778
  set_proc_info(saved_proc_info);
894
 
  pthread_mutex_unlock(&mysys_var->mutex);
895
 
}
896
 
 
897
 
 
898
 
/*
899
 
  Open table which is already name-locked by this thread.
900
 
 
901
 
  SYNOPSIS
902
 
  reopen_name_locked_table()
903
 
  session         Thread handle
904
 
  table_list  TableList object for table to be open, TableList::table
905
 
  member should point to Table object which was used for
906
 
  name-locking.
907
 
  link_in     true  - if Table object for table to be opened should be
908
 
  linked into Session::open_tables list.
909
 
  false - placeholder used for name-locking is already in
910
 
  this list so we only need to preserve Table::next
911
 
  pointer.
912
 
 
913
 
  NOTE
914
 
  This function assumes that its caller already acquired LOCK_open mutex.
915
 
 
916
 
  RETURN VALUE
917
 
  false - Success
918
 
  true  - Error
919
 
*/
920
 
 
921
 
bool Session::reopen_name_locked_table(TableList* table_list, bool link_in)
922
 
{
923
 
  Table *table= table_list->table;
924
 
  TableShare *share;
925
 
  char *table_name= table_list->table_name;
926
 
  Table orig_table;
927
 
 
928
 
  safe_mutex_assert_owner(&LOCK_open);
929
 
 
930
 
  if (killed || !table)
931
 
    return true;
932
 
 
933
 
  orig_table= *table;
934
 
 
935
 
  if (open_unireg_entry(this, table, table_list, table_name,
936
 
                        table->s->table_cache_key.str,
937
 
                        table->s->table_cache_key.length))
938
 
  {
939
 
    table->intern_close_table();
940
 
    /*
941
 
      If there was an error during opening of table (for example if it
942
 
      does not exist) '*table' object can be wiped out. To be able
943
 
      properly release name-lock in this case we should restore this
944
 
      object to its original state.
945
 
    */
946
 
    *table= orig_table;
947
 
    return true;
948
 
  }
949
 
 
950
 
  share= table->s;
951
 
  /*
952
 
    We want to prevent other connections from opening this table until end
953
 
    of statement as it is likely that modifications of table's metadata are
954
 
    not yet finished (for example CREATE TRIGGER have to change .TRG cursor,
955
 
    or we might want to drop table if CREATE TABLE ... SELECT fails).
956
 
    This also allows us to assume that no other connection will sneak in
957
 
    before we will get table-level lock on this table.
958
 
  */
959
 
  share->version=0;
960
 
  table->in_use = this;
961
 
 
962
 
  if (link_in)
963
 
  {
964
 
    table->next= open_tables;
965
 
    open_tables= table;
966
 
  }
967
 
  else
968
 
  {
969
 
    /*
970
 
      Table object should be already in Session::open_tables list so we just
971
 
      need to set Table::next correctly.
972
 
    */
973
 
    table->next= orig_table.next;
974
 
  }
975
 
 
976
 
  table->tablenr= current_tablenr++;
977
 
  table->used_fields= 0;
978
 
  table->const_table= 0;
979
 
  table->null_row= false;
980
 
  table->maybe_null= false;
981
 
  table->force_index= false;
982
 
  table->status= STATUS_NO_RECORD;
983
 
 
984
 
  return false;
985
779
}
986
780
 
987
781
 
998
792
  case of failure.
999
793
*/
1000
794
 
1001
 
Table *Session::table_cache_insert_placeholder(const char *key, uint32_t key_length)
 
795
table::Placeholder *Session::table_cache_insert_placeholder(const drizzled::identifier::Table &arg)
1002
796
{
1003
 
  Table *table;
1004
 
  TableShare *share;
1005
 
  char *key_buff;
1006
 
 
1007
 
  safe_mutex_assert_owner(&LOCK_open);
 
797
  safe_mutex_assert_owner(table::Cache::singleton().mutex().native_handle());
1008
798
 
1009
799
  /*
1010
800
    Create a table entry with the right key and with an old refresh version
1011
 
    Note that we must use multi_malloc() here as this is freed by the
1012
 
    table cache
1013
801
  */
1014
 
  if (! memory::multi_malloc(true,
1015
 
                             &table, sizeof(*table),
1016
 
                             &share, sizeof(*share),
1017
 
                             &key_buff, key_length,
1018
 
                             NULL))
1019
 
    return NULL;
1020
 
 
1021
 
  table->s= share;
1022
 
  share->set_table_cache_key(key_buff, key, key_length);
1023
 
  share->tmp_table= message::Table::INTERNAL;  // for intern_close_table
1024
 
  table->in_use= this;
1025
 
  table->locked_by_name=1;
1026
 
 
1027
 
  if (my_hash_insert(&open_cache, (unsigned char*)table))
 
802
  identifier::Table identifier(arg.getSchemaName(), arg.getTableName(), message::Table::INTERNAL);
 
803
  table::Placeholder *table= new table::Placeholder(this, identifier);
 
804
 
 
805
  if (not table::Cache::singleton().insert(table))
1028
806
  {
1029
 
    free((unsigned char*) table);
 
807
    delete table;
 
808
 
1030
809
    return NULL;
1031
810
  }
1032
811
 
1055
834
  @retval  true   Error occured (OOM)
1056
835
  @retval  false  Success. 'table' parameter set according to above rules.
1057
836
*/
1058
 
bool Session::lock_table_name_if_not_cached(TableIdentifier &identifier, Table **table)
1059
 
{
1060
 
  return lock_table_name_if_not_cached(identifier.getSchemaName().c_str(), identifier.getTableName().c_str(), table);
1061
 
}
1062
 
 
1063
 
bool Session::lock_table_name_if_not_cached(const char *new_db,
1064
 
                                            const char *table_name, Table **table)
1065
 
{
1066
 
  char key[MAX_DBKEY_LENGTH];
1067
 
  char *key_pos= key;
1068
 
  uint32_t key_length;
1069
 
 
1070
 
  key_pos= strcpy(key_pos, new_db) + strlen(new_db);
1071
 
  key_pos= strcpy(key_pos+1, table_name) + strlen(table_name);
1072
 
  key_length= (uint32_t) (key_pos-key)+1;
1073
 
 
1074
 
  pthread_mutex_lock(&LOCK_open); /* Obtain a name lock even though table is not in cache (like for create table)  */
1075
 
 
1076
 
  if (hash_search(&open_cache, (unsigned char *)key, key_length))
 
837
bool Session::lock_table_name_if_not_cached(const identifier::Table &identifier, Table **table)
 
838
{
 
839
  const identifier::Table::Key &key(identifier.getKey());
 
840
 
 
841
  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)  */
 
842
 
 
843
  table::CacheMap::iterator iter;
 
844
 
 
845
  iter= table::getCache().find(key);
 
846
 
 
847
  if (iter != table::getCache().end())
1077
848
  {
1078
 
    pthread_mutex_unlock(&LOCK_open);
1079
849
    *table= 0;
1080
850
    return false;
1081
851
  }
1082
 
  if (not (*table= table_cache_insert_placeholder(key, key_length)))
 
852
 
 
853
  if (not (*table= table_cache_insert_placeholder(identifier)))
1083
854
  {
1084
 
    pthread_mutex_unlock(&LOCK_open);
1085
855
    return true;
1086
856
  }
1087
857
  (*table)->open_placeholder= true;
1088
 
  (*table)->next= open_tables;
 
858
  (*table)->setNext(open_tables);
1089
859
  open_tables= *table;
1090
 
  pthread_mutex_unlock(&LOCK_open);
1091
860
 
1092
861
  return false;
1093
862
}
1128
897
Table *Session::openTable(TableList *table_list, bool *refresh, uint32_t flags)
1129
898
{
1130
899
  Table *table;
1131
 
  char key[MAX_DBKEY_LENGTH];
1132
 
  unsigned int key_length;
1133
900
  const char *alias= table_list->alias;
1134
 
  HASH_SEARCH_STATE state;
1135
901
 
1136
902
  /* Parsing of partitioning information from .frm needs session->lex set up. */
1137
903
  assert(lex->is_lex_started);
1144
910
  if (check_stack_overrun(this, STACK_MIN_SIZE_FOR_OPEN, (unsigned char *)&alias))
1145
911
    return NULL;
1146
912
 
1147
 
  if (killed)
 
913
  if (getKilled())
1148
914
    return NULL;
1149
915
 
1150
 
  key_length= table_list->create_table_def_key(key);
 
916
  identifier::Table identifier(table_list->getSchemaName(), table_list->getTableName());
 
917
  const identifier::Table::Key &key(identifier.getKey());
 
918
  table::CacheRange ppp;
1151
919
 
1152
920
  /*
1153
921
    Unless requested otherwise, try to resolve this table in the list
1156
924
    same name. This block implements the behaviour.
1157
925
    TODO -> move this block into a separate function.
1158
926
  */
1159
 
  for (table= temporary_tables; table ; table=table->next)
 
927
  bool reset= false;
 
928
  for (table= getTemporaryTables(); table ; table=table->getNext())
1160
929
  {
1161
 
    if (table->s->table_cache_key.length == key_length && !memcmp(table->s->table_cache_key.str, key, key_length))
 
930
    if (table->getShare()->getCacheKey() == key)
1162
931
    {
1163
932
      /*
1164
933
        We're trying to use the same temporary table twice in a query.
1168
937
      */
1169
938
      if (table->query_id)
1170
939
      {
1171
 
        my_error(ER_CANT_REOPEN_TABLE, MYF(0), table->alias);
 
940
        my_error(ER_CANT_REOPEN_TABLE, MYF(0), table->getAlias());
1172
941
        return NULL;
1173
942
      }
1174
943
      table->query_id= getQueryId();
1175
 
      goto reset;
1176
 
    }
1177
 
  }
1178
 
 
1179
 
  if (flags & DRIZZLE_OPEN_TEMPORARY_ONLY)
1180
 
  {
1181
 
    my_error(ER_NO_SUCH_TABLE, MYF(0), table_list->db, table_list->table_name);
1182
 
    return NULL;
1183
 
  }
1184
 
 
1185
 
  /*
1186
 
    If it's the first table from a list of tables used in a query,
1187
 
    remember refresh_version (the version of open_cache state).
1188
 
    If the version changes while we're opening the remaining tables,
1189
 
    we will have to back off, close all the tables opened-so-far,
1190
 
    and try to reopen them.
1191
 
 
1192
 
    Note-> refresh_version is currently changed only during FLUSH TABLES.
1193
 
  */
1194
 
  if (!open_tables)
1195
 
    version= refresh_version;
1196
 
  else if ((version != refresh_version) &&
1197
 
           ! (flags & DRIZZLE_LOCK_IGNORE_FLUSH))
1198
 
  {
1199
 
    /* Someone did a refresh while thread was opening tables */
1200
 
    if (refresh)
1201
 
      *refresh= true;
1202
 
 
1203
 
    return NULL;
1204
 
  }
1205
 
 
1206
 
  /*
1207
 
    Before we test the global cache, we test our local session cache.
1208
 
  */
1209
 
  if (cached_table)
1210
 
  {
1211
 
    assert(false); /* Not implemented yet */
1212
 
  }
1213
 
 
1214
 
  /*
1215
 
    Non pre-locked/LOCK TABLES mode, and the table is not temporary:
1216
 
    this is the normal use case.
1217
 
    Now we should:
1218
 
    - try to find the table in the table cache.
1219
 
    - if one of the discovered Table instances is name-locked
1220
 
    (table->s->version == 0) back off -- we have to wait
1221
 
    until no one holds a name lock on the table.
1222
 
    - if there is no such Table in the name cache, read the table definition
1223
 
    and insert it into the cache.
1224
 
    We perform all of the above under LOCK_open which currently protects
1225
 
    the open cache (also known as table cache) and table definitions stored
1226
 
    on disk.
1227
 
  */
1228
 
 
1229
 
  pthread_mutex_lock(&LOCK_open); /* Lock for FLUSH TABLES for open table */
1230
 
 
1231
 
  /*
1232
 
    Actually try to find the table in the open_cache.
1233
 
    The cache may contain several "Table" instances for the same
1234
 
    physical table. The instances that are currently "in use" by
1235
 
    some thread have their "in_use" member != NULL.
1236
 
    There is no good reason for having more than one entry in the
1237
 
    hash for the same physical table, except that we use this as
1238
 
    an implicit "pending locks queue" - see
1239
 
    wait_for_locked_table_names for details.
1240
 
  */
1241
 
  for (table= (Table*) hash_first(&open_cache, (unsigned char*) key, key_length,
1242
 
                                  &state);
1243
 
       table && table->in_use ;
1244
 
       table= (Table*) hash_next(&open_cache, (unsigned char*) key, key_length,
1245
 
                                 &state))
1246
 
  {
 
944
      reset= true;
 
945
      break;
 
946
    }
 
947
  }
 
948
 
 
949
  if (not reset)
 
950
  {
 
951
    if (flags & DRIZZLE_OPEN_TEMPORARY_ONLY)
 
952
    {
 
953
      my_error(ER_TABLE_UNKNOWN, identifier);
 
954
      return NULL;
 
955
    }
 
956
 
1247
957
    /*
1248
 
      Here we flush tables marked for flush.
1249
 
      Normally, table->s->version contains the value of
1250
 
      refresh_version from the moment when this table was
1251
 
      (re-)opened and added to the cache.
1252
 
      If since then we did (or just started) FLUSH TABLES
1253
 
      statement, refresh_version has been increased.
1254
 
      For "name-locked" Table instances, table->s->version is set
1255
 
      to 0 (see lock_table_name for details).
1256
 
      In case there is a pending FLUSH TABLES or a name lock, we
1257
 
      need to back off and re-start opening tables.
1258
 
      If we do not back off now, we may dead lock in case of lock
1259
 
      order mismatch with some other thread:
1260
 
c1: name lock t1; -- sort of exclusive lock
1261
 
c2: open t2;      -- sort of shared lock
1262
 
c1: name lock t2; -- blocks
1263
 
c2: open t1; -- blocks
 
958
      If it's the first table from a list of tables used in a query,
 
959
      remember refresh_version (the version of open_cache state).
 
960
      If the version changes while we're opening the remaining tables,
 
961
      we will have to back off, close all the tables opened-so-far,
 
962
      and try to reopen them.
 
963
 
 
964
      Note-> refresh_version is currently changed only during FLUSH TABLES.
1264
965
    */
1265
 
    if (table->needs_reopen_or_name_lock())
1266
 
    {
1267
 
      if (flags & DRIZZLE_LOCK_IGNORE_FLUSH)
1268
 
      {
1269
 
        /* Force close at once after usage */
1270
 
        version= table->s->version;
1271
 
        continue;
1272
 
      }
1273
 
 
1274
 
      /* Avoid self-deadlocks by detecting self-dependencies. */
1275
 
      if (table->open_placeholder && table->in_use == this)
1276
 
      {
1277
 
        pthread_mutex_unlock(&LOCK_open);
1278
 
        my_error(ER_UPDATE_TABLE_USED, MYF(0), table->s->table_name.str);
1279
 
        return NULL;
1280
 
      }
1281
 
 
1282
 
      /*
1283
 
        Back off, part 1: mark the table as "unused" for the
1284
 
        purpose of name-locking by setting table->db_stat to 0. Do
1285
 
        that only for the tables in this thread that have an old
1286
 
        table->s->version (this is an optimization (?)).
1287
 
        table->db_stat == 0 signals wait_for_locked_table_names
1288
 
        that the tables in question are not used any more. See
1289
 
        table_is_used call for details.
1290
 
      */
1291
 
      close_old_data_files(false, false);
1292
 
 
1293
 
      /*
1294
 
        Back-off part 2: try to avoid "busy waiting" on the table:
1295
 
        if the table is in use by some other thread, we suspend
1296
 
        and wait till the operation is complete: when any
1297
 
        operation that juggles with table->s->version completes,
1298
 
        it broadcasts COND_refresh condition variable.
1299
 
        If 'old' table we met is in use by current thread we return
1300
 
        without waiting since in this situation it's this thread
1301
 
        which is responsible for broadcasting on COND_refresh
1302
 
        (and this was done already in Session::close_old_data_files()).
1303
 
        Good example of such situation is when we have statement
1304
 
        that needs two instances of table and FLUSH TABLES comes
1305
 
        after we open first instance but before we open second
1306
 
        instance.
1307
 
      */
1308
 
      if (table->in_use != this)
1309
 
      {
1310
 
        /* wait_for_conditionwill unlock LOCK_open for us */
1311
 
        wait_for_condition(&LOCK_open, &COND_refresh);
1312
 
      }
1313
 
      else
1314
 
      {
1315
 
        pthread_mutex_unlock(&LOCK_open);
1316
 
      }
1317
 
      /*
1318
 
        There is a refresh in progress for this table.
1319
 
        Signal the caller that it has to try again.
1320
 
      */
 
966
    if (!open_tables)
 
967
    {
 
968
      version= refresh_version;
 
969
    }
 
970
    else if ((version != refresh_version) &&
 
971
             ! (flags & DRIZZLE_LOCK_IGNORE_FLUSH))
 
972
    {
 
973
      /* Someone did a refresh while thread was opening tables */
1321
974
      if (refresh)
1322
975
        *refresh= true;
 
976
 
1323
977
      return NULL;
1324
978
    }
1325
 
  }
1326
 
  if (table)
1327
 
  {
1328
 
    /* Unlink the table from "unused_tables" list. */
1329
 
    if (table == unused_tables)
1330
 
    {  // First unused
1331
 
      unused_tables=unused_tables->next; // Remove from link
1332
 
      if (table == unused_tables)
1333
 
        unused_tables= NULL;
 
979
 
 
980
    /*
 
981
      Before we test the global cache, we test our local session cache.
 
982
    */
 
983
    if (cached_table)
 
984
    {
 
985
      assert(false); /* Not implemented yet */
1334
986
    }
1335
 
    table->prev->next=table->next; /* Remove from unused list */
1336
 
    table->next->prev=table->prev;
1337
 
    table->in_use= this;
1338
 
  }
1339
 
  else
1340
 
  {
1341
 
    /* Insert a new Table instance into the open cache */
1342
 
    int error;
1343
 
    /* Free cache if too big */
1344
 
    while (open_cache.records > table_cache_size && unused_tables)
1345
 
      hash_delete(&open_cache,(unsigned char*) unused_tables);
1346
 
 
1347
 
    if (table_list->create)
 
987
 
 
988
    /*
 
989
      Non pre-locked/LOCK TABLES mode, and the table is not temporary:
 
990
      this is the normal use case.
 
991
      Now we should:
 
992
      - try to find the table in the table cache.
 
993
      - if one of the discovered Table instances is name-locked
 
994
      (table->getShare()->version == 0) back off -- we have to wait
 
995
      until no one holds a name lock on the table.
 
996
      - if there is no such Table in the name cache, read the table definition
 
997
      and insert it into the cache.
 
998
      We perform all of the above under table::Cache::singleton().mutex() which currently protects
 
999
      the open cache (also known as table cache) and table definitions stored
 
1000
      on disk.
 
1001
    */
 
1002
 
1348
1003
    {
1349
 
      TableIdentifier  lock_table_identifier(table_list->db, table_list->table_name, message::Table::STANDARD);
1350
 
 
1351
 
      if (not plugin::StorageEngine::doesTableExist(*this, lock_table_identifier))
 
1004
      boost::mutex::scoped_lock scopedLock(table::Cache::singleton().mutex());
 
1005
 
 
1006
      /*
 
1007
        Actually try to find the table in the open_cache.
 
1008
        The cache may contain several "Table" instances for the same
 
1009
        physical table. The instances that are currently "in use" by
 
1010
        some thread have their "in_use" member != NULL.
 
1011
        There is no good reason for having more than one entry in the
 
1012
        hash for the same physical table, except that we use this as
 
1013
        an implicit "pending locks queue" - see
 
1014
        wait_for_locked_table_names for details.
 
1015
      */
 
1016
      ppp= table::getCache().equal_range(key);
 
1017
 
 
1018
      table= NULL;
 
1019
      for (table::CacheMap::const_iterator iter= ppp.first;
 
1020
           iter != ppp.second; ++iter, table= NULL)
1352
1021
      {
 
1022
        table= (*iter).second;
 
1023
 
 
1024
        if (not table->in_use)
 
1025
          break;
1353
1026
        /*
1354
 
          Table to be created, so we need to create placeholder in table-cache.
 
1027
          Here we flush tables marked for flush.
 
1028
          Normally, table->getShare()->version contains the value of
 
1029
          refresh_version from the moment when this table was
 
1030
          (re-)opened and added to the cache.
 
1031
          If since then we did (or just started) FLUSH TABLES
 
1032
          statement, refresh_version has been increased.
 
1033
          For "name-locked" Table instances, table->getShare()->version is set
 
1034
          to 0 (see lock_table_name for details).
 
1035
          In case there is a pending FLUSH TABLES or a name lock, we
 
1036
          need to back off and re-start opening tables.
 
1037
          If we do not back off now, we may dead lock in case of lock
 
1038
          order mismatch with some other thread:
 
1039
          c1-> name lock t1; -- sort of exclusive lock
 
1040
          c2-> open t2;      -- sort of shared lock
 
1041
          c1-> name lock t2; -- blocks
 
1042
          c2-> open t1; -- blocks
1355
1043
        */
1356
 
        if (!(table= table_cache_insert_placeholder(key, key_length)))
 
1044
        if (table->needs_reopen_or_name_lock())
1357
1045
        {
1358
 
          pthread_mutex_unlock(&LOCK_open);
 
1046
          if (flags & DRIZZLE_LOCK_IGNORE_FLUSH)
 
1047
          {
 
1048
            /* Force close at once after usage */
 
1049
            version= table->getShare()->getVersion();
 
1050
            continue;
 
1051
          }
 
1052
 
 
1053
          /* Avoid self-deadlocks by detecting self-dependencies. */
 
1054
          if (table->open_placeholder && table->in_use == this)
 
1055
          {
 
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
            scopedLock.release();
 
1091
          }
 
1092
          else
 
1093
          {
 
1094
            scopedLock.unlock();
 
1095
          }
 
1096
 
 
1097
          /*
 
1098
            There is a refresh in progress for this table.
 
1099
            Signal the caller that it has to try again.
 
1100
          */
 
1101
          if (refresh)
 
1102
            *refresh= true;
 
1103
 
1359
1104
          return NULL;
1360
1105
        }
1361
 
        /*
1362
 
          Link placeholder to the open tables list so it will be automatically
1363
 
          removed once tables are closed. Also mark it so it won't be ignored
1364
 
          by other trying to take name-lock.
1365
 
        */
1366
 
        table->open_placeholder= true;
1367
 
        table->next= open_tables;
1368
 
        open_tables= table;
1369
 
        pthread_mutex_unlock(&LOCK_open);
1370
 
 
1371
 
        return table ;
1372
 
      }
1373
 
      /* Table exists. Let us try to open it. */
1374
 
    }
1375
 
 
1376
 
    /* make a new table */
1377
 
    table= (Table *)malloc(sizeof(Table));
1378
 
    if (table == NULL)
1379
 
    {
1380
 
      pthread_mutex_unlock(&LOCK_open);
1381
 
      return NULL;
1382
 
    }
1383
 
 
1384
 
    error= open_unireg_entry(this, table, table_list, alias, key, key_length);
1385
 
    if (error != 0)
1386
 
    {
1387
 
      free(table);
1388
 
      pthread_mutex_unlock(&LOCK_open);
1389
 
      return NULL;
1390
 
    }
1391
 
    my_hash_insert(&open_cache, (unsigned char*) table);
1392
 
  }
1393
 
 
1394
 
  pthread_mutex_unlock(&LOCK_open);
1395
 
  if (refresh)
1396
 
  {
1397
 
    table->next= open_tables; /* Link into simple list */
1398
 
    open_tables=table;
1399
 
  }
1400
 
  table->reginfo.lock_type= TL_READ; /* Assume read */
1401
 
 
1402
 
reset:
1403
 
  assert(table->s->ref_count > 0 || table->s->tmp_table != message::Table::STANDARD);
1404
 
 
1405
 
  if (lex->need_correct_ident())
1406
 
    table->alias_name_used= my_strcasecmp(table_alias_charset,
1407
 
                                          table->s->table_name.str, alias);
 
1106
      }
 
1107
 
 
1108
      if (table)
 
1109
      {
 
1110
        table::getUnused().unlink(static_cast<table::Concurrent *>(table));
 
1111
        table->in_use= this;
 
1112
      }
 
1113
      else
 
1114
      {
 
1115
        /* Insert a new Table instance into the open cache */
 
1116
        int error;
 
1117
        /* Free cache if too big */
 
1118
        table::getUnused().cull();
 
1119
 
 
1120
        if (table_list->isCreate())
 
1121
        {
 
1122
          identifier::Table  lock_table_identifier(table_list->getSchemaName(), table_list->getTableName(), message::Table::STANDARD);
 
1123
 
 
1124
          if (not plugin::StorageEngine::doesTableExist(*this, lock_table_identifier))
 
1125
          {
 
1126
            /*
 
1127
              Table to be created, so we need to create placeholder in table-cache.
 
1128
            */
 
1129
            if (!(table= table_cache_insert_placeholder(lock_table_identifier)))
 
1130
            {
 
1131
              return NULL;
 
1132
            }
 
1133
            /*
 
1134
              Link placeholder to the open tables list so it will be automatically
 
1135
              removed once tables are closed. Also mark it so it won't be ignored
 
1136
              by other trying to take name-lock.
 
1137
            */
 
1138
            table->open_placeholder= true;
 
1139
            table->setNext(open_tables);
 
1140
            open_tables= table;
 
1141
 
 
1142
            return table ;
 
1143
          }
 
1144
          /* Table exists. Let us try to open it. */
 
1145
        }
 
1146
 
 
1147
        /* make a new table */
 
1148
        {
 
1149
          table::Concurrent *new_table= new table::Concurrent;
 
1150
          table= new_table;
 
1151
          if (new_table == NULL)
 
1152
          {
 
1153
            return NULL;
 
1154
          }
 
1155
 
 
1156
          error= new_table->open_unireg_entry(this, alias, identifier);
 
1157
          if (error != 0)
 
1158
          {
 
1159
            delete new_table;
 
1160
            return NULL;
 
1161
          }
 
1162
          (void)table::Cache::singleton().insert(new_table);
 
1163
        }
 
1164
      }
 
1165
    }
 
1166
 
 
1167
    if (refresh)
 
1168
    {
 
1169
      table->setNext(open_tables); /* Link into simple list */
 
1170
      open_tables= table;
 
1171
    }
 
1172
    table->reginfo.lock_type= TL_READ; /* Assume read */
 
1173
 
 
1174
  }
 
1175
  assert(table->getShare()->getTableCount() > 0 || table->getShare()->getType() != message::Table::STANDARD);
 
1176
 
1408
1177
  /* Fix alias if table name changes */
1409
 
  if (strcmp(table->alias, alias))
 
1178
  if (strcmp(table->getAlias(), alias))
1410
1179
  {
1411
 
    uint32_t length=(uint32_t) strlen(alias)+1;
1412
 
    table->alias= (char*) realloc((char*) table->alias, length);
1413
 
    memcpy((void*) table->alias, alias, length);
 
1180
    table->setAlias(alias);
1414
1181
  }
1415
1182
 
1416
1183
  /* These variables are also set in reopen_table() */
1421
1188
  table->maybe_null= false;
1422
1189
  table->force_index= false;
1423
1190
  table->status=STATUS_NO_RECORD;
1424
 
  table->insert_values= 0;
 
1191
  table->insert_values.clear();
1425
1192
  /* Catch wrong handling of the auto_increment_field_not_null. */
1426
1193
  assert(!table->auto_increment_field_not_null);
1427
1194
  table->auto_increment_field_not_null= false;
1428
1195
  if (table->timestamp_field)
 
1196
  {
1429
1197
    table->timestamp_field_type= table->timestamp_field->get_auto_set_type();
 
1198
  }
1430
1199
  table->pos_in_table_list= table_list;
1431
1200
  table->clear_column_bitmaps();
1432
1201
  assert(table->key_read == 0);
1435
1204
}
1436
1205
 
1437
1206
 
1438
 
/*
1439
 
  Reopen an table because the definition has changed.
1440
 
 
1441
 
  SYNOPSIS
1442
 
  reopen_table()
1443
 
  table Table object
1444
 
 
1445
 
  NOTES
1446
 
  The data cursor for the table is already closed and the share is released
1447
 
  The table has a 'dummy' share that mainly contains database and table name.
1448
 
 
1449
 
  RETURN
1450
 
  0  ok
1451
 
  1  error. The old table object is not changed.
1452
 
*/
1453
 
 
1454
 
bool reopen_table(Table *table)
1455
 
{
1456
 
  Table tmp;
1457
 
  bool error= 1;
1458
 
  Field **field;
1459
 
  uint32_t key,part;
1460
 
  TableList table_list;
1461
 
  Session *session= table->in_use;
1462
 
 
1463
 
  assert(table->s->ref_count == 0);
1464
 
  assert(!table->sort.io_cache);
1465
 
 
1466
 
#ifdef EXTRA_DEBUG
1467
 
  if (table->db_stat)
1468
 
    errmsg_printf(ERRMSG_LVL_ERROR, _("Table %s had a open data Cursor in reopen_table"),
1469
 
                  table->alias);
1470
 
#endif
1471
 
  table_list.db=         const_cast<char *>(table->s->getSchemaName());
1472
 
  table_list.table_name= table->s->table_name.str;
1473
 
  table_list.table=      table;
1474
 
 
1475
 
  if (wait_for_locked_table_names(session, &table_list))
1476
 
    return true;                             // Thread was killed
1477
 
 
1478
 
  if (open_unireg_entry(session, &tmp, &table_list,
1479
 
                        table->alias,
1480
 
                        table->s->table_cache_key.str,
1481
 
                        table->s->table_cache_key.length))
1482
 
    goto end;
1483
 
 
1484
 
  /* This list copies variables set by open_table */
1485
 
  tmp.tablenr=          table->tablenr;
1486
 
  tmp.used_fields=      table->used_fields;
1487
 
  tmp.const_table=      table->const_table;
1488
 
  tmp.null_row=         table->null_row;
1489
 
  tmp.maybe_null=       table->maybe_null;
1490
 
  tmp.status=           table->status;
1491
 
 
1492
 
  /* Get state */
1493
 
  tmp.in_use=           session;
1494
 
  tmp.reginfo.lock_type=table->reginfo.lock_type;
1495
 
 
1496
 
  /* Replace table in open list */
1497
 
  tmp.next=             table->next;
1498
 
  tmp.prev=             table->prev;
1499
 
 
1500
 
  if (table->cursor)
1501
 
    table->closefrm(true);              // close cursor, free everything
1502
 
 
1503
 
  *table= tmp;
1504
 
  table->default_column_bitmaps();
1505
 
  table->cursor->change_table_ptr(table, table->s);
1506
 
 
1507
 
  assert(table->alias != 0);
1508
 
  for (field=table->field ; *field ; field++)
1509
 
  {
1510
 
    (*field)->table= (*field)->orig_table= table;
1511
 
    (*field)->table_name= &table->alias;
1512
 
  }
1513
 
  for (key=0 ; key < table->s->keys ; key++)
1514
 
  {
1515
 
    for (part=0 ; part < table->key_info[key].usable_key_parts ; part++)
1516
 
      table->key_info[key].key_part[part].field->table= table;
1517
 
  }
1518
 
 
1519
 
  broadcast_refresh();
1520
 
  error= false;
1521
 
 
1522
 
end:
1523
 
  return(error);
1524
 
}
1525
 
 
1526
 
 
1527
1207
/**
1528
1208
  Close all instances of a table open by this thread and replace
1529
1209
  them with exclusive name-locks.
1541
1221
  the strings are used in a loop even after the share may be freed.
1542
1222
*/
1543
1223
 
1544
 
void Session::close_data_files_and_morph_locks(TableIdentifier &identifier)
1545
 
{
1546
 
  close_data_files_and_morph_locks(identifier.getSchemaName().c_str(), identifier.getTableName().c_str());
1547
 
}
1548
 
 
1549
 
void Session::close_data_files_and_morph_locks(const char *new_db, const char *new_table_name)
1550
 
{
1551
 
  Table *table;
1552
 
 
1553
 
  safe_mutex_assert_owner(&LOCK_open); /* Adjust locks at the end of ALTER TABLEL */
 
1224
void Session::close_data_files_and_morph_locks(const identifier::Table &identifier)
 
1225
{
 
1226
  safe_mutex_assert_owner(table::Cache::singleton().mutex().native_handle()); /* Adjust locks at the end of ALTER TABLEL */
1554
1227
 
1555
1228
  if (lock)
1556
1229
  {
1558
1231
      If we are not under LOCK TABLES we should have only one table
1559
1232
      open and locked so it makes sense to remove the lock at once.
1560
1233
    */
1561
 
    mysql_unlock_tables(this, lock);
 
1234
    unlockTables(lock);
1562
1235
    lock= 0;
1563
1236
  }
1564
1237
 
1567
1240
    for target table name if we process ALTER Table ... RENAME.
1568
1241
    So loop below makes sense even if we are not under LOCK TABLES.
1569
1242
  */
1570
 
  for (table= open_tables; table ; table=table->next)
 
1243
  for (Table *table= open_tables; table ; table=table->getNext())
1571
1244
  {
1572
 
    if (!strcmp(table->s->table_name.str, new_table_name) &&
1573
 
        !strcasecmp(table->s->getSchemaName(), new_db))
 
1245
    if (table->getShare()->getCacheKey() == identifier.getKey())
1574
1246
    {
1575
1247
      table->open_placeholder= true;
1576
1248
      close_handle_and_leave_table_as_lock(table);
1594
1266
  combination when one needs tables to be reopened (for
1595
1267
  example see openTablesLock()).
1596
1268
 
1597
 
  @note One should have lock on LOCK_open when calling this.
 
1269
  @note One should have lock on table::Cache::singleton().mutex() when calling this.
1598
1270
 
1599
1271
  @return false in case of success, true - otherwise.
1600
1272
*/
1601
1273
 
1602
 
bool Session::reopen_tables(bool get_locks, bool mark_share_as_old)
 
1274
bool Session::reopen_tables()
1603
1275
{
1604
1276
  Table *table,*next,**prev;
1605
 
  Table **tables,**tables_ptr;                  // For locks
1606
 
  bool error=0, not_used;
 
1277
  Table **tables= 0;                    // For locks
 
1278
  Table **tables_ptr= 0;                        // For locks
 
1279
  bool error= false;
1607
1280
  const uint32_t flags= DRIZZLE_LOCK_NOTIFY_IF_NEED_REOPEN |
1608
1281
    DRIZZLE_LOCK_IGNORE_GLOBAL_READ_LOCK |
1609
1282
    DRIZZLE_LOCK_IGNORE_FLUSH;
1611
1284
  if (open_tables == NULL)
1612
1285
    return false;
1613
1286
 
1614
 
  safe_mutex_assert_owner(&LOCK_open);
1615
 
  if (get_locks)
 
1287
  safe_mutex_assert_owner(table::Cache::singleton().mutex().native_handle());
1616
1288
  {
1617
1289
    /*
1618
1290
      The ptr is checked later
1620
1292
    */
1621
1293
    uint32_t opens= 0;
1622
1294
 
1623
 
    for (table= open_tables; table ; table=table->next)
 
1295
    for (table= open_tables; table ; table=table->getNext())
 
1296
    {
1624
1297
      opens++;
 
1298
    }
1625
1299
    tables= new Table *[opens];
1626
1300
  }
1627
 
  else
1628
 
    tables= &open_tables;
 
1301
 
1629
1302
  tables_ptr =tables;
1630
1303
 
1631
1304
  prev= &open_tables;
1632
1305
  for (table= open_tables; table ; table=next)
1633
1306
  {
1634
 
    uint32_t db_stat= table->db_stat;
1635
 
    next= table->next;
1636
 
    if (!tables || (!db_stat && reopen_table(table)))
1637
 
    {
1638
 
      my_error(ER_CANT_REOPEN_TABLE, MYF(0), table->alias);
1639
 
      hash_delete(&open_cache,(unsigned char*) table);
1640
 
      error= 1;
1641
 
    }
1642
 
    else
1643
 
    {
1644
 
      *prev= table;
1645
 
      prev= &table->next;
1646
 
      /* Do not handle locks of MERGE children. */
1647
 
      if (get_locks && !db_stat)
1648
 
        *tables_ptr++= table;                   // need new lock on this
1649
 
      if (mark_share_as_old)
1650
 
      {
1651
 
        table->s->version= 0;
1652
 
        table->open_placeholder= false;
1653
 
      }
1654
 
    }
 
1307
    next= table->getNext();
 
1308
 
 
1309
    my_error(ER_CANT_REOPEN_TABLE, MYF(0), table->getAlias());
 
1310
    table::remove_table(static_cast<table::Concurrent *>(table));
 
1311
    error= 1;
1655
1312
  }
1656
1313
  *prev=0;
 
1314
 
1657
1315
  if (tables != tables_ptr)                     // Should we get back old locks
1658
1316
  {
1659
 
    DRIZZLE_LOCK *local_lock;
 
1317
    DrizzleLock *local_lock;
1660
1318
    /*
1661
1319
      We should always get these locks. Anyway, we must not go into
1662
 
      wait_for_tables() as it tries to acquire LOCK_open, which is
 
1320
      wait_for_tables() as it tries to acquire table::Cache::singleton().mutex(), which is
1663
1321
      already locked.
1664
1322
    */
1665
1323
    some_tables_deleted= false;
1666
1324
 
1667
 
    if ((local_lock= mysql_lock_tables(this, tables, (uint32_t) (tables_ptr - tables),
1668
 
                                 flags, &not_used)))
 
1325
    if ((local_lock= lockTables(tables, (uint32_t) (tables_ptr - tables), flags)))
1669
1326
    {
1670
1327
      /* unused */
1671
1328
    }
1681
1338
    }
1682
1339
  }
1683
1340
 
1684
 
  if (get_locks && tables)
1685
 
    delete [] tables;
1686
 
 
1687
 
  broadcast_refresh();
1688
 
 
1689
 
  return(error);
 
1341
  delete [] tables;
 
1342
 
 
1343
  locking::broadcast_refresh();
 
1344
 
 
1345
  return error;
1690
1346
}
1691
1347
 
1692
1348
 
1710
1366
 
1711
1367
  Table *table= open_tables;
1712
1368
 
1713
 
  for (; table ; table=table->next)
 
1369
  for (; table ; table=table->getNext())
1714
1370
  {
1715
1371
    /*
1716
1372
      Reopen marked for flush.
1717
1373
    */
1718
1374
    if (table->needs_reopen_or_name_lock())
1719
1375
    {
1720
 
      found=1;
 
1376
      found= true;
1721
1377
      if (table->db_stat)
1722
1378
      {
1723
1379
        if (morph_locks)
1731
1387
              lock on it. This will also give them a chance to close their
1732
1388
              instances of this table.
1733
1389
            */
1734
 
            mysql_lock_abort(this, ulcktbl);
1735
 
            mysql_lock_remove(this, ulcktbl);
 
1390
            abortLock(ulcktbl);
 
1391
            removeLock(ulcktbl);
1736
1392
            ulcktbl->lock_count= 0;
1737
1393
          }
1738
1394
          if ((ulcktbl != table) && ulcktbl->db_stat)
1772
1428
    }
1773
1429
  }
1774
1430
  if (found)
1775
 
    broadcast_refresh();
1776
 
}
1777
 
 
1778
 
 
1779
 
/*
1780
 
  Wait until all threads has closed the tables in the list
1781
 
  We have also to wait if there is thread that has a lock on this table even
1782
 
  if the table is closed
1783
 
*/
1784
 
 
1785
 
bool table_is_used(Table *table, bool wait_for_name_lock)
1786
 
{
1787
 
  do
1788
 
  {
1789
 
    char *key= table->s->table_cache_key.str;
1790
 
    uint32_t key_length= table->s->table_cache_key.length;
1791
 
 
1792
 
    HASH_SEARCH_STATE state;
1793
 
    for (Table *search= (Table*) hash_first(&open_cache, (unsigned char*) key,
1794
 
                                            key_length, &state);
1795
 
         search ;
1796
 
         search= (Table*) hash_next(&open_cache, (unsigned char*) key,
1797
 
                                    key_length, &state))
1798
 
    {
1799
 
      if (search->in_use == table->in_use)
1800
 
        continue;                               // Name locked by this thread
1801
 
      /*
1802
 
        We can't use the table under any of the following conditions:
1803
 
        - There is an name lock on it (Table is to be deleted or altered)
1804
 
        - If we are in flush table and we didn't execute the flush
1805
 
        - If the table engine is open and it's an old version
1806
 
        (We must wait until all engines are shut down to use the table)
1807
 
      */
1808
 
      if ( (search->locked_by_name && wait_for_name_lock) ||
1809
 
           (search->is_name_opened() && search->needs_reopen_or_name_lock()))
1810
 
        return 1;
1811
 
    }
1812
 
  } while ((table=table->next));
1813
 
  return 0;
1814
 
}
1815
 
 
1816
 
 
1817
 
/* Wait until all used tables are refreshed */
1818
 
 
1819
 
bool wait_for_tables(Session *session)
1820
 
{
1821
 
  bool result;
1822
 
 
1823
 
  session->set_proc_info("Waiting for tables");
1824
 
  pthread_mutex_lock(&LOCK_open); /* Lock for all tables to be refreshed */
1825
 
  while (!session->killed)
1826
 
  {
1827
 
    session->some_tables_deleted= false;
1828
 
    session->close_old_data_files(false, dropping_tables != 0);
1829
 
    if (!table_is_used(session->open_tables, 1))
1830
 
      break;
1831
 
    (void) pthread_cond_wait(&COND_refresh,&LOCK_open);
1832
 
  }
1833
 
  if (session->killed)
1834
 
    result= true;                                       // aborted
1835
 
  else
1836
 
  {
1837
 
    /* Now we can open all tables without any interference */
1838
 
    session->set_proc_info("Reopen tables");
1839
 
    session->version= refresh_version;
1840
 
    result= session->reopen_tables(false, false);
1841
 
  }
1842
 
  pthread_mutex_unlock(&LOCK_open);
1843
 
  session->set_proc_info(0);
1844
 
 
1845
 
  return result;
 
1431
    locking::broadcast_refresh();
1846
1432
}
1847
1433
 
1848
1434
 
1870
1456
*/
1871
1457
 
1872
1458
 
1873
 
Table *drop_locked_tables(Session *session,const char *db, const char *table_name)
 
1459
Table *drop_locked_tables(Session *session, const drizzled::identifier::Table &identifier)
1874
1460
{
1875
1461
  Table *table,*next,**prev, *found= 0;
1876
1462
  prev= &session->open_tables;
1877
1463
 
1878
1464
  /*
1879
 
    Note that we need to hold LOCK_open while changing the
 
1465
    Note that we need to hold table::Cache::singleton().mutex() while changing the
1880
1466
    open_tables list. Another thread may work on it.
1881
 
    (See: remove_table_from_cache(), mysql_wait_completed_table())
 
1467
    (See: table::Cache::singleton().removeTable(), wait_completed_table())
1882
1468
    Closing a MERGE child before the parent would be fatal if the
1883
1469
    other thread tries to abort the MERGE lock in between.
1884
1470
  */
1885
1471
  for (table= session->open_tables; table ; table=next)
1886
1472
  {
1887
 
    next=table->next;
1888
 
    if (!strcmp(table->s->table_name.str, table_name) &&
1889
 
        !strcasecmp(table->s->getSchemaName(), db))
 
1473
    next=table->getNext();
 
1474
    if (table->getShare()->getCacheKey() == identifier.getKey())
1890
1475
    {
1891
 
      mysql_lock_remove(session, table);
 
1476
      session->removeLock(table);
1892
1477
 
1893
1478
      if (!found)
1894
1479
      {
1903
1488
      else
1904
1489
      {
1905
1490
        /* We already have a name lock, remove copy */
1906
 
        hash_delete(&open_cache,(unsigned char*) table);
 
1491
        table::remove_table(static_cast<table::Concurrent *>(table));
1907
1492
      }
1908
1493
    }
1909
1494
    else
1910
1495
    {
1911
1496
      *prev=table;
1912
 
      prev= &table->next;
 
1497
      prev= table->getNextPtr();
1913
1498
    }
1914
1499
  }
1915
1500
  *prev=0;
 
1501
 
1916
1502
  if (found)
1917
 
    broadcast_refresh();
 
1503
    locking::broadcast_refresh();
1918
1504
 
1919
 
  return(found);
 
1505
  return found;
1920
1506
}
1921
1507
 
1922
1508
 
1926
1512
  other threads trying to get the lock.
1927
1513
*/
1928
1514
 
1929
 
void abort_locked_tables(Session *session,const char *db, const char *table_name)
 
1515
void abort_locked_tables(Session *session, const drizzled::identifier::Table &identifier)
1930
1516
{
1931
1517
  Table *table;
1932
 
  for (table= session->open_tables; table ; table= table->next)
 
1518
  for (table= session->open_tables; table ; table= table->getNext())
1933
1519
  {
1934
 
    if (!strcmp(table->s->table_name.str, table_name) &&
1935
 
        !strcmp(table->s->getSchemaName(), db))
 
1520
    if (table->getShare()->getCacheKey() == identifier.getKey())
1936
1521
    {
1937
1522
      /* If MERGE child, forward lock handling to parent. */
1938
 
      mysql_lock_abort(session, table);
 
1523
      session->abortLock(table);
 
1524
      assert(0);
1939
1525
      break;
1940
1526
    }
1941
1527
  }
1942
1528
}
1943
1529
 
1944
 
/*
1945
 
  Load a table definition from cursor and open unireg table
1946
 
 
1947
 
  SYNOPSIS
1948
 
  open_unireg_entry()
1949
 
  session                       Thread handle
1950
 
  entry         Store open table definition here
1951
 
  table_list            TableList with db, table_name
1952
 
  alias         Alias name
1953
 
  cache_key             Key for share_cache
1954
 
  cache_key_length      length of cache_key
1955
 
 
1956
 
  NOTES
1957
 
  Extra argument for open is taken from session->open_options
1958
 
  One must have a lock on LOCK_open when calling this function
1959
 
 
1960
 
  RETURN
1961
 
  0     ok
1962
 
#       Error
1963
 
*/
1964
 
 
1965
 
static int open_unireg_entry(Session *session, Table *entry, TableList *table_list,
1966
 
                             const char *alias,
1967
 
                             char *cache_key, uint32_t cache_key_length)
1968
 
{
1969
 
  int error;
1970
 
  TableShare *share;
1971
 
  uint32_t discover_retry_count= 0;
1972
 
 
1973
 
  safe_mutex_assert_owner(&LOCK_open);
1974
 
retry:
1975
 
  if (not (share= TableShare::getShare(session, table_list, cache_key,
1976
 
                                       cache_key_length,
1977
 
                                       table_list->i_s_requested_object,
1978
 
                                       &error)))
1979
 
    return 1;
1980
 
 
1981
 
  while ((error= open_table_from_share(session, share, alias,
1982
 
                                       (uint32_t) (HA_OPEN_KEYFILE |
1983
 
                                                   HA_OPEN_RNDFILE |
1984
 
                                                   HA_GET_INDEX |
1985
 
                                                   HA_TRY_READ_ONLY),
1986
 
                                       session->open_options, entry)))
1987
 
  {
1988
 
    if (error == 7)                             // Table def changed
1989
 
    {
1990
 
      share->version= 0;                        // Mark share as old
1991
 
      if (discover_retry_count++)               // Retry once
1992
 
        goto err;
1993
 
 
1994
 
      /*
1995
 
        TODO->
1996
 
        Here we should wait until all threads has released the table.
1997
 
        For now we do one retry. This may cause a deadlock if there
1998
 
        is other threads waiting for other tables used by this thread.
1999
 
 
2000
 
        Proper fix would be to if the second retry failed:
2001
 
        - Mark that table def changed
2002
 
        - Return from open table
2003
 
        - Close all tables used by this thread
2004
 
        - Start waiting that the share is released
2005
 
        - Retry by opening all tables again
2006
 
      */
2007
 
 
2008
 
      /*
2009
 
        TO BE FIXED
2010
 
        To avoid deadlock, only wait for release if no one else is
2011
 
        using the share.
2012
 
      */
2013
 
      if (share->ref_count != 1)
2014
 
        goto err;
2015
 
      /* Free share and wait until it's released by all threads */
2016
 
      TableShare::release(share);
2017
 
 
2018
 
      if (!session->killed)
2019
 
      {
2020
 
        drizzle_reset_errors(session, 1);         // Clear warnings
2021
 
        session->clear_error();                 // Clear error message
2022
 
        goto retry;
2023
 
      }
2024
 
      return 1;
2025
 
    }
2026
 
 
2027
 
    goto err;
2028
 
  }
2029
 
 
2030
 
  return 0;
2031
 
 
2032
 
err:
2033
 
  TableShare::release(share);
2034
 
 
2035
 
  return 1;
2036
 
}
2037
 
 
2038
1530
 
2039
1531
/*
2040
1532
  Open all tables in list
2102
1594
     * to see if it exists so that an unauthorized user cannot phish for
2103
1595
     * table/schema information via error messages
2104
1596
     */
2105
 
    if (not plugin::Authorization::isAuthorized(getSecurityContext(),
2106
 
                                                string(tables->db),
2107
 
                                                string(tables->table_name)))
 
1597
    identifier::Table the_table(tables->getSchemaName(), tables->getTableName());
 
1598
    if (not plugin::Authorization::isAuthorized(user(), the_table))
2108
1599
    {
2109
1600
      result= -1;                               // Fatal error
2110
1601
      break;
2150
1641
    {
2151
1642
      if (tables->lock_type == TL_WRITE_DEFAULT)
2152
1643
        tables->table->reginfo.lock_type= update_lock_default;
2153
 
      else if (tables->table->s->tmp_table == message::Table::STANDARD)
 
1644
      else if (tables->table->getShare()->getType() == message::Table::STANDARD)
2154
1645
        tables->table->reginfo.lock_type= tables->lock_type;
2155
1646
    }
2156
1647
  }
2201
1692
 
2202
1693
  set_proc_info("Opening table");
2203
1694
  current_tablenr= 0;
2204
 
  while (!(table= openTable(table_list, &refresh)) &&
2205
 
         refresh)
2206
 
    ;
 
1695
  while (!(table= openTable(table_list, &refresh)) && refresh) ;
2207
1696
 
2208
1697
  if (table)
2209
1698
  {
2212
1701
 
2213
1702
    assert(lock == 0);  // You must lock everything at once
2214
1703
    if ((table->reginfo.lock_type= lock_type) != TL_UNLOCK)
2215
 
      if (! (lock= mysql_lock_tables(this, &table_list->table, 1, 0, &refresh)))
2216
 
        table= 0;
 
1704
    {
 
1705
      if (not (lock= lockTables(&table_list->table, 1, 0)))
 
1706
        table= NULL;
 
1707
    }
2217
1708
  }
2218
1709
 
2219
1710
  set_proc_info(0);
2269
1760
 
2270
1761
  if (!(ptr=start=(Table**) session->alloc(sizeof(Table*)*count)))
2271
1762
    return -1;
 
1763
 
2272
1764
  for (table= tables; table; table= table->next_global)
2273
1765
  {
2274
1766
    if (!table->placeholder())
2275
1767
      *(ptr++)= table->table;
2276
1768
  }
2277
1769
 
2278
 
  if (!(session->lock= mysql_lock_tables(session, start, (uint32_t) (ptr - start),
2279
 
                                         lock_flag, need_reopen)))
 
1770
  if (not (session->lock= session->lockTables(start, (uint32_t) (ptr - start), lock_flag)))
2280
1771
  {
2281
1772
    return -1;
2282
1773
  }
2305
1796
#  Table object
2306
1797
*/
2307
1798
 
2308
 
Table *Session::open_temporary_table(TableIdentifier &identifier,
2309
 
                                     bool link_in_list)
 
1799
Table *Open_tables_state::open_temporary_table(const identifier::Table &identifier,
 
1800
                                               bool link_in_list)
2310
1801
{
2311
 
  Table *new_tmp_table;
2312
 
  TableShare *share;
2313
 
  char cache_key[MAX_DBKEY_LENGTH], *saved_cache_key, *tmp_path;
2314
 
  uint32_t key_length, path_length;
2315
 
  TableList table_list;
2316
 
 
2317
 
  table_list.db=         const_cast<char*>(identifier.getSchemaName().c_str());
2318
 
  table_list.table_name= const_cast<char*>(identifier.getTableName().c_str());
2319
 
  /* Create the cache_key for temporary tables */
2320
 
  key_length= table_list.create_table_def_key(cache_key);
2321
 
  path_length= identifier.getPath().length();
2322
 
 
2323
 
  if (!(new_tmp_table= (Table*) malloc(sizeof(*new_tmp_table) + sizeof(*share) +
2324
 
                                       path_length + 1 + key_length)))
 
1802
  assert(identifier.isTmp());
 
1803
 
 
1804
 
 
1805
  table::Temporary *new_tmp_table= new table::Temporary(identifier.getType(),
 
1806
                                                        identifier,
 
1807
                                                        const_cast<char *>(const_cast<identifier::Table&>(identifier).getPath().c_str()),
 
1808
                                                        static_cast<uint32_t>(identifier.getPath().length()));
 
1809
  if (not new_tmp_table)
2325
1810
    return NULL;
2326
1811
 
2327
 
  share= (TableShare*) (new_tmp_table+1);
2328
 
  tmp_path= (char*) (share+1);
2329
 
  saved_cache_key= strcpy(tmp_path, identifier.getPath().c_str())+path_length+1;
2330
 
  memcpy(saved_cache_key, cache_key, key_length);
2331
 
 
2332
 
  share->init(saved_cache_key, key_length, strchr(saved_cache_key, '\0')+1, tmp_path);
2333
 
 
2334
1812
  /*
2335
1813
    First open the share, and then open the table from the share we just opened.
2336
1814
  */
2337
 
  if (open_table_def(*this, identifier, share) ||
2338
 
      open_table_from_share(this, share, identifier.getTableName().c_str(),
2339
 
                            (uint32_t) (HA_OPEN_KEYFILE | HA_OPEN_RNDFILE |
2340
 
                                        HA_GET_INDEX),
2341
 
                            ha_open_options,
2342
 
                            new_tmp_table))
 
1815
  if (new_tmp_table->getMutableShare()->open_table_def(*static_cast<Session *>(this), identifier) ||
 
1816
      new_tmp_table->getMutableShare()->open_table_from_share(static_cast<Session *>(this), identifier, identifier.getTableName().c_str(),
 
1817
                                                              (uint32_t) (HA_OPEN_KEYFILE | HA_OPEN_RNDFILE |
 
1818
                                                                          HA_GET_INDEX),
 
1819
                                                              ha_open_options,
 
1820
                                                              *new_tmp_table))
2343
1821
  {
2344
1822
    /* No need to lock share->mutex as this is not needed for tmp tables */
2345
 
    share->free_table_share();
2346
 
    free((char*) new_tmp_table);
 
1823
    delete new_tmp_table->getMutableShare();
 
1824
    delete new_tmp_table;
 
1825
 
2347
1826
    return 0;
2348
1827
  }
2349
1828
 
2350
1829
  new_tmp_table->reginfo.lock_type= TL_WRITE;    // Simulate locked
2351
 
  share->tmp_table= message::Table::TEMPORARY;
2352
1830
 
2353
1831
  if (link_in_list)
2354
1832
  {
2355
1833
    /* growing temp list at the head */
2356
 
    new_tmp_table->next= this->temporary_tables;
2357
 
    if (new_tmp_table->next)
2358
 
      new_tmp_table->next->prev= new_tmp_table;
 
1834
    new_tmp_table->setNext(this->temporary_tables);
 
1835
    if (new_tmp_table->getNext())
 
1836
    {
 
1837
      new_tmp_table->getNext()->setPrev(new_tmp_table);
 
1838
    }
2359
1839
    this->temporary_tables= new_tmp_table;
2360
 
    this->temporary_tables->prev= 0;
 
1840
    this->temporary_tables->setPrev(0);
2361
1841
  }
2362
1842
  new_tmp_table->pos_in_table_list= 0;
2363
1843
 
2382
1862
{
2383
1863
  if (session->mark_used_columns != MARK_COLUMNS_NONE)
2384
1864
  {
2385
 
    MyBitmap *current_bitmap, *other_bitmap;
 
1865
    boost::dynamic_bitset<> *current_bitmap= NULL;
2386
1866
 
2387
1867
    /*
2388
1868
      We always want to register the used keys, as the column bitmap may have
2395
1875
    if (session->mark_used_columns == MARK_COLUMNS_READ)
2396
1876
    {
2397
1877
      current_bitmap= table->read_set;
2398
 
      other_bitmap=   table->write_set;
2399
1878
    }
2400
1879
    else
2401
1880
    {
2402
1881
      current_bitmap= table->write_set;
2403
 
      other_bitmap=   table->read_set;
2404
1882
    }
2405
1883
 
2406
 
    if (current_bitmap->testAndSet(field->field_index))
 
1884
    //if (current_bitmap->testAndSet(field->position()))
 
1885
    if (current_bitmap->test(field->position()))
2407
1886
    {
2408
1887
      if (session->mark_used_columns == MARK_COLUMNS_WRITE)
2409
1888
        session->dup_field= field;
2462
1941
    {
2463
1942
      if (nj_col)
2464
1943
      {
2465
 
        my_error(ER_NON_UNIQ_ERROR, MYF(0), name, session->where);
 
1944
        my_error(ER_NON_UNIQ_ERROR, MYF(0), name, session->where());
2466
1945
        return NULL;
2467
1946
      }
2468
1947
      nj_col= curr_nj_col;
2472
1951
    return NULL;
2473
1952
  {
2474
1953
    /* This is a base table. */
2475
 
    assert(nj_col->table_ref->table == nj_col->table_field->table);
 
1954
    assert(nj_col->table_ref->table == nj_col->table_field->getTable());
2476
1955
    found_field= nj_col->table_field;
2477
1956
    update_field_dependencies(session, found_field, nj_col->table_ref->table);
2478
1957
  }
2509
1988
  uint32_t cached_field_index= *cached_field_index_ptr;
2510
1989
 
2511
1990
  /* We assume here that table->field < NO_CACHED_FIELD_INDEX = UINT_MAX */
2512
 
  if (cached_field_index < table->s->fields &&
 
1991
  if (cached_field_index < table->getShare()->sizeFields() &&
2513
1992
      !my_strcasecmp(system_charset_info,
2514
 
                     table->field[cached_field_index]->field_name, name))
2515
 
    field_ptr= table->field + cached_field_index;
2516
 
  else if (table->s->name_hash.records)
2517
 
  {
2518
 
    field_ptr= (Field**) hash_search(&table->s->name_hash, (unsigned char*) name,
2519
 
                                     length);
 
1993
                     table->getField(cached_field_index)->field_name, name))
 
1994
  {
 
1995
    field_ptr= table->getFields() + cached_field_index;
 
1996
  }
 
1997
  else if (table->getShare()->getNamedFieldSize())
 
1998
  {
 
1999
    field_ptr= table->getMutableShare()->getNamedField(std::string(name, length));
2520
2000
    if (field_ptr)
2521
2001
    {
2522
2002
      /*
2523
2003
        field_ptr points to field in TableShare. Convert it to the matching
2524
2004
        field in table
2525
2005
      */
2526
 
      field_ptr= (table->field + (field_ptr - table->s->field));
 
2006
      field_ptr= (table->getFields() + table->getShare()->positionFields(field_ptr));
2527
2007
    }
2528
2008
  }
2529
2009
  else
2530
2010
  {
2531
 
    if (!(field_ptr= table->field))
 
2011
    if (!(field_ptr= table->getFields()))
2532
2012
      return((Field *)0);
2533
2013
    for (; *field_ptr; ++field_ptr)
2534
2014
      if (!my_strcasecmp(system_charset_info, (*field_ptr)->field_name, name))
2537
2017
 
2538
2018
  if (field_ptr && *field_ptr)
2539
2019
  {
2540
 
    *cached_field_index_ptr= field_ptr - table->field;
 
2020
    *cached_field_index_ptr= field_ptr - table->getFields();
2541
2021
    field= *field_ptr;
2542
2022
  }
2543
2023
  else
2544
2024
  {
2545
2025
    if (!allow_rowid ||
2546
2026
        my_strcasecmp(system_charset_info, name, "_rowid") ||
2547
 
        table->s->rowid_field_offset == 0)
 
2027
        table->getShare()->rowid_field_offset == 0)
2548
2028
      return((Field*) 0);
2549
 
    field= table->field[table->s->rowid_field_offset-1];
 
2029
    field= table->getField(table->getShare()->rowid_field_offset-1);
2550
2030
  }
2551
2031
 
2552
2032
  update_field_dependencies(session, field, table);
2625
2105
    inside the view, but we want to search directly in the view columns
2626
2106
    which are represented as a 'field_translation'.
2627
2107
 
2628
 
TODO: Ensure that table_name, db_name and tables->db always points to
2629
 
something !
 
2108
    TODO-> Ensure that table_name, db_name and tables->db always points to something !
2630
2109
  */
2631
2110
  if (/* Exclude nested joins. */
2632
 
      (!table_list->nested_join) &&
 
2111
      (!table_list->getNestedJoin()) &&
2633
2112
      /* Include merge views and information schema tables. */
2634
2113
      /*
2635
2114
        Test if the field qualifiers match the table reference we plan
2637
2116
      */
2638
2117
      table_name && table_name[0] &&
2639
2118
      (my_strcasecmp(table_alias_charset, table_list->alias, table_name) ||
2640
 
       (db_name && db_name[0] && table_list->db && table_list->db[0] &&
2641
 
        strcmp(db_name, table_list->db))))
 
2119
       (db_name && db_name[0] && table_list->getSchemaName() && table_list->getSchemaName()[0] &&
 
2120
        strcmp(db_name, table_list->getSchemaName()))))
2642
2121
    return 0;
2643
2122
 
2644
2123
  *actual_table= NULL;
2645
2124
 
2646
 
  if (!table_list->nested_join)
 
2125
  if (!table_list->getNestedJoin())
2647
2126
  {
2648
2127
    /* 'table_list' is a stored table. */
2649
2128
    assert(table_list->table);
2663
2142
    */
2664
2143
    if (table_name && table_name[0])
2665
2144
    {
2666
 
      List_iterator<TableList> it(table_list->nested_join->join_list);
 
2145
      List_iterator<TableList> it(table_list->getNestedJoin()->join_list);
2667
2146
      TableList *table;
2668
2147
      while ((table= it++))
2669
2148
      {
2711
2190
        field_to_set= fld;
2712
2191
      if (field_to_set)
2713
2192
      {
2714
 
        Table *table= field_to_set->table;
 
2193
        Table *table= field_to_set->getTable();
2715
2194
        if (session->mark_used_columns == MARK_COLUMNS_READ)
2716
 
          table->setReadSet(field_to_set->field_index);
 
2195
          table->setReadSet(field_to_set->position());
2717
2196
        else
2718
 
          table->setWriteSet(field_to_set->field_index);
 
2197
          table->setWriteSet(field_to_set->position());
2719
2198
      }
2720
2199
    }
2721
2200
  }
2859
2338
      */
2860
2339
      item->cached_table= found ?  0 : actual_table;
2861
2340
 
2862
 
      assert(session->where);
 
2341
      assert(session->where());
2863
2342
      /*
2864
2343
        If we found a fully qualified field we return it directly as it can't
2865
2344
        have duplicates.
2872
2351
        if (report_error == REPORT_ALL_ERRORS ||
2873
2352
            report_error == IGNORE_EXCEPT_NON_UNIQUE)
2874
2353
          my_error(ER_NON_UNIQ_ERROR, MYF(0),
2875
 
                   table_name ? item->full_name() : name, session->where);
 
2354
                   table_name ? item->full_name() : name, session->where());
2876
2355
        return (Field*) 0;
2877
2356
      }
2878
2357
      found= cur_field;
2905
2384
      strcat(buff, table_name);
2906
2385
      table_name=buff;
2907
2386
    }
2908
 
    my_error(ER_UNKNOWN_TABLE, MYF(0), table_name, session->where);
 
2387
    my_error(ER_UNKNOWN_TABLE, MYF(0), table_name, session->where());
2909
2388
  }
2910
2389
  else
2911
2390
  {
2912
2391
    if (report_error == REPORT_ALL_ERRORS ||
2913
2392
        report_error == REPORT_EXCEPT_NON_UNIQUE)
2914
 
      my_error(ER_BAD_FIELD_ERROR, MYF(0), item->full_name(), session->where);
 
2393
      my_error(ER_BAD_FIELD_ERROR, MYF(0), item->full_name(), session->where());
2915
2394
    else
2916
2395
      found= not_found_field;
2917
2396
  }
2957
2436
 
2958
2437
 
2959
2438
Item **
2960
 
find_item_in_list(Item *find, List<Item> &items, uint32_t *counter,
 
2439
find_item_in_list(Session *session,
 
2440
                  Item *find, List<Item> &items, uint32_t *counter,
2961
2441
                  find_item_error_report_type report_error,
2962
2442
                  enum_resolution_type *resolution)
2963
2443
{
3037
2517
            */
3038
2518
            if (report_error != IGNORE_ERRORS)
3039
2519
              my_error(ER_NON_UNIQ_ERROR, MYF(0),
3040
 
                       find->full_name(), current_session->where);
 
2520
                       find->full_name(), session->where());
3041
2521
            return (Item**) 0;
3042
2522
          }
3043
2523
          found_unaliased= li.ref();
3068
2548
              continue;                           // Same field twice
3069
2549
            if (report_error != IGNORE_ERRORS)
3070
2550
              my_error(ER_NON_UNIQ_ERROR, MYF(0),
3071
 
                       find->full_name(), current_session->where);
 
2551
                       find->full_name(), session->where());
3072
2552
            return (Item**) 0;
3073
2553
          }
3074
2554
          found= li.ref();
3120
2600
    {
3121
2601
      if (report_error != IGNORE_ERRORS)
3122
2602
        my_error(ER_NON_UNIQ_ERROR, MYF(0),
3123
 
                 find->full_name(), current_session->where);
 
2603
                 find->full_name(), session->where());
3124
2604
      return (Item **) 0;
3125
2605
    }
3126
2606
    if (found_unaliased)
3136
2616
  {
3137
2617
    if (report_error == REPORT_ALL_ERRORS)
3138
2618
      my_error(ER_BAD_FIELD_ERROR, MYF(0),
3139
 
               find->full_name(), current_session->where);
 
2619
               find->full_name(), session->where());
3140
2620
    return (Item **) 0;
3141
2621
  }
3142
2622
  else
3254
2734
    Leaf table references to which new natural join columns are added
3255
2735
    if the leaves are != NULL.
3256
2736
  */
3257
 
  TableList *leaf_1= (table_ref_1->nested_join &&
3258
 
                      !table_ref_1->is_natural_join) ?
 
2737
  TableList *leaf_1= (table_ref_1->getNestedJoin() &&
 
2738
                      ! table_ref_1->is_natural_join) ?
3259
2739
    NULL : table_ref_1;
3260
 
  TableList *leaf_2= (table_ref_2->nested_join &&
3261
 
                      !table_ref_2->is_natural_join) ?
 
2740
  TableList *leaf_2= (table_ref_2->getNestedJoin() &&
 
2741
                      ! table_ref_2->is_natural_join) ?
3262
2742
    NULL : table_ref_2;
3263
2743
 
3264
2744
  *found_using_fields= 0;
3270
2750
    /* true if field_name_1 is a member of using_fields */
3271
2751
    bool is_using_column_1;
3272
2752
    if (!(nj_col_1= it_1.get_or_create_column_ref(leaf_1)))
3273
 
      goto err;
 
2753
      return(result);
3274
2754
    field_name_1= nj_col_1->name();
3275
2755
    is_using_column_1= using_fields &&
3276
2756
      test_if_string_in_list(field_name_1, using_fields);
3288
2768
      Natural_join_column *cur_nj_col_2;
3289
2769
      const char *cur_field_name_2;
3290
2770
      if (!(cur_nj_col_2= it_2.get_or_create_column_ref(leaf_2)))
3291
 
        goto err;
 
2771
        return(result);
3292
2772
      cur_field_name_2= cur_nj_col_2->name();
3293
2773
 
3294
2774
      /*
3307
2787
        if (cur_nj_col_2->is_common ||
3308
2788
            (found && (!using_fields || is_using_column_1)))
3309
2789
        {
3310
 
          my_error(ER_NON_UNIQ_ERROR, MYF(0), field_name_1, session->where);
3311
 
          goto err;
 
2790
          my_error(ER_NON_UNIQ_ERROR, MYF(0), field_name_1, session->where());
 
2791
          return(result);
3312
2792
        }
3313
2793
        nj_col_2= cur_nj_col_2;
3314
2794
        found= true;
3341
2821
      Item_func_eq *eq_cond;
3342
2822
 
3343
2823
      if (!item_1 || !item_2)
3344
 
        goto err;                               // out of memory
 
2824
        return(result); // out of memory
3345
2825
 
3346
2826
      /*
3347
2827
        In the case of no_wrap_view_item == 0, the created items must be
3366
2846
      */
3367
2847
      if (set_new_item_local_context(session, item_ident_1, nj_col_1->table_ref) ||
3368
2848
          set_new_item_local_context(session, item_ident_2, nj_col_2->table_ref))
3369
 
        goto err;
 
2849
        return(result);
3370
2850
 
3371
2851
      if (!(eq_cond= new Item_func_eq(item_ident_1, item_ident_2)))
3372
 
        goto err;                               /* Out of memory. */
 
2852
        return(result);                               /* Out of memory. */
3373
2853
 
3374
2854
      /*
3375
2855
        Add the new equi-join condition to the ON clause. Notice that
3386
2866
      {
3387
2867
        Table *table_1= nj_col_1->table_ref->table;
3388
2868
        /* Mark field_1 used for table cache. */
3389
 
        table_1->setReadSet(field_1->field_index);
 
2869
        table_1->setReadSet(field_1->position());
3390
2870
        table_1->covering_keys&= field_1->part_of_key;
3391
2871
        table_1->merge_keys|= field_1->part_of_key;
3392
2872
      }
3394
2874
      {
3395
2875
        Table *table_2= nj_col_2->table_ref->table;
3396
2876
        /* Mark field_2 used for table cache. */
3397
 
        table_2->setReadSet(field_2->field_index);
 
2877
        table_2->setReadSet(field_2->position());
3398
2878
        table_2->covering_keys&= field_2->part_of_key;
3399
2879
        table_2->merge_keys|= field_2->part_of_key;
3400
2880
      }
3415
2895
  */
3416
2896
  result= false;
3417
2897
 
3418
 
err:
3419
2898
  return(result);
3420
2899
}
3421
2900
 
3457
2936
*/
3458
2937
 
3459
2938
static bool
3460
 
store_natural_using_join_columns(Session *,
 
2939
store_natural_using_join_columns(Session *session,
3461
2940
                                 TableList *natural_using_join,
3462
2941
                                 TableList *table_ref_1,
3463
2942
                                 TableList *table_ref_2,
3473
2952
 
3474
2953
  if (!(non_join_columns= new List<Natural_join_column>) ||
3475
2954
      !(natural_using_join->join_columns= new List<Natural_join_column>))
3476
 
    goto err;
 
2955
  {
 
2956
    return(result);
 
2957
  }
3477
2958
 
3478
2959
  /* Append the columns of the first join operand. */
3479
2960
  for (it_1.set(table_ref_1); !it_1.end_of_fields(); it_1.next())
3511
2992
        if (!(common_field= it++))
3512
2993
        {
3513
2994
          my_error(ER_BAD_FIELD_ERROR, MYF(0), using_field_name_ptr,
3514
 
                   current_session->where);
3515
 
          goto err;
 
2995
                   session->where());
 
2996
          return(result);
3516
2997
        }
3517
2998
        if (!my_strcasecmp(system_charset_info,
3518
2999
                           common_field->name(), using_field_name_ptr))
3540
3021
 
3541
3022
  result= false;
3542
3023
 
3543
 
err:
3544
3024
  return(result);
3545
3025
}
3546
3026
 
3583
3063
  bool result= true;
3584
3064
 
3585
3065
  /* Call the procedure recursively for each nested table reference. */
3586
 
  if (table_ref->nested_join)
 
3066
  if (table_ref->getNestedJoin())
3587
3067
  {
3588
 
    List_iterator_fast<TableList> nested_it(table_ref->nested_join->join_list);
 
3068
    List_iterator_fast<TableList> nested_it(table_ref->getNestedJoin()->join_list);
3589
3069
    TableList *same_level_left_neighbor= nested_it++;
3590
3070
    TableList *same_level_right_neighbor= NULL;
3591
3071
    /* Left/right-most neighbors, possibly at higher levels in the join tree. */
3610
3090
          cur_table_ref->outer_join & JOIN_TYPE_RIGHT)
3611
3091
      {
3612
3092
        /* This can happen only for JOIN ... ON. */
3613
 
        assert(table_ref->nested_join->join_list.elements == 2);
 
3093
        assert(table_ref->getNestedJoin()->join_list.elements == 2);
3614
3094
        std::swap(same_level_left_neighbor, cur_table_ref);
3615
3095
      }
3616
3096
 
3623
3103
      real_right_neighbor= (same_level_right_neighbor) ?
3624
3104
        same_level_right_neighbor : right_neighbor;
3625
3105
 
3626
 
      if (cur_table_ref->nested_join &&
 
3106
      if (cur_table_ref->getNestedJoin() &&
3627
3107
          store_top_level_join_columns(session, cur_table_ref,
3628
3108
                                       real_left_neighbor, real_right_neighbor))
3629
 
        goto err;
 
3109
        return(result);
3630
3110
      same_level_right_neighbor= cur_table_ref;
3631
3111
    }
3632
3112
  }
3637
3117
  */
3638
3118
  if (table_ref->is_natural_join)
3639
3119
  {
3640
 
    assert(table_ref->nested_join &&
3641
 
           table_ref->nested_join->join_list.elements == 2);
3642
 
    List_iterator_fast<TableList> operand_it(table_ref->nested_join->join_list);
 
3120
    assert(table_ref->getNestedJoin() &&
 
3121
           table_ref->getNestedJoin()->join_list.elements == 2);
 
3122
    List_iterator_fast<TableList> operand_it(table_ref->getNestedJoin()->join_list);
3643
3123
    /*
3644
3124
      Notice that the order of join operands depends on whether table_ref
3645
3125
      represents a LEFT or a RIGHT join. In a RIGHT join, the operands are
3658
3138
      std::swap(table_ref_1, table_ref_2);
3659
3139
    if (mark_common_columns(session, table_ref_1, table_ref_2,
3660
3140
                            using_fields, &found_using_fields))
3661
 
      goto err;
 
3141
      return(result);
3662
3142
 
3663
3143
    /*
3664
3144
      Swap the join operands back, so that we pick the columns of the second
3670
3150
    if (store_natural_using_join_columns(session, table_ref, table_ref_1,
3671
3151
                                         table_ref_2, using_fields,
3672
3152
                                         found_using_fields))
3673
 
      goto err;
 
3153
      return(result);
3674
3154
 
3675
3155
    /*
3676
3156
      Change NATURAL JOIN to JOIN ... ON. We do this for both operands
3703
3183
  }
3704
3184
  result= false; /* All is OK. */
3705
3185
 
3706
 
err:
3707
3186
  return(result);
3708
3187
}
3709
3188
 
3736
3215
                                         List<TableList> *from_clause,
3737
3216
                                         Name_resolution_context *context)
3738
3217
{
3739
 
  session->where= "from clause";
 
3218
  session->setWhere("from clause");
3740
3219
  if (from_clause->elements == 0)
3741
3220
    return false; /* We come here in the case of UNIONs. */
3742
3221
 
3857
3336
  session->mark_used_columns= mark_used_columns;
3858
3337
  if (allow_sum_func)
3859
3338
    session->lex->allow_sum_func|= 1 << session->lex->current_select->nest_level;
3860
 
  session->where= Session::DEFAULT_WHERE;
 
3339
  session->setWhere(Session::DEFAULT_WHERE);
3861
3340
  save_is_item_list_lookup= session->lex->current_select->is_item_list_lookup;
3862
3341
  session->lex->current_select->is_item_list_lookup= 0;
3863
3342
 
3869
3348
    There is other way to solve problem: fill array with pointers to list,
3870
3349
    but it will be slower.
3871
3350
 
3872
 
TODO: remove it when (if) we made one list for allfields and
3873
 
ref_pointer_array
 
3351
    TODO-> remove it when (if) we made one list for allfields and ref_pointer_array
3874
3352
  */
3875
3353
  if (ref_pointer_array)
 
3354
  {
3876
3355
    memset(ref_pointer_array, 0, sizeof(Item *) * fields.elements);
 
3356
  }
3877
3357
 
3878
3358
  Item **ref= ref_pointer_array;
3879
3359
  session->lex->current_select->cur_pos_in_select_list= 0;
4105
3585
    assert(tables->is_leaf_for_name_resolution());
4106
3586
 
4107
3587
    if ((table_name && my_strcasecmp(table_alias_charset, table_name, tables->alias)) ||
4108
 
        (db_name && strcasecmp(tables->db,db_name)))
 
3588
        (db_name && my_strcasecmp(system_charset_info, tables->getSchemaName(),db_name)))
4109
3589
      continue;
4110
3590
 
4111
3591
    /*
4141
3621
      if ((field= field_iterator.field()))
4142
3622
      {
4143
3623
        /* Mark fields as used to allow storage engine to optimze access */
4144
 
        field->table->setReadSet(field->field_index);
 
3624
        field->getTable()->setReadSet(field->position());
4145
3625
        if (table)
4146
3626
        {
4147
3627
          table->covering_keys&= field->part_of_key;
4169
3649
        }
4170
3650
      }
4171
3651
      else
 
3652
      {
4172
3653
        session->used_tables|= item->used_tables();
 
3654
      }
 
3655
 
4173
3656
      session->lex->current_select->cur_pos_in_select_list++;
4174
3657
    }
4175
3658
    /*
4179
3662
      For NATURAL joins, used_tables is updated in the IF above.
4180
3663
    */
4181
3664
    if (table)
4182
 
      table->used_fields= table->s->fields;
 
3665
      table->used_fields= table->getShare()->sizeFields();
4183
3666
  }
4184
3667
  if (found)
4185
3668
    return false;
4189
3672
    qualified '*', and all columns were coalesced, we have to give a more
4190
3673
    meaningful message than ER_BAD_TABLE_ERROR.
4191
3674
  */
4192
 
  if (!table_name)
 
3675
  if (not table_name)
 
3676
  {
4193
3677
    my_message(ER_NO_TABLES_USED, ER(ER_NO_TABLES_USED), MYF(0));
 
3678
  }
4194
3679
  else
 
3680
  {
4195
3681
    my_error(ER_BAD_TABLE_ERROR, MYF(0), table_name);
 
3682
  }
4196
3683
 
4197
3684
  return true;
4198
3685
}
4241
3728
  session->session_marker= (void*)1;
4242
3729
  if (*conds)
4243
3730
  {
4244
 
    session->where="where clause";
 
3731
    session->setWhere("where clause");
4245
3732
    if ((!(*conds)->fixed && (*conds)->fix_fields(session, conds)) ||
4246
3733
        (*conds)->check_cols(1))
4247
3734
      goto err_no_arena;
4263
3750
      {
4264
3751
        /* Make a join an a expression */
4265
3752
        session->session_marker= (void*)embedded;
4266
 
        session->where="on clause";
 
3753
        session->setWhere("on clause");
4267
3754
        if ((!embedded->on_expr->fixed && embedded->on_expr->fix_fields(session, &embedded->on_expr)) ||
4268
3755
            embedded->on_expr->check_cols(1))
4269
3756
          goto err_no_arena;
4270
3757
        select_lex->cond_count++;
4271
3758
      }
4272
 
      embedding= embedded->embedding;
 
3759
      embedding= embedded->getEmbedding();
4273
3760
    }
4274
3761
    while (embedding &&
4275
 
           embedding->nested_join->join_list.head() == embedded);
 
3762
           embedding->getNestedJoin()->join_list.head() == embedded);
4276
3763
 
4277
3764
  }
4278
3765
  session->session_marker= save_session_marker;
4331
3818
      thus we safely can take table from the first field.
4332
3819
    */
4333
3820
    field= static_cast<Item_field *>(f++);
4334
 
    table= field->field->table;
 
3821
    table= field->field->getTable();
4335
3822
    table->auto_increment_field_not_null= false;
4336
3823
    f.rewind();
4337
3824
  }
4341
3828
    value= v++;
4342
3829
 
4343
3830
    Field *rfield= field->field;
4344
 
    table= rfield->table;
 
3831
    table= rfield->getTable();
4345
3832
 
4346
3833
    if (rfield == table->next_number_field)
4347
3834
      table->auto_increment_field_not_null= true;
4348
3835
    if ((value->save_in_field(rfield, 0) < 0) && !ignore_errors)
4349
3836
    {
4350
3837
      my_message(ER_UNKNOWN_ERROR, ER(ER_UNKNOWN_ERROR), MYF(0));
4351
 
      goto err;
 
3838
      if (table)
 
3839
        table->auto_increment_field_not_null= false;
 
3840
 
 
3841
      return true;
4352
3842
    }
4353
3843
  }
4354
3844
 
4355
3845
  return session->is_error();
4356
 
 
4357
 
err:
4358
 
  if (table)
4359
 
    table->auto_increment_field_not_null= false;
4360
 
 
4361
 
  return true;
4362
3846
}
4363
3847
 
4364
3848
 
4398
3882
      On INSERT or UPDATE fields are checked to be from the same table,
4399
3883
      thus we safely can take table from the first field.
4400
3884
    */
4401
 
    table= (*ptr)->table;
 
3885
    table= (*ptr)->getTable();
4402
3886
    table->auto_increment_field_not_null= false;
4403
3887
  }
 
3888
 
4404
3889
  while ((field = *ptr++) && ! session->is_error())
4405
3890
  {
4406
3891
    value=v++;
4407
 
    table= field->table;
 
3892
    table= field->getTable();
 
3893
 
4408
3894
    if (field == table->next_number_field)
4409
3895
      table->auto_increment_field_not_null= true;
 
3896
 
4410
3897
    if (value->save_in_field(field, 0) < 0)
4411
 
      goto err;
 
3898
    {
 
3899
      if (table)
 
3900
        table->auto_increment_field_not_null= false;
 
3901
 
 
3902
      return true;
 
3903
    }
4412
3904
  }
4413
3905
 
4414
3906
  return(session->is_error());
4415
 
 
4416
 
err:
4417
 
  if (table)
4418
 
    table->auto_increment_field_not_null= false;
4419
 
 
4420
 
  return true;
4421
3907
}
4422
3908
 
4423
3909
 
4424
3910
bool drizzle_rm_tmp_tables()
4425
3911
{
4426
 
  Session *session;
4427
 
 
4428
 
  assert(drizzle_tmpdir);
4429
 
 
4430
 
  if (!(session= new Session(plugin::Listen::getNullClient())))
 
3912
 
 
3913
  assert(drizzle_tmpdir.size());
 
3914
  Session::shared_ptr session= Session::make_shared(plugin::Listen::getNullClient(), catalog::local());
 
3915
 
 
3916
  if (not session)
4431
3917
    return true;
4432
 
  session->thread_stack= (char*) &session;
 
3918
  session->thread_stack= (char*) session.get();
4433
3919
  session->storeGlobals();
4434
3920
 
4435
 
  plugin::StorageEngine::removeLostTemporaryTables(*session, drizzle_tmpdir);
4436
 
 
4437
 
  delete session;
 
3921
  plugin::StorageEngine::removeLostTemporaryTables(*session, drizzle_tmpdir.c_str());
4438
3922
 
4439
3923
  return false;
4440
3924
}
4445
3929
  unireg support functions
4446
3930
 *****************************************************************************/
4447
3931
 
4448
 
/*
4449
 
  Invalidate any cache entries that are for some DB
4450
 
 
4451
 
  SYNOPSIS
4452
 
  remove_db_from_cache()
4453
 
  db            Database name. This will be in lower case if
4454
 
  lower_case_table_name is set
4455
 
 
4456
 
NOTE:
4457
 
We can't use hash_delete when looping hash_elements. We mark them first
4458
 
and afterwards delete those marked unused.
4459
 
*/
4460
 
 
4461
 
void remove_db_from_cache(SchemaIdentifier &schema_identifier)
4462
 
{
4463
 
  safe_mutex_assert_owner(&LOCK_open);
4464
 
 
4465
 
  for (uint32_t idx=0 ; idx < open_cache.records ; idx++)
4466
 
  {
4467
 
    Table *table=(Table*) hash_element(&open_cache,idx);
4468
 
    if (not schema_identifier.getPath().compare(table->s->getSchemaName()))
4469
 
    {
4470
 
      table->s->version= 0L;                    /* Free when thread is ready */
4471
 
      if (not table->in_use)
4472
 
        relink_unused(table);
4473
 
    }
4474
 
  }
4475
 
  while (unused_tables && !unused_tables->s->version)
4476
 
    hash_delete(&open_cache,(unsigned char*) unused_tables);
4477
 
}
4478
 
 
4479
 
 
4480
 
/*
4481
 
  Mark all entries with the table as deleted to force an reopen of the table
4482
 
 
4483
 
  The table will be closed (not stored in cache) by the current thread when
4484
 
  close_thread_tables() is called.
4485
 
 
4486
 
  PREREQUISITES
4487
 
  Lock on LOCK_open()
4488
 
 
4489
 
  RETURN
4490
 
  0  This thread now have exclusive access to this table and no other thread
4491
 
  can access the table until close_thread_tables() is called.
4492
 
  1  Table is in use by another thread
4493
 
*/
4494
 
 
4495
 
bool remove_table_from_cache(Session *session, const char *db, const char *table_name,
4496
 
                             uint32_t flags)
4497
 
{
4498
 
  char key[MAX_DBKEY_LENGTH];
4499
 
  char *key_pos= key;
4500
 
  uint32_t key_length;
4501
 
  Table *table;
4502
 
  bool result= false; 
4503
 
  bool signalled= false;
4504
 
 
4505
 
  key_pos= strcpy(key_pos, db) + strlen(db);
4506
 
  key_pos= strcpy(key_pos+1, table_name) + strlen(table_name);
4507
 
  key_length= (uint32_t) (key_pos-key)+1;
4508
 
 
4509
 
  for (;;)
4510
 
  {
4511
 
    HASH_SEARCH_STATE state;
4512
 
    result= signalled= false;
4513
 
 
4514
 
    for (table= (Table*) hash_first(&open_cache, (unsigned char*) key, key_length,
4515
 
                                    &state);
4516
 
         table;
4517
 
         table= (Table*) hash_next(&open_cache, (unsigned char*) key, key_length,
4518
 
                                   &state))
4519
 
    {
4520
 
      Session *in_use;
4521
 
 
4522
 
      table->s->version=0L;             /* Free when thread is ready */
4523
 
      if (!(in_use=table->in_use))
4524
 
      {
4525
 
        relink_unused(table);
4526
 
      }
4527
 
      else if (in_use != session)
4528
 
      {
4529
 
        /*
4530
 
          Mark that table is going to be deleted from cache. This will
4531
 
          force threads that are in mysql_lock_tables() (but not yet
4532
 
          in thr_multi_lock()) to abort it's locks, close all tables and retry
4533
 
        */
4534
 
        in_use->some_tables_deleted= true;
4535
 
        if (table->is_name_opened())
4536
 
        {
4537
 
          result= true;
4538
 
        }
4539
 
        /*
4540
 
          Now we must abort all tables locks used by this thread
4541
 
          as the thread may be waiting to get a lock for another table.
4542
 
          Note that we need to hold LOCK_open while going through the
4543
 
          list. So that the other thread cannot change it. The other
4544
 
          thread must also hold LOCK_open whenever changing the
4545
 
          open_tables list. Aborting the MERGE lock after a child was
4546
 
          closed and before the parent is closed would be fatal.
4547
 
        */
4548
 
        for (Table *session_table= in_use->open_tables;
4549
 
             session_table ;
4550
 
             session_table= session_table->next)
4551
 
        {
4552
 
          /* Do not handle locks of MERGE children. */
4553
 
          if (session_table->db_stat)   // If table is open
4554
 
            signalled|= mysql_lock_abort_for_thread(session, session_table);
4555
 
        }
4556
 
      }
4557
 
      else
4558
 
        result= result || (flags & RTFC_OWNED_BY_Session_FLAG);
4559
 
    }
4560
 
    while (unused_tables && !unused_tables->s->version)
4561
 
      hash_delete(&open_cache,(unsigned char*) unused_tables);
4562
 
 
4563
 
    /* Remove table from table definition cache if it's not in use */
4564
 
    TableShare::release(key, key_length);
4565
 
 
4566
 
    if (result && (flags & RTFC_WAIT_OTHER_THREAD_FLAG))
4567
 
    {
4568
 
      /*
4569
 
        Signal any thread waiting for tables to be freed to
4570
 
        reopen their tables
4571
 
      */
4572
 
      broadcast_refresh();
4573
 
      if (!(flags & RTFC_CHECK_KILLED_FLAG) || !session->killed)
4574
 
      {
4575
 
        dropping_tables++;
4576
 
        if (likely(signalled))
4577
 
          (void) pthread_cond_wait(&COND_refresh, &LOCK_open);
4578
 
        else
4579
 
        {
4580
 
          struct timespec abstime;
4581
 
          /*
4582
 
            It can happen that another thread has opened the
4583
 
            table but has not yet locked any table at all. Since
4584
 
            it can be locked waiting for a table that our thread
4585
 
            has done LOCK Table x WRITE on previously, we need to
4586
 
            ensure that the thread actually hears our signal
4587
 
            before we go to sleep. Thus we wait for a short time
4588
 
            and then we retry another loop in the
4589
 
            remove_table_from_cache routine.
4590
 
          */
4591
 
          set_timespec(abstime, 10);
4592
 
          pthread_cond_timedwait(&COND_refresh, &LOCK_open, &abstime);
4593
 
        }
4594
 
        dropping_tables--;
4595
 
        continue;
4596
 
      }
4597
 
    }
4598
 
    break;
4599
 
  }
4600
 
  return result;
4601
 
}
 
3932
 
4602
3933
 
4603
3934
 
4604
3935
/**