~drizzle-trunk/drizzle/development

« back to all changes in this revision

Viewing changes to drizzled/sql_base.cc

This will now require someone to do a --plugin-add in order to have csv,
archive, or blackhole running.

Show diffs side-by-side

added added

removed removed

Lines of Context:
11
11
 
12
12
  You should have received a copy of the GNU General Public License
13
13
  along with this program; if not, write to the Free Software
14
 
  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA */
 
14
  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA */
15
15
 
16
16
 
17
17
/* Basic functions needed by many modules */
45
45
#include <drizzled/lock.h>
46
46
#include <drizzled/plugin/listen.h>
47
47
#include "drizzled/cached_directory.h"
48
 
#include <drizzled/field/epoch.h>
 
48
#include <drizzled/field/timestamp.h>
49
49
#include <drizzled/field/null.h>
50
50
#include "drizzled/sql_table.h"
51
51
#include "drizzled/global_charset_info.h"
53
53
#include "drizzled/internal/iocache.h"
54
54
#include "drizzled/drizzled.h"
55
55
#include "drizzled/plugin/authorization.h"
56
 
#include "drizzled/table/temporary.h"
57
 
#include "drizzled/table/placeholder.h"
58
 
#include "drizzled/table/unused.h"
59
 
#include "drizzled/plugin/storage_engine.h"
60
 
 
61
 
#include <drizzled/refresh_version.h>
 
56
#include "drizzled/table_placeholder.h"
62
57
 
63
58
using namespace std;
64
59
 
67
62
 
68
63
extern bool volatile shutdown_in_progress;
69
64
 
 
65
TableOpenCache &get_open_cache()
 
66
{
 
67
  static TableOpenCache open_cache;                             /* Used by mysql_test */
 
68
 
 
69
  return open_cache;
 
70
}
 
71
 
 
72
static void free_cache_entry(Table *entry);
 
73
 
 
74
void remove_table(Table *arg)
 
75
{
 
76
  TableOpenCacheRange ppp;
 
77
  ppp= get_open_cache().equal_range(arg->getShare()->getCacheKey());
 
78
 
 
79
  for (TableOpenCache::const_iterator iter= ppp.first;
 
80
         iter != ppp.second; ++iter)
 
81
  {
 
82
    Table *found_table= (*iter).second;
 
83
 
 
84
    if (found_table == arg)
 
85
    {
 
86
      free_cache_entry(arg);
 
87
      get_open_cache().erase(iter);
 
88
      return;
 
89
    }
 
90
  }
 
91
}
 
92
 
 
93
static bool add_table(Table *arg)
 
94
{
 
95
  TableOpenCache &open_cache(get_open_cache());
 
96
 
 
97
  TableOpenCache::iterator returnable= open_cache.insert(make_pair(arg->getShare()->getCacheKey(), arg));
 
98
 
 
99
  return not (returnable == open_cache.end());
 
100
}
 
101
 
 
102
class UnusedTables {
 
103
  Table *tables;                                /* Used by mysql_test */
 
104
 
 
105
  Table *getTable() const
 
106
  {
 
107
    return tables;
 
108
  }
 
109
 
 
110
  Table *setTable(Table *arg)
 
111
  {
 
112
    return tables= arg;
 
113
  }
 
114
 
 
115
public:
 
116
 
 
117
  void cull()
 
118
  {
 
119
    /* Free cache if too big */
 
120
    while (cached_open_tables() > table_cache_size && getTable())
 
121
      remove_table(getTable());
 
122
  }
 
123
 
 
124
  void cullByVersion()
 
125
  {
 
126
    while (getTable() && not getTable()->getShare()->getVersion())
 
127
      remove_table(getTable());
 
128
  }
 
129
  
 
130
  void link(Table *table)
 
131
  {
 
132
    if (getTable())
 
133
    {
 
134
      table->setNext(getTable());               /* Link in last */
 
135
      table->setPrev(getTable()->getPrev());
 
136
      getTable()->setPrev(table);
 
137
      table->getPrev()->setNext(table);
 
138
    }
 
139
    else
 
140
    {
 
141
      table->setPrev(setTable(table));
 
142
      table->setNext(table->getPrev());
 
143
      assert(table->getNext() == table && table->getPrev() == table);
 
144
    }
 
145
  }
 
146
 
 
147
 
 
148
  void unlink(Table *table)
 
149
  {
 
150
    table->unlink();
 
151
 
 
152
    /* Unlink the table from "unused_tables" list. */
 
153
    if (table == getTable())
 
154
    {  // First unused
 
155
      setTable(getTable()->getNext()); // Remove from link
 
156
      if (table == getTable())
 
157
        setTable(NULL);
 
158
    }
 
159
  }
 
160
 
 
161
/* move table first in unused links */
 
162
 
 
163
  void relink(Table *table)
 
164
  {
 
165
    if (table != getTable())
 
166
    {
 
167
      table->unlink();
 
168
 
 
169
      table->setNext(getTable());                       /* Link in unused tables */
 
170
      table->setPrev(getTable()->getPrev());
 
171
      getTable()->getPrev()->setNext(table);
 
172
      getTable()->setPrev(table);
 
173
      setTable(table);
 
174
    }
 
175
  }
 
176
 
 
177
 
 
178
  void clear()
 
179
  {
 
180
    while (getTable())
 
181
      remove_table(getTable());
 
182
  }
 
183
 
 
184
  UnusedTables():
 
185
    tables(NULL)
 
186
  { }
 
187
 
 
188
  ~UnusedTables()
 
189
  { 
 
190
  }
 
191
};
 
192
 
 
193
static UnusedTables unused_tables;
 
194
static int open_unireg_entry(Session *session,
 
195
                             Table *entry,
 
196
                             const char *alias,
 
197
                             TableIdentifier &identifier);
 
198
 
 
199
unsigned char *table_cache_key(const unsigned char *record,
 
200
                               size_t *length,
 
201
                               bool );
 
202
 
 
203
#if 0
 
204
static bool reopen_table(Table *table);
 
205
#endif
 
206
 
 
207
unsigned char *table_cache_key(const unsigned char *record,
 
208
                               size_t *length,
 
209
                               bool )
 
210
{
 
211
  Table *entry=(Table*) record;
 
212
  *length= entry->getShare()->getCacheKey().size();
 
213
  return (unsigned char*) &entry->getShare()->getCacheKey()[0];
 
214
}
 
215
 
70
216
bool table_cache_init(void)
71
217
{
72
218
  return false;
74
220
 
75
221
uint32_t cached_open_tables(void)
76
222
{
77
 
  return table::getCache().size();
 
223
  return get_open_cache().size();
78
224
}
79
225
 
80
226
void table_cache_free(void)
81
227
{
82
228
  refresh_version++;                            // Force close of open tables
83
229
 
84
 
  table::getUnused().clear();
85
 
  table::getCache().clear();
 
230
  unused_tables.clear();
 
231
  get_open_cache().clear();
86
232
}
87
233
 
88
234
/*
96
242
  By leaving the table in the table cache, it disallows any other thread
97
243
  to open the table
98
244
 
99
 
  session->getKilled() will be set if we run out of memory
 
245
  session->killed will be set if we run out of memory
100
246
 
101
247
  If closing a MERGE child, the calling function has to take care for
102
248
  closing the parent too, if necessary.
105
251
 
106
252
void close_handle_and_leave_table_as_lock(Table *table)
107
253
{
 
254
  TableShare *share, *old_share= table->getMutableShare();
108
255
  assert(table->db_stat);
109
256
  assert(table->getShare()->getType() == message::Table::STANDARD);
110
257
 
113
260
    This has to be done to ensure that the table share is removed from
114
261
    the table defintion cache as soon as the last instance is removed
115
262
  */
116
 
  identifier::Table identifier(table->getShare()->getSchemaName(), table->getShare()->getTableName(), message::Table::INTERNAL);
117
 
  const identifier::Table::Key &key(identifier.getKey());
118
 
  TableShare *share= new TableShare(identifier.getType(),
119
 
                                    identifier,
120
 
                                    const_cast<char *>(key.vector()),  static_cast<uint32_t>(table->getShare()->getCacheKeySize()));
 
263
  TableIdentifier identifier(table->getShare()->getSchemaName(), table->getShare()->getTableName(), message::Table::INTERNAL);
 
264
  const TableIdentifier::Key &key(identifier.getKey());
 
265
  share= new TableShare(identifier.getType(),
 
266
                        identifier,
 
267
                        const_cast<char *>(&key[0]),  static_cast<uint32_t>(old_share->getCacheKeySize()));
121
268
 
122
269
  table->cursor->close();
123
270
  table->db_stat= 0;                            // Mark cursor closed
124
 
  table::instance::release(table->getMutableShare());
 
271
  TableShare::release(table->getMutableShare());
125
272
  table->setShare(share);
 
273
  table->cursor->change_table_ptr(table, table->getMutableShare());
126
274
}
127
275
 
128
276
 
140
288
  }
141
289
}
142
290
 
 
291
/*
 
292
  Remove table from the open table cache
 
293
 
 
294
  SYNOPSIS
 
295
  free_cache_entry()
 
296
  entry         Table to remove
 
297
 
 
298
  NOTE
 
299
  We need to have a lock on LOCK_open when calling this
 
300
*/
 
301
 
 
302
void free_cache_entry(Table *table)
 
303
{
 
304
  table->intern_close_table();
 
305
  if (not table->in_use)
 
306
  {
 
307
    unused_tables.unlink(table);
 
308
  }
 
309
 
 
310
  delete table;
 
311
}
 
312
 
143
313
/* Free resources allocated by filesort() and read_record() */
144
314
 
