~drizzle-trunk/drizzle/development

« back to all changes in this revision

Viewing changes to drizzled/sql_base.cc

  • Committer: Brian Aker
  • Date: 2010-09-22 22:25:29 UTC
  • mto: (1791.1.1 drizzle)
  • mto: This revision was merged to the branch mainline in revision 1792.
  • Revision ID: brian@tangent.org-20100922222529-geo4wggmu5ntqa5k
Current boost work (more conversion).

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;
 
426
    session->mysys_var->current_cond= &COND_refresh;
 
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
    boost::mutex::scoped_lock scopedLock(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);
331
501
  move one table to free list 
332
502
*/
333
503
 
334
 
bool Session::free_cached_table(boost::mutex::scoped_lock &scopedLock)
 
504
bool Session::free_cached_table()
335
505
{
336
506
  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());
 
507
  Table *table= open_tables;
 
508
 
 
509
  safe_mutex_assert_owner(LOCK_open.native_handle());
343
510
  assert(table->key_read == 0);
344
511
  assert(!table->cursor || table->cursor->inited == Cursor::NONE);
345
512
 
348
515
  if (table->needs_reopen_or_name_lock() ||
349
516
      version != refresh_version || !table->db_stat)
350
517
  {
351
 
    table::remove_table(table);
 
518
    remove_table(table);
352
519
    found_old_table= true;
353
520
  }
354
521
  else
361
528
 
362
529
    /* Free memory and reset for next loop */
363
530
    table->cursor->ha_reset();
364
 
    table->in_use= NULL;
 
531
    table->in_use= false;
365
532
 
366
 
    table::getUnused().link(table);
 
533
    unused_tables.link(table);
367
534
  }
368
535
 
369
536
  return found_old_table;
382
549
{
383
550
  bool found_old_table= false;
384
551
 
385
 
  safe_mutex_assert_not_owner(table::Cache::singleton().mutex().native_handle());
 
552
  safe_mutex_assert_not_owner(LOCK_open.native_handle());
386
553
 
387
 
  boost_unique_lock_t scoped_lock(table::Cache::singleton().mutex()); /* Close all open tables on Session */
 
554
  boost::mutex::scoped_lock scoped_lock(LOCK_open); /* Close all open tables on Session */
388
555
 
389
556
  while (open_tables)
390
557
  {
391
 
    found_old_table|= free_cached_table(scoped_lock);
 
558
    found_old_table|= free_cached_table();
392
559
  }
393
560
  some_tables_deleted= false;
394
561
 
395
562
  if (found_old_table)
396
563
  {
397
564
    /* Tell threads waiting for refresh that something has happened */
398
 
    locking::broadcast_refresh();
 
565
    broadcast_refresh();
399
566
  }
400
567
}
401
568
 
424
591
{
425
592
  for (; table; table= table->*link )
426
593
  {
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
 
    {
 
594
    if ((table->table == 0 || table->table->getShare()->getType() == message::Table::STANDARD) &&
 
595
        strcasecmp(table->db, db_name) == 0 &&
 
596
        strcasecmp(table->table_name, table_name) == 0)
431
597
      break;
432
 
    }
433
598
  }
434
599
  return table;
435
600
}
499
664
    */
500
665
    assert(table);
501
666
  }
502
 
  d_name= table->getSchemaName();
503
 
  t_name= table->getTableName();
 
667
  d_name= table->db;
 
668
  t_name= table->table_name;
504
669
  t_alias= table->alias;
505
670
 
506
671
  for (;;)
521
686
}
522
687
 
523
688
 
524
 
void Open_tables_state::doGetTableNames(const identifier::Schema &schema_identifier,
525
 
                                        std::set<std::string>& set_of_names)
 
689
void Session::doGetTableNames(const SchemaIdentifier &schema_identifier,
 
690
                              std::set<std::string>& set_of_names)