145
315
void Table::free_io_cache()
146
316
{
147
317
  if (sort.io_cache)
148
318
  {
149
 
    sort.io_cache->close_cached_file();
 
319
    close_cached_file(sort.io_cache);
150
320
    delete sort.io_cache;
151
321
    sort.io_cache= 0;
152
322
  }
158
328
 
159
329
  @param session Thread context (may be NULL)
160
330
  @param tables List of tables to remove from the cache
161
 
  @param have_lock If table::Cache::singleton().mutex() is locked
 
331
  @param have_lock If LOCK_open is locked
162
332
  @param wait_for_refresh Wait for a impending flush
163
333
  @param wait_for_placeholders Wait for tables being reopened so that the GRL
164
334
  won't proceed while write-locked tables are being reopened by other
173
343
  bool result= false;
174
344
  Session *session= this;
175
345
 
176
 
  {
177
 
    boost::mutex::scoped_lock scopedLock(table::Cache::singleton().mutex()); /* Optionally lock for remove tables from open_cahe if not in use */
178
 
 
179
 
    if (tables == NULL)
180
 
    {
181
 
      refresh_version++;                                // Force close of open tables
182
 
 
183
 
      table::getUnused().clear();
184
 
 
185
 
      if (wait_for_refresh)
186
 
      {
 
346
  LOCK_open.lock(); /* Optionally lock for remove tables from open_cahe if not in use */
 
347
 
 
348
  if (tables == NULL)
 
349
  {
 
350
    refresh_version++;                          // Force close of open tables
 
351
 
 
352
    unused_tables.clear();
 
353
 
 
354
    if (wait_for_refresh)
 
355
    {
 
356
      /*
 
357
        Other threads could wait in a loop in open_and_lock_tables(),
 
358
        trying to lock one or more of our tables.
 
359
 
 
360
        If they wait for the locks in thr_multi_lock(), their lock
 
361
        request is aborted. They loop in open_and_lock_tables() and
 
362
        enter open_table(). Here they notice the table is refreshed and
 
363
        wait for COND_refresh. Then they loop again in
 
364
        openTablesLock() and this time open_table() succeeds. At
 
365
        this moment, if we (the FLUSH TABLES thread) are scheduled and
 
366
        on another FLUSH TABLES enter close_cached_tables(), they could
 
367
        awake while we sleep below, waiting for others threads (us) to
 
368
        close their open tables. If this happens, the other threads
 
369
        would find the tables unlocked. They would get the locks, one
 
370
        after the other, and could do their destructive work. This is an
 
371
        issue if we have LOCK TABLES in effect.
 
372
 
 
373
        The problem is that the other threads passed all checks in
 
374
        open_table() before we refresh the table.
 
375
 
 
376
        The fix for this problem is to set some_tables_deleted for all
 
377
        threads with open tables. These threads can still get their
 
378
        locks, but will immediately release them again after checking
 
379
        this variable. They will then loop in openTablesLock()
 
380
        again. There they will wait until we update all tables version
 
381
        below.
 
382
 
 
383
        Setting some_tables_deleted is done by remove_table_from_cache()
 
384
        in the other branch.
 
385
 
 
386
        In other words (reviewer suggestion): You need this setting of
 
387
        some_tables_deleted for the case when table was opened and all
 
388
        related checks were passed before incrementing refresh_version
 
389
        (which you already have) but attempt to lock the table happened
 
390
        after the call to Session::close_old_data_files() i.e. after removal of
 
391
        current thread locks.
 
392
      */
 
393
      for (TableOpenCache::const_iterator iter= get_open_cache().begin();
 
394
           iter != get_open_cache().end();
 
395
           iter++)
 
396
      {
 
397
        Table *table= (*iter).second;
 
398
        if (table->in_use)
 
399
          table->in_use->some_tables_deleted= false;
 
400
      }
 
401
    }
 
402
  }
 
403
  else
 
404
  {
 
405
    bool found= false;
 
406
    for (TableList *table= tables; table; table= table->next_local)
 
407
    {
 
408
      TableIdentifier identifier(table->db, table->table_name);
 
409
      if (remove_table_from_cache(session, identifier,
 
410
                                  RTFC_OWNED_BY_Session_FLAG))
 
411
      {
 
412
        found= true;
 
413
      }
 
414
    }
 
415
    if (!found)
 
416
      wait_for_refresh= false;                  // Nothing to wait for
 
417
  }
 
418
 
 
419
  if (wait_for_refresh)
 
420
  {
 
421
    /*
 
422
      If there is any table that has a lower refresh_version, wait until
 
423
      this is closed (or this thread is killed) before returning
 
424
    */
 
425
    session->mysys_var->current_mutex= LOCK_open.native_handle();
 
426
    session->mysys_var->current_cond= COND_refresh.native_handle();
 
427
    session->set_proc_info("Flushing tables");
 
428
 
 
429
    session->close_old_data_files();
 
430
 
 
431
    bool found= true;
 
432
    /* Wait until all threads has closed all the tables we had locked */
 
433
    while (found && ! session->killed)
 
434
    {
 
435
      found= false;
 
436
      for (TableOpenCache::const_iterator iter= get_open_cache().begin();
 
437
           iter != get_open_cache().end();
 
438
           iter++)
 
439
      {
 
440
        Table *table= (*iter).second;
 
441
        /* Avoid a self-deadlock. */
 
442
        if (table->in_use == session)
 
443
          continue;
187
444
        /*
188
 
          Other threads could wait in a loop in open_and_lock_tables(),
189
 
          trying to lock one or more of our tables.
190
 
 
191
 
          If they wait for the locks in thr_multi_lock(), their lock
192
 
          request is aborted. They loop in open_and_lock_tables() and
193
 
          enter open_table(). Here they notice the table is refreshed and
194
 
          wait for COND_refresh. Then they loop again in
195
 
          openTablesLock() and this time open_table() succeeds. At
196
 
          this moment, if we (the FLUSH TABLES thread) are scheduled and
197
 
          on another FLUSH TABLES enter close_cached_tables(), they could
198
 
          awake while we sleep below, waiting for others threads (us) to
199
 
          close their open tables. If this happens, the other threads
200
 
          would find the tables unlocked. They would get the locks, one
201
 
          after the other, and could do their destructive work. This is an
202
 
          issue if we have LOCK TABLES in effect.
203
 
 
204
 
          The problem is that the other threads passed all checks in
205
 
          open_table() before we refresh the table.
206
 
 
207
 
          The fix for this problem is to set some_tables_deleted for all
208
 
          threads with open tables. These threads can still get their
209
 
          locks, but will immediately release them again after checking
210
 
          this variable. They will then loop in openTablesLock()
211
 
          again. There they will wait until we update all tables version
212
 
          below.
213
 
 
214
 
          Setting some_tables_deleted is done by table::Cache::singleton().removeTable()
215
 
          in the other branch.
216
 
 
217
 
          In other words (reviewer suggestion): You need this setting of
218
 
          some_tables_deleted for the case when table was opened and all
219
 
          related checks were passed before incrementing refresh_version
220
 
          (which you already have) but attempt to lock the table happened
221
 
          after the call to Session::close_old_data_files() i.e. after removal of
222
 
          current thread locks.
 
445
          Note that we wait here only for tables which are actually open, and
 
446
          not for placeholders with Table::open_placeholder set. Waiting for
 
447
          latter will cause deadlock in the following scenario, for example:
 
448
 
 
449
          conn1-> lock table t1 write;
 
450
          conn2-> lock table t2 write;
 
451
          conn1-> flush tables;
 
452
          conn2-> flush tables;
 
453
 
 
454
          It also does not make sense to wait for those of placeholders that
 
455
          are employed by CREATE TABLE as in this case table simply does not
 
456
          exist yet.
223
457
        */
224
 
        for (table::CacheMap::const_iterator iter= table::getCache().begin();
225
 
             iter != table::getCache().end();
226
 
             iter++)
227
 
        {
228
 
          Table *table= (*iter).second;
229
 
          if (table->in_use)
230
 
            table->in_use->some_tables_deleted= false;
231
 
        }
232
 
      }
233
 
    }
234
 
    else
235
 
    {
236
 
      bool found= false;
237
 
      for (TableList *table= tables; table; table= table->next_local)
238
 
      {
239
 
        identifier::Table identifier(table->getSchemaName(), table->getTableName());
240
 
        if (table::Cache::singleton().removeTable(session, identifier,
241
 
                                    RTFC_OWNED_BY_Session_FLAG))
 
458
        if (table->needs_reopen_or_name_lock() && (table->db_stat ||
 
459
                                                   (table->open_placeholder && wait_for_placeholders)))
242
460
        {
243
461
          found= true;
 
462
          pthread_cond_wait(COND_refresh.native_handle(),LOCK_open.native_handle());
 
463
          break;
244
464
        }
245
465
      }
246
 
      if (!found)
247
 
        wait_for_refresh= false;                        // Nothing to wait for
248
466
    }
 
467
    /*
 
468
      No other thread has the locked tables open; reopen them and get the
 
469
      old locks. This should always succeed (unless some external process
 
470
      has removed the tables)
 
471
    */
 
472
    result= session->reopen_tables(true, true);
249
473
 
250
 
    if (wait_for_refresh)
 
474
    /* Set version for table */
 
475
    for (Table *table= session->open_tables; table ; table= table->getNext())
251
476
    {
252
477
      /*
253
 
        If there is any table that has a lower refresh_version, wait until
254
 
        this is closed (or this thread is killed) before returning
255
 
      */
256
 
      session->mysys_var->current_mutex= &table::Cache::singleton().mutex();
257
 
      session->mysys_var->current_cond= &COND_refresh;
258
 
      session->set_proc_info("Flushing tables");
259
 
 
260
 
      session->close_old_data_files();
261
 
 
262
 
      bool found= true;
263
 
      /* Wait until all threads has closed all the tables we had locked */
264
 
      while (found && ! session->getKilled())
265
 
      {
266
 
        found= false;
267
 
        for (table::CacheMap::const_iterator iter= table::getCache().begin();
268
 
             iter != table::getCache().end();
269
 
             iter++)
270
 
        {
271
 
          Table *table= (*iter).second;
272
 
          /* Avoid a self-deadlock. */
273
 
          if (table->in_use == session)
274
 
            continue;
275
 
          /*
276
 
            Note that we wait here only for tables which are actually open, and
277
 
            not for placeholders with Table::open_placeholder set. Waiting for
278
 
            latter will cause deadlock in the following scenario, for example:
279
 
 
280
 
            conn1-> lock table t1 write;
281
 
            conn2-> lock table t2 write;
282
 
            conn1-> flush tables;
283
 
            conn2-> flush tables;
284
 
 
285
 
            It also does not make sense to wait for those of placeholders that
286
 
            are employed by CREATE TABLE as in this case table simply does not
287
 
            exist yet.
288
 
          */
289
 
          if (table->needs_reopen_or_name_lock() && (table->db_stat ||
290
 
                                                     (table->open_placeholder && wait_for_placeholders)))
291
 
          {
292
 
            found= true;
293
 
            COND_refresh.wait(scopedLock);
294
 
            break;
295
 
          }
296
 
        }
297
 
      }
298
 
      /*
299
 
        No other thread has the locked tables open; reopen them and get the
300
 
        old locks. This should always succeed (unless some external process
301
 
        has removed the tables)
302
 
      */
303
 
      result= session->reopen_tables();
304
 
 
305
 
      /* Set version for table */
306
 
      for (Table *table= session->open_tables; table ; table= table->getNext())
307
 
      {
308
 
        /*
309
 
          Preserve the version (0) of write locked tables so that a impending
310
 
          global read lock won't sneak in.
311
 
        */
312
 
        if (table->reginfo.lock_type < TL_WRITE_ALLOW_WRITE)
313
 
          table->getMutableShare()->refreshVersion();
314
 
      }
 
478
        Preserve the version (0) of write locked tables so that a impending
 
479
        global read lock won't sneak in.
 
480
      */
 
481
      if (table->reginfo.lock_type < TL_WRITE_ALLOW_WRITE)
 
482
        table->getMutableShare()->refreshVersion();
315
483
    }
316
484
  }
317
485
 
 
486
  LOCK_open.unlock();
 
487
 
318
488
  if (wait_for_refresh)
319
489
  {
320
 
    boost_unique_lock_t scopedLock(session->mysys_var->mutex);
 
490
    pthread_mutex_lock(&session->mysys_var->mutex);
321
491
    session->mysys_var->current_mutex= 0;
322
492
    session->mysys_var->current_cond= 0;
323
493
    session->set_proc_info(0);
 
494
    pthread_mutex_unlock(&session->mysys_var->mutex);
324
495
  }
325
496
 
326
497
  return result;
331
502
  move one table to free list 
332
503
*/
333
504
 
334
 
bool Session::free_cached_table(boost::mutex::scoped_lock &scopedLock)
 
505
bool Session::free_cached_table()
335
506
{
336
507
  bool found_old_table= false;
337
 
 
338
 
  (void)scopedLock;
339
 
 
340
 
  table::Concurrent *table= static_cast<table::Concurrent *>(open_tables);
341
 
 
342
 
  safe_mutex_assert_owner(table::Cache::singleton().mutex().native_handle());
 
508
  Table *table= open_tables;
 
509
 
 
510
  safe_mutex_assert_owner(LOCK_open.native_handle());
343
511
  assert(table->key_read == 0);
344
512
  assert(!table->cursor || table->cursor->inited == Cursor::NONE);
345
513
 
348
516
  if (table->needs_reopen_or_name_lock() ||
349
517
      version != refresh_version || !table->db_stat)
350
518
  {
351
 
    table::remove_table(table);
 
519
    remove_table(table);
352
520
    found_old_table= true;
353
521
  }
354
522
  else
361
529
 
362
530
    /* Free memory and reset for next loop */
363
531
    table->cursor->ha_reset();
364
 
    table->in_use= NULL;
 
532
    table->in_use= false;
365
533
 
366
 
    table::getUnused().link(table);
 
534
    unused_tables.link(table);
367
535
  }
368
536
 
369
537
  return found_old_table;
382
550
{
383
551
  bool found_old_table= false;
384
552
 
385
 
  safe_mutex_assert_not_owner(table::Cache::singleton().mutex().native_handle());
 
553
  safe_mutex_assert_not_owner(LOCK_open.native_handle());
386
554
 
387
 
  boost_unique_lock_t scoped_lock(table::Cache::singleton().mutex()); /* Close all open tables on Session */
 
555
  boost::mutex::scoped_lock scoped_lock(LOCK_open); /* Close all open tables on Session */
388
556
 
389
557
  while (open_tables)
390
558
  {
391
 
    found_old_table|= free_cached_table(scoped_lock);
 
559
    found_old_table|= free_cached_table();
392
560
  }
393
561
  some_tables_deleted= false;
394
562
 
395
563
  if (found_old_table)
396
564
  {
397
565
    /* Tell threads waiting for refresh that something has happened */
398
 
    locking::broadcast_refresh();
 
566
    broadcast_refresh();
399
567
  }
400
568
}
401
569
 
424
592
{
425
593
  for (; table; table= table->*link )
426
594
  {
427
 
    if ((table->table == 0 || table->table->getShare()->getType() == message::Table::STANDARD) and
428
 
        my_strcasecmp(system_charset_info, table->getSchemaName(), db_name) == 0 and
429
 
        my_strcasecmp(system_charset_info, table->getTableName(), table_name) == 0)
430
 
    {
 
595
    if ((table->table == 0 || table->table->getShare()->getType() == message::Table::STANDARD) &&
 
596
        strcasecmp(table->db, db_name) == 0 &&
 
597
        strcasecmp(table->table_name, table_name) == 0)
431
598
      break;
432
 
    }
433
599
  }
434
600
  return table;
435
601
}
499
665
    */
500
666
    assert(table);
501
667
  }
502
 
  d_name= table->getSchemaName();
503
 
  t_name= table->getTableName();
 
668
  d_name= table->db;
 
669
  t_name= table->table_name;
504
670
  t_alias= table->alias;
505
671
 
506
672
  for (;;)
521
687
}
522
688
 
523
689
 
524
 
void Open_tables_state::doGetTableNames(const identifier::Schema &schema_identifier,
525
 
                                        std::set<std::string>& set_of_names)
 
690
void Session::doGetTableNames(const SchemaIdentifier &schema_identifier,
 
691
                              std::set<std::string>& set_of_names)
526
692
{
527
 
  for (Table *table= getTemporaryTables() ; table ; table= table->getNext())
 
693
  for (Table *table= temporary_tables ; table ; table= table->getNext())
528
694
  {
529
695
    if (schema_identifier.compare(table->getShare()->getSchemaName()))
530
696
    {
533
699
  }
534
700
}
535
701
 
536
 
void Open_tables_state::doGetTableNames(CachedDirectory &,
537
 
                                        const identifier::Schema &schema_identifier,
538
 
                                        std::set<std::string> &set_of_names)
 
702
void Session::doGetTableNames(CachedDirectory &,
 
703
                              const SchemaIdentifier &schema_identifier,
 
704
                              std::set<std::string> &set_of_names)
539
705
{
540
706
  doGetTableNames(schema_identifier, set_of_names);
541
707
}
542
708
 
543
 
void Open_tables_state::doGetTableIdentifiers(const identifier::Schema &schema_identifier,
544
 
                                              identifier::Table::vector &set_of_identifiers)
 
709
void Session::doGetTableIdentifiers(const SchemaIdentifier &schema_identifier,
 
710
                                    TableIdentifiers &set_of_identifiers)
545
711
{
546
 
  for (Table *table= getTemporaryTables() ; table ; table= table->getNext())
 
712
  for (Table *table= temporary_tables ; table ; table= table->getNext())
547
713
  {
548
714
    if (schema_identifier.compare(table->getShare()->getSchemaName()))
549
715
    {
550
 
      set_of_identifiers.push_back(identifier::Table(table->getShare()->getSchemaName(),
 
716
      set_of_identifiers.push_back(TableIdentifier(table->getShare()->getSchemaName(),
551
717
                                                   table->getShare()->getTableName(),
552
718
                                                   table->getShare()->getPath()));
553
719
    }
554
720
  }
555
721
}
556
722
 
557
 
void Open_tables_state::doGetTableIdentifiers(CachedDirectory &,
558
 
                                              const identifier::Schema &schema_identifier,
559
 
                                              identifier::Table::vector &set_of_identifiers)
 
723
void Session::doGetTableIdentifiers(CachedDirectory &,
 
724
                                    const SchemaIdentifier &schema_identifier,
 
725
                                    TableIdentifiers &set_of_identifiers)
560
726
{
561
727
  doGetTableIdentifiers(schema_identifier, set_of_identifiers);
562
728
}
563
729
 
564
 
bool Open_tables_state::doDoesTableExist(const identifier::Table &identifier)
 
730
bool Session::doDoesTableExist(const TableIdentifier &identifier)
565
731
{
566
 
  for (Table *table= getTemporaryTables() ; table ; table= table->getNext())
 
732
  for (Table *table= temporary_tables ; table ; table= table->getNext())
567
733
  {
568
734
    if (table->getShare()->getType() == message::Table::TEMPORARY)
569
735
    {
577
743
  return false;
578
744
}
579
745
 
580
 
int Open_tables_state::doGetTableDefinition(const identifier::Table &identifier,
581
 
                                            message::Table &table_proto)
 
746
int Session::doGetTableDefinition(const TableIdentifier &identifier,
 
747
                                  message::Table &table_proto)
582
748
{
583
 
  for (Table *table= getTemporaryTables() ; table ; table= table->getNext())
 
749
  for (Table *table= temporary_tables ; table ; table= table->getNext())
584
750
  {
585
751
    if (table->getShare()->getType() == message::Table::TEMPORARY)
586
752
    {
587
753
      if (identifier.getKey() == table->getShare()->getCacheKey())
588
754
      {
589
 
        table_proto.CopyFrom(*(table->getShare()->getTableMessage()));
 
755
        table_proto.CopyFrom(*(table->getShare()->getTableProto()));
590
756
 
591
757
        return EEXIST;
592
758
      }
596
762
  return ENOENT;
597
763
}
598
764
 
599
 
Table *Open_tables_state::find_temporary_table(const identifier::Table &identifier)
 
765
Table *Session::find_temporary_table(const char *new_db, const char *table_name)
 
766
{
 
767
  char  key[MAX_DBKEY_LENGTH];
 
768
  uint  key_length;
 
769
 
 
770
  key_length= TableIdentifier::createKey(key, new_db, table_name);
 
771
 
 
772
  for (Table *table= temporary_tables ; table ; table= table->getNext())
 
773
  {
 
774
    const TableIdentifier::Key &share_key(table->getShare()->getCacheKey());
 
775
    if (share_key.size() == key_length &&
 
776
        not memcmp(&share_key[0], key, key_length))
 
777
    {
 
778
      return table;
 
779
    }
 
780
  }
 
781
  return NULL;                               // Not a temporary table
 
782
}
 
783
 
 
784
Table *Session::find_temporary_table(TableList *table_list)
 
785
{
 
786
  return find_temporary_table(table_list->db, table_list->table_name);
 
787
}
 
788
 
 
789
Table *Session::find_temporary_table(TableIdentifier &identifier)
600
790
{
601
791
  for (Table *table= temporary_tables ; table ; table= table->getNext())
602
792
  {
634
824
  @retval -1  the table is in use by a outer query
635
825
*/
636
826
 
637
 
int Open_tables_state::drop_temporary_table(const drizzled::identifier::Table &identifier)
 
827
int Session::drop_temporary_table(TableList *table_list)
638
828
{
639
829
  Table *table;
640
830
 
641
 
  if (not (table= find_temporary_table(identifier)))
 
831
  if (not (table= find_temporary_table(table_list)))
642
832
    return 1;
643
833
 
644
834
  /* Table might be in use by some outer statement. */
645
 
  if (table->query_id && table->query_id != getQueryId())
 
835
  if (table->query_id && table->query_id != query_id)
646
836
  {
647
837
    my_error(ER_CANT_REOPEN_TABLE, MYF(0), table->getAlias());
648
838
    return -1;
660
850
 
661
851
  @param  session     Thread context
662
852
  @param  find    Table to remove
663
 
 
664
 
  @note because we risk the chance of deleting the share, we can't assume that it will exist past, this should be modified once we can use a TableShare::shared_ptr here.
665
853
*/
666
854
 
667
855
void Session::unlink_open_table(Table *find)
668
856
{
669
 
  const identifier::Table::Key find_key(find->getShare()->getCacheKey());
670
 
  Table **prev;
671
 
  safe_mutex_assert_owner(table::Cache::singleton().mutex().native_handle());
 
857
  char key[MAX_DBKEY_LENGTH];
 
858
  uint32_t key_length= find->getShare()->getCacheKeySize();
 
859
  Table *list, **prev;
 
860
  safe_mutex_assert_owner(LOCK_open.native_handle());
672
861
 
 
862
  memcpy(key, &find->getMutableShare()->getCacheKey()[0], key_length);
673
863
  /*
674
 
    Note that we need to hold table::Cache::singleton().mutex() while changing the
 
864
    Note that we need to hold LOCK_open while changing the
675
865
    open_tables list. Another thread may work on it.
676
 
    (See: table::Cache::singleton().removeTable(), wait_completed_table())
 
866
    (See: remove_table_from_cache(), mysql_wait_completed_table())
677
867
    Closing a MERGE child before the parent would be fatal if the
678
868
    other thread tries to abort the MERGE lock in between.
679
869
  */
680
870
  for (prev= &open_tables; *prev; )
681
871
  {
682
 
    Table *list= *prev;
 
872
    list= *prev;
683
873
 
684
 
    if (list->getShare()->getCacheKey() == find_key)
 
874
    if (list->getShare()->getCacheKeySize() == key_length &&
 
875
        not memcmp(&list->getShare()->getCacheKey()[0], key, key_length))
685
876
    {
686
877
      /* Remove table from open_tables list. */
687
878
      *prev= list->getNext();
688
879
 
689
880
      /* Close table. */
690
 
      table::remove_table(static_cast<table::Concurrent *>(list));
 
881
      remove_table(list);
691
882
    }
692
883
    else
693
884
    {
697
888
  }
698
889
 
699
890
  // Notify any 'refresh' threads
700
 
  locking::broadcast_refresh();
 
891
  broadcast_refresh();
701
892
}
702
893
 
703
894
 
720
911
  table that was locked with LOCK TABLES.
721
912
*/
722
913
 
723
 
void Session::drop_open_table(Table *table, const identifier::Table &identifier)
 
914
void Session::drop_open_table(Table *table, TableIdentifier &identifier)
724
915
{
725
916
  if (table->getShare()->getType())
726
917
  {
728
919
  }
729
920
  else
730
921
  {
731
 
    boost_unique_lock_t scoped_lock(table::Cache::singleton().mutex()); /* Close and drop a table (AUX routine) */
 
922
    boost::mutex::scoped_lock scoped_lock(LOCK_open); /* Close and drop a table (AUX routine) */
732
923
    /*
733
924
      unlink_open_table() also tells threads waiting for refresh or close
734
925
      that something has happened.
735
926
    */
736
927
    unlink_open_table(table);
737
 
    (void)plugin::StorageEngine::dropTable(*this, identifier);
 
928
    quick_rm_table(*this, identifier);
738
929
  }
739
930
}
740
931
 
750
941
  cond  Condition to wait for
751
942
*/
752
943
 
753
 
void Session::wait_for_condition(boost::mutex &mutex, boost::condition_variable_any &cond)
 
944
void Session::wait_for_condition(boost::mutex &mutex, boost::condition_variable &cond)
754
945
{
755
946
  /* Wait until the current table is up to date */
756
947
  const char *saved_proc_info;
757
 
  mysys_var->current_mutex= &mutex;
758
 
  mysys_var->current_cond= &cond;
 
948
  mysys_var->current_mutex= mutex.native_handle();
 
949
  mysys_var->current_cond= cond.native_handle();
759
950
  saved_proc_info= get_proc_info();
760
951
  set_proc_info("Waiting for table");
761
 
  {
762
 
    /*
763
 
      We must unlock mutex first to avoid deadlock becasue conditions are
764
 
      sent to this thread by doing locks in the following order:
765
 
      lock(mysys_var->mutex)
766
 
      lock(mysys_var->current_mutex)
767
 
 
768
 
      One by effect of this that one can only use wait_for_condition with
769
 
      condition variables that are guranteed to not disapper (freed) even if this
770
 
      mutex is unlocked
771
 
    */
772
 
    boost_unique_lock_t scopedLock(mutex, boost::adopt_lock_t());
773
 
    if (not getKilled())
774
 
    {
775
 
      cond.wait(scopedLock);
776
 
    }
777
 
  }
778
 
  boost_unique_lock_t mysys_scopedLock(mysys_var->mutex);
 
952
  if (!killed)
 
953
    (void) pthread_cond_wait(cond.native_handle(), mutex.native_handle());
 
954
 
 
955
  /*
 
956
    We must unlock mutex first to avoid deadlock becasue conditions are
 
957
    sent to this thread by doing locks in the following order:
 
958
    lock(mysys_var->mutex)
 
959
    lock(mysys_var->current_mutex)
 
960
 
 
961
    One by effect of this that one can only use wait_for_condition with
 
962
    condition variables that are guranteed to not disapper (freed) even if this
 
963
    mutex is unlocked
 
964
  */
 
965
 
 
966
  pthread_mutex_unlock(mutex.native_handle());
 
967
  pthread_mutex_lock(&mysys_var->mutex);
779
968
  mysys_var->current_mutex= 0;
780
969
  mysys_var->current_cond= 0;
781
970
  set_proc_info(saved_proc_info);
 
971
  pthread_mutex_unlock(&mysys_var->mutex);
 
972
}
 
973
 
 
974
 
 
975
/*
 
976
  Open table which is already name-locked by this thread.
 
977
 
 
978
  SYNOPSIS
 
979
  reopen_name_locked_table()
 
980
  session         Thread handle
 
981
  table_list  TableList object for table to be open, TableList::table
 
982
  member should point to Table object which was used for
 
983
  name-locking.
 
984
  link_in     true  - if Table object for table to be opened should be
 
985
  linked into Session::open_tables list.
 
986
  false - placeholder used for name-locking is already in
 
987
  this list so we only need to preserve Table::next
 
988
  pointer.
 
989
 
 
990
  NOTE
 
991
  This function assumes that its caller already acquired LOCK_open mutex.
 
992
 
 
993
  RETURN VALUE
 
994
  false - Success
 
995
  true  - Error
 
996
*/
 
997
 
 
998
bool Session::reopen_name_locked_table(TableList* table_list, bool link_in)
 
999
{
 
1000
  Table *table= table_list->table;
 
1001
  TableShare *share;
 
1002
  char *table_name= table_list->table_name;
 
1003
  Table orig_table;
 
1004
 
 
1005
  safe_mutex_assert_owner(LOCK_open.native_handle());
 
1006
 
 
1007
  if (killed || !table)
 
1008
    return true;
 
1009
 
 
1010
  orig_table= *table;
 
1011
 
 
1012
  TableIdentifier identifier(table_list->db, table_list->table_name);
 
1013
  if (open_unireg_entry(this, table, table_name, identifier))
 
1014
  {
 
1015
    table->intern_close_table();
 
1016
    /*
 
1017
      If there was an error during opening of table (for example if it
 
1018
      does not exist) '*table' object can be wiped out. To be able
 
1019
      properly release name-lock in this case we should restore this
 
1020
      object to its original state.
 
1021
    */
 
1022
    *table= orig_table;
 
1023
    return true;
 
1024
  }
 
1025
 
 
1026
  share= table->getMutableShare();
 
1027
  /*
 
1028
    We want to prevent other connections from opening this table until end
 
1029
    of statement as it is likely that modifications of table's metadata are
 
1030
    not yet finished (for example CREATE TRIGGER have to change .TRG cursor,
 
1031
    or we might want to drop table if CREATE TABLE ... SELECT fails).
 
1032
    This also allows us to assume that no other connection will sneak in
 
1033
    before we will get table-level lock on this table.
 
1034
  */
 
1035
  share->resetVersion();
 
1036
  table->in_use = this;
 
1037
 
 
1038
  if (link_in)
 
1039
  {
 
1040
    table->setNext(open_tables);
 
1041
    open_tables= table;
 
1042
  }
 
1043
  else
 
1044
  {
 
1045
    /*
 
1046
      Table object should be already in Session::open_tables list so we just
 
1047
      need to set Table::next correctly.
 
1048
    */
 
1049
    table->setNext(orig_table.getNext());
 
1050
  }
 
1051
 
 
1052
  table->tablenr= current_tablenr++;
 
1053
  table->used_fields= 0;
 
1054
  table->const_table= 0;
 
1055
  table->null_row= false;
 
1056
  table->maybe_null= false;
 
1057
  table->force_index= false;
 
1058
  table->status= STATUS_NO_RECORD;
 
1059
 
 
1060
  return false;
782
1061
}
783
1062
 
784
1063
 
795
1074
  case of failure.
796
1075
*/
797
1076
 
798
 
table::Placeholder *Session::table_cache_insert_placeholder(const drizzled::identifier::Table &arg)
 
1077
Table *Session::table_cache_insert_placeholder(const char *db_name, const char *table_name)
799
1078
{
800
 
  safe_mutex_assert_owner(table::Cache::singleton().mutex().native_handle());
 
1079
  safe_mutex_assert_owner(LOCK_open.native_handle());
801
1080
 
802
1081
  /*
803
1082
    Create a table entry with the right key and with an old refresh version
804
1083
  */
805
 
  identifier::Table identifier(arg.getSchemaName(), arg.getTableName(), message::Table::INTERNAL);
806
 
  table::Placeholder *table= new table::Placeholder(this, identifier);
 
1084
  TableIdentifier identifier(db_name, table_name, message::Table::INTERNAL);
 
1085
  TablePlaceholder *table= new TablePlaceholder(this, identifier);
807
1086
 
808
 
  if (not table::Cache::singleton().insert(table))
 
1087
  if (not add_table(table))
809
1088
  {
810
1089
    delete table;
811
1090
 
837
1116
  @retval  true   Error occured (OOM)
838
1117
  @retval  false  Success. 'table' parameter set according to above rules.
839
1118
*/
840
 
bool Session::lock_table_name_if_not_cached(const identifier::Table &identifier, Table **table)
 
1119
bool Session::lock_table_name_if_not_cached(TableIdentifier &identifier, Table **table)
841
1120
{
842
 
  const identifier::Table::Key &key(identifier.getKey());
843
 
 
844
 
  boost_unique_lock_t scope_lock(table::Cache::singleton().mutex()); /* Obtain a name lock even though table is not in cache (like for create table)  */
845
 
 
846
 
  table::CacheMap::iterator iter;
847
 
 
848
 
  iter= table::getCache().find(key);
849
 
 
850
 
  if (iter != table::getCache().end())
 
1121
  const TableIdentifier::Key &key(identifier.getKey());
 
1122
 
 
1123
  boost::mutex::scoped_lock scope_lock(LOCK_open); /* Obtain a name lock even though table is not in cache (like for create table)  */
 
1124
 
 
1125
  TableOpenCache::iterator iter;
 
1126
 
 
1127
  iter= get_open_cache().find(key);
 
1128
 
 
1129
  if (iter != get_open_cache().end())
851
1130
  {
852
1131
    *table= 0;
853
1132
    return false;
854
1133
  }
855
1134
 
856
 
  if (not (*table= table_cache_insert_placeholder(identifier)))
 
1135
  if (not (*table= table_cache_insert_placeholder(identifier.getSchemaName().c_str(), identifier.getTableName().c_str())))
857
1136
  {
858
1137
    return true;
859
1138
  }
913
1192
  if (check_stack_overrun(this, STACK_MIN_SIZE_FOR_OPEN, (unsigned char *)&alias))
914
1193
    return NULL;
915
1194
 
916
 
  if (getKilled())
 
1195
  if (killed)
917
1196
    return NULL;
918
1197
 
919
 
  identifier::Table identifier(table_list->getSchemaName(), table_list->getTableName());
920
 
  const identifier::Table::Key &key(identifier.getKey());
921
 
  table::CacheRange ppp;
 
1198
  TableIdentifier identifier(table_list->db, table_list->table_name);
 
1199
  const TableIdentifier::Key &key(identifier.getKey());
 
1200
  TableOpenCacheRange ppp;
922
1201
 
923
1202
  /*
924
1203
    Unless requested otherwise, try to resolve this table in the list
927
1206
    same name. This block implements the behaviour.
928
1207
    TODO -> move this block into a separate function.
929
1208
  */
930
 
  bool reset= false;
931
 
  for (table= getTemporaryTables(); table ; table=table->getNext())
 
1209
  for (table= temporary_tables; table ; table=table->getNext())
932
1210
  {
933
1211
    if (table->getShare()->getCacheKey() == key)
934
1212
    {
944
1222
        return NULL;
945
1223
      }
946
1224
      table->query_id= getQueryId();
947
 
      reset= true;
 
1225
      goto reset;
 
1226
    }
 
1227
  }
 
1228
 
 
1229
  if (flags & DRIZZLE_OPEN_TEMPORARY_ONLY)
 
1230
  {
 
1231
    my_error(ER_NO_SUCH_TABLE, MYF(0), table_list->db, table_list->table_name);
 
1232
    return NULL;
 
1233
  }
 
1234
 
 
1235
  /*
 
1236
    If it's the first table from a list of tables used in a query,
 
1237
    remember refresh_version (the version of open_cache state).
 
1238
    If the version changes while we're opening the remaining tables,
 
1239
    we will have to back off, close all the tables opened-so-far,
 
1240
    and try to reopen them.
 
1241
 
 
1242
    Note-> refresh_version is currently changed only during FLUSH TABLES.
 
1243
  */
 
1244
  if (!open_tables)
 
1245
  {
 
1246
    version= refresh_version;
 
1247
  }
 
1248
  else if ((version != refresh_version) &&
 
1249
           ! (flags & DRIZZLE_LOCK_IGNORE_FLUSH))
 
1250
  {
 
1251
    /* Someone did a refresh while thread was opening tables */
 
1252
    if (refresh)
 
1253
      *refresh= true;
 
1254
 
 
1255
    return NULL;
 
1256
  }
 
1257
 
 
1258
  /*
 
1259
    Before we test the global cache, we test our local session cache.
 
1260
  */
 
1261
  if (cached_table)
 
1262
  {
 
1263
    assert(false); /* Not implemented yet */
 
1264
  }
 
1265
 
 
1266
  /*
 
1267
    Non pre-locked/LOCK TABLES mode, and the table is not temporary:
 
1268
    this is the normal use case.
 
1269
    Now we should:
 
1270
    - try to find the table in the table cache.
 
1271
    - if one of the discovered Table instances is name-locked
 
1272
    (table->getShare()->version == 0) back off -- we have to wait
 
1273
    until no one holds a name lock on the table.
 
1274
    - if there is no such Table in the name cache, read the table definition
 
1275
    and insert it into the cache.
 
1276
    We perform all of the above under LOCK_open which currently protects
 
1277
    the open cache (also known as table cache) and table definitions stored
 
1278
    on disk.
 
1279
  */
 
1280
 
 
1281
  LOCK_open.lock(); /* Lock for FLUSH TABLES for open table */
 
1282
 
 
1283
  /*
 
1284
    Actually try to find the table in the open_cache.
 
1285
    The cache may contain several "Table" instances for the same
 
1286
    physical table. The instances that are currently "in use" by
 
1287
    some thread have their "in_use" member != NULL.
 
1288
    There is no good reason for having more than one entry in the
 
1289
    hash for the same physical table, except that we use this as
 
1290
    an implicit "pending locks queue" - see
 
1291
    wait_for_locked_table_names for details.
 
1292
  */
 
1293
  ppp= get_open_cache().equal_range(key);
 
1294
 
 
1295
  table= NULL;
 
1296
  for (TableOpenCache::const_iterator iter= ppp.first;
 
1297
       iter != ppp.second; ++iter, table= NULL)
 
1298
  {
 
1299
    table= (*iter).second;
 
1300
 
 
1301
    if (not table->in_use)
948
1302
      break;
949
 
    }
950
 
  }
951
 
 
952
 
  if (not reset)
953
 
  {
954
 
    if (flags & DRIZZLE_OPEN_TEMPORARY_ONLY)
955
 
    {
956
 
      my_error(ER_TABLE_UNKNOWN, identifier);
957
 
      return NULL;
958
 
    }
959
 
 
960
1303
    /*
961
 
      If it's the first table from a list of tables used in a query,
962
 
      remember refresh_version (the version of open_cache state).
963
 
      If the version changes while we're opening the remaining tables,
964
 
      we will have to back off, close all the tables opened-so-far,
965
 
      and try to reopen them.
966
 
 
967
 
      Note-> refresh_version is currently changed only during FLUSH TABLES.
 
1304
      Here we flush tables marked for flush.
 
1305
      Normally, table->getShare()->version contains the value of
 
1306
      refresh_version from the moment when this table was
 
1307
      (re-)opened and added to the cache.
 
1308
      If since then we did (or just started) FLUSH TABLES
 
1309
      statement, refresh_version has been increased.
 
1310
      For "name-locked" Table instances, table->getShare()->version is set
 
1311
      to 0 (see lock_table_name for details).
 
1312
      In case there is a pending FLUSH TABLES or a name lock, we
 
1313
      need to back off and re-start opening tables.
 
1314
      If we do not back off now, we may dead lock in case of lock
 
1315
      order mismatch with some other thread:
 
1316
      c1-> name lock t1; -- sort of exclusive lock
 
1317
      c2-> open t2;      -- sort of shared lock
 
1318
      c1-> name lock t2; -- blocks
 
1319
      c2-> open t1; -- blocks
968
1320
    */
969
 
    if (!open_tables)
970
 
    {
971
 
      version= refresh_version;
972
 
    }
973
 
    else if ((version != refresh_version) &&
974
 
             ! (flags & DRIZZLE_LOCK_IGNORE_FLUSH))
975
 
    {
976
 
      /* Someone did a refresh while thread was opening tables */
 
1321
    if (table->needs_reopen_or_name_lock())
 
1322
    {
 
1323
      if (flags & DRIZZLE_LOCK_IGNORE_FLUSH)
 
1324
      {
 
1325
        /* Force close at once after usage */
 
1326
        version= table->getShare()->getVersion();
 
1327
        continue;
 
1328
      }
 
1329
 
 
1330
      /* Avoid self-deadlocks by detecting self-dependencies. */
 
1331
      if (table->open_placeholder && table->in_use == this)
 
1332
      {
 
1333
        LOCK_open.unlock();
 
1334
        my_error(ER_UPDATE_TABLE_USED, MYF(0), table->getMutableShare()->getTableName());
 
1335
        return NULL;
 
1336
      }
 
1337
 
 
1338
      /*
 
1339
        Back off, part 1: mark the table as "unused" for the
 
1340
        purpose of name-locking by setting table->db_stat to 0. Do
 
1341
        that only for the tables in this thread that have an old
 
1342
        table->getShare()->version (this is an optimization (?)).
 
1343
        table->db_stat == 0 signals wait_for_locked_table_names
 
1344
        that the tables in question are not used any more. See
 
1345
        table_is_used call for details.
 
1346
      */
 
1347
      close_old_data_files(false, false);
 
1348
 
 
1349
      /*
 
1350
        Back-off part 2: try to avoid "busy waiting" on the table:
 
1351
        if the table is in use by some other thread, we suspend
 
1352
        and wait till the operation is complete: when any
 
1353
        operation that juggles with table->getShare()->version completes,
 
1354
        it broadcasts COND_refresh condition variable.
 
1355
        If 'old' table we met is in use by current thread we return
 
1356
        without waiting since in this situation it's this thread
 
1357
        which is responsible for broadcasting on COND_refresh
 
1358
        (and this was done already in Session::close_old_data_files()).
 
1359
        Good example of such situation is when we have statement
 
1360
        that needs two instances of table and FLUSH TABLES comes
 
1361
        after we open first instance but before we open second
 
1362
        instance.
 
1363
      */
 
1364
      if (table->in_use != this)
 
1365
      {
 
1366
        /* wait_for_conditionwill unlock LOCK_open for us */
 
1367
        wait_for_condition(LOCK_open, COND_refresh);
 
1368
      }
 
1369
      else
 
1370
      {
 
1371
        LOCK_open.unlock();
 
1372
      }
 
1373
      /*
 
1374
        There is a refresh in progress for this table.
 
1375
        Signal the caller that it has to try again.
 
1376
      */
977
1377
      if (refresh)
978
1378
        *refresh= true;
979
 
 
980
1379
      return NULL;
981
1380
    }
982
 
 
983
 
    /*
984
 
      Before we test the global cache, we test our local session cache.
985
 
    */
986
 
    if (cached_table)
987
 
    {
988
 
      assert(false); /* Not implemented yet */
989
 
    }
990
 
 
991
 
    /*
992
 
      Non pre-locked/LOCK TABLES mode, and the table is not temporary:
993
 
      this is the normal use case.
994
 
      Now we should:
995
 
      - try to find the table in the table cache.
996
 
      - if one of the discovered Table instances is name-locked
997
 
      (table->getShare()->version == 0) back off -- we have to wait
998
 
      until no one holds a name lock on the table.
999
 
      - if there is no such Table in the name cache, read the table definition
1000
 
      and insert it into the cache.
1001
 
      We perform all of the above under table::Cache::singleton().mutex() which currently protects
1002
 
      the open cache (also known as table cache) and table definitions stored
1003
 
      on disk.
1004
 
    */
1005
 
 
1006
 
    {
1007
 
      boost::mutex::scoped_lock scopedLock(table::Cache::singleton().mutex());
1008
 
 
1009
 
      /*
1010
 
        Actually try to find the table in the open_cache.
1011
 
        The cache may contain several "Table" instances for the same
1012
 
        physical table. The instances that are currently "in use" by
1013
 
        some thread have their "in_use" member != NULL.
1014
 
        There is no good reason for having more than one entry in the
1015
 
        hash for the same physical table, except that we use this as
1016
 
        an implicit "pending locks queue" - see
1017
 
        wait_for_locked_table_names for details.
1018
 
      */
1019
 
      ppp= table::getCache().equal_range(key);
1020
 
 
1021
 
      table= NULL;
1022
 
      for (table::CacheMap::const_iterator iter= ppp.first;
1023
 
           iter != ppp.second; ++iter, table= NULL)
 
1381
  }
 
1382
  if (table)
 
1383
  {
 
1384
    unused_tables.unlink(table);
 
1385
    table->in_use= this;
 
1386
  }
 
1387
  else
 
1388
  {
 
1389
    /* Insert a new Table instance into the open cache */
 
1390
    int error;
 
1391
    /* Free cache if too big */
 
1392
    unused_tables.cull();
 
1393
 
 
1394
    if (table_list->isCreate())
 
1395
    {
 
1396
      TableIdentifier  lock_table_identifier(table_list->db, table_list->table_name, message::Table::STANDARD);
 
1397
 
 
1398
      if (not plugin::StorageEngine::doesTableExist(*this, lock_table_identifier))
1024
1399
      {
1025
 
        table= (*iter).second;
1026
 
 
1027
 
        if (not table->in_use)
1028
 
          break;
1029
1400
        /*
1030
 
          Here we flush tables marked for flush.
1031
 
          Normally, table->getShare()->version contains the value of
1032
 
          refresh_version from the moment when this table was
1033
 
          (re-)opened and added to the cache.
1034
 
          If since then we did (or just started) FLUSH TABLES
1035
 
          statement, refresh_version has been increased.
1036
 
          For "name-locked" Table instances, table->getShare()->version is set
1037
 
          to 0 (see lock_table_name for details).
1038
 
          In case there is a pending FLUSH TABLES or a name lock, we
1039
 
          need to back off and re-start opening tables.
1040
 
          If we do not back off now, we may dead lock in case of lock
1041
 
          order mismatch with some other thread:
1042
 
          c1-> name lock t1; -- sort of exclusive lock
1043
 
          c2-> open t2;      -- sort of shared lock
1044
 
          c1-> name lock t2; -- blocks
1045
 
          c2-> open t1; -- blocks
 
1401
          Table to be created, so we need to create placeholder in table-cache.
1046
1402
        */
1047
 
        if (table->needs_reopen_or_name_lock())
 
1403
        if (!(table= table_cache_insert_placeholder(table_list->db, table_list->table_name)))
1048
1404
        {
1049
 
          if (flags & DRIZZLE_LOCK_IGNORE_FLUSH)
1050
 
          {
1051
 
            /* Force close at once after usage */
1052
 
            version= table->getShare()->getVersion();
1053
 
            continue;
1054
 
          }
1055
 
 
1056
 
          /* Avoid self-deadlocks by detecting self-dependencies. */
1057
 
          if (table->open_placeholder && table->in_use == this)
1058
 
          {
1059
 
            my_error(ER_UPDATE_TABLE_USED, MYF(0), table->getShare()->getTableName());
1060
 
            return NULL;
1061
 
          }
1062
 
 
1063
 
          /*
1064
 
            Back off, part 1: mark the table as "unused" for the
1065
 
            purpose of name-locking by setting table->db_stat to 0. Do
1066
 
            that only for the tables in this thread that have an old
1067
 
            table->getShare()->version (this is an optimization (?)).
1068
 
            table->db_stat == 0 signals wait_for_locked_table_names
1069
 
            that the tables in question are not used any more. See
1070
 
            table_is_used call for details.
1071
 
          */
1072
 
          close_old_data_files(false, false);
1073
 
 
1074
 
          /*
1075
 
            Back-off part 2: try to avoid "busy waiting" on the table:
1076
 
            if the table is in use by some other thread, we suspend
1077
 
            and wait till the operation is complete: when any
1078
 
            operation that juggles with table->getShare()->version completes,
1079
 
            it broadcasts COND_refresh condition variable.
1080
 
            If 'old' table we met is in use by current thread we return
1081
 
            without waiting since in this situation it's this thread
1082
 
            which is responsible for broadcasting on COND_refresh
1083
 
            (and this was done already in Session::close_old_data_files()).
1084
 
            Good example of such situation is when we have statement
1085
 
            that needs two instances of table and FLUSH TABLES comes
1086
 
            after we open first instance but before we open second
1087
 
            instance.
1088
 
          */
1089
 
          if (table->in_use != this)
1090
 
          {
1091
 
            /* wait_for_conditionwill unlock table::Cache::singleton().mutex() for us */
1092
 
            wait_for_condition(table::Cache::singleton().mutex(), COND_refresh);
1093
 
            scopedLock.release();
1094
 
          }
1095
 
          else
1096
 
          {
1097
 
            scopedLock.unlock();
1098
 
          }
1099
 
 
1100
 
          /*
1101
 
            There is a refresh in progress for this table.
1102
 
            Signal the caller that it has to try again.
1103
 
          */
1104
 
          if (refresh)
1105
 
            *refresh= true;
1106
 
 
 
1405
          LOCK_open.unlock();
1107
1406
          return NULL;
1108
1407
        }
1109
 
      }
1110
 
 
1111
 
      if (table)
1112
 
      {
1113
 
        table::getUnused().unlink(static_cast<table::Concurrent *>(table));
1114
 
        table->in_use= this;
1115
 
      }
1116
 
      else
1117
 
      {
1118
 
        /* Insert a new Table instance into the open cache */
1119
 
        int error;
1120
 
        /* Free cache if too big */
1121
 
        table::getUnused().cull();
1122
 
 
1123
 
        if (table_list->isCreate())
1124
 
        {
1125
 
          identifier::Table  lock_table_identifier(table_list->getSchemaName(), table_list->getTableName(), message::Table::STANDARD);
1126
 
 
1127
 
          if (not plugin::StorageEngine::doesTableExist(*this, lock_table_identifier))
1128
 
          {
1129
 
            /*
1130
 
              Table to be created, so we need to create placeholder in table-cache.
1131
 
            */
1132
 
            if (!(table= table_cache_insert_placeholder(lock_table_identifier)))
1133
 
            {
1134
 
              return NULL;
1135
 
            }
1136
 
            /*
1137
 
              Link placeholder to the open tables list so it will be automatically
1138
 
              removed once tables are closed. Also mark it so it won't be ignored
1139
 
              by other trying to take name-lock.
1140
 
            */
1141
 
            table->open_placeholder= true;
1142
 
            table->setNext(open_tables);
1143
 
            open_tables= table;
1144
 
 
1145
 
            return table ;
1146
 
          }
1147
 
          /* Table exists. Let us try to open it. */
1148
 
        }
1149
 
 
1150
 
        /* make a new table */
1151
 
        {
1152
 
          table::Concurrent *new_table= new table::Concurrent;
1153
 
          table= new_table;
1154
 
          if (new_table == NULL)
1155
 
          {
1156
 
            return NULL;
1157
 
          }
1158
 
 
1159
 
          error= new_table->open_unireg_entry(this, alias, identifier);
1160
 
          if (error != 0)
1161
 
          {
1162
 
            delete new_table;
1163
 
            return NULL;
1164
 
          }
1165
 
          (void)table::Cache::singleton().insert(new_table);
1166
 
        }
1167
 
      }
1168
 
    }
1169
 
 
1170
 
    if (refresh)
1171
 
    {
1172
 
      table->setNext(open_tables); /* Link into simple list */
1173
 
      open_tables= table;
1174
 
    }
1175
 
    table->reginfo.lock_type= TL_READ; /* Assume read */
1176
 
 
1177
 
  }
 
1408
        /*
 
1409
          Link placeholder to the open tables list so it will be automatically
 
1410
          removed once tables are closed. Also mark it so it won't be ignored
 
1411
          by other trying to take name-lock.
 
1412
        */
 
1413
        table->open_placeholder= true;
 
1414
        table->setNext(open_tables);
 
1415
        open_tables= table;
 
1416
        LOCK_open.unlock();
 
1417
 
 
1418
        return table ;
 
1419
      }
 
1420
      /* Table exists. Let us try to open it. */
 
1421
    }
 
1422
 
 
1423
    /* make a new table */
 
1424
    table= new Table;
 
1425
    if (table == NULL)
 
1426
    {
 
1427
      LOCK_open.unlock();
 
1428
      return NULL;
 
1429
    }
 
1430
 
 
1431
    error= open_unireg_entry(this, table, alias, identifier);
 
1432
    if (error != 0)
 
1433
    {
 
1434
      delete table;
 
1435
      LOCK_open.unlock();
 
1436
      return NULL;
 
1437
    }
 
1438
    (void)add_table(table);
 
1439
  }
 
1440
 
 
1441
  LOCK_open.unlock();
 
1442
  if (refresh)
 
1443
  {
 
1444
    table->setNext(open_tables); /* Link into simple list */
 
1445
    open_tables= table;
 
1446
  }
 
1447
  table->reginfo.lock_type= TL_READ; /* Assume read */
 
1448
 
 
1449
reset:
1178
1450
  assert(table->getShare()->getTableCount() > 0 || table->getShare()->getType() != message::Table::STANDARD);
1179
1451
 
 
1452
  if (lex->need_correct_ident())
 
1453
    table->alias_name_used= my_strcasecmp(table_alias_charset,
 
1454
                                          table->getMutableShare()->getTableName(), alias);
1180
1455
  /* Fix alias if table name changes */
1181
1456
  if (strcmp(table->getAlias(), alias))
1182
1457
  {
1183
 
    table->setAlias(alias);
 
1458
    uint32_t length=(uint32_t) strlen(alias)+1;
 
1459
    table->alias= (char*) realloc((char*) table->alias, length);
 
1460
    memcpy((void*) table->alias, alias, length);
1184
1461
  }
1185
1462
 
1186
1463
  /* These variables are also set in reopen_table() */
1207
1484
}
1208
1485
 
1209
1486
 
 
1487
#if 0
 
1488
/*
 
1489
  Reopen an table because the definition has changed.
 
1490
 
 
1491
  SYNOPSIS
 
1492
  reopen_table()
 
1493
  table Table object
 
1494
 
 
1495
  NOTES
 
1496
  The data cursor for the table is already closed and the share is released
 
1497
  The table has a 'dummy' share that mainly contains database and table name.
 
1498
 
 
1499
  RETURN
 
1500
  0  ok
 
1501
  1  error. The old table object is not changed.
 
1502
*/
 
1503
 
 
1504
bool reopen_table(Table *table)
 
1505
{
 
1506
  Table tmp;
 
1507
  bool error= 1;
 
1508
  Field **field;
 
1509
  uint32_t key,part;
 
1510
  TableList table_list;
 
1511
  Session *session= table->in_use;
 
1512
 
 
1513
  assert(table->getShare()->ref_count == 0);
 
1514
  assert(!table->sort.io_cache);
 
1515
 
 
1516
#ifdef EXTRA_DEBUG
 
1517
  if (table->db_stat)
 
1518
    errmsg_printf(ERRMSG_LVL_ERROR, _("Table %s had a open data Cursor in reopen_table"),
 
1519
                  table->alias);
 
1520
#endif
 
1521
  table_list.db=         const_cast<char *>(table->getShare()->getSchemaName());
 
1522
  table_list.table_name= table->getShare()->getTableName();
 
1523
  table_list.table=      table;
 
1524
 
 
1525
  if (wait_for_locked_table_names(session, &table_list))
 
1526
    return true;                             // Thread was killed
 
1527
 
 
1528
  if (open_unireg_entry(session, &tmp, &table_list,
 
1529
                        table->alias,
 
1530
                        table->getShare()->getCacheKey(),
 
1531
                        table->getShare()->getCacheKeySize()))
 
1532
    goto end;
 
1533
 
 
1534
  /* This list copies variables set by open_table */
 
1535
  tmp.tablenr=          table->tablenr;
 
1536
  tmp.used_fields=      table->used_fields;
 
1537
  tmp.const_table=      table->const_table;
 
1538
  tmp.null_row=         table->null_row;
 
1539
  tmp.maybe_null=       table->maybe_null;
 
1540
  tmp.status=           table->status;
 
1541
 
 
1542
  /* Get state */
 
1543
  tmp.in_use=           session;
 
1544
  tmp.reginfo.lock_type=table->reginfo.lock_type;
 
1545
 
 
1546
  /* Replace table in open list */
 
1547
  tmp.next=             table->next;
 
1548
  tmp.prev=             table->prev;
 
1549
 
 
1550
  if (table->cursor)
 
1551
    table->delete_table(true);          // close cursor, free everything
 
1552
 
 
1553
  *table= tmp;
 
1554
  table->default_column_bitmaps();
 
1555
  table->cursor->change_table_ptr(table, table->s);
 
1556
 
 
1557
  assert(table->alias != 0);
 
1558
  for (field=table->field ; *field ; field++)
 
1559
  {
 
1560
    (*field)->table= (*field)->orig_table= table;
 
1561
    (*field)->table_name= &table->alias;
 
1562
  }
 
1563
  for (key=0 ; key < table->getShare()->keys ; key++)
 
1564
  {
 
1565
    for (part=0 ; part < table->key_info[key].usable_key_parts ; part++)
 
1566
      table->key_info[key].key_part[part].field->table= table;
 
1567
  }
 
1568
 
 
1569
  broadcast_refresh();
 
1570
  error= false;
 
1571
 
 
1572
end:
 
1573
  return(error);
 
1574
}
 
1575
#endif
 
1576
 
 
1577
 
1210
1578
/**
1211
1579
  Close all instances of a table open by this thread and replace
1212
1580
  them with exclusive name-locks.
1224
1592
  the strings are used in a loop even after the share may be freed.
1225
1593
*/
1226
1594
 
1227
 
void Session::close_data_files_and_morph_locks(const identifier::Table &identifier)
 
1595
void Session::close_data_files_and_morph_locks(TableIdentifier &identifier)
1228
1596
{
1229
 
  safe_mutex_assert_owner(table::Cache::singleton().mutex().native_handle()); /* Adjust locks at the end of ALTER TABLEL */
 
1597
  safe_mutex_assert_owner(LOCK_open.native_handle()); /* Adjust locks at the end of ALTER TABLEL */
1230
1598
 
1231
1599
  if (lock)
1232
1600
  {
1234
1602
      If we are not under LOCK TABLES we should have only one table
1235
1603
      open and locked so it makes sense to remove the lock at once.
1236
1604
    */
1237
 
    unlockTables(lock);
 
1605
    mysql_unlock_tables(this, lock);
1238
1606
    lock= 0;
1239
1607
  }
1240
1608
 
1269
1637
  combination when one needs tables to be reopened (for
1270
1638
  example see openTablesLock()).
1271
1639
 
1272
 
  @note One should have lock on table::Cache::singleton().mutex() when calling this.
 
1640
  @note One should have lock on LOCK_open when calling this.
1273
1641
 
1274
1642
  @return false in case of success, true - otherwise.
1275
1643
*/
1276
1644
 
1277
 
bool Session::reopen_tables()
 
1645
bool Session::reopen_tables(bool get_locks, bool)
1278
1646
{
1279
1647
  Table *table,*next,**prev;
1280
 
  Table **tables= 0;                    // For locks
1281
 
  Table **tables_ptr= 0;                        // For locks
1282
 
  bool error= false;
 
1648
  Table **tables,**tables_ptr;                  // For locks
 
1649
  bool error=0, not_used;
1283
1650
  const uint32_t flags= DRIZZLE_LOCK_NOTIFY_IF_NEED_REOPEN |
1284
1651
    DRIZZLE_LOCK_IGNORE_GLOBAL_READ_LOCK |
1285
1652
    DRIZZLE_LOCK_IGNORE_FLUSH;
1287
1654
  if (open_tables == NULL)
1288
1655
    return false;
1289
1656
 
1290
 
  safe_mutex_assert_owner(table::Cache::singleton().mutex().native_handle());
 
1657
  safe_mutex_assert_owner(LOCK_open.native_handle());
 
1658
  if (get_locks)
1291
1659
  {
1292
1660
    /*
1293
1661
      The ptr is checked later
1301
1669
    }
1302
1670
    tables= new Table *[opens];
1303
1671
  }
1304
 
 
 
1672
  else
 
1673
  {
 
1674
    tables= &open_tables;
 
1675
  }
1305
1676
  tables_ptr =tables;
1306
1677
 
1307
1678
  prev= &open_tables;
1310
1681
    next= table->getNext();
1311
1682
 
1312
1683
    my_error(ER_CANT_REOPEN_TABLE, MYF(0), table->getAlias());
1313
 
    table::remove_table(static_cast<table::Concurrent *>(table));
 
1684
    remove_table(table);
1314
1685
    error= 1;
1315
1686
  }
1316
1687
  *prev=0;
1317
 
 
1318
1688
  if (tables != tables_ptr)                     // Should we get back old locks
1319
1689
  {
1320
1690
    DrizzleLock *local_lock;
1321
1691
    /*
1322
1692
      We should always get these locks. Anyway, we must not go into
1323
 
      wait_for_tables() as it tries to acquire table::Cache::singleton().mutex(), which is
 
1693
      wait_for_tables() as it tries to acquire LOCK_open, which is
1324
1694
      already locked.
1325
1695
    */
1326
1696
    some_tables_deleted= false;
1327
1697
 
1328
 
    if ((local_lock= lockTables(tables, (uint32_t) (tables_ptr - tables), flags)))
 
1698
    if ((local_lock= mysql_lock_tables(this, tables, (uint32_t) (tables_ptr - tables),
 
1699
                                 flags, &not_used)))
1329
1700
    {
1330
1701
      /* unused */
1331
1702
    }
1341
1712
    }
1342
1713
  }
1343
1714
 
1344
 
  delete [] tables;
1345
 
 
1346
 
  locking::broadcast_refresh();
1347
 
 
1348
 
  return error;
 
1715
  if (get_locks && tables)
 
1716
    delete [] tables;
 
1717
 
 
1718
  broadcast_refresh();
 
1719
 
 
1720
  return(error);
1349
1721
}
1350
1722
 
1351
1723
 
1376
1748
    */
1377
1749
    if (table->needs_reopen_or_name_lock())
1378
1750
    {
1379
 
      found= true;
 
1751
      found=1;
1380
1752
      if (table->db_stat)
1381
1753
      {
1382
1754
        if (morph_locks)
1390
1762
              lock on it. This will also give them a chance to close their
1391
1763
              instances of this table.
1392
1764
            */
1393
 
            abortLock(ulcktbl);
1394
 
            removeLock(ulcktbl);
 
1765
            mysql_lock_abort(this, ulcktbl);
 
1766
            mysql_lock_remove(this, ulcktbl);
1395
1767
            ulcktbl->lock_count= 0;
1396
1768
          }
1397
1769
          if ((ulcktbl != table) && ulcktbl->db_stat)
1431
1803
    }
1432
1804
  }
1433
1805
  if (found)
1434
 
    locking::broadcast_refresh();
 
1806
    broadcast_refresh();
 
1807
}
 
1808
 
 
1809
 
 
1810
/*
 
1811
  Wait until all threads has closed the tables in the list
 
1812
  We have also to wait if there is thread that has a lock on this table even
 
1813
  if the table is closed
 
1814
*/
 
1815
 
 
1816
bool table_is_used(Table *table, bool wait_for_name_lock)
 
1817
{
 
1818
  do
 
1819
  {
 
1820
    const TableIdentifier::Key &key(table->getShare()->getCacheKey());
 
1821
 
 
1822
    TableOpenCacheRange ppp;
 
1823
    ppp= get_open_cache().equal_range(key);
 
1824
 
 
1825
    for (TableOpenCache::const_iterator iter= ppp.first;
 
1826
         iter != ppp.second; ++iter)
 
1827
    {
 
1828
      Table *search= (*iter).second;
 
1829
      if (search->in_use == table->in_use)
 
1830
        continue;                               // Name locked by this thread
 
1831
      /*
 
1832
        We can't use the table under any of the following conditions:
 
1833
        - There is an name lock on it (Table is to be deleted or altered)
 
1834
        - If we are in flush table and we didn't execute the flush
 
1835
        - If the table engine is open and it's an old version
 
1836
        (We must wait until all engines are shut down to use the table)
 
1837
      */
 
1838
      if ( (search->locked_by_name && wait_for_name_lock) ||
 
1839
           (search->is_name_opened() && search->needs_reopen_or_name_lock()))
 
1840
        return 1;
 
1841
    }
 
1842
  } while ((table=table->getNext()));
 
1843
  return 0;
 
1844
}
 
1845
 
 
1846
 
 
1847
/* Wait until all used tables are refreshed */
 
1848
 
 
1849
bool wait_for_tables(Session *session)
 
1850
{
 
1851
  bool result;
 
1852
 
 
1853
  session->set_proc_info("Waiting for tables");
 
1854
  {
 
1855
    boost::mutex::scoped_lock lock(LOCK_open);
 
1856
    while (!session->killed)
 
1857
    {
 
1858
      session->some_tables_deleted= false;
 
1859
      session->close_old_data_files(false, dropping_tables != 0);
 
1860
      if (!table_is_used(session->open_tables, 1))
 
1861
        break;
 
1862
      COND_refresh.wait(lock);
 
1863
    }
 
1864
    if (session->killed)
 
1865
      result= true;                                     // aborted
 
1866
    else
 
1867
    {
 
1868
      /* Now we can open all tables without any interference */
 
1869
      session->set_proc_info("Reopen tables");
 
1870
      session->version= refresh_version;
 
1871
      result= session->reopen_tables(false, false);
 
1872
    }
 
1873
  }
 
1874
  session->set_proc_info(0);
 
1875
 
 
1876
  return result;
1435
1877
}
1436
1878
 
1437
1879
 
1459
1901
*/
1460
1902
 
1461
1903
 
1462
 
Table *drop_locked_tables(Session *session, const drizzled::identifier::Table &identifier)
 
1904
Table *drop_locked_tables(Session *session, const drizzled::TableIdentifier &identifier)
1463
1905
{
1464
1906
  Table *table,*next,**prev, *found= 0;
1465
1907
  prev= &session->open_tables;
1466
1908
 
1467
1909
  /*
1468
 
    Note that we need to hold table::Cache::singleton().mutex() while changing the
 
1910
    Note that we need to hold LOCK_open while changing the
1469
1911
    open_tables list. Another thread may work on it.
1470
 
    (See: table::Cache::singleton().removeTable(), wait_completed_table())
 
1912
    (See: remove_table_from_cache(), mysql_wait_completed_table())
1471
1913
    Closing a MERGE child before the parent would be fatal if the
1472
1914
    other thread tries to abort the MERGE lock in between.
1473
1915
  */
1476
1918
    next=table->getNext();
1477
1919
    if (table->getShare()->getCacheKey() == identifier.getKey())
1478
1920
    {
1479
 
      session->removeLock(table);
 
1921
      mysql_lock_remove(session, table);
1480
1922
 
1481
1923
      if (!found)
1482
1924
      {
1491
1933
      else
1492
1934
      {
1493
1935
        /* We already have a name lock, remove copy */
1494
 
        table::remove_table(static_cast<table::Concurrent *>(table));
 
1936
        remove_table(table);
1495
1937
      }
1496
1938
    }
1497
1939
    else
1501
1943
    }
1502
1944
  }
1503
1945
  *prev=0;
1504
 
 
1505
1946
  if (found)
1506
 
    locking::broadcast_refresh();
 
1947
    broadcast_refresh();
1507
1948
 
1508
 
  return found;
 
1949
  return(found);
1509
1950
}
1510
1951
 
1511
1952
 
1515
1956
  other threads trying to get the lock.
1516
1957
*/
1517
1958
 
1518
 
void abort_locked_tables(Session *session, const drizzled::identifier::Table &identifier)
 
1959
void abort_locked_tables(Session *session, const drizzled::TableIdentifier &identifier)
1519
1960
{
1520
1961
  Table *table;
1521
1962
  for (table= session->open_tables; table ; table= table->getNext())
1523
1964
    if (table->getShare()->getCacheKey() == identifier.getKey())
1524
1965
    {
1525
1966
      /* If MERGE child, forward lock handling to parent. */
1526
 
      session->abortLock(table);
1527
 
      assert(0);
 
1967
      mysql_lock_abort(session, table);
1528
1968
      break;
1529
1969
    }
1530
1970
  }
1531
1971
}
1532
1972
 
 
1973
/*
 
1974
  Load a table definition from cursor and open unireg table
 
1975
 
 
1976
  SYNOPSIS
 
1977
  open_unireg_entry()
 
1978
  session                       Thread handle
 
1979
  entry         Store open table definition here
 
1980
  table_list            TableList with db, table_name
 
1981
  alias         Alias name
 
1982
  cache_key             Key for share_cache
 
1983
  cache_key_length      length of cache_key
 
1984
 
 
1985
  NOTES
 
1986
  Extra argument for open is taken from session->open_options
 
1987
  One must have a lock on LOCK_open when calling this function
 
1988
 
 
1989
  RETURN
 
1990
  0     ok
 
1991
#       Error
 
1992
*/
 
1993
 
 
1994
static int open_unireg_entry(Session *session,
 
1995
                             Table *entry,
 
1996
                             const char *alias,
 
1997
                             TableIdentifier &identifier)
 
1998
{
 
1999
  int error;
 
2000
  TableShare *share;
 
2001
  uint32_t discover_retry_count= 0;
 
2002
 
 
2003
  safe_mutex_assert_owner(LOCK_open.native_handle());
 
2004
retry:
 
2005
  if (not (share= TableShare::getShareCreate(session,
 
2006
                                             identifier,
 
2007
                                             &error)))
 
2008
    return 1;
 
2009
 
 
2010
  while ((error= share->open_table_from_share(session,
 
2011
                                              identifier,
 
2012
                                              alias,
 
2013
                                              (uint32_t) (HA_OPEN_KEYFILE |
 
2014
                                                          HA_OPEN_RNDFILE |
 
2015
                                                          HA_GET_INDEX |
 
2016
                                                          HA_TRY_READ_ONLY),
 
2017
                                              session->open_options, *entry)))
 
2018
  {
 
2019
    if (error == 7)                             // Table def changed
 
2020
    {
 
2021
      share->resetVersion();                        // Mark share as old
 
2022
      if (discover_retry_count++)               // Retry once
 
2023
        goto err;
 
2024
 
 
2025
      /*
 
2026
        TODO->
 
2027
        Here we should wait until all threads has released the table.
 
2028
        For now we do one retry. This may cause a deadlock if there
 
2029
        is other threads waiting for other tables used by this thread.
 
2030
 
 
2031
        Proper fix would be to if the second retry failed:
 
2032
        - Mark that table def changed
 
2033
        - Return from open table
 
2034
        - Close all tables used by this thread
 
2035
        - Start waiting that the share is released
 
2036
        - Retry by opening all tables again
 
2037
      */
 
2038
 
 
2039
      /*
 
2040
        TO BE FIXED
 
2041
        To avoid deadlock, only wait for release if no one else is
 
2042
        using the share.
 
2043
      */
 
2044
      if (share->getTableCount() != 1)
 
2045
        goto err;
 
2046
      /* Free share and wait until it's released by all threads */
 
2047
      TableShare::release(share);
 
2048
 
 
2049
      if (!session->killed)
 
2050
      {
 
2051
        drizzle_reset_errors(session, 1);         // Clear warnings
 
2052
        session->clear_error();                 // Clear error message
 
2053
        goto retry;
 
2054
      }
 
2055
      return 1;
 
2056
    }
 
2057
 
 
2058
    goto err;
 
2059
  }
 
2060
 
 
2061
  return 0;
 
2062
 
 
2063
err:
 
2064
  TableShare::release(share);
 
2065
 
 
2066
  return 1;
 
2067
}
 
2068
 
1533
2069
 
1534
2070
/*
1535
2071
  Open all tables in list
1597
2133
     * to see if it exists so that an unauthorized user cannot phish for
1598
2134
     * table/schema information via error messages
1599
2135
     */
1600
 
    identifier::Table the_table(tables->getSchemaName(), tables->getTableName());
1601
 
    if (not plugin::Authorization::isAuthorized(user(), the_table))
 
2136
    TableIdentifier the_table(tables->db, tables->table_name);
 
2137
    if (not plugin::Authorization::isAuthorized(getSecurityContext(),
 
2138
                                                the_table))
1602
2139
    {
1603
2140
      result= -1;                               // Fatal error
1604
2141
      break;
1695
2232
 
1696
2233
  set_proc_info("Opening table");
1697
2234
  current_tablenr= 0;
1698
 
  while (!(table= openTable(table_list, &refresh)) && refresh) ;
 
2235
  while (!(table= openTable(table_list, &refresh)) &&
 
2236
         refresh)
 
2237
    ;
1699
2238
 
1700
2239
  if (table)
1701
2240
  {
1704
2243
 
1705
2244
    assert(lock == 0);  // You must lock everything at once
1706
2245
    if ((table->reginfo.lock_type= lock_type) != TL_UNLOCK)
1707
 
    {
1708
 
      if (not (lock= lockTables(&table_list->table, 1, 0)))
1709
 
        table= NULL;
1710
 
    }
 
2246
      if (! (lock= mysql_lock_tables(this, &table_list->table, 1, 0, &refresh)))
 
2247
        table= 0;
1711
2248
  }
1712
2249
 
1713
2250
  set_proc_info(0);
1761
2298
  Table **start,**ptr;
1762
2299
  uint32_t lock_flag= DRIZZLE_LOCK_NOTIFY_IF_NEED_REOPEN;
1763
2300
 
1764
 
  if (!(ptr=start=(Table**) session->getMemRoot()->allocate(sizeof(Table*)*count)))
 
2301
  if (!(ptr=start=(Table**) session->alloc(sizeof(Table*)*count)))
1765
2302
    return -1;
1766
 
 
1767
2303
  for (table= tables; table; table= table->next_global)
1768
2304
  {
1769
2305
    if (!table->placeholder())
1770
2306
      *(ptr++)= table->table;
1771
2307
  }
1772
2308
 
1773
 
  if (not (session->lock= session->lockTables(start, (uint32_t) (ptr - start), lock_flag)))
 
2309
  if (!(session->lock= mysql_lock_tables(session, start, (uint32_t) (ptr - start),
 
2310
                                         lock_flag, need_reopen)))
1774
2311
  {
1775
2312
    return -1;
1776
2313
  }
1799
2336
#  Table object
1800
2337
*/
1801
2338
 
1802
 
Table *Open_tables_state::open_temporary_table(const identifier::Table &identifier,
1803
 
                                               bool link_in_list)
 
2339
Table *Session::open_temporary_table(TableIdentifier &identifier,
 
2340
                                     bool link_in_list)
1804
2341
{
 
2342
  TableShare *share;
 
2343
 
1805
2344
  assert(identifier.isTmp());
1806
 
 
1807
 
 
1808
 
  table::Temporary *new_tmp_table= new table::Temporary(identifier.getType(),
1809
 
                                                        identifier,
1810
 
                                                        const_cast<char *>(const_cast<identifier::Table&>(identifier).getPath().c_str()),
1811
 
                                                        static_cast<uint32_t>(identifier.getPath().length()));
 
2345
  share= new TableShare(identifier.getType(),
 
2346
                        identifier,
 
2347
                        const_cast<char *>(identifier.getPath().c_str()), static_cast<uint32_t>(identifier.getPath().length()));
 
2348
 
 
2349
 
 
2350
  Table *new_tmp_table= new Table;
1812
2351
  if (not new_tmp_table)
1813
2352
    return NULL;
1814
2353
 
1815
2354
  /*
1816
2355
    First open the share, and then open the table from the share we just opened.
1817
2356
  */
1818
 
  if (new_tmp_table->getMutableShare()->open_table_def(*static_cast<Session *>(this), identifier) ||
1819
 
      new_tmp_table->getMutableShare()->open_table_from_share(static_cast<Session *>(this), identifier, identifier.getTableName().c_str(),
1820
 
                                                              (uint32_t) (HA_OPEN_KEYFILE | HA_OPEN_RNDFILE |
1821
 
                                                                          HA_GET_INDEX),
1822
 
                                                              ha_open_options,
1823
 
                                                              *new_tmp_table))
 
2357
  if (share->open_table_def(*this, identifier) ||
 
2358
      share->open_table_from_share(this, identifier, identifier.getTableName().c_str(),
 
2359
                            (uint32_t) (HA_OPEN_KEYFILE | HA_OPEN_RNDFILE |
 
2360
                                        HA_GET_INDEX),
 
2361
                            ha_open_options,
 
2362
                            *new_tmp_table))
1824
2363
  {
1825
2364
    /* No need to lock share->mutex as this is not needed for tmp tables */
1826
 
    delete new_tmp_table->getMutableShare();
 
2365
    delete share;
1827
2366
    delete new_tmp_table;
1828
2367
 
1829
2368
    return 0;
1865
2404
{
1866
2405
  if (session->mark_used_columns != MARK_COLUMNS_NONE)
1867
2406
  {
1868
 
    boost::dynamic_bitset<> *current_bitmap= NULL;
 
2407
    MyBitmap *current_bitmap, *other_bitmap;
1869
2408
 
1870
2409
    /*
1871
2410
      We always want to register the used keys, as the column bitmap may have
1878
2417
    if (session->mark_used_columns == MARK_COLUMNS_READ)
1879
2418
    {
1880
2419
      current_bitmap= table->read_set;
 
2420
      other_bitmap=   table->write_set;
1881
2421
    }
1882
2422
    else
1883
2423
    {
1884
2424
      current_bitmap= table->write_set;
 
2425
      other_bitmap=   table->read_set;
1885
2426
    }
1886
2427
 
1887
 
    //if (current_bitmap->testAndSet(field->position()))
1888
 
    if (current_bitmap->test(field->position()))
 
2428
    if (current_bitmap->testAndSet(field->field_index))
1889
2429
    {
1890
2430
      if (session->mark_used_columns == MARK_COLUMNS_WRITE)
1891
2431
        session->dup_field= field;
1944
2484
    {
1945
2485
      if (nj_col)
1946
2486
      {
1947
 
        my_error(ER_NON_UNIQ_ERROR, MYF(0), name, session->where());
 
2487
        my_error(ER_NON_UNIQ_ERROR, MYF(0), name, session->where);
1948
2488
        return NULL;
1949
2489
      }
1950
2490
      nj_col= curr_nj_col;
2119
2659
      */
2120
2660
      table_name && table_name[0] &&
2121
2661
      (my_strcasecmp(table_alias_charset, table_list->alias, table_name) ||
2122
 
       (db_name && db_name[0] && table_list->getSchemaName() && table_list->getSchemaName()[0] &&
2123
 
        strcmp(db_name, table_list->getSchemaName()))))
 
2662
       (db_name && db_name[0] && table_list->db && table_list->db[0] &&
 
2663
        strcmp(db_name, table_list->db))))
2124
2664
    return 0;
2125
2665
 
2126
2666
  *actual_table= NULL;
2195
2735
      {
2196
2736
        Table *table= field_to_set->getTable();
2197
2737
        if (session->mark_used_columns == MARK_COLUMNS_READ)
2198
 
          table->setReadSet(field_to_set->position());
 
2738
          table->setReadSet(field_to_set->field_index);
2199
2739
        else
2200
 
          table->setWriteSet(field_to_set->position());
 
2740
          table->setWriteSet(field_to_set->field_index);
2201
2741
      }
2202
2742
    }
2203
2743
  }
2341
2881
      */
2342
2882
      item->cached_table= found ?  0 : actual_table;
2343
2883
 
2344
 
      assert(session->where());
 
2884
      assert(session->where);
2345
2885
      /*
2346
2886
        If we found a fully qualified field we return it directly as it can't
2347
2887
        have duplicates.
2354
2894
        if (report_error == REPORT_ALL_ERRORS ||
2355
2895
            report_error == IGNORE_EXCEPT_NON_UNIQUE)
2356
2896
          my_error(ER_NON_UNIQ_ERROR, MYF(0),
2357
 
                   table_name ? item->full_name() : name, session->where());
 
2897
                   table_name ? item->full_name() : name, session->where);
2358
2898
        return (Field*) 0;
2359
2899
      }
2360
2900
      found= cur_field;
2387
2927
      strcat(buff, table_name);
2388
2928
      table_name=buff;
2389
2929
    }
2390
 
    my_error(ER_UNKNOWN_TABLE, MYF(0), table_name, session->where());
 
2930
    my_error(ER_UNKNOWN_TABLE, MYF(0), table_name, session->where);
2391
2931
  }
2392
2932
  else
2393
2933
  {
2394
2934
    if (report_error == REPORT_ALL_ERRORS ||
2395
2935
        report_error == REPORT_EXCEPT_NON_UNIQUE)
2396
 
      my_error(ER_BAD_FIELD_ERROR, MYF(0), item->full_name(), session->where());
 
2936
      my_error(ER_BAD_FIELD_ERROR, MYF(0), item->full_name(), session->where);
2397
2937
    else
2398
2938
      found= not_found_field;
2399
2939
  }
2520
3060
            */
2521
3061
            if (report_error != IGNORE_ERRORS)
2522
3062
              my_error(ER_NON_UNIQ_ERROR, MYF(0),
2523
 
                       find->full_name(), session->where());
 
3063
                       find->full_name(), session->where);
2524
3064
            return (Item**) 0;
2525
3065
          }
2526
3066
          found_unaliased= li.ref();
2551
3091
              continue;                           // Same field twice
2552
3092
            if (report_error != IGNORE_ERRORS)
2553
3093
              my_error(ER_NON_UNIQ_ERROR, MYF(0),
2554
 
                       find->full_name(), session->where());
 
3094
                       find->full_name(), session->where);
2555
3095
            return (Item**) 0;
2556
3096
          }
2557
3097
          found= li.ref();
2603
3143
    {
2604
3144
      if (report_error != IGNORE_ERRORS)
2605
3145
        my_error(ER_NON_UNIQ_ERROR, MYF(0),
2606
 
                 find->full_name(), session->where());
 
3146
                 find->full_name(), session->where);
2607
3147
      return (Item **) 0;
2608
3148
    }
2609
3149
    if (found_unaliased)
2619
3159
  {
2620
3160
    if (report_error == REPORT_ALL_ERRORS)
2621
3161
      my_error(ER_BAD_FIELD_ERROR, MYF(0),
2622
 
               find->full_name(), session->where());
 
3162
               find->full_name(), session->where);
2623
3163
    return (Item **) 0;
2624
3164
  }
2625
3165
  else
2753
3293
    /* true if field_name_1 is a member of using_fields */
2754
3294
    bool is_using_column_1;
2755
3295
    if (!(nj_col_1= it_1.get_or_create_column_ref(leaf_1)))
2756
 
      return(result);
 
3296
      goto err;
2757
3297
    field_name_1= nj_col_1->name();
2758
3298
    is_using_column_1= using_fields &&
2759
3299
      test_if_string_in_list(field_name_1, using_fields);
2771
3311
      Natural_join_column *cur_nj_col_2;
2772
3312
      const char *cur_field_name_2;
2773
3313
      if (!(cur_nj_col_2= it_2.get_or_create_column_ref(leaf_2)))
2774
 
        return(result);
 
3314
        goto err;
2775
3315
      cur_field_name_2= cur_nj_col_2->name();
2776
3316
 
2777
3317
      /*
2790
3330
        if (cur_nj_col_2->is_common ||
2791
3331
            (found && (!using_fields || is_using_column_1)))
2792
3332
        {
2793
 
          my_error(ER_NON_UNIQ_ERROR, MYF(0), field_name_1, session->where());
2794
 
          return(result);
 
3333
          my_error(ER_NON_UNIQ_ERROR, MYF(0), field_name_1, session->where);
 
3334
          goto err;
2795
3335
        }
2796
3336
        nj_col_2= cur_nj_col_2;
2797
3337
        found= true;
2824
3364
      Item_func_eq *eq_cond;
2825
3365
 
2826
3366
      if (!item_1 || !item_2)
2827
 
        return(result); // out of memory
 
3367
        goto err;                               // out of memory
2828
3368
 
2829
3369
      /*
2830
3370
        In the case of no_wrap_view_item == 0, the created items must be
2849
3389
      */
2850
3390
      if (set_new_item_local_context(session, item_ident_1, nj_col_1->table_ref) ||
2851
3391
          set_new_item_local_context(session, item_ident_2, nj_col_2->table_ref))
2852
 
        return(result);
 
3392
        goto err;
2853
3393
 
2854
3394
      if (!(eq_cond= new Item_func_eq(item_ident_1, item_ident_2)))
2855
 
        return(result);                               /* Out of memory. */
 
3395
        goto err;                               /* Out of memory. */
2856
3396
 
2857
3397
      /*
2858
3398
        Add the new equi-join condition to the ON clause. Notice that
2869
3409
      {
2870
3410
        Table *table_1= nj_col_1->table_ref->table;
2871
3411
        /* Mark field_1 used for table cache. */
2872
 
        table_1->setReadSet(field_1->position());
 
3412
        table_1->setReadSet(field_1->field_index);
2873
3413
        table_1->covering_keys&= field_1->part_of_key;
2874
3414
        table_1->merge_keys|= field_1->part_of_key;
2875
3415
      }
2877
3417
      {
2878
3418
        Table *table_2= nj_col_2->table_ref->table;
2879
3419
        /* Mark field_2 used for table cache. */
2880
 
        table_2->setReadSet(field_2->position());
 
3420
        table_2->setReadSet(field_2->field_index);
2881
3421
        table_2->covering_keys&= field_2->part_of_key;
2882
3422
        table_2->merge_keys|= field_2->part_of_key;
2883
3423
      }
2898
3438
  */
2899
3439
  result= false;
2900
3440
 
 
3441
err:
2901
3442
  return(result);
2902
3443
}
2903
3444
 
2955
3496
 
2956
3497
  if (!(non_join_columns= new List<Natural_join_column>) ||
2957
3498
      !(natural_using_join->join_columns= new List<Natural_join_column>))
2958
 
  {
2959
 
    return(result);
2960
 
  }
 
3499
    goto err;
2961
3500
 
2962
3501
  /* Append the columns of the first join operand. */
2963
3502
  for (it_1.set(table_ref_1); !it_1.end_of_fields(); it_1.next())
2995
3534
        if (!(common_field= it++))
2996
3535
        {
2997
3536
          my_error(ER_BAD_FIELD_ERROR, MYF(0), using_field_name_ptr,
2998
 
                   session->where());
2999
 
          return(result);
 
3537
                   session->where);
 
3538
          goto err;
3000
3539
        }