526
691
{
527
 
  for (Table *table= getTemporaryTables() ; table ; table= table->getNext())
 
692
  for (Table *table= temporary_tables ; table ; table= table->getNext())
528
693
  {
529
694
    if (schema_identifier.compare(table->getShare()->getSchemaName()))
530
695
    {
533
698
  }
534
699
}
535
700
 
536
 
void Open_tables_state::doGetTableNames(CachedDirectory &,
537
 
                                        const identifier::Schema &schema_identifier,
538
 
                                        std::set<std::string> &set_of_names)
 
701
void Session::doGetTableNames(CachedDirectory &,
 
702
                              const SchemaIdentifier &schema_identifier,
 
703
                              std::set<std::string> &set_of_names)
539
704
{
540
705
  doGetTableNames(schema_identifier, set_of_names);
541
706
}
542
707
 
543
 
void Open_tables_state::doGetTableIdentifiers(const identifier::Schema &schema_identifier,
544
 
                                              identifier::Table::vector &set_of_identifiers)
 
708
void Session::doGetTableIdentifiers(const SchemaIdentifier &schema_identifier,
 
709
                                    TableIdentifiers &set_of_identifiers)
545
710
{
546
 
  for (Table *table= getTemporaryTables() ; table ; table= table->getNext())
 
711
  for (Table *table= temporary_tables ; table ; table= table->getNext())
547
712
  {
548
713
    if (schema_identifier.compare(table->getShare()->getSchemaName()))
549
714
    {
550
 
      set_of_identifiers.push_back(identifier::Table(table->getShare()->getSchemaName(),
 
715
      set_of_identifiers.push_back(TableIdentifier(table->getShare()->getSchemaName(),
551
716
                                                   table->getShare()->getTableName(),
552
717
                                                   table->getShare()->getPath()));
553
718
    }
554
719
  }
555
720
}
556
721
 
557
 
void Open_tables_state::doGetTableIdentifiers(CachedDirectory &,
558
 
                                              const identifier::Schema &schema_identifier,
559
 
                                              identifier::Table::vector &set_of_identifiers)
 
722
void Session::doGetTableIdentifiers(CachedDirectory &,
 
723
                                    const SchemaIdentifier &schema_identifier,
 
724
                                    TableIdentifiers &set_of_identifiers)
560
725
{
561
726
  doGetTableIdentifiers(schema_identifier, set_of_identifiers);
562
727
}
563
728
 
564
 
bool Open_tables_state::doDoesTableExist(const identifier::Table &identifier)
 
729
bool Session::doDoesTableExist(const TableIdentifier &identifier)
565
730
{
566
 
  for (Table *table= getTemporaryTables() ; table ; table= table->getNext())
 
731
  for (Table *table= temporary_tables ; table ; table= table->getNext())
567
732
  {
568
733
    if (table->getShare()->getType() == message::Table::TEMPORARY)
569
734
    {
577
742
  return false;
578
743
}
579
744
 
580
 
int Open_tables_state::doGetTableDefinition(const identifier::Table &identifier,
581
 
                                            message::Table &table_proto)
 
745
int Session::doGetTableDefinition(const TableIdentifier &identifier,
 
746
                                  message::Table &table_proto)
582
747
{
583
 
  for (Table *table= getTemporaryTables() ; table ; table= table->getNext())
 
748
  for (Table *table= temporary_tables ; table ; table= table->getNext())
584
749
  {
585
750
    if (table->getShare()->getType() == message::Table::TEMPORARY)
586
751
    {
587
752
      if (identifier.getKey() == table->getShare()->getCacheKey())
588
753
      {
589
 
        table_proto.CopyFrom(*(table->getShare()->getTableMessage()));
 
754
        table_proto.CopyFrom(*(table->getShare()->getTableProto()));
590
755
 
591
756
        return EEXIST;
592
757
      }
596
761
  return ENOENT;
597
762
}
598
763
 
599
 
Table *Open_tables_state::find_temporary_table(const identifier::Table &identifier)
 
764
Table *Session::find_temporary_table(const char *new_db, const char *table_name)
 
765
{
 
766
  char  key[MAX_DBKEY_LENGTH];
 
767
  uint  key_length;
 
768
 
 
769
  key_length= TableIdentifier::createKey(key, new_db, table_name);
 
770
 
 
771
  for (Table *table= temporary_tables ; table ; table= table->getNext())
 
772
  {
 
773
    const TableIdentifier::Key &share_key(table->getShare()->getCacheKey());
 
774
    if (share_key.size() == key_length &&
 
775
        not memcmp(&share_key[0], key, key_length))
 
776
    {
 
777
      return table;
 
778
    }
 
779
  }
 
780
  return NULL;                               // Not a temporary table
 
781
}
 
782
 
 
783
Table *Session::find_temporary_table(TableList *table_list)
 
784
{
 
785
  return find_temporary_table(table_list->db, table_list->table_name);
 
786
}
 
787
 
 
788
Table *Session::find_temporary_table(TableIdentifier &identifier)
600
789
{
601
790
  for (Table *table= temporary_tables ; table ; table= table->getNext())
602
791
  {
634
823
  @retval -1  the table is in use by a outer query
635
824
*/
636
825
 
637
 
int Open_tables_state::drop_temporary_table(const drizzled::identifier::Table &identifier)
 
826
int Session::drop_temporary_table(TableList *table_list)
638
827
{
639
828
  Table *table;
640
829
 
641
 
  if (not (table= find_temporary_table(identifier)))
 
830
  if (not (table= find_temporary_table(table_list)))
642
831
    return 1;
643
832
 
644
833
  /* Table might be in use by some outer statement. */
645
 
  if (table->query_id && table->query_id != getQueryId())
 
834
  if (table->query_id && table->query_id != query_id)
646
835
  {
647
836
    my_error(ER_CANT_REOPEN_TABLE, MYF(0), table->getAlias());
648
837
    return -1;
660
849
 
661
850
  @param  session     Thread context
662
851
  @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
852
*/
666
853
 
667
854
void Session::unlink_open_table(Table *find)
668
855
{
669
 
  const identifier::Table::Key find_key(find->getShare()->getCacheKey());
670
 
  Table **prev;
671
 
  safe_mutex_assert_owner(table::Cache::singleton().mutex().native_handle());
 
856
  char key[MAX_DBKEY_LENGTH];
 
857
  uint32_t key_length= find->getShare()->getCacheKeySize();
 
858
  Table *list, **prev;
 
859
  safe_mutex_assert_owner(LOCK_open.native_handle());
672
860
 
 
861
  memcpy(key, &find->getMutableShare()->getCacheKey()[0], key_length);
673
862
  /*
674
 
    Note that we need to hold table::Cache::singleton().mutex() while changing the
 
863
    Note that we need to hold LOCK_open while changing the
675
864
    open_tables list. Another thread may work on it.
676
 
    (See: table::Cache::singleton().removeTable(), wait_completed_table())
 
865
    (See: remove_table_from_cache(), mysql_wait_completed_table())
677
866
    Closing a MERGE child before the parent would be fatal if the
678
867
    other thread tries to abort the MERGE lock in between.
679
868
  */
680
869
  for (prev= &open_tables; *prev; )
681
870
  {
682
 
    Table *list= *prev;
 
871
    list= *prev;
683
872
 
684
 
    if (list->getShare()->getCacheKey() == find_key)
 
873
    if (list->getShare()->getCacheKeySize() == key_length &&
 
874
        not memcmp(&list->getShare()->getCacheKey()[0], key, key_length))
685
875
    {
686
876
      /* Remove table from open_tables list. */
687
877
      *prev= list->getNext();
688
878
 
689
879
      /* Close table. */
690
 
      table::remove_table(static_cast<table::Concurrent *>(list));
 
880
      remove_table(list);
691
881
    }
692
882
    else
693
883
    {
697
887
  }
698
888
 
699
889
  // Notify any 'refresh' threads
700
 
  locking::broadcast_refresh();
 
890
  broadcast_refresh();
701
891
}
702
892
 
703
893
 
720
910
  table that was locked with LOCK TABLES.
721
911
*/
722
912
 
723
 
void Session::drop_open_table(Table *table, const identifier::Table &identifier)
 
913
void Session::drop_open_table(Table *table, TableIdentifier &identifier)
724
914
{
725
915
  if (table->getShare()->getType())
726
916
  {
728
918
  }
729
919
  else
730
920
  {
731
 
    boost_unique_lock_t scoped_lock(table::Cache::singleton().mutex()); /* Close and drop a table (AUX routine) */
 
921
    boost::mutex::scoped_lock scoped_lock(LOCK_open); /* Close and drop a table (AUX routine) */
732
922
    /*
733
923
      unlink_open_table() also tells threads waiting for refresh or close
734
924
      that something has happened.
735
925
    */
736
926
    unlink_open_table(table);
737
 
    (void)plugin::StorageEngine::dropTable(*this, identifier);
 
927
    quick_rm_table(*this, identifier);
738
928
  }
739
929
}
740
930
 
750
940
  cond  Condition to wait for
751
941
*/
752
942
 
753
 
void Session::wait_for_condition(boost::mutex &mutex, boost::condition_variable_any &cond)
 
943
void Session::wait_for_condition(boost::mutex &mutex, boost::condition_variable &cond)
754
944
{
755
945
  /* Wait until the current table is up to date */
756
946
  const char *saved_proc_info;
758
948
  mysys_var->current_cond= &cond;
759
949
  saved_proc_info= get_proc_info();
760
950
  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);
 
951
  if (!killed)
 
952
    (void) pthread_cond_wait(cond.native_handle(), mutex.native_handle());
 
953
 
 
954
  /*
 
955
    We must unlock mutex first to avoid deadlock becasue conditions are
 
956
    sent to this thread by doing locks in the following order:
 
957
    lock(mysys_var->mutex)
 
958
    lock(mysys_var->current_mutex)
 
959
 
 
960
    One by effect of this that one can only use wait_for_condition with
 
961
    condition variables that are guranteed to not disapper (freed) even if this
 
962
    mutex is unlocked
 
963
  */
 
964
 
 
965
  pthread_mutex_unlock(mutex.native_handle());
 
966
  boost::mutex::scoped_lock (mysys_var->mutex);
779
967
  mysys_var->current_mutex= 0;
780
968
  mysys_var->current_cond= 0;
781
969
  set_proc_info(saved_proc_info);
782
970
}
783
971
 
784
972
 
 
973
/*
 
974
  Open table which is already name-locked by this thread.
 
975
 
 
976
  SYNOPSIS
 
977
  reopen_name_locked_table()
 
978
  session         Thread handle
 
979
  table_list  TableList object for table to be open, TableList::table
 
980
  member should point to Table object which was used for
 
981
  name-locking.
 
982
  link_in     true  - if Table object for table to be opened should be
 
983
  linked into Session::open_tables list.
 
984
  false - placeholder used for name-locking is already in
 
985
  this list so we only need to preserve Table::next
 
986
  pointer.
 
987
 
 
988
  NOTE
 
989
  This function assumes that its caller already acquired LOCK_open mutex.
 
990
 
 
991
  RETURN VALUE
 
992
  false - Success
 
993
  true  - Error
 
994
*/
 
995
 
 
996
bool Session::reopen_name_locked_table(TableList* table_list, bool link_in)
 
997
{
 
998
  Table *table= table_list->table;
 
999
  TableShare *share;
 
1000
  char *table_name= table_list->table_name;
 
1001
  Table orig_table;
 
1002
 
 
1003
  safe_mutex_assert_owner(LOCK_open.native_handle());
 
1004
 
 
1005
  if (killed || !table)
 
1006
    return true;
 
1007
 
 
1008
  orig_table= *table;
 
1009
 
 
1010
  TableIdentifier identifier(table_list->db, table_list->table_name);
 
1011
  if (open_unireg_entry(this, table, table_name, identifier))
 
1012
  {
 
1013
    table->intern_close_table();
 
1014
    /*
 
1015
      If there was an error during opening of table (for example if it
 
1016
      does not exist) '*table' object can be wiped out. To be able
 
1017
      properly release name-lock in this case we should restore this
 
1018
      object to its original state.
 
1019
    */
 
1020
    *table= orig_table;
 
1021
    return true;
 
1022
  }
 
1023
 
 
1024
  share= table->getMutableShare();
 
1025
  /*
 
1026
    We want to prevent other connections from opening this table until end
 
1027
    of statement as it is likely that modifications of table's metadata are
 
1028
    not yet finished (for example CREATE TRIGGER have to change .TRG cursor,
 
1029
    or we might want to drop table if CREATE TABLE ... SELECT fails).
 
1030
    This also allows us to assume that no other connection will sneak in
 
1031
    before we will get table-level lock on this table.
 
1032
  */
 
1033
  share->resetVersion();
 
1034
  table->in_use = this;
 
1035
 
 
1036
  if (link_in)
 
1037
  {
 
1038
    table->setNext(open_tables);
 
1039
    open_tables= table;
 
1040
  }
 
1041
  else
 
1042
  {
 
1043
    /*
 
1044
      Table object should be already in Session::open_tables list so we just
 
1045
      need to set Table::next correctly.
 
1046
    */
 
1047
    table->setNext(orig_table.getNext());
 
1048
  }
 
1049
 
 
1050
  table->tablenr= current_tablenr++;
 
1051
  table->used_fields= 0;
 
1052
  table->const_table= 0;
 
1053
  table->null_row= false;
 
1054
  table->maybe_null= false;
 
1055
  table->force_index= false;
 
1056
  table->status= STATUS_NO_RECORD;
 
1057
 
 
1058
  return false;
 
1059
}
 
1060
 
 
1061
 
785
1062
/**
786
1063
  Create and insert into table cache placeholder for table
787
1064
  which will prevent its opening (or creation) (a.k.a lock
795
1072
  case of failure.
796
1073
*/
797
1074
 
798
 
table::Placeholder *Session::table_cache_insert_placeholder(const drizzled::identifier::Table &arg)
 
1075
Table *Session::table_cache_insert_placeholder(const char *db_name, const char *table_name)
799
1076
{
800
 
  safe_mutex_assert_owner(table::Cache::singleton().mutex().native_handle());
 
1077
  safe_mutex_assert_owner(LOCK_open.native_handle());
801
1078
 
802
1079
  /*
803
1080
    Create a table entry with the right key and with an old refresh version
804
1081
  */
805
 
  identifier::Table identifier(arg.getSchemaName(), arg.getTableName(), message::Table::INTERNAL);
806
 
  table::Placeholder *table= new table::Placeholder(this, identifier);
 
1082
  TableIdentifier identifier(db_name, table_name, message::Table::INTERNAL);
 
1083
  TablePlaceholder *table= new TablePlaceholder(this, identifier);
807
1084
 
808
 
  if (not table::Cache::singleton().insert(table))
 
1085
  if (not add_table(table))
809
1086
  {
810
1087
    delete table;
811
1088
 
837
1114
  @retval  true   Error occured (OOM)
838
1115
  @retval  false  Success. 'table' parameter set according to above rules.
839
1116
*/
840
 
bool Session::lock_table_name_if_not_cached(const identifier::Table &identifier, Table **table)
 
1117
bool Session::lock_table_name_if_not_cached(TableIdentifier &identifier, Table **table)
841
1118
{
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())
 
1119
  const TableIdentifier::Key &key(identifier.getKey());
 
1120
 
 
1121
  boost::mutex::scoped_lock scope_lock(LOCK_open); /* Obtain a name lock even though table is not in cache (like for create table)  */
 
1122
 
 
1123
  TableOpenCache::iterator iter;
 
1124
 
 
1125
  iter= get_open_cache().find(key);
 
1126
 
 
1127
  if (iter != get_open_cache().end())
851
1128
  {
852
1129
    *table= 0;
853
1130
    return false;
854
1131
  }
855
1132
 
856
 
  if (not (*table= table_cache_insert_placeholder(identifier)))
 
1133
  if (not (*table= table_cache_insert_placeholder(identifier.getSchemaName().c_str(), identifier.getTableName().c_str())))
857
1134
  {
858
1135
    return true;
859
1136
  }
913
1190
  if (check_stack_overrun(this, STACK_MIN_SIZE_FOR_OPEN, (unsigned char *)&alias))
914
1191
    return NULL;
915
1192
 
916
 
  if (getKilled())
 
1193
  if (killed)
917
1194
    return NULL;
918
1195
 
919
 
  identifier::Table identifier(table_list->getSchemaName(), table_list->getTableName());
920
 
  const identifier::Table::Key &key(identifier.getKey());
921
 
  table::CacheRange ppp;
 
1196
  TableIdentifier identifier(table_list->db, table_list->table_name);
 
1197
  const TableIdentifier::Key &key(identifier.getKey());
 
1198
  TableOpenCacheRange ppp;
922
1199
 
923
1200
  /*
924
1201
    Unless requested otherwise, try to resolve this table in the list
927
1204
    same name. This block implements the behaviour.
928
1205
    TODO -> move this block into a separate function.
929
1206
  */
930
 
  bool reset= false;
931
 
  for (table= getTemporaryTables(); table ; table=table->getNext())
 
1207
  for (table= temporary_tables; table ; table=table->getNext())
932
1208
  {
933
1209
    if (table->getShare()->getCacheKey() == key)
934
1210
    {
944
1220
        return NULL;
945
1221
      }
946
1222
      table->query_id= getQueryId();
947
 
      reset= true;
 
1223
      goto reset;
 
1224
    }
 
1225
  }
 
1226
 
 
1227
  if (flags & DRIZZLE_OPEN_TEMPORARY_ONLY)
 
1228
  {
 
1229
    my_error(ER_NO_SUCH_TABLE, MYF(0), table_list->db, table_list->table_name);
 
1230
    return NULL;
 
1231
  }
 
1232
 
 
1233
  /*
 
1234
    If it's the first table from a list of tables used in a query,
 
1235
    remember refresh_version (the version of open_cache state).
 
1236
    If the version changes while we're opening the remaining tables,
 
1237
    we will have to back off, close all the tables opened-so-far,
 
1238
    and try to reopen them.
 
1239
 
 
1240
    Note-> refresh_version is currently changed only during FLUSH TABLES.
 
1241
  */
 
1242
  if (!open_tables)
 
1243
  {
 
1244
    version= refresh_version;
 
1245
  }
 
1246
  else if ((version != refresh_version) &&
 
1247
           ! (flags & DRIZZLE_LOCK_IGNORE_FLUSH))
 
1248
  {
 
1249
    /* Someone did a refresh while thread was opening tables */
 
1250
    if (refresh)
 
1251
      *refresh= true;
 
1252
 
 
1253
    return NULL;
 
1254
  }
 
1255
 
 
1256
  /*
 
1257
    Before we test the global cache, we test our local session cache.
 
1258
  */
 
1259
  if (cached_table)
 
1260
  {
 
1261
    assert(false); /* Not implemented yet */
 
1262
  }
 
1263
 
 
1264
  /*
 
1265
    Non pre-locked/LOCK TABLES mode, and the table is not temporary:
 
1266
    this is the normal use case.
 
1267
    Now we should:
 
1268
    - try to find the table in the table cache.
 
1269
    - if one of the discovered Table instances is name-locked
 
1270
    (table->getShare()->version == 0) back off -- we have to wait
 
1271
    until no one holds a name lock on the table.
 
1272
    - if there is no such Table in the name cache, read the table definition
 
1273
    and insert it into the cache.
 
1274
    We perform all of the above under LOCK_open which currently protects
 
1275
    the open cache (also known as table cache) and table definitions stored
 
1276
    on disk.
 
1277
  */
 
1278
 
 
1279
  LOCK_open.lock(); /* Lock for FLUSH TABLES for open table */
 
1280
 
 
1281
  /*
 
1282
    Actually try to find the table in the open_cache.
 
1283
    The cache may contain several "Table" instances for the same
 
1284
    physical table. The instances that are currently "in use" by
 
1285
    some thread have their "in_use" member != NULL.
 
1286
    There is no good reason for having more than one entry in the
 
1287
    hash for the same physical table, except that we use this as
 
1288
    an implicit "pending locks queue" - see
 
1289
    wait_for_locked_table_names for details.
 
1290
  */
 
1291
  ppp= get_open_cache().equal_range(key);
 
1292
 
 
1293
  table= NULL;
 
1294
  for (TableOpenCache::const_iterator iter= ppp.first;
 
1295
       iter != ppp.second; ++iter, table= NULL)
 
1296
  {
 
1297
    table= (*iter).second;
 
1298
 
 
1299
    if (not table->in_use)
948
1300
      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
1301
    /*
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.
 
1302
      Here we flush tables marked for flush.
 
1303
      Normally, table->getShare()->version contains the value of
 
1304
      refresh_version from the moment when this table was
 
1305
      (re-)opened and added to the cache.
 
1306
      If since then we did (or just started) FLUSH TABLES
 
1307
      statement, refresh_version has been increased.
 
1308
      For "name-locked" Table instances, table->getShare()->version is set
 
1309
      to 0 (see lock_table_name for details).
 
1310
      In case there is a pending FLUSH TABLES or a name lock, we
 
1311
      need to back off and re-start opening tables.
 
1312
      If we do not back off now, we may dead lock in case of lock
 
1313
      order mismatch with some other thread:
 
1314
      c1-> name lock t1; -- sort of exclusive lock
 
1315
      c2-> open t2;      -- sort of shared lock
 
1316
      c1-> name lock t2; -- blocks
 
1317
      c2-> open t1; -- blocks
968
1318
    */
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 */
 
1319
    if (table->needs_reopen_or_name_lock())
 
1320
    {
 
1321
      if (flags & DRIZZLE_LOCK_IGNORE_FLUSH)
 
1322
      {
 
1323
        /* Force close at once after usage */
 
1324
        version= table->getShare()->getVersion();
 
1325
        continue;
 
1326
      }
 
1327
 
 
1328
      /* Avoid self-deadlocks by detecting self-dependencies. */
 
1329
      if (table->open_placeholder && table->in_use == this)
 
1330
      {
 
1331
        LOCK_open.unlock();
 
1332
        my_error(ER_UPDATE_TABLE_USED, MYF(0), table->getMutableShare()->getTableName());
 
1333
        return NULL;
 
1334
      }
 
1335
 
 
1336
      /*
 
1337
        Back off, part 1: mark the table as "unused" for the
 
1338
        purpose of name-locking by setting table->db_stat to 0. Do
 
1339
        that only for the tables in this thread that have an old
 
1340
        table->getShare()->version (this is an optimization (?)).
 
1341
        table->db_stat == 0 signals wait_for_locked_table_names
 
1342
        that the tables in question are not used any more. See
 
1343
        table_is_used call for details.
 
1344
      */
 
1345
      close_old_data_files(false, false);
 
1346
 
 
1347
      /*
 
1348
        Back-off part 2: try to avoid "busy waiting" on the table:
 
1349
        if the table is in use by some other thread, we suspend
 
1350
        and wait till the operation is complete: when any
 
1351
        operation that juggles with table->getShare()->version completes,
 
1352
        it broadcasts COND_refresh condition variable.
 
1353
        If 'old' table we met is in use by current thread we return
 
1354
        without waiting since in this situation it's this thread
 
1355
        which is responsible for broadcasting on COND_refresh
 
1356
        (and this was done already in Session::close_old_data_files()).
 
1357
        Good example of such situation is when we have statement
 
1358
        that needs two instances of table and FLUSH TABLES comes
 
1359
        after we open first instance but before we open second
 
1360
        instance.
 
1361
      */
 
1362
      if (table->in_use != this)
 
1363
      {
 
1364
        /* wait_for_conditionwill unlock LOCK_open for us */
 
1365
        wait_for_condition(LOCK_open, COND_refresh);
 
1366
      }
 
1367
      else
 
1368
      {
 
1369
        LOCK_open.unlock();
 
1370
      }
 
1371
      /*
 
1372
        There is a refresh in progress for this table.
 
1373
        Signal the caller that it has to try again.
 
1374
      */
977
1375
      if (refresh)
978
1376
        *refresh= true;
979
 
 
980
1377
      return NULL;
981
1378
    }
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)
 
1379
  }
 
1380
  if (table)
 
1381
  {
 
1382
    unused_tables.unlink(table);
 
1383
    table->in_use= this;
 
1384
  }
 
1385
  else
 
1386
  {
 
1387
    /* Insert a new Table instance into the open cache */
 
1388
    int error;
 
1389
    /* Free cache if too big */
 
1390
    unused_tables.cull();
 
1391
 
 
1392
    if (table_list->isCreate())
 
1393
    {
 
1394
      TableIdentifier  lock_table_identifier(table_list->db, table_list->table_name, message::Table::STANDARD);
 
1395
 
 
1396
      if (not plugin::StorageEngine::doesTableExist(*this, lock_table_identifier))
1024
1397
      {
1025
 
        table= (*iter).second;
1026
 
 
1027
 
        if (not table->in_use)
1028
 
          break;
1029
1398
        /*
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
 
1399
          Table to be created, so we need to create placeholder in table-cache.
1046
1400
        */
1047
 
        if (table->needs_reopen_or_name_lock())
 
1401
        if (!(table= table_cache_insert_placeholder(table_list->db, table_list->table_name)))
1048
1402
        {
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
 
 
 
1403
          LOCK_open.unlock();
1107
1404
          return NULL;
1108
1405
        }
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
 
  }
 
1406
        /*
 
1407
          Link placeholder to the open tables list so it will be automatically
 
1408
          removed once tables are closed. Also mark it so it won't be ignored
 
1409
          by other trying to take name-lock.
 
1410
        */
 
1411
        table->open_placeholder= true;
 
1412
        table->setNext(open_tables);
 
1413
        open_tables= table;
 
1414
        LOCK_open.unlock();
 
1415
 
 
1416
        return table ;
 
1417
      }
 
1418
      /* Table exists. Let us try to open it. */
 
1419
    }
 
1420
 
 
1421
    /* make a new table */
 
1422
    table= new Table;
 
1423
    if (table == NULL)
 
1424
    {
 
1425
      LOCK_open.unlock();
 
1426
      return NULL;
 
1427
    }
 
1428
 
 
1429
    error= open_unireg_entry(this, table, alias, identifier);
 
1430
    if (error != 0)
 
1431
    {
 
1432
      delete table;
 
1433
      LOCK_open.unlock();
 
1434
      return NULL;
 
1435
    }
 
1436
    (void)add_table(table);
 
1437
  }
 
1438
 
 
1439
  LOCK_open.unlock();
 
1440
  if (refresh)
 
1441
  {
 
1442
    table->setNext(open_tables); /* Link into simple list */
 
1443
    open_tables= table;
 
1444
  }
 
1445
  table->reginfo.lock_type= TL_READ; /* Assume read */
 
1446
 
 
1447
reset:
1178
1448
  assert(table->getShare()->getTableCount() > 0 || table->getShare()->getType() != message::Table::STANDARD);
1179
1449
 
 
1450
  if (lex->need_correct_ident())
 
1451
    table->alias_name_used= my_strcasecmp(table_alias_charset,
 
1452
                                          table->getMutableShare()->getTableName(), alias);
1180
1453
  /* Fix alias if table name changes */
1181
1454
  if (strcmp(table->getAlias(), alias))
1182
1455
  {
1183
 
    table->setAlias(alias);
 
1456
    uint32_t length=(uint32_t) strlen(alias)+1;
 
1457
    table->alias= (char*) realloc((char*) table->alias, length);
 
1458
    memcpy((void*) table->alias, alias, length);
1184
1459
  }
1185
1460
 
1186
1461
  /* These variables are also set in reopen_table() */
1207
1482
}
1208
1483
 
1209
1484
 
 
1485
#if 0
 
1486
/*
 
1487
  Reopen an table because the definition has changed.
 
1488
 
 
1489
  SYNOPSIS
 
1490
  reopen_table()
 
1491
  table Table object
 
1492
 
 
1493
  NOTES
 
1494
  The data cursor for the table is already closed and the share is released
 
1495
  The table has a 'dummy' share that mainly contains database and table name.
 
1496
 
 
1497
  RETURN
 
1498
  0  ok
 
1499
  1  error. The old table object is not changed.
 
1500
*/
 
1501
 
 
1502
bool reopen_table(Table *table)
 
1503
{
 
1504
  Table tmp;
 
1505
  bool error= 1;
 
1506
  Field **field;
 
1507
  uint32_t key,part;
 
1508
  TableList table_list;
 
1509
  Session *session= table->in_use;
 
1510
 
 
1511
  assert(table->getShare()->ref_count == 0);
 
1512
  assert(!table->sort.io_cache);
 
1513
 
 
1514
#ifdef EXTRA_DEBUG
 
1515
  if (table->db_stat)
 
1516
    errmsg_printf(ERRMSG_LVL_ERROR, _("Table %s had a open data Cursor in reopen_table"),
 
1517
                  table->alias);
 
1518
#endif
 
1519
  table_list.db=         const_cast<char *>(table->getShare()->getSchemaName());
 
1520
  table_list.table_name= table->getShare()->getTableName();
 
1521
  table_list.table=      table;
 
1522
 
 
1523
  if (wait_for_locked_table_names(session, &table_list))
 
1524
    return true;                             // Thread was killed
 
1525
 
 
1526
  if (open_unireg_entry(session, &tmp, &table_list,
 
1527
                        table->alias,
 
1528
                        table->getShare()->getCacheKey(),
 
1529
                        table->getShare()->getCacheKeySize()))
 
1530
    goto end;
 
1531
 
 
1532
  /* This list copies variables set by open_table */
 
1533
  tmp.tablenr=          table->tablenr;
 
1534
  tmp.used_fields=      table->used_fields;
 
1535
  tmp.const_table=      table->const_table;
 
1536
  tmp.null_row=         table->null_row;
 
1537
  tmp.maybe_null=       table->maybe_null;
 
1538
  tmp.status=           table->status;
 
1539
 
 
1540
  /* Get state */
 
1541
  tmp.in_use=           session;
 
1542
  tmp.reginfo.lock_type=table->reginfo.lock_type;
 
1543
 
 
1544
  /* Replace table in open list */
 
1545
  tmp.next=             table->next;
 
1546
  tmp.prev=             table->prev;
 
1547
 
 
1548
  if (table->cursor)
 
1549
    table->delete_table(true);          // close cursor, free everything
 
1550
 
 
1551
  *table= tmp;
 
1552
  table->default_column_bitmaps();
 
1553
  table->cursor->change_table_ptr(table, table->s);
 
1554
 
 
1555
  assert(table->alias != 0);
 
1556
  for (field=table->field ; *field ; field++)
 
1557
  {
 
1558
    (*field)->table= (*field)->orig_table= table;
 
1559
    (*field)->table_name= &table->alias;
 
1560
  }
 
1561
  for (key=0 ; key < table->getShare()->keys ; key++)
 
1562
  {
 
1563
    for (part=0 ; part < table->key_info[key].usable_key_parts ; part++)
 
1564
      table->key_info[key].key_part[part].field->table= table;
 
1565
  }
 
1566
 
 
1567
  broadcast_refresh();
 
1568
  error= false;
 
1569
 
 
1570
end:
 
1571
  return(error);
 
1572
}
 
1573
#endif
 
1574
 
 
1575
 
1210
1576
/**
1211
1577
  Close all instances of a table open by this thread and replace
1212
1578
  them with exclusive name-locks.
1224
1590
  the strings are used in a loop even after the share may be freed.
1225
1591
*/
1226
1592
 
1227
 
void Session::close_data_files_and_morph_locks(const identifier::Table &identifier)
 
1593
void Session::close_data_files_and_morph_locks(TableIdentifier &identifier)
1228
1594
{
1229
 
  safe_mutex_assert_owner(table::Cache::singleton().mutex().native_handle()); /* Adjust locks at the end of ALTER TABLEL */
 
1595
  safe_mutex_assert_owner(LOCK_open.native_handle()); /* Adjust locks at the end of ALTER TABLEL */
1230
1596
 
1231
1597
  if (lock)
1232
1598
  {
1234
1600
      If we are not under LOCK TABLES we should have only one table
1235
1601
      open and locked so it makes sense to remove the lock at once.
1236
1602
    */
1237
 
    unlockTables(lock);
 
1603
    mysql_unlock_tables(this, lock);
1238
1604
    lock= 0;
1239
1605
  }
1240
1606
 
1269
1635
  combination when one needs tables to be reopened (for
1270
1636
  example see openTablesLock()).
1271
1637
 
1272
 
  @note One should have lock on table::Cache::singleton().mutex() when calling this.
 
1638
  @note One should have lock on LOCK_open when calling this.
1273
1639
 
1274
1640
  @return false in case of success, true - otherwise.
1275
1641
*/
1276
1642
 
1277
 
bool Session::reopen_tables()
 
1643
bool Session::reopen_tables(bool get_locks, bool)
1278
1644
{
1279
1645
  Table *table,*next,**prev;
1280
 
  Table **tables= 0;                    // For locks
1281
 
  Table **tables_ptr= 0;                        // For locks
1282
 
  bool error= false;
 
1646
  Table **tables,**tables_ptr;                  // For locks
 
1647
  bool error=0, not_used;
1283
1648
  const uint32_t flags= DRIZZLE_LOCK_NOTIFY_IF_NEED_REOPEN |
1284
1649
    DRIZZLE_LOCK_IGNORE_GLOBAL_READ_LOCK |
1285
1650
    DRIZZLE_LOCK_IGNORE_FLUSH;
1287
1652
  if (open_tables == NULL)
1288
1653
    return false;
1289
1654
 
1290
 
  safe_mutex_assert_owner(table::Cache::singleton().mutex().native_handle());
 
1655
  safe_mutex_assert_owner(LOCK_open.native_handle());
 
1656
  if (get_locks)
1291
1657
  {
1292
1658
    /*
1293
1659
      The ptr is checked later
1301
1667
    }
1302
1668
    tables= new Table *[opens];
1303
1669
  }
1304
 
 
 
1670
  else
 
1671
  {
 
1672
    tables= &open_tables;
 
1673
  }
1305
1674
  tables_ptr =tables;
1306
1675
 
1307
1676
  prev= &open_tables;
1310
1679
    next= table->getNext();
1311
1680
 
1312
1681
    my_error(ER_CANT_REOPEN_TABLE, MYF(0), table->getAlias());
1313
 
    table::remove_table(static_cast<table::Concurrent *>(table));
 
1682
    remove_table(table);
1314
1683
    error= 1;
1315
1684
  }
1316
1685
  *prev=0;
1317
 
 
1318
1686
  if (tables != tables_ptr)                     // Should we get back old locks
1319
1687
  {
1320
1688
    DrizzleLock *local_lock;
1321
1689
    /*
1322
1690
      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
 
1691
      wait_for_tables() as it tries to acquire LOCK_open, which is
1324
1692
      already locked.
1325
1693
    */
1326
1694
    some_tables_deleted= false;
1327
1695
 
1328
 
    if ((local_lock= lockTables(tables, (uint32_t) (tables_ptr - tables), flags)))
 
1696
    if ((local_lock= mysql_lock_tables(this, tables, (uint32_t) (tables_ptr - tables),
 
1697
                                 flags, &not_used)))
1329
1698
    {
1330
1699
      /* unused */
1331
1700
    }
1341
1710
    }
1342
1711
  }
1343
1712
 
1344
 
  delete [] tables;
1345
 
 
1346
 
  locking::broadcast_refresh();
1347
 
 
1348
 
  return error;
 
1713
  if (get_locks && tables)
 
1714
    delete [] tables;
 
1715
 
 
1716
  broadcast_refresh();
 
1717
 
 
1718
  return(error);
1349
1719
}
1350
1720
 
1351
1721
 
1376
1746
    */
1377
1747
    if (table->needs_reopen_or_name_lock())
1378
1748
    {
1379
 
      found= true;
 
1749
      found=1;
1380
1750
      if (table->db_stat)
1381
1751
      {
1382
1752
        if (morph_locks)
1390
1760
              lock on it. This will also give them a chance to close their
1391
1761
              instances of this table.
1392
1762
            */
1393
 
            abortLock(ulcktbl);
1394
 
            removeLock(ulcktbl);
 
1763
            mysql_lock_abort(this, ulcktbl);
 
1764
            mysql_lock_remove(this, ulcktbl);
1395
1765
            ulcktbl->lock_count= 0;
1396
1766
          }
1397
1767
          if ((ulcktbl != table) && ulcktbl->db_stat)
1431
1801
    }
1432
1802
  }
1433
1803
  if (found)
1434
 
    locking::broadcast_refresh();
 
1804
    broadcast_refresh();
 
1805
}
 
1806
 
 
1807
 
 
1808
/*
 
1809
  Wait until all threads has closed the tables in the list
 
1810
  We have also to wait if there is thread that has a lock on this table even
 
1811
  if the table is closed
 
1812
*/
 
1813
 
 
1814
bool table_is_used(Table *table, bool wait_for_name_lock)
 
1815
{
 
1816
  do
 
1817
  {
 
1818
    const TableIdentifier::Key &key(table->getShare()->getCacheKey());
 
1819
 
 
1820
    TableOpenCacheRange ppp;
 
1821
    ppp= get_open_cache().equal_range(key);
 
1822
 
 
1823
    for (TableOpenCache::const_iterator iter= ppp.first;
 
1824
         iter != ppp.second; ++iter)
 
1825
    {
 
1826
      Table *search= (*iter).second;
 
1827
      if (search->in_use == table->in_use)
 
1828
        continue;                               // Name locked by this thread
 
1829
      /*
 
1830
        We can't use the table under any of the following conditions:
 
1831
        - There is an name lock on it (Table is to be deleted or altered)
 
1832
        - If we are in flush table and we didn't execute the flush
 
1833
        - If the table engine is open and it's an old version
 
1834
        (We must wait until all engines are shut down to use the table)
 
1835
      */
 
1836
      if ( (search->locked_by_name && wait_for_name_lock) ||
 
1837
           (search->is_name_opened() && search->needs_reopen_or_name_lock()))
 
1838
        return 1;
 
1839
    }
 
1840
  } while ((table=table->getNext()));
 
1841
  return 0;
 
1842
}
 
1843
 
 
1844
 
 
1845
/* Wait until all used tables are refreshed */
 
1846
 
 
1847
bool wait_for_tables(Session *session)
 
1848
{
 
1849
  bool result;
 
1850
 
 
1851
  session->set_proc_info("Waiting for tables");
 
1852
  {
 
1853
    boost::mutex::scoped_lock lock(LOCK_open);
 
1854
    while (!session->killed)
 
1855
    {
 
1856
      session->some_tables_deleted= false;
 
1857
      session->close_old_data_files(false, dropping_tables != 0);
 
1858
      if (!table_is_used(session->open_tables, 1))
 
1859
        break;
 
1860
      COND_refresh.wait(lock);
 
1861
    }
 
1862
    if (session->killed)
 
1863
      result= true;                                     // aborted
 
1864
    else
 
1865
    {
 
1866
      /* Now we can open all tables without any interference */
 
1867
      session->set_proc_info("Reopen tables");
 
1868
      session->version= refresh_version;
 
1869
      result= session->reopen_tables(false, false);
 
1870
    }
 
1871
  }
 
1872
  session->set_proc_info(0);
 
1873
 
 
1874
  return result;
1435
1875
}
1436
1876
 
1437
1877
 
1459
1899
*/
1460
1900
 
1461
1901
 
1462
 
Table *drop_locked_tables(Session *session, const drizzled::identifier::Table &identifier)
 
1902
Table *drop_locked_tables(Session *session, const drizzled::TableIdentifier &identifier)
1463
1903
{
1464
1904
  Table *table,*next,**prev, *found= 0;
1465
1905
  prev= &session->open_tables;
1466
1906
 
1467
1907
  /*
1468
 
    Note that we need to hold table::Cache::singleton().mutex() while changing the
 
1908
    Note that we need to hold LOCK_open while changing the
1469
1909
    open_tables list. Another thread may work on it.
1470
 
    (See: table::Cache::singleton().removeTable(), wait_completed_table())
 
1910
    (See: remove_table_from_cache(), mysql_wait_completed_table())
1471
1911
    Closing a MERGE child before the parent would be fatal if the
1472
1912
    other thread tries to abort the MERGE lock in between.
1473
1913
  */
1476
1916
    next=table->getNext();
1477
1917
    if (table->getShare()->getCacheKey() == identifier.getKey())
1478
1918
    {
1479
 
      session->removeLock(table);
 
1919
      mysql_lock_remove(session, table);
1480
1920
 
1481
1921
      if (!found)
1482
1922
      {
1491
1931
      else
1492
1932
      {
1493
1933
        /* We already have a name lock, remove copy */
1494
 
        table::remove_table(static_cast<table::Concurrent *>(table));
 
1934
        remove_table(table);
1495
1935
      }
1496
1936
    }
1497
1937
    else
1501
1941
    }
1502
1942
  }
1503
1943
  *prev=0;
1504
 
 
1505
1944
  if (found)
1506
 
    locking::broadcast_refresh();
 
1945
    broadcast_refresh();
1507
1946
 
1508
 
  return found;
 
1947
  return(found);
1509
1948
}
1510
1949
 
1511
1950
 
1515
1954
  other threads trying to get the lock.
1516
1955
*/
1517
1956
 
1518
 
void abort_locked_tables(Session *session, const drizzled::identifier::Table &identifier)
 
1957
void abort_locked_tables(Session *session, const drizzled::TableIdentifier &identifier)
1519
1958
{
1520
1959
  Table *table;
1521
1960
  for (table= session->open_tables; table ; table= table->getNext())
1523
1962
    if (table->getShare()->getCacheKey() == identifier.getKey())
1524
1963
    {
1525
1964
      /* If MERGE child, forward lock handling to parent. */
1526
 
      session->abortLock(table);
1527
 
      assert(0);
 
1965
      mysql_lock_abort(session, table);
1528
1966
      break;
1529
1967
    }
1530
1968
  }
1531
1969
}
1532
1970
 
 
1971
/*
 
1972
  Load a table definition from cursor and open unireg table
 
1973
 
 
1974
  SYNOPSIS
 
1975
  open_unireg_entry()
 
1976
  session                       Thread handle
 
1977
  entry         Store open table definition here
 
1978
  table_list            TableList with db, table_name
 
1979
  alias         Alias name
 
1980
  cache_key             Key for share_cache
 
1981
  cache_key_length      length of cache_key
 
1982
 
 
1983
  NOTES
 
1984
  Extra argument for open is taken from session->open_options
 
1985
  One must have a lock on LOCK_open when calling this function
 
1986
 
 
1987
  RETURN
 
1988
  0     ok
 
1989
#       Error
 
1990
*/
 
1991
 
 
1992
static int open_unireg_entry(Session *session,
 
1993
                             Table *entry,
 
1994
                             const char *alias,
 
1995
                             TableIdentifier &identifier)
 
1996
{
 
1997
  int error;
 
1998
  TableShare *share;
 
1999
  uint32_t discover_retry_count= 0;
 
2000
 
 
2001
  safe_mutex_assert_owner(LOCK_open.native_handle());
 
2002
retry:
 
2003
  if (not (share= TableShare::getShareCreate(session,
 
2004
                                             identifier,
 
2005
                                             &error)))
 
2006
    return 1;
 
2007
 
 
2008
  while ((error= share->open_table_from_share(session,
 
2009
                                              identifier,
 
2010
                                              alias,
 
2011
                                              (uint32_t) (HA_OPEN_KEYFILE |
 
2012
                                                          HA_OPEN_RNDFILE |
 
2013
                                                          HA_GET_INDEX |
 
2014
                                                          HA_TRY_READ_ONLY),
 
2015
                                              session->open_options, *entry)))
 
2016
  {
 
2017
    if (error == 7)                             // Table def changed
 
2018
    {
 
2019
      share->resetVersion();                        // Mark share as old
 
2020
      if (discover_retry_count++)               // Retry once
 
2021
        goto err;
 
2022
 
 
2023
      /*
 
2024
        TODO->
 
2025
        Here we should wait until all threads has released the table.
 
2026
        For now we do one retry. This may cause a deadlock if there
 
2027
        is other threads waiting for other tables used by this thread.
 
2028
 
 
2029
        Proper fix would be to if the second retry failed:
 
2030
        - Mark that table def changed
 
2031
        - Return from open table
 
2032
        - Close all tables used by this thread
 
2033
        - Start waiting that the share is released
 
2034
        - Retry by opening all tables again
 
2035
      */
 
2036
 
 
2037
      /*
 
2038
        TO BE FIXED
 
2039
        To avoid deadlock, only wait for release if no one else is
 
2040
        using the share.
 
2041
      */
 
2042
      if (share->getTableCount() != 1)
 
2043
        goto err;
 
2044
      /* Free share and wait until it's released by all threads */
 
2045
      TableShare::release(share);
 
2046
 
 
2047
      if (!session->killed)
 
2048
      {
 
2049
        drizzle_reset_errors(session, 1);         // Clear warnings
 
2050
        session->clear_error();                 // Clear error message
 
2051
        goto retry;
 
2052
      }
 
2053
      return 1;
 
2054
    }
 
2055
 
 
2056
    goto err;
 
2057
  }
 
2058
 
 
2059
  return 0;
 
2060
 
 
2061
err:
 
2062
  TableShare::release(share);
 
2063
 
 
2064
  return 1;
 
2065
}
 
2066
 
1533
2067
 
1534
2068
/*
1535
2069
  Open all tables in list
1597
2131
     * to see if it exists so that an unauthorized user cannot phish for
1598
2132
     * table/schema information via error messages
1599
2133
     */
1600
 
    identifier::Table the_table(tables->getSchemaName(), tables->getTableName());
1601
 
    if (not plugin::Authorization::isAuthorized(user(), the_table))
 
2134
    TableIdentifier the_table(tables->db, tables->table_name);
 
2135
    if (not plugin::Authorization::isAuthorized(getSecurityContext(),
 
2136
                                                the_table))
1602
2137
    {
1603
2138
      result= -1;                               // Fatal error
1604
2139
      break;
1695
2230
 
1696
2231
  set_proc_info("Opening table");
1697
2232
  current_tablenr= 0;
1698
 
  while (!(table= openTable(table_list, &refresh)) && refresh) ;
 
2233
  while (!(table= openTable(table_list, &refresh)) &&
 
2234
         refresh)
 
2235
    ;
1699
2236
 
1700
2237
  if (table)
1701
2238
  {
1704
2241
 
1705
2242
    assert(lock == 0);  // You must lock everything at once
1706
2243
    if ((table->reginfo.lock_type= lock_type) != TL_UNLOCK)
1707
 
    {
1708
 
      if (not (lock= lockTables(&table_list->table, 1, 0)))
1709
 
        table= NULL;
1710
 
    }
 
2244
      if (! (lock= mysql_lock_tables(this, &table_list->table, 1, 0, &refresh)))
 
2245
        table= 0;
1711
2246
  }
1712
2247
 
1713
2248
  set_proc_info(0);
1761
2296
  Table **start,**ptr;
1762
2297
  uint32_t lock_flag= DRIZZLE_LOCK_NOTIFY_IF_NEED_REOPEN;
1763
2298
 
1764
 
  if (!(ptr=start=(Table**) session->getMemRoot()->allocate(sizeof(Table*)*count)))
 
2299
  if (!(ptr=start=(Table**) session->alloc(sizeof(Table*)*count)))
1765
2300
    return -1;
1766
 
 
1767
2301
  for (table= tables; table; table= table->next_global)
1768
2302
  {
1769
2303
    if (!table->placeholder())
1770
2304
      *(ptr++)= table->table;
1771
2305
  }
1772
2306
 
1773
 
  if (not (session->lock= session->lockTables(start, (uint32_t) (ptr - start), lock_flag)))
 
2307
  if (!(session->lock= mysql_lock_tables(session, start, (uint32_t) (ptr - start),
 
2308
                                         lock_flag, need_reopen)))
1774
2309
  {
1775
2310
    return -1;
1776
2311
  }
1799
2334
#  Table object
1800
2335
*/
1801
2336
 
1802
 
Table *Open_tables_state::open_temporary_table(const identifier::Table &identifier,
1803
 
                                               bool link_in_list)
 
2337
Table *Session::open_temporary_table(TableIdentifier &identifier,
 
2338
                                     bool link_in_list)
1804
2339
{
 
2340
  TableShare *share;
 
2341
 
1805
2342
  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()));
 
2343
  share= new TableShare(identifier.getType(),
 
2344
                        identifier,
 
2345
                        const_cast<char *>(identifier.getPath().c_str()), static_cast<uint32_t>(identifier.getPath().length()));
 
2346
 
 
2347
 
 
2348
  Table *new_tmp_table= new Table;
1812
2349
  if (not new_tmp_table)
1813
2350
    return NULL;
1814
2351
 
1815
2352
  /*
1816
2353
    First open the share, and then open the table from the share we just opened.
1817
2354
  */
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))
 
2355
  if (share->open_table_def(*this, identifier) ||
 
2356
      share->open_table_from_share(this, identifier, identifier.getTableName().c_str(),
 
2357
                            (uint32_t) (HA_OPEN_KEYFILE | HA_OPEN_RNDFILE |
 
2358
                                        HA_GET_INDEX),
 
2359
                            ha_open_options,
 
2360
                            *new_tmp_table))
1824
2361
  {
1825
2362
    /* No need to lock share->mutex as this is not needed for tmp tables */
1826
 
    delete new_tmp_table->getMutableShare();
 
2363
    delete share;
1827
2364
    delete new_tmp_table;
1828
2365
 
1829
2366
    return 0;
1865
2402
{
1866
2403
  if (session->mark_used_columns != MARK_COLUMNS_NONE)
1867
2404
  {
1868
 
    boost::dynamic_bitset<> *current_bitmap= NULL;
 
2405
    MyBitmap *current_bitmap, *other_bitmap;
1869
2406
 
1870
2407
    /*
1871
2408
      We always want to register the used keys, as the column bitmap may have
1878
2415
    if (session->mark_used_columns == MARK_COLUMNS_READ)
1879
2416
    {
1880
2417
      current_bitmap= table->read_set;
 
2418
      other_bitmap=   table->write_set;
1881
2419
    }
1882
2420
    else
1883
2421
    {
1884
2422
      current_bitmap= table->write_set;
 
2423
      other_bitmap=   table->read_set;
1885
2424
    }
1886
2425
 
1887
 
    //if (current_bitmap->testAndSet(field->position()))
1888
 
    if (current_bitmap->test(field->position()))
 
2426
    if (current_bitmap->testAndSet(field->field_index))
1889
2427
    {
1890
2428
      if (session->mark_used_columns == MARK_COLUMNS_WRITE)
1891
2429
        session->dup_field= field;
1944
2482
    {
1945
2483
      if (nj_col)
1946
2484
      {
1947
 
        my_error(ER_NON_UNIQ_ERROR, MYF(0), name, session->where());
 
2485
        my_error(ER_NON_UNIQ_ERROR, MYF(0), name, session->where);
1948
2486
        return NULL;
1949
2487
      }
1950
2488
      nj_col= curr_nj_col;
2119
2657
      */
2120
2658
      table_name && table_name[0] &&
2121
2659
      (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()))))
 
2660
       (db_name && db_name[0] && table_list->db && table_list->db[0] &&
 
2661
        strcmp(db_name, table_list->db))))
2124
2662
    return 0;
2125
2663
 
2126
2664
  *actual_table= NULL;
2195
2733
      {
2196
2734
        Table *table= field_to_set->getTable();
2197
2735
        if (session->mark_used_columns == MARK_COLUMNS_READ)
2198
 
          table->setReadSet(field_to_set->position());
 
2736
          table->setReadSet(field_to_set->field_index);
2199
2737
        else
2200
 
          table->setWriteSet(field_to_set->position());
 
2738
          table->setWriteSet(field_to_set->field_index);
2201
2739
      }
2202
2740
    }