3001
3540
        if (!my_strcasecmp(system_charset_info,
3002
3541
                           common_field->name(), using_field_name_ptr))
3024
3563
 
3025
3564
  result= false;
3026
3565
 
 
3566
err:
3027
3567
  return(result);
3028
3568
}
3029
3569
 
3109
3649
      if (cur_table_ref->getNestedJoin() &&
3110
3650
          store_top_level_join_columns(session, cur_table_ref,
3111
3651
                                       real_left_neighbor, real_right_neighbor))
3112
 
        return(result);
 
3652
        goto err;
3113
3653
      same_level_right_neighbor= cur_table_ref;
3114
3654
    }
3115
3655
  }
3141
3681
      std::swap(table_ref_1, table_ref_2);
3142
3682
    if (mark_common_columns(session, table_ref_1, table_ref_2,
3143
3683
                            using_fields, &found_using_fields))
3144
 
      return(result);
 
3684
      goto err;
3145
3685
 
3146
3686
    /*
3147
3687
      Swap the join operands back, so that we pick the columns of the second
3153
3693
    if (store_natural_using_join_columns(session, table_ref, table_ref_1,
3154
3694
                                         table_ref_2, using_fields,
3155
3695
                                         found_using_fields))
3156
 
      return(result);
 
3696
      goto err;
3157
3697
 
3158
3698
    /*
3159
3699
      Change NATURAL JOIN to JOIN ... ON. We do this for both operands
3186
3726
  }
3187
3727
  result= false; /* All is OK. */
3188
3728
 
 
3729
err:
3189
3730
  return(result);
3190
3731
}
3191
3732
 
3218
3759
                                         List<TableList> *from_clause,
3219
3760
                                         Name_resolution_context *context)
3220
3761
{
3221
 
  session->setWhere("from clause");
 
3762
  session->where= "from clause";
3222
3763
  if (from_clause->elements == 0)
3223
3764
    return false; /* We come here in the case of UNIONs. */
3224
3765
 
3339
3880
  session->mark_used_columns= mark_used_columns;
3340
3881
  if (allow_sum_func)
3341
3882
    session->lex->allow_sum_func|= 1 << session->lex->current_select->nest_level;
3342
 
  session->setWhere(Session::DEFAULT_WHERE);
 
3883
  session->where= Session::DEFAULT_WHERE;
3343
3884
  save_is_item_list_lookup= session->lex->current_select->is_item_list_lookup;
3344
3885
  session->lex->current_select->is_item_list_lookup= 0;
3345
3886
 
3351
3892
    There is other way to solve problem: fill array with pointers to list,
3352
3893
    but it will be slower.
3353
3894
 
3354
 
    TODO-> remove it when (if) we made one list for allfields and ref_pointer_array
 
3895
TODO: remove it when (if) we made one list for allfields and
 
3896
ref_pointer_array
3355
3897
  */
3356
3898
  if (ref_pointer_array)
3357
 
  {
3358
3899
    memset(ref_pointer_array, 0, sizeof(Item *) * fields.elements);
3359
 
  }
3360
3900
 
3361
3901
  Item **ref= ref_pointer_array;
3362
3902
  session->lex->current_select->cur_pos_in_select_list= 0;
3588
4128
    assert(tables->is_leaf_for_name_resolution());
3589
4129
 
3590
4130
    if ((table_name && my_strcasecmp(table_alias_charset, table_name, tables->alias)) ||
3591
 
        (db_name && my_strcasecmp(system_charset_info, tables->getSchemaName(),db_name)))
 
4131
        (db_name && strcasecmp(tables->db,db_name)))