2203
2741
  }
2341
2879
      */
2342
2880
      item->cached_table= found ?  0 : actual_table;
2343
2881
 
2344
 
      assert(session->where());
 
2882
      assert(session->where);
2345
2883
      /*
2346
2884
        If we found a fully qualified field we return it directly as it can't
2347
2885
        have duplicates.
2354
2892
        if (report_error == REPORT_ALL_ERRORS ||
2355
2893
            report_error == IGNORE_EXCEPT_NON_UNIQUE)
2356
2894
          my_error(ER_NON_UNIQ_ERROR, MYF(0),
2357
 
                   table_name ? item->full_name() : name, session->where());
 
2895
                   table_name ? item->full_name() : name, session->where);
2358
2896
        return (Field*) 0;
2359
2897
      }
2360
2898
      found= cur_field;
2387
2925
      strcat(buff, table_name);
2388
2926
      table_name=buff;
2389
2927
    }
2390
 
    my_error(ER_UNKNOWN_TABLE, MYF(0), table_name, session->where());
 
2928
    my_error(ER_UNKNOWN_TABLE, MYF(0), table_name, session->where);
2391
2929
  }
2392
2930
  else
2393
2931
  {
2394
2932
    if (report_error == REPORT_ALL_ERRORS ||
2395
2933
        report_error == REPORT_EXCEPT_NON_UNIQUE)
2396
 
      my_error(ER_BAD_FIELD_ERROR, MYF(0), item->full_name(), session->where());
 
2934
      my_error(ER_BAD_FIELD_ERROR, MYF(0), item->full_name(), session->where);
2397
2935
    else
2398
2936
      found= not_found_field;
2399
2937
  }
2520
3058
            */