3592
4132
      continue;
3593
4133
 
3594
4134
    /*
3624
4164
      if ((field= field_iterator.field()))
3625
4165
      {
3626
4166
        /* Mark fields as used to allow storage engine to optimze access */
3627
 
        field->getTable()->setReadSet(field->position());
 
4167
        field->getTable()->setReadSet(field->field_index);
3628
4168
        if (table)
3629
4169
        {
3630
4170
          table->covering_keys&= field->part_of_key;
3652
4192
        }
3653
4193
      }
3654
4194
      else
3655
 
      {
3656
4195
        session->used_tables|= item->used_tables();
3657
 
      }
3658
 
 
3659
4196
      session->lex->current_select->cur_pos_in_select_list++;
3660
4197
    }
3661
4198
    /*
3675
4212
    qualified '*', and all columns were coalesced, we have to give a more
3676
4213
    meaningful message than ER_BAD_TABLE_ERROR.
3677
4214
  */
3678
 
  if (not table_name)
3679
 
  {
 
4215
  if (!table_name)
3680
4216
    my_message(ER_NO_TABLES_USED, ER(ER_NO_TABLES_USED), MYF(0));
3681
 
  }
3682
4217
  else
3683
 
  {
3684
4218
    my_error(ER_BAD_TABLE_ERROR, MYF(0), table_name);
3685
 
  }