2521
3059
            if (report_error != IGNORE_ERRORS)
2522
3060
              my_error(ER_NON_UNIQ_ERROR, MYF(0),
2523
 
                       find->full_name(), session->where());
 
3061
                       find->full_name(), session->where);
2524
3062
            return (Item**) 0;
2525
3063
          }
2526
3064
          found_unaliased= li.ref();
2551
3089
              continue;                           // Same field twice
2552
3090
            if (report_error != IGNORE_ERRORS)
2553
3091
              my_error(ER_NON_UNIQ_ERROR, MYF(0),
2554
 
                       find->full_name(), session->where());
 
3092
                       find->full_name(), session->where);
2555
3093
            return (Item**) 0;
2556
3094
          }
2557
3095
          found= li.ref();
2603
3141
    {
2604
3142
      if (report_error != IGNORE_ERRORS)
2605
3143
        my_error(ER_NON_UNIQ_ERROR, MYF(0),
2606
 
                 find->full_name(), session->where());
 
3144
                 find->full_name(), session->where);
2607
3145
      return (Item **) 0;
2608
3146
    }
2609
3147
    if (found_unaliased)
2619
3157
  {
2620
3158
    if (report_error == REPORT_ALL_ERRORS)
2621
3159
      my_error(ER_BAD_FIELD_ERROR, MYF(0),
2622
 
               find->full_name(), session->where());
 
3160
               find->full_name(), session->where);
2623
3161
    return (Item **) 0;
2624
3162
  }
2625
3163
  else
2753
3291
    /* true if field_name_1 is a member of using_fields */
2754
3292
    bool is_using_column_1;
2755
3293
    if (!(nj_col_1= it_1.get_or_create_column_ref(leaf_1)))
2756
 
      return(result);
 
3294
      goto err;
2757
3295
    field_name_1= nj_col_1->name();
2758
3296
    is_using_column_1= using_fields &&
2759
3297
      test_if_string_in_list(field_name_1, using_fields);
2771
3309
      Natural_join_column *cur_nj_col_2;
2772
3310
      const char *cur_field_name_2;
2773
3311
      if (!(cur_nj_col_2= it_2.get_or_create_column_ref(leaf_2)))
2774
 
        return(result);
 
3312
        goto err;
2775
3313
      cur_field_name_2= cur_nj_col_2->name();
2776
3314
 
2777
3315
      /*
2790
3328
        if (cur_nj_col_2->is_common ||
2791
3329
            (found && (!using_fields || is_using_column_1)))
2792
3330
        {
2793
 
          my_error(ER_NON_UNIQ_ERROR, MYF(0), field_name_1, session->where());
2794
 
          return(result);
 
3331
          my_error(ER_NON_UNIQ_ERROR, MYF(0), field_name_1, session->where);
 
3332
          goto err;
2795
3333
        }
2796
3334
        nj_col_2= cur_nj_col_2;
2797
3335
        found= true;
2824
3362
      Item_func_eq *eq_cond;
2825
3363
 
2826
3364
      if (!item_1 || !item_2)
2827
 
        return(result); // out of memory
 
3365
        goto err;                               // out of memory
2828
3366
 
2829
3367
      /*
2830
3368
        In the case of no_wrap_view_item == 0, the created items must be
2849
3387
      */