3686
4219
 
3687
4220
  return true;
3688
4221
}
3731
4264
  session->session_marker= (void*)1;
3732
4265
  if (*conds)
3733
4266
  {
3734
 
    session->setWhere("where clause");
 
4267
    session->where="where clause";
3735
4268
    if ((!(*conds)->fixed && (*conds)->fix_fields(session, conds)) ||
3736
4269
        (*conds)->check_cols(1))
3737
4270
      goto err_no_arena;
3753
4286
      {
3754
4287
        /* Make a join an a expression */
3755
4288
        session->session_marker= (void*)embedded;
3756
 
        session->setWhere("on clause");
 
4289
        session->where="on clause";
3757
4290
        if ((!embedded->on_expr->fixed && embedded->on_expr->fix_fields(session, &embedded->on_expr)) ||
3758
4291
            embedded->on_expr->check_cols(1))
3759
4292
          goto err_no_arena;
3838
4371
    if ((value->save_in_field(rfield, 0) < 0) && !ignore_errors)
3839
4372
    {
3840
4373
      my_message(ER_UNKNOWN_ERROR, ER(ER_UNKNOWN_ERROR), MYF(0));
3841
 
      if (table)
3842
 
        table->auto_increment_field_not_null= false;
3843
 
 
3844
 
      return true;
 
4374
      goto err;
3845
4375
    }
3846
4376
  }
3847
4377
 
3848
4378
  return session->is_error();
 
4379
 
 
4380
err:
 
4381
  if (table)
 
4382
    table->auto_increment_field_not_null= false;
 
4383
 
 
4384
  return true;
3849
4385
}
3850
4386
 
3851
4387
 
3888
4424
    table= (*ptr)->getTable();
3889
4425
    table->auto_increment_field_not_null= false;
3890
4426
  }
3891
 
 
3892
4427
  while ((field = *ptr++) && ! session->is_error())
3893
4428
  {
3894
4429
    value=v++;
3895
4430
    table= field->getTable();
3896
 
 
3897
4431
    if (field == table->next_number_field)
3898
4432
      table->auto_increment_field_not_null= true;
3899
 
 
3900
4433
    if (value->save_in_field(field, 0) < 0)
3901
 
    {
3902
 
      if (table)
3903
 
        table->auto_increment_field_not_null= false;
3904
 
 
3905
 
      return true;
3906
 
    }
 
4434
      goto err;
3907
4435
  }
3908
4436
 
3909
4437
  return(session->is_error());
 
4438
 
 
4439
err:
 
4440
  if (table)
 
4441
    table->auto_increment_field_not_null= false;
 
4442
 
 
4443
  return true;
3910
4444
}
3911
4445
 
3912
4446
 
3913
4447
bool drizzle_rm_tmp_tables()
3914
4448
{
 
4449
  Session *session;
3915
4450
 
3916
4451
  assert(drizzle_tmpdir.size());
3917
 
  Session::shared_ptr session= Session::make_shared(plugin::Listen::getNullClient(), catalog::local());
3918
4452
 
3919
 
  if (not session)
 
4453
  if (!(session= new Session(plugin::Listen::getNullClient())))
3920
4454
    return true;
3921
 
  session->thread_stack= (char*) session.get();
 
4455
  session->thread_stack= (char*) &session;
3922
4456
  session->storeGlobals();
3923
4457
 
3924
4458
  plugin::StorageEngine::removeLostTemporaryTables(*session, drizzle_tmpdir.c_str());
3925
4459
 
 
4460
  session->lockForDelete();
 
4461
  delete session;
 
4462
 
3926
4463
  return false;
3927
4464
}
3928
4465
 