2850
3388
      if (set_new_item_local_context(session, item_ident_1, nj_col_1->table_ref) ||
2851
3389
          set_new_item_local_context(session, item_ident_2, nj_col_2->table_ref))
2852
 
        return(result);
 
3390
        goto err;
2853
3391
 
2854
3392
      if (!(eq_cond= new Item_func_eq(item_ident_1, item_ident_2)))
2855
 
        return(result);                               /* Out of memory. */
 
3393
        goto err;                               /* Out of memory. */
2856
3394
 
2857
3395
      /*
2858
3396
        Add the new equi-join condition to the ON clause. Notice that
2869
3407
      {
2870
3408
        Table *table_1= nj_col_1->table_ref->table;
2871
3409
        /* Mark field_1 used for table cache. */
2872
 
        table_1->setReadSet(field_1->position());
 
3410
        table_1->setReadSet(field_1->field_index);
2873
3411
        table_1->covering_keys&= field_1->part_of_key;
2874
3412
        table_1->merge_keys|= field_1->part_of_key;
2875
3413
      }
2877
3415
      {
2878
3416
        Table *table_2= nj_col_2->table_ref->table;
2879
3417
        /* Mark field_2 used for table cache. */
2880
 
        table_2->setReadSet(field_2->position());
 
3418
        table_2->setReadSet(field_2->field_index);
2881
3419
        table_2->covering_keys&= field_2->part_of_key;
2882
3420
        table_2->merge_keys|= field_2->part_of_key;
2883
3421
      }