3932
4469
  unireg support functions
3933
4470
 *****************************************************************************/
3934
4471
 
3935
 
 
 
4472
/*
 
4473
  Invalidate any cache entries that are for some DB
 
4474
 
 
4475
  SYNOPSIS
 
4476
  remove_db_from_cache()
 
4477
  db            Database name. This will be in lower case if
 
4478
  lower_case_table_name is set
 
4479
 
 
4480
NOTE:
 
4481
We can't use hash_delete when looping hash_elements. We mark them first
 
4482
and afterwards delete those marked unused.
 
4483
*/
 
4484
 
 
4485
void remove_db_from_cache(const SchemaIdentifier &schema_identifier)
 
4486
{
 
4487
  safe_mutex_assert_owner(LOCK_open.native_handle());
 
4488
 
 
4489
  for (TableOpenCache::const_iterator iter= get_open_cache().begin();
 
4490
       iter != get_open_cache().end();
 
4491
       iter++)
 
4492
  {
 
4493
    Table *table= (*iter).second;
 
4494
 
 
4495
    if (not schema_identifier.getPath().compare(table->getMutableShare()->getSchemaName()))
 
4496
    {
 
4497
      table->getMutableShare()->resetVersion();                 /* Free when thread is ready */
 
4498
      if (not table->in_use)
 
4499
        unused_tables.relink(table);
 
4500
    }
 
4501
  }
 
4502
 
 
4503
  unused_tables.cullByVersion();
 
4504
}
 
4505
 
 
4506
 
 
4507
/*
 
4508
  Mark all entries with the table as deleted to force an reopen of the table
 
4509
 
 
4510
  The table will be closed (not stored in cache) by the current thread when
 
4511
  close_thread_tables() is called.
 
4512
 
 
4513
  PREREQUISITES
 
4514
  Lock on LOCK_open()
 
4515
 
 
4516
  RETURN
 
4517
  0  This thread now have exclusive access to this table and no other thread
 
4518
  can access the table until close_thread_tables() is called.
 
4519
  1  Table is in use by another thread
 
4520
*/
 
4521
 
 
4522
bool remove_table_from_cache(Session *session, TableIdentifier &identifier, uint32_t flags)
 
4523
{
 
4524
  const TableIdentifier::Key &key(identifier.getKey());
 
4525
  bool result= false; 
 
4526
  bool signalled= false;
 
4527
 
 
4528
  for (;;)
 
4529
  {
 
4530
    result= signalled= false;
 
4531
 
 
4532
    TableOpenCacheRange ppp;
 
4533
    ppp= get_open_cache().equal_range(key);
 
4534
 
 
4535
    for (TableOpenCache::const_iterator iter= ppp.first;
 
4536
         iter != ppp.second; ++iter)
 
4537
    {
 
4538
      Table *table= (*iter).second;
 
4539
      Session *in_use;
 
4540
 
 
4541
      table->getMutableShare()->resetVersion();         /* Free when thread is ready */
 
4542
      if (!(in_use=table->in_use))
 
4543
      {
 
4544
        unused_tables.relink(table);
 
4545
      }
 
4546
      else if (in_use != session)
 
4547
      {
 
4548
        /*
 
4549
          Mark that table is going to be deleted from cache. This will
 
4550
          force threads that are in mysql_lock_tables() (but not yet
 
4551
          in thr_multi_lock()) to abort it's locks, close all tables and retry
 
4552
        */
 
4553
        in_use->some_tables_deleted= true;
 
4554
        if (table->is_name_opened())
 
4555
        {
 
4556
          result= true;
 
4557
        }
 
4558
        /*
 
4559
          Now we must abort all tables locks used by this thread
 
4560
          as the thread may be waiting to get a lock for another table.
 
4561
          Note that we need to hold LOCK_open while going through the
 
4562
          list. So that the other thread cannot change it. The other
 
4563
          thread must also hold LOCK_open whenever changing the
 
4564
          open_tables list. Aborting the MERGE lock after a child was
 
4565
          closed and before the parent is closed would be fatal.
 
4566
        */
 
4567
        for (Table *session_table= in_use->open_tables;
 
4568
             session_table ;
 
4569
             session_table= session_table->getNext())
 
4570
        {
 
4571
          /* Do not handle locks of MERGE children. */
 
4572
          if (session_table->db_stat)   // If table is open
 
4573
            signalled|= mysql_lock_abort_for_thread(session, session_table);
 
4574
        }
 
4575
      }
 
4576
      else
 
4577
        result= result || (flags & RTFC_OWNED_BY_Session_FLAG);
 
4578
    }
 
4579
 
 
4580
    unused_tables.cullByVersion();
 
4581
 
 
4582
    /* Remove table from table definition cache if it's not in use */
 
4583
    TableShare::release(identifier);
 
4584
 
 
4585
    if (result && (flags & RTFC_WAIT_OTHER_THREAD_FLAG))
 
4586
    {
 
4587
      /*
 
4588
        Signal any thread waiting for tables to be freed to
 
4589
        reopen their tables
 
4590
      */
 
4591
      broadcast_refresh();
 
4592
      if (!(flags & RTFC_CHECK_KILLED_FLAG) || !session->killed)
 
4593
      {
 
4594
        dropping_tables++;
 
4595
        if (likely(signalled))
 
4596
          (void) pthread_cond_wait(COND_refresh.native_handle(), LOCK_open.native_handle());
 
4597
        else
 
4598
        {
 
4599
          struct timespec abstime;
 
4600
          /*
 
4601
            It can happen that another thread has opened the
 
4602
            table but has not yet locked any table at all. Since
 
4603
            it can be locked waiting for a table that our thread
 
4604
            has done LOCK Table x WRITE on previously, we need to
 
4605
            ensure that the thread actually hears our signal
 
4606
            before we go to sleep. Thus we wait for a short time
 
4607
            and then we retry another loop in the
 
4608
            remove_table_from_cache routine.
 
4609
          */
 
4610
          set_timespec(abstime, 10);
 
4611
          pthread_cond_timedwait(COND_refresh.native_handle(), LOCK_open.native_handle(), &abstime);
 
4612
        }
 
4613
        dropping_tables--;
 
4614
        continue;
 
4615
      }
 
4616
    }
 
4617
    break;
 
4618
  }
 
4619
 
 
4620
  return result;
 
4621
}
3936
4622
 
3937
4623
 
3938
4624
/**