2898
3436
  */
2899
3437
  result= false;
2900
3438
 
 
3439
err:
2901
3440
  return(result);
2902
3441
}
2903
3442
 
2955
3494
 
2956
3495
  if (!(non_join_columns= new List<Natural_join_column>) ||
2957
3496
      !(natural_using_join->join_columns= new List<Natural_join_column>))
2958
 
  {
2959
 
    return(result);
2960
 
  }
 
3497
    goto err;
2961
3498
 
2962
3499
  /* Append the columns of the first join operand. */
2963
3500
  for (it_1.set(table_ref_1); !it_1.end_of_fields(); it_1.next())
2995
3532
        if (!(common_field= it++))
2996
3533
        {
2997
3534
          my_error(ER_BAD_FIELD_ERROR, MYF(0), using_field_name_ptr,
2998
 
                   session->where());
2999
 
          return(result);
 
3535
                   session->where);
 
3536
          goto err;
3000
3537
        }
3001
3538
        if (!my_strcasecmp(system_charset_info,
3002
3539
                           common_field->name(), using_field_name_ptr))
3024
3561
 
3025
3562
  result= false;
3026
3563
 
 
3564
err:
3027
3565
  return(result);
3028
3566
}
3029
3567
 
3109
3647
      if (cur_table_ref->getNestedJoin() &&
3110
3648
          store_top_level_join_columns(session, cur_table_ref,
3111
3649
                                       real_left_neighbor, real_right_neighbor))
3112
 
        return(result);
 
3650
        goto err;
3113
3651
      same_level_right_neighbor= cur_table_ref;
3114
3652
    }
3115
3653
  }
3141
3679
      std::swap(table_ref_1, table_ref_2);
3142
3680
    if (mark_common_columns(session, table_ref_1, table_ref_2,
3143
3681
                            using_fields, &found_using_fields))
3144
 
      return(result);
 
3682
      goto err;
3145
3683
 
3146
3684
    /*
3147
3685
      Swap the join operands back, so that we pick the columns of the second
3153
3691
    if (store_natural_using_join_columns(session, table_ref, table_ref_1,
3154
3692
                                         table_ref_2, using_fields,
3155
3693
                                         found_using_fields))
3156
 
      return(result);
 
3694
      goto err;
3157
3695
 
3158
3696
    /*
3159
3697
      Change NATURAL JOIN to JOIN ... ON. We do this for both operands
3186
3724
  }
3187
3725
  result= false; /* All is OK. */
3188
3726
 
 
3727
err:
3189
3728
  return(result);
3190
3729
}
3191
3730
 
3218
3757
                                         List<TableList> *from_clause,
3219
3758
                                         Name_resolution_context *context)
3220
3759
{
3221
 
  session->setWhere("from clause");
 
3760
  session->where= "from clause";
3222
3761
  if (from_clause->elements == 0)
3223
3762
    return false; /* We come here in the case of UNIONs. */
3224
3763
 
3339
3878
  session->mark_used_columns= mark_used_columns;
3340
3879
  if (allow_sum_func)
3341
3880
    session->lex->allow_sum_func|= 1 << session->lex->current_select->nest_level;
3342
 
  session->setWhere(Session::DEFAULT_WHERE);
 
3881
  session->where= Session::DEFAULT_WHERE;
3343
3882
  save_is_item_list_lookup= session->lex->current_select->is_item_list_lookup;
3344
3883
  session->lex->current_select->is_item_list_lookup= 0;
3345
3884
 
3351
3890
    There is other way to solve problem: fill array with pointers to list,
3352
3891
    but it will be slower.
3353
3892
 
3354
 
    TODO-> remove it when (if) we made one list for allfields and ref_pointer_array
 
3893
TODO: remove it when (if) we made one list for allfields and
 
3894
ref_pointer_array
3355
3895
  */
3356
3896
  if (ref_pointer_array)
3357
 
  {
3358
3897
    memset(ref_pointer_array, 0, sizeof(Item *) * fields.elements);
3359
 
  }
3360
3898
 
3361
3899
  Item **ref= ref_pointer_array;
3362
3900
  session->lex->current_select->cur_pos_in_select_list= 0;
3588
4126
    assert(tables->is_leaf_for_name_resolution());
3589
4127
 
3590
4128
    if ((table_name && my_strcasecmp(table_alias_charset, table_name, tables->alias)) ||
3591
 
        (db_name && my_strcasecmp(system_charset_info, tables->getSchemaName(),db_name)))
 
4129
        (db_name && strcasecmp(tables->db,db_name)))
3592
4130
      continue;
3593
4131
 
3594
4132
    /*
3624
4162
      if ((field= field_iterator.field()))
3625
4163
      {
3626
4164
        /* Mark fields as used to allow storage engine to optimze access */
3627
 
        field->getTable()->setReadSet(field->position());
 
4165
        field->getTable()->setReadSet(field->field_index);
3628
4166
        if (table)
3629
4167
        {
3630
4168
          table->covering_keys&= field->part_of_key;
3652
4190
        }
3653
4191
      }
3654
4192
      else
3655
 
      {
3656
4193
        session->used_tables|= item->used_tables();
3657
 
      }
3658
 
 
3659
4194
      session->lex->current_select->cur_pos_in_select_list++;
3660
4195
    }
3661
4196
    /*
3675
4210
    qualified '*', and all columns were coalesced, we have to give a more
3676
4211
    meaningful message than ER_BAD_TABLE_ERROR.
3677
4212
  */
3678
 
  if (not table_name)
3679
 
  {
 
4213
  if (!table_name)
3680
4214
    my_message(ER_NO_TABLES_USED, ER(ER_NO_TABLES_USED), MYF(0));
3681
 
  }
3682
4215
  else
3683
 
  {
3684
4216
    my_error(ER_BAD_TABLE_ERROR, MYF(0), table_name);
3685
 
  }
3686
4217
 
3687
4218
  return true;
3688
4219
}
3731
4262
  session->session_marker= (void*)1;
3732
4263
  if (*conds)
3733
4264
  {
3734
 
    session->setWhere("where clause");
 
4265
    session->where="where clause";
3735
4266
    if ((!(*conds)->fixed && (*conds)->fix_fields(session, conds)) ||
3736
4267
        (*conds)->check_cols(1))
3737
4268
      goto err_no_arena;
3753
4284
      {
3754
4285
        /* Make a join an a expression */
3755
4286
        session->session_marker= (void*)embedded;
3756
 
        session->setWhere("on clause");
 
4287
        session->where="on clause";
3757
4288
        if ((!embedded->on_expr->fixed && embedded->on_expr->fix_fields(session, &embedded->on_expr)) ||
3758
4289
            embedded->on_expr->check_cols(1))
3759
4290
          goto err_no_arena;
3838
4369
    if ((value->save_in_field(rfield, 0) < 0) && !ignore_errors)
3839
4370
    {
3840
4371
      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;
 
4372
      goto err;
3845
4373
    }
3846
4374
  }
3847
4375
 
3848
4376
  return session->is_error();
 
4377
 
 
4378
err:
 
4379
  if (table)
 
4380
    table->auto_increment_field_not_null= false;
 
4381
 
 
4382
  return true;
3849
4383
}
3850
4384
 
3851
4385
 
3888
4422
    table= (*ptr)->getTable();
3889
4423
    table->auto_increment_field_not_null= false;
3890
4424
  }
3891
 
 
3892
4425
  while ((field = *ptr++) && ! session->is_error())
3893
4426
  {
3894
4427
    value=v++;
3895
4428
    table= field->getTable();
3896
 
 
3897
4429
    if (field == table->next_number_field)
3898
4430
      table->auto_increment_field_not_null= true;
3899
 
 
3900
4431
    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
 
    }
 
4432
      goto err;
3907
4433
  }
3908
4434
 
3909
4435
  return(session->is_error());
 
4436
 
 
4437
err:
 
4438
  if (table)
 
4439
    table->auto_increment_field_not_null= false;
 
4440
 
 
4441
  return true;
3910
4442
}
3911
4443
 
3912
4444
 
3913
4445
bool drizzle_rm_tmp_tables()
3914
4446
{
 
4447
  Session *session;
3915
4448
 
3916
4449
  assert(drizzle_tmpdir.size());
3917
 
  Session::shared_ptr session= Session::make_shared(plugin::Listen::getNullClient(), catalog::local());
3918
4450
 
3919
 
  if (not session)
 
4451
  if (!(session= new Session(plugin::Listen::getNullClient())))
3920
4452
    return true;
3921
 
  session->thread_stack= (char*) session.get();
 
4453
  session->thread_stack= (char*) &session;
3922
4454
  session->storeGlobals();
3923
4455
 
3924
4456
  plugin::StorageEngine::removeLostTemporaryTables(*session, drizzle_tmpdir.c_str());
3925
4457
 
 
4458
  session->lockForDelete();
 
4459
  delete session;
 
4460
 
3926
4461
  return false;
3927
4462
}
3928
4463
 
3932
4467
  unireg support functions
3933
4468
 *****************************************************************************/
3934
4469
 
3935
 
 
 
4470
/*
 
4471
  Invalidate any cache entries that are for some DB
 
4472
 
 
4473
  SYNOPSIS
 
4474
  remove_db_from_cache()
 
4475
  db            Database name. This will be in lower case if
 
4476
  lower_case_table_name is set
 
4477
 
 
4478
NOTE:
 
4479
We can't use hash_delete when looping hash_elements. We mark them first
 
4480
and afterwards delete those marked unused.
 
4481
*/
 
4482
 
 
4483
void remove_db_from_cache(const SchemaIdentifier &schema_identifier)
 
4484
{
 
4485
  safe_mutex_assert_owner(LOCK_open.native_handle());
 
4486
 
 
4487
  for (TableOpenCache::const_iterator iter= get_open_cache().begin();
 
4488
       iter != get_open_cache().end();
 
4489
       iter++)
 
4490
  {
 
4491
    Table *table= (*iter).second;
 
4492
 
 
4493
    if (not schema_identifier.getPath().compare(table->getMutableShare()->getSchemaName()))
 
4494
    {
 
4495
      table->getMutableShare()->resetVersion();                 /* Free when thread is ready */
 
4496
      if (not table->in_use)
 
4497
        unused_tables.relink(table);
 
4498
    }
 
4499
  }
 
4500
 
 
4501
  unused_tables.cullByVersion();
 
4502
}
 
4503
 
 
4504
 
 
4505
/*
 
4506
  Mark all entries with the table as deleted to force an reopen of the table
 
4507
 
 
4508
  The table will be closed (not stored in cache) by the current thread when
 
4509
  close_thread_tables() is called.
 
4510
 
 
4511
  PREREQUISITES
 
4512
  Lock on LOCK_open()
 
4513
 
 
4514
  RETURN
 
4515
  0  This thread now have exclusive access to this table and no other thread
 
4516
  can access the table until close_thread_tables() is called.
 
4517
  1  Table is in use by another thread
 
4518
*/
 
4519
 
 
4520
bool remove_table_from_cache(Session *session, TableIdentifier &identifier, uint32_t flags)
 
4521
{
 
4522
  const TableIdentifier::Key &key(identifier.getKey());
 
4523
  bool result= false; 
 
4524
  bool signalled= false;
 
4525
 
 
4526
  for (;;)
 
4527
  {
 
4528
    result= signalled= false;
 
4529
 
 
4530
    TableOpenCacheRange ppp;
 
4531
    ppp= get_open_cache().equal_range(key);
 
4532
 
 
4533
    for (TableOpenCache::const_iterator iter= ppp.first;
 
4534
         iter != ppp.second; ++iter)
 
4535
    {
 
4536
      Table *table= (*iter).second;
 
4537
      Session *in_use;
 
4538
 
 
4539
      table->getMutableShare()->resetVersion();         /* Free when thread is ready */
 
4540
      if (!(in_use=table->in_use))
 
4541
      {
 
4542
        unused_tables.relink(table);
 
4543
      }
 
4544
      else if (in_use != session)
 
4545
      {
 
4546
        /*
 
4547
          Mark that table is going to be deleted from cache. This will
 
4548
          force threads that are in mysql_lock_tables() (but not yet
 
4549
          in thr_multi_lock()) to abort it's locks, close all tables and retry
 
4550
        */
 
4551
        in_use->some_tables_deleted= true;
 
4552
        if (table->is_name_opened())
 
4553
        {
 
4554
          result= true;
 
4555
        }
 
4556
        /*
 
4557
          Now we must abort all tables locks used by this thread
 
4558
          as the thread may be waiting to get a lock for another table.
 
4559
          Note that we need to hold LOCK_open while going through the
 
4560
          list. So that the other thread cannot change it. The other
 
4561
          thread must also hold LOCK_open whenever changing the
 
4562
          open_tables list. Aborting the MERGE lock after a child was
 
4563
          closed and before the parent is closed would be fatal.
 
4564
        */
 
4565
        for (Table *session_table= in_use->open_tables;
 
4566
             session_table ;
 
4567
             session_table= session_table->getNext())
 
4568
        {
 
4569
          /* Do not handle locks of MERGE children. */
 
4570
          if (session_table->db_stat)   // If table is open
 
4571
            signalled|= mysql_lock_abort_for_thread(session, session_table);
 
4572
        }
 
4573
      }
 
4574
      else
 
4575
        result= result || (flags & RTFC_OWNED_BY_Session_FLAG);
 
4576
    }
 
4577
 
 
4578
    unused_tables.cullByVersion();
 
4579
 
 
4580
    /* Remove table from table definition cache if it's not in use */
 
4581
    TableShare::release(identifier);
 
4582
 
 
4583
    if (result && (flags & RTFC_WAIT_OTHER_THREAD_FLAG))
 
4584
    {
 
4585
      /*
 
4586
        Signal any thread waiting for tables to be freed to
 
4587
        reopen their tables
 
4588
      */
 
4589
      broadcast_refresh();
 
4590
      if (!(flags & RTFC_CHECK_KILLED_FLAG) || !session->killed)
 
4591
      {
 
4592
        dropping_tables++;
 
4593
        if (likely(signalled))
 
4594
          (void) pthread_cond_wait(COND_refresh.native_handle(), LOCK_open.native_handle());
 
4595
        else
 
4596
        {
 
4597
          struct timespec abstime;
 
4598
          /*
 
4599
            It can happen that another thread has opened the
 
4600
            table but has not yet locked any table at all. Since
 
4601
            it can be locked waiting for a table that our thread
 
4602
            has done LOCK Table x WRITE on previously, we need to
 
4603
            ensure that the thread actually hears our signal
 
4604
            before we go to sleep. Thus we wait for a short time
 
4605
            and then we retry another loop in the
 
4606
            remove_table_from_cache routine.
 
4607
          */
 
4608
          set_timespec(abstime, 10);
 
4609
          pthread_cond_timedwait(COND_refresh.native_handle(), LOCK_open.native_handle(), &abstime);
 
4610
        }
 
4611
        dropping_tables--;
 
4612
        continue;
 
4613
      }
 
4614
    }
 
4615
    break;
 
4616
  }
 
4617
 
 
4618
  return result;
 
4619
}
3936
4620
 
3937
4621
 
3938
4622
/**