~drizzle-trunk/drizzle/development

« back to all changes in this revision

Viewing changes to drizzled/sql_base.cc

  • Committer: Brian Aker
  • Date: 2010-08-18 16:12:58 UTC
  • mto: This revision was merged to the branch mainline in revision 1720.
  • Revision ID: brian@tangent.org-20100818161258-1vm71da888dfvwsx
Remove the code surrounding stack trace.

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 */
47
47
#include "drizzled/cached_directory.h"
48
48
#include <drizzled/field/timestamp.h>
49
49
#include <drizzled/field/null.h>
 
50
#include "drizzled/memory/multi_malloc.h"
50
51
#include "drizzled/sql_table.h"
51
52
#include "drizzled/global_charset_info.h"
52
53
#include "drizzled/pthread_globals.h"
53
54
#include "drizzled/internal/iocache.h"
54
55
#include "drizzled/drizzled.h"
55
56
#include "drizzled/plugin/authorization.h"
56
 
#include "drizzled/table/temporary.h"
57
 
#include "drizzled/table/placeholder.h"
58
 
#include "drizzled/table/unused.h"
 
57
#include "drizzled/table_placeholder.h"
59
58
 
60
59
using namespace std;
61
60
 
64
63
 
65
64
extern bool volatile shutdown_in_progress;
66
65
 
 
66
TableOpenCache &get_open_cache()
 
67
{
 
68
  static TableOpenCache open_cache;                             /* Used by mysql_test */
 
69
 
 
70
  return open_cache;
 
71
}
 
72
 
 
73
static void free_cache_entry(Table *entry);
 
74
 
 
75
void remove_table(Table *arg)
 
76
{
 
77
  TableOpenCacheRange ppp;
 
78
  ppp= get_open_cache().equal_range(arg->getShare()->getCacheKey());
 
79
 
 
80
  for (TableOpenCache::const_iterator iter= ppp.first;
 
81
         iter != ppp.second; ++iter)
 
82
  {
 
83
    Table *found_table= (*iter).second;
 
84
 
 
85
    if (found_table == arg)
 
86
    {
 
87
      free_cache_entry(arg);
 
88
      get_open_cache().erase(iter);
 
89
      return;
 
90
    }
 
91
  }
 
92
}
 
93
 
 
94
static bool add_table(Table *arg)
 
95
{
 
96
  TableOpenCache &open_cache(get_open_cache());
 
97
 
 
98
  TableOpenCache::iterator returnable= open_cache.insert(make_pair(arg->getShare()->getCacheKey(), arg));
 
99
 
 
100
  return not (returnable == open_cache.end());
 
101
}
 
102
 
 
103
class UnusedTables {
 
104
  Table *tables;                                /* Used by mysql_test */
 
105
 
 
106
  Table *getTable() const
 
107
  {
 
108
    return tables;
 
109
  }
 
110
 
 
111
  Table *setTable(Table *arg)
 
112
  {
 
113
    return tables= arg;
 
114
  }
 
115
 
 
116
public:
 
117
 
 
118
  void cull()
 
119
  {
 
120
    /* Free cache if too big */
 
121
    while (cached_open_tables() > table_cache_size && getTable())
 
122
      remove_table(getTable());
 
123
  }
 
124
 
 
125
  void cullByVersion()
 
126
  {
 
127
    while (getTable() && not getTable()->getShare()->getVersion())
 
128
      remove_table(getTable());
 
129
  }
 
130
  
 
131
  void link(Table *table)
 
132
  {
 
133
    if (getTable())
 
134
    {
 
135
      table->setNext(getTable());               /* Link in last */
 
136
      table->setPrev(getTable()->getPrev());
 
137
      getTable()->setPrev(table);
 
138
      table->getPrev()->setNext(table);
 
139
    }
 
140
    else
 
141
    {
 
142
      table->setPrev(setTable(table));
 
143
      table->setNext(table->getPrev());
 
144
      assert(table->getNext() == table && table->getPrev() == table);
 
145
    }
 
146
  }
 
147
 
 
148
 
 
149
  void unlink(Table *table)
 
150
  {
 
151
    table->unlink();
 
152
 
 
153
    /* Unlink the table from "unused_tables" list. */
 
154
    if (table == getTable())
 
155
    {  // First unused
 
156
      setTable(getTable()->getNext()); // Remove from link
 
157
      if (table == getTable())
 
158
        setTable(NULL);
 
159
    }
 
160
  }
 
161
 
 
162
/* move table first in unused links */
 
163
 
 
164
  void relink(Table *table)
 
165
  {
 
166
    if (table != getTable())
 
167
    {
 
168
      table->unlink();
 
169
 
 
170
      table->setNext(getTable());                       /* Link in unused tables */
 
171
      table->setPrev(getTable()->getPrev());
 
172
      getTable()->getPrev()->setNext(table);
 
173
      getTable()->setPrev(table);
 
174
      setTable(table);
 
175
    }
 
176
  }
 
177
 
 
178
 
 
179
  void clear()
 
180
  {
 
181
    while (getTable())
 
182
      remove_table(getTable());
 
183
  }
 
184
 
 
185
  UnusedTables():
 
186
    tables(NULL)
 
187
  { }
 
188
 
 
189
  ~UnusedTables()
 
190
  { 
 
191
  }
 
192
};
 
193
 
 
194
static UnusedTables unused_tables;
 
195
static int open_unireg_entry(Session *session,
 
196
                             Table *entry,
 
197
                             const char *alias,
 
198
                             TableIdentifier &identifier);
 
199
 
 
200
unsigned char *table_cache_key(const unsigned char *record,
 
201
                               size_t *length,
 
202
                               bool );
 
203
 
 
204
#if 0
 
205
static bool reopen_table(Table *table);
 
206
#endif
 
207
 
 
208
unsigned char *table_cache_key(const unsigned char *record,
 
209
                               size_t *length,
 
210
                               bool )
 
211
{
 
212
  Table *entry=(Table*) record;
 
213
  *length= entry->getShare()->getCacheKey().size();
 
214
  return (unsigned char*) &entry->getShare()->getCacheKey()[0];
 
215
}
 
216
 
67
217
bool table_cache_init(void)
68
218
{
69
219
  return false;
71
221
 
72
222
uint32_t cached_open_tables(void)
73
223
{
74
 
  return table::getCache().size();
 
224
  return get_open_cache().size();
75
225
}
76
226
 
77
227
void table_cache_free(void)
78
228
{
79
229
  refresh_version++;                            // Force close of open tables
80
230
 
81
 
  table::getUnused().clear();
82
 
  table::getCache().clear();
 
231
  unused_tables.clear();
 
232
  get_open_cache().clear();
83
233
}
84
234
 
85
235
/*
93
243
  By leaving the table in the table cache, it disallows any other thread
94
244
  to open the table
95
245
 
96
 
  session->getKilled() will be set if we run out of memory
 
246
  session->killed will be set if we run out of memory
97
247
 
98
248
  If closing a MERGE child, the calling function has to take care for
99
249
  closing the parent too, if necessary.
102
252
 
103
253
void close_handle_and_leave_table_as_lock(Table *table)
104
254
{
 
255
  TableShare *share, *old_share= table->getMutableShare();
105
256
  assert(table->db_stat);
106
257
  assert(table->getShare()->getType() == message::Table::STANDARD);
107
258
 
112
263
  */
113
264
  TableIdentifier identifier(table->getShare()->getSchemaName(), table->getShare()->getTableName(), message::Table::INTERNAL);
114
265
  const TableIdentifier::Key &key(identifier.getKey());
115
 
  TableShare *share= new TableShare(identifier.getType(),
116
 
                                    identifier,
117
 
                                    const_cast<char *>(key.vector()),  static_cast<uint32_t>(table->getShare()->getCacheKeySize()));
 
266
  share= new TableShare(identifier.getType(),
 
267
                        identifier,
 
268
                        const_cast<char *>(&key[0]),  static_cast<uint32_t>(old_share->getCacheKeySize()));
118
269
 
119
270
  table->cursor->close();
120
271
  table->db_stat= 0;                            // Mark cursor closed
121
272
  TableShare::release(table->getMutableShare());
122
273
  table->setShare(share);
 
274
  table->cursor->change_table_ptr(table, table->getMutableShare());
123
275
}
124
276
 
125
277
 
137
289
  }
138
290
}
139
291
 
 
292
/*
 
293
  Remove table from the open table cache
 
294
 
 
295
  SYNOPSIS
 
296
  free_cache_entry()
 
297
  entry         Table to remove
 
298
 
 
299
  NOTE
 
300
  We need to have a lock on LOCK_open when calling this
 
301
*/
 
302
 
 
303
void free_cache_entry(Table *table)
 
304
{
 
305
  table->intern_close_table();
 
306
  if (not table->in_use)
 
307
  {
 
308
    unused_tables.unlink(table);
 
309
  }
 
310
 
 
311
  delete table;
 
312
}
 
313
 
140
314
/* Free resources allocated by filesort() and read_record() */
141
315
 
142
316
void Table::free_io_cache()
143
317
{
144
318
  if (sort.io_cache)
145
319
  {
146
 
    sort.io_cache->close_cached_file();
 
320
    close_cached_file(sort.io_cache);
147
321
    delete sort.io_cache;
148
322
    sort.io_cache= 0;
149
323
  }
155
329
 
156
330
  @param session Thread context (may be NULL)
157
331
  @param tables List of tables to remove from the cache
158
 
  @param have_lock If table::Cache::singleton().mutex() is locked
 
332
  @param have_lock If LOCK_open is locked
159
333
  @param wait_for_refresh Wait for a impending flush
160
334
  @param wait_for_placeholders Wait for tables being reopened so that the GRL
161
335
  won't proceed while write-locked tables are being reopened by other
170
344
  bool result= false;
171
345
  Session *session= this;
172
346
 
173
 
  {
174
 
    table::Cache::singleton().mutex().lock(); /* Optionally lock for remove tables from open_cahe if not in use */
175
 
 
176
 
    if (tables == NULL)
177
 
    {
178
 
      refresh_version++;                                // Force close of open tables
179
 
 
180
 
      table::getUnused().clear();
181
 
 
182
 
      if (wait_for_refresh)
183
 
      {
 
347
  LOCK_open.lock(); /* Optionally lock for remove tables from open_cahe if not in use */
 
348
 
 
349
  if (tables == NULL)
 
350
  {
 
351
    refresh_version++;                          // Force close of open tables
 
352
 
 
353
    unused_tables.clear();
 
354
 
 
355
    if (wait_for_refresh)
 
356
    {
 
357
      /*
 
358
        Other threads could wait in a loop in open_and_lock_tables(),
 
359
        trying to lock one or more of our tables.
 
360
 
 
361
        If they wait for the locks in thr_multi_lock(), their lock
 
362
        request is aborted. They loop in open_and_lock_tables() and
 
363
        enter open_table(). Here they notice the table is refreshed and
 
364
        wait for COND_refresh. Then they loop again in
 
365
        openTablesLock() and this time open_table() succeeds. At
 
366
        this moment, if we (the FLUSH TABLES thread) are scheduled and
 
367
        on another FLUSH TABLES enter close_cached_tables(), they could
 
368
        awake while we sleep below, waiting for others threads (us) to
 
369
        close their open tables. If this happens, the other threads
 
370
        would find the tables unlocked. They would get the locks, one
 
371
        after the other, and could do their destructive work. This is an
 
372
        issue if we have LOCK TABLES in effect.
 
373
 
 
374
        The problem is that the other threads passed all checks in
 
375
        open_table() before we refresh the table.
 
376
 
 
377
        The fix for this problem is to set some_tables_deleted for all
 
378
        threads with open tables. These threads can still get their
 
379
        locks, but will immediately release them again after checking
 
380
        this variable. They will then loop in openTablesLock()
 
381
        again. There they will wait until we update all tables version
 
382
        below.
 
383
 
 
384
        Setting some_tables_deleted is done by remove_table_from_cache()
 
385
        in the other branch.
 
386
 
 
387
        In other words (reviewer suggestion): You need this setting of
 
388
        some_tables_deleted for the case when table was opened and all
 
389
        related checks were passed before incrementing refresh_version
 
390
        (which you already have) but attempt to lock the table happened
 
391
        after the call to Session::close_old_data_files() i.e. after removal of
 
392
        current thread locks.
 
393
      */
 
394
      for (TableOpenCache::const_iterator iter= get_open_cache().begin();
 
395
           iter != get_open_cache().end();
 
396
           iter++)
 
397
      {
 
398
        Table *table= (*iter).second;
 
399
        if (table->in_use)
 
400
          table->in_use->some_tables_deleted= false;
 
401
      }
 
402
    }
 
403
  }
 
404
  else
 
405
  {
 
406
    bool found= false;
 
407
    for (TableList *table= tables; table; table= table->next_local)
 
408
    {
 
409
      TableIdentifier identifier(table->db, table->table_name);
 
410
      if (remove_table_from_cache(session, identifier,
 
411
                                  RTFC_OWNED_BY_Session_FLAG))
 
412
      {
 
413
        found= true;
 
414
      }
 
415
    }
 
416
    if (!found)
 
417
      wait_for_refresh= false;                  // Nothing to wait for
 
418
  }
 
419
 
 
420
  if (wait_for_refresh)
 
421
  {
 
422
    /*
 
423
      If there is any table that has a lower refresh_version, wait until
 
424
      this is closed (or this thread is killed) before returning
 
425
    */
 
426
    session->mysys_var->current_mutex= LOCK_open.native_handle();
 
427
    session->mysys_var->current_cond= COND_refresh.native_handle();
 
428
    session->set_proc_info("Flushing tables");
 
429
 
 
430
    session->close_old_data_files();
 
431
 
 
432
    bool found= true;
 
433
    /* Wait until all threads has closed all the tables we had locked */
 
434
    while (found && ! session->killed)
 
435
    {
 
436
      found= false;
 
437
      for (TableOpenCache::const_iterator iter= get_open_cache().begin();
 
438
           iter != get_open_cache().end();
 
439
           iter++)
 
440
      {
 
441
        Table *table= (*iter).second;
 
442
        /* Avoid a self-deadlock. */
 
443
        if (table->in_use == session)
 
444
          continue;
184
445
        /*
185
 
          Other threads could wait in a loop in open_and_lock_tables(),
186
 
          trying to lock one or more of our tables.
187
 
 
188
 
          If they wait for the locks in thr_multi_lock(), their lock
189
 
          request is aborted. They loop in open_and_lock_tables() and
190
 
          enter open_table(). Here they notice the table is refreshed and
191
 
          wait for COND_refresh. Then they loop again in
192
 
          openTablesLock() and this time open_table() succeeds. At
193
 
          this moment, if we (the FLUSH TABLES thread) are scheduled and
194
 
          on another FLUSH TABLES enter close_cached_tables(), they could
195
 
          awake while we sleep below, waiting for others threads (us) to
196
 
          close their open tables. If this happens, the other threads
197
 
          would find the tables unlocked. They would get the locks, one
198
 
          after the other, and could do their destructive work. This is an
199
 
          issue if we have LOCK TABLES in effect.
200
 
 
201
 
          The problem is that the other threads passed all checks in
202
 
          open_table() before we refresh the table.
203
 
 
204
 
          The fix for this problem is to set some_tables_deleted for all
205
 
          threads with open tables. These threads can still get their
206
 
          locks, but will immediately release them again after checking
207
 
          this variable. They will then loop in openTablesLock()
208
 
          again. There they will wait until we update all tables version
209
 
          below.
210
 
 
211
 
          Setting some_tables_deleted is done by table::Cache::singleton().removeTable()
212
 
          in the other branch.
213
 
 
214
 
          In other words (reviewer suggestion): You need this setting of
215
 
          some_tables_deleted for the case when table was opened and all
216
 
          related checks were passed before incrementing refresh_version
217
 
          (which you already have) but attempt to lock the table happened
218
 
          after the call to Session::close_old_data_files() i.e. after removal of
219
 
          current thread locks.
 
446
          Note that we wait here only for tables which are actually open, and
 
447
          not for placeholders with Table::open_placeholder set. Waiting for
 
448
          latter will cause deadlock in the following scenario, for example:
 
449
 
 
450
          conn1-> lock table t1 write;
 
451
          conn2-> lock table t2 write;
 
452
          conn1-> flush tables;
 
453
          conn2-> flush tables;
 
454
 
 
455
          It also does not make sense to wait for those of placeholders that
 
456
          are employed by CREATE TABLE as in this case table simply does not
 
457
          exist yet.
220
458
        */
221
 
        for (table::CacheMap::const_iterator iter= table::getCache().begin();
222
 
             iter != table::getCache().end();
223
 
             iter++)
224
 
        {
225
 
          Table *table= (*iter).second;
226
 
          if (table->in_use)
227
 
            table->in_use->some_tables_deleted= false;
228
 
        }
229
 
      }
230
 
    }
231
 
    else
232
 
    {
233
 
      bool found= false;
234
 
      for (TableList *table= tables; table; table= table->next_local)
235
 
      {
236
 
        TableIdentifier identifier(table->getSchemaName(), table->getTableName());
237
 
        if (table::Cache::singleton().removeTable(session, identifier,
238
 
                                    RTFC_OWNED_BY_Session_FLAG))
 
459
        if (table->needs_reopen_or_name_lock() && (table->db_stat ||
 
460
                                                   (table->open_placeholder && wait_for_placeholders)))
239
461
        {
240
462
          found= true;
 
463
          pthread_cond_wait(COND_refresh.native_handle(),LOCK_open.native_handle());
 
464
          break;
241
465
        }
242
466
      }
243
 
      if (!found)
244
 
        wait_for_refresh= false;                        // Nothing to wait for
245
467
    }
 
468
    /*
 
469
      No other thread has the locked tables open; reopen them and get the
 
470
      old locks. This should always succeed (unless some external process
 
471
      has removed the tables)
 
472
    */
 
473
    result= session->reopen_tables(true, true);
246
474
 
247
 
    if (wait_for_refresh)
 
475
    /* Set version for table */
 
476
    for (Table *table= session->open_tables; table ; table= table->getNext())
248
477
    {
249
478
      /*
250
 
        If there is any table that has a lower refresh_version, wait until
251
 
        this is closed (or this thread is killed) before returning
252
 
      */
253
 
      session->mysys_var->current_mutex= &table::Cache::singleton().mutex();
254
 
      session->mysys_var->current_cond= &COND_refresh;
255
 
      session->set_proc_info("Flushing tables");
256
 
 
257
 
      session->close_old_data_files();
258
 
 
259
 
      bool found= true;
260
 
      /* Wait until all threads has closed all the tables we had locked */
261
 
      while (found && ! session->getKilled())
262
 
      {
263
 
        found= false;
264
 
        for (table::CacheMap::const_iterator iter= table::getCache().begin();
265
 
             iter != table::getCache().end();
266
 
             iter++)
267
 
        {
268
 
          Table *table= (*iter).second;
269
 
          /* Avoid a self-deadlock. */
270
 
          if (table->in_use == session)
271
 
            continue;
272
 
          /*
273
 
            Note that we wait here only for tables which are actually open, and
274
 
            not for placeholders with Table::open_placeholder set. Waiting for
275
 
            latter will cause deadlock in the following scenario, for example:
276
 
 
277
 
            conn1-> lock table t1 write;
278
 
            conn2-> lock table t2 write;
279
 
            conn1-> flush tables;
280
 
            conn2-> flush tables;
281
 
 
282
 
            It also does not make sense to wait for those of placeholders that
283
 
            are employed by CREATE TABLE as in this case table simply does not
284
 
            exist yet.
285
 
          */
286
 
          if (table->needs_reopen_or_name_lock() && (table->db_stat ||
287
 
                                                     (table->open_placeholder && wait_for_placeholders)))
288
 
          {
289
 
            found= true;
290
 
            boost_unique_lock_t scoped(table::Cache::singleton().mutex(), boost::adopt_lock_t());
291
 
            COND_refresh.wait(scoped);
292
 
            scoped.release();
293
 
            break;
294
 
          }
295
 
        }
296
 
      }
297
 
      /*
298
 
        No other thread has the locked tables open; reopen them and get the
299
 
        old locks. This should always succeed (unless some external process
300
 
        has removed the tables)
301
 
      */
302
 
      result= session->reopen_tables(true, true);
303
 
 
304
 
      /* Set version for table */
305
 
      for (Table *table= session->open_tables; table ; table= table->getNext())
306
 
      {
307
 
        /*
308
 
          Preserve the version (0) of write locked tables so that a impending
309
 
          global read lock won't sneak in.
310
 
        */
311
 
        if (table->reginfo.lock_type < TL_WRITE_ALLOW_WRITE)
312
 
          table->getMutableShare()->refreshVersion();
313
 
      }
 
479
        Preserve the version (0) of write locked tables so that a impending
 
480
        global read lock won't sneak in.
 
481
      */
 
482
      if (table->reginfo.lock_type < TL_WRITE_ALLOW_WRITE)
 
483
        table->getMutableShare()->refreshVersion();
314
484
    }
315
 
 
316
 
    table::Cache::singleton().mutex().unlock();
317
485
  }
318
486
 
 
487
  LOCK_open.unlock();
 
488
 
319
489
  if (wait_for_refresh)
320
490
  {
321
 
    boost_unique_lock_t scopedLock(session->mysys_var->mutex);
 
491
    pthread_mutex_lock(&session->mysys_var->mutex);
322
492
    session->mysys_var->current_mutex= 0;
323
493
    session->mysys_var->current_cond= 0;
324
494
    session->set_proc_info(0);
 
495
    pthread_mutex_unlock(&session->mysys_var->mutex);
325
496
  }
326
497
 
327
498
  return result;
335
506
bool Session::free_cached_table()
336
507
{
337
508
  bool found_old_table= false;
338
 
  table::Concurrent *table= static_cast<table::Concurrent *>(open_tables);
 
509
  Table *table= open_tables;
339
510
 
340
 
  safe_mutex_assert_owner(table::Cache::singleton().mutex().native_handle());
 
511
  safe_mutex_assert_owner(LOCK_open.native_handle());
341
512
  assert(table->key_read == 0);
342
513
  assert(!table->cursor || table->cursor->inited == Cursor::NONE);
343
514
 
346
517
  if (table->needs_reopen_or_name_lock() ||
347
518
      version != refresh_version || !table->db_stat)
348
519
  {
349
 
    table::remove_table(table);
 
520
    remove_table(table);
350
521
    found_old_table= true;
351
522
  }
352
523
  else
359
530
 
360
531
    /* Free memory and reset for next loop */
361
532
    table->cursor->ha_reset();
362
 
    table->in_use= NULL;
 
533
    table->in_use= false;
363
534
 
364
 
    table::getUnused().link(table);
 
535
    unused_tables.link(table);
365
536
  }
366
537
 
367
538
  return found_old_table;
380
551
{
381
552
  bool found_old_table= false;
382
553
 
383
 
  safe_mutex_assert_not_owner(table::Cache::singleton().mutex().native_handle());
 
554
  safe_mutex_assert_not_owner(LOCK_open.native_handle());
384
555
 
385
 
  boost_unique_lock_t scoped_lock(table::Cache::singleton().mutex()); /* Close all open tables on Session */
 
556
  LOCK_open.lock(); /* Close all open tables on Session */
386
557
 
387
558
  while (open_tables)
388
559
  {
393
564
  if (found_old_table)
394
565
  {
395
566
    /* Tell threads waiting for refresh that something has happened */
396
 
    locking::broadcast_refresh();
 
567
    broadcast_refresh();
397
568
  }
 
569
 
 
570
  LOCK_open.unlock();
398
571
}
399
572
 
400
573
/*
423
596
  for (; table; table= table->*link )
424
597
  {
425
598
    if ((table->table == 0 || table->table->getShare()->getType() == message::Table::STANDARD) &&
426
 
        strcasecmp(table->getSchemaName(), db_name) == 0 &&
427
 
        strcasecmp(table->getTableName(), table_name) == 0)
 
599
        strcasecmp(table->db, db_name) == 0 &&
 
600
        strcasecmp(table->table_name, table_name) == 0)
428
601
      break;
429
602
  }
430
603
  return table;
495
668
    */
496
669
    assert(table);
497
670
  }
498
 
  d_name= table->getSchemaName();
499
 
  t_name= table->getTableName();
 
671
  d_name= table->db;
 
672
  t_name= table->table_name;
500
673
  t_alias= table->alias;
501
674
 
502
675
  for (;;)
517
690
}
518
691
 
519
692
 
520
 
void Open_tables_state::doGetTableNames(const SchemaIdentifier &schema_identifier,
521
 
                                        std::set<std::string>& set_of_names)
 
693
void Session::doGetTableNames(const SchemaIdentifier &schema_identifier,
 
694
                              std::set<std::string>& set_of_names)
522
695
{
523
 
  for (Table *table= getTemporaryTables() ; table ; table= table->getNext())
 
696
  for (Table *table= temporary_tables ; table ; table= table->getNext())
524
697
  {
525
698
    if (schema_identifier.compare(table->getShare()->getSchemaName()))
526
699
    {
529
702
  }
530
703
}
531
704
 
532
 
void Open_tables_state::doGetTableNames(CachedDirectory &,
533
 
                                        const SchemaIdentifier &schema_identifier,
534
 
                                        std::set<std::string> &set_of_names)
 
705
void Session::doGetTableNames(CachedDirectory &,
 
706
                              const SchemaIdentifier &schema_identifier,
 
707
                              std::set<std::string> &set_of_names)
535
708
{
536
709
  doGetTableNames(schema_identifier, set_of_names);
537
710
}
538
711
 
539
 
void Open_tables_state::doGetTableIdentifiers(const SchemaIdentifier &schema_identifier,
540
 
                                              TableIdentifier::vector &set_of_identifiers)
 
712
void Session::doGetTableIdentifiers(const SchemaIdentifier &schema_identifier,
 
713
                                    TableIdentifiers &set_of_identifiers)
541
714
{
542
 
  for (Table *table= getTemporaryTables() ; table ; table= table->getNext())
 
715
  for (Table *table= temporary_tables ; table ; table= table->getNext())
543
716
  {
544
717
    if (schema_identifier.compare(table->getShare()->getSchemaName()))
545
718
    {
550
723
  }
551
724
}
552
725
 
553
 
void Open_tables_state::doGetTableIdentifiers(CachedDirectory &,
554
 
                                              const SchemaIdentifier &schema_identifier,
555
 
                                              TableIdentifier::vector &set_of_identifiers)
 
726
void Session::doGetTableIdentifiers(CachedDirectory &,
 
727
                                    const SchemaIdentifier &schema_identifier,
 
728
                                    TableIdentifiers &set_of_identifiers)
556
729
{
557
730
  doGetTableIdentifiers(schema_identifier, set_of_identifiers);
558
731
}
559
732
 
560
 
bool Open_tables_state::doDoesTableExist(const TableIdentifier &identifier)
 
733
bool Session::doDoesTableExist(const TableIdentifier &identifier)
561
734
{
562
 
  for (Table *table= getTemporaryTables() ; table ; table= table->getNext())
 
735
  for (Table *table= temporary_tables ; table ; table= table->getNext())
563
736
  {
564
737
    if (table->getShare()->getType() == message::Table::TEMPORARY)
565
738
    {
573
746
  return false;
574
747
}
575
748
 
576
 
int Open_tables_state::doGetTableDefinition(const TableIdentifier &identifier,
 
749
int Session::doGetTableDefinition(const TableIdentifier &identifier,
577
750
                                  message::Table &table_proto)
578
751
{
579
 
  for (Table *table= getTemporaryTables() ; table ; table= table->getNext())
 
752
  for (Table *table= temporary_tables ; table ; table= table->getNext())
580
753
  {
581
754
    if (table->getShare()->getType() == message::Table::TEMPORARY)
582
755
    {
592
765
  return ENOENT;
593
766
}
594
767
 
595
 
Table *Open_tables_state::find_temporary_table(const TableIdentifier &identifier)
 
768
Table *Session::find_temporary_table(const char *new_db, const char *table_name)
 
769
{
 
770
  char  key[MAX_DBKEY_LENGTH];
 
771
  uint  key_length;
 
772
 
 
773
  key_length= TableIdentifier::createKey(key, new_db, table_name);
 
774
 
 
775
  for (Table *table= temporary_tables ; table ; table= table->getNext())
 
776
  {
 
777
    const TableIdentifier::Key &share_key(table->getShare()->getCacheKey());
 
778
    if (share_key.size() == key_length &&
 
779
        not memcmp(&share_key[0], key, key_length))
 
780
    {
 
781
      return table;
 
782
    }
 
783
  }
 
784
  return NULL;                               // Not a temporary table
 
785
}
 
786
 
 
787
Table *Session::find_temporary_table(TableList *table_list)
 
788
{
 
789
  return find_temporary_table(table_list->db, table_list->table_name);
 
790
}
 
791
 
 
792
Table *Session::find_temporary_table(TableIdentifier &identifier)
596
793
{
597
794
  for (Table *table= temporary_tables ; table ; table= table->getNext())
598
795
  {
630
827
  @retval -1  the table is in use by a outer query
631
828
*/
632
829
 
633
 
int Open_tables_state::drop_temporary_table(const drizzled::TableIdentifier &identifier)
 
830
int Session::drop_temporary_table(TableList *table_list)
634
831
{
635
832
  Table *table;
636
833
 
637
 
  if (not (table= find_temporary_table(identifier)))
 
834
  if (not (table= find_temporary_table(table_list)))
638
835
    return 1;
639
836
 
640
837
  /* Table might be in use by some outer statement. */
641
 
  if (table->query_id && table->query_id != getQueryId())
 
838
  if (table->query_id && table->query_id != query_id)
642
839
  {
643
840
    my_error(ER_CANT_REOPEN_TABLE, MYF(0), table->getAlias());
644
841
    return -1;
656
853
 
657
854
  @param  session     Thread context
658
855
  @param  find    Table to remove
659
 
 
660
 
  @note because we risk the chance of deleting the share, we can't assume that it will exist past, this should be modified once we can use a TableShare::shared_ptr here.
661
856
*/
662
857
 
663
858
void Session::unlink_open_table(Table *find)
664
859
{
665
 
  const TableIdentifier::Key find_key(find->getShare()->getCacheKey());
666
 
  Table **prev;
667
 
  safe_mutex_assert_owner(table::Cache::singleton().mutex().native_handle());
 
860
  char key[MAX_DBKEY_LENGTH];
 
861
  uint32_t key_length= find->getShare()->getCacheKeySize();
 
862
  Table *list, **prev;
 
863
  safe_mutex_assert_owner(LOCK_open.native_handle());
668
864
 
 
865
  memcpy(key, &find->getMutableShare()->getCacheKey()[0], key_length);
669
866
  /*
670
 
    Note that we need to hold table::Cache::singleton().mutex() while changing the
 
867
    Note that we need to hold LOCK_open while changing the
671
868
    open_tables list. Another thread may work on it.
672
 
    (See: table::Cache::singleton().removeTable(), mysql_wait_completed_table())
 
869
    (See: remove_table_from_cache(), mysql_wait_completed_table())
673
870
    Closing a MERGE child before the parent would be fatal if the
674
871
    other thread tries to abort the MERGE lock in between.
675
872
  */
676
873
  for (prev= &open_tables; *prev; )
677
874
  {
678
 
    Table *list= *prev;
 
875
    list= *prev;
679
876
 
680
 
    if (list->getShare()->getCacheKey() == find_key)
 
877
    if (list->getShare()->getCacheKeySize() == key_length &&
 
878
        not memcmp(&list->getShare()->getCacheKey()[0], key, key_length))
681
879
    {
682
880
      /* Remove table from open_tables list. */
683
881
      *prev= list->getNext();
684
882
 
685
883
      /* Close table. */
686
 
      table::remove_table(static_cast<table::Concurrent *>(list));
 
884
      remove_table(list);
687
885
    }
688
886
    else
689
887
    {
693
891
  }
694
892
 
695
893
  // Notify any 'refresh' threads
696
 
  locking::broadcast_refresh();
 
894
  broadcast_refresh();
697
895
}
698
896
 
699
897
 
716
914
  table that was locked with LOCK TABLES.
717
915
*/
718
916
 
719
 
void Session::drop_open_table(Table *table, const TableIdentifier &identifier)
 
917
void Session::drop_open_table(Table *table, TableIdentifier &identifier)
720
918
{
721
919
  if (table->getShare()->getType())
722
920
  {
724
922
  }
725
923
  else
726
924
  {
727
 
    boost_unique_lock_t scoped_lock(table::Cache::singleton().mutex()); /* Close and drop a table (AUX routine) */
 
925
    LOCK_open.lock(); /* Close and drop a table (AUX routine) */
728
926
    /*
729
927
      unlink_open_table() also tells threads waiting for refresh or close
730
928
      that something has happened.
731
929
    */
732
930
    unlink_open_table(table);
733
 
    plugin::StorageEngine::dropTable(*this, identifier);
 
931
    quick_rm_table(*this, identifier);
 
932
    LOCK_open.unlock();
734
933
  }
735
934
}
736
935
 
746
945
  cond  Condition to wait for
747
946
*/
748
947
 
749
 
void Session::wait_for_condition(boost::mutex &mutex, boost::condition_variable_any &cond)
 
948
void Session::wait_for_condition(boost::mutex &mutex, boost::condition_variable &cond)
750
949
{
751
950
  /* Wait until the current table is up to date */
752
951
  const char *saved_proc_info;
753
 
  mysys_var->current_mutex= &mutex;
754
 
  mysys_var->current_cond= &cond;
 
952
  mysys_var->current_mutex= mutex.native_handle();
 
953
  mysys_var->current_cond= cond.native_handle();
755
954
  saved_proc_info= get_proc_info();
756
955
  set_proc_info("Waiting for table");
757
 
  {
758
 
    /*
759
 
      We must unlock mutex first to avoid deadlock becasue conditions are
760
 
      sent to this thread by doing locks in the following order:
761
 
      lock(mysys_var->mutex)
762
 
      lock(mysys_var->current_mutex)
763
 
 
764
 
      One by effect of this that one can only use wait_for_condition with
765
 
      condition variables that are guranteed to not disapper (freed) even if this
766
 
      mutex is unlocked
767
 
    */
768
 
    boost_unique_lock_t scopedLock(mutex, boost::adopt_lock_t());
769
 
    if (not getKilled())
770
 
    {
771
 
      cond.wait(scopedLock);
772
 
    }
773
 
  }
774
 
  boost_unique_lock_t mysys_scopedLock(mysys_var->mutex);
 
956
  if (!killed)
 
957
    (void) pthread_cond_wait(cond.native_handle(), mutex.native_handle());
 
958
 
 
959
  /*
 
960
    We must unlock mutex first to avoid deadlock becasue conditions are
 
961
    sent to this thread by doing locks in the following order:
 
962
    lock(mysys_var->mutex)
 
963
    lock(mysys_var->current_mutex)
 
964
 
 
965
    One by effect of this that one can only use wait_for_condition with
 
966
    condition variables that are guranteed to not disapper (freed) even if this
 
967
    mutex is unlocked
 
968
  */
 
969
 
 
970
  pthread_mutex_unlock(mutex.native_handle());
 
971
  pthread_mutex_lock(&mysys_var->mutex);
775
972
  mysys_var->current_mutex= 0;
776
973
  mysys_var->current_cond= 0;
777
974
  set_proc_info(saved_proc_info);
 
975
  pthread_mutex_unlock(&mysys_var->mutex);
 
976
}
 
977
 
 
978
 
 
979
/*
 
980
  Open table which is already name-locked by this thread.
 
981
 
 
982
  SYNOPSIS
 
983
  reopen_name_locked_table()
 
984
  session         Thread handle
 
985
  table_list  TableList object for table to be open, TableList::table
 
986
  member should point to Table object which was used for
 
987
  name-locking.
 
988
  link_in     true  - if Table object for table to be opened should be
 
989
  linked into Session::open_tables list.
 
990
  false - placeholder used for name-locking is already in
 
991
  this list so we only need to preserve Table::next
 
992
  pointer.
 
993
 
 
994
  NOTE
 
995
  This function assumes that its caller already acquired LOCK_open mutex.
 
996
 
 
997
  RETURN VALUE
 
998
  false - Success
 
999
  true  - Error
 
1000
*/
 
1001
 
 
1002
bool Session::reopen_name_locked_table(TableList* table_list, bool link_in)
 
1003
{
 
1004
  Table *table= table_list->table;
 
1005
  TableShare *share;
 
1006
  char *table_name= table_list->table_name;
 
1007
  Table orig_table;
 
1008
 
 
1009
  safe_mutex_assert_owner(LOCK_open.native_handle());
 
1010
 
 
1011
  if (killed || !table)
 
1012
    return true;
 
1013
 
 
1014
  orig_table= *table;
 
1015
 
 
1016
  TableIdentifier identifier(table_list->db, table_list->table_name);
 
1017
  if (open_unireg_entry(this, table, table_name, identifier))
 
1018
  {
 
1019
    table->intern_close_table();
 
1020
    /*
 
1021
      If there was an error during opening of table (for example if it
 
1022
      does not exist) '*table' object can be wiped out. To be able
 
1023
      properly release name-lock in this case we should restore this
 
1024
      object to its original state.
 
1025
    */
 
1026
    *table= orig_table;
 
1027
    return true;
 
1028
  }
 
1029
 
 
1030
  share= table->getMutableShare();
 
1031
  /*
 
1032
    We want to prevent other connections from opening this table until end
 
1033
    of statement as it is likely that modifications of table's metadata are
 
1034
    not yet finished (for example CREATE TRIGGER have to change .TRG cursor,
 
1035
    or we might want to drop table if CREATE TABLE ... SELECT fails).
 
1036
    This also allows us to assume that no other connection will sneak in
 
1037
    before we will get table-level lock on this table.
 
1038
  */
 
1039
  share->resetVersion();
 
1040
  table->in_use = this;
 
1041
 
 
1042
  if (link_in)
 
1043
  {
 
1044
    table->setNext(open_tables);
 
1045
    open_tables= table;
 
1046
  }
 
1047
  else
 
1048
  {
 
1049
    /*
 
1050
      Table object should be already in Session::open_tables list so we just
 
1051
      need to set Table::next correctly.
 
1052
    */
 
1053
    table->setNext(orig_table.getNext());
 
1054
  }
 
1055
 
 
1056
  table->tablenr= current_tablenr++;
 
1057
  table->used_fields= 0;
 
1058
  table->const_table= 0;
 
1059
  table->null_row= false;
 
1060
  table->maybe_null= false;
 
1061
  table->force_index= false;
 
1062
  table->status= STATUS_NO_RECORD;
 
1063
 
 
1064
  return false;
778
1065
}
779
1066
 
780
1067
 
791
1078
  case of failure.
792
1079
*/
793
1080
 
794
 
table::Placeholder *Session::table_cache_insert_placeholder(const drizzled::TableIdentifier &arg)
 
1081
Table *Session::table_cache_insert_placeholder(const char *db_name, const char *table_name)
795
1082
{
796
 
  safe_mutex_assert_owner(table::Cache::singleton().mutex().native_handle());
 
1083
  safe_mutex_assert_owner(LOCK_open.native_handle());
797
1084
 
798
1085
  /*
799
1086
    Create a table entry with the right key and with an old refresh version
 
1087
    Note that we must use multi_malloc() here as this is freed by the
 
1088
    table cache
800
1089
  */
801
 
  TableIdentifier identifier(arg.getSchemaName(), arg.getTableName(), message::Table::INTERNAL);
802
 
  table::Placeholder *table= new table::Placeholder(this, identifier);
 
1090
  TableIdentifier identifier(db_name, table_name, message::Table::INTERNAL);
 
1091
  TablePlaceholder *table= new TablePlaceholder(this, identifier);
803
1092
 
804
 
  if (not table::Cache::singleton().insert(table))
 
1093
  if (not add_table(table))
805
1094
  {
806
1095
    delete table;
807
1096
 
833
1122
  @retval  true   Error occured (OOM)
834
1123
  @retval  false  Success. 'table' parameter set according to above rules.
835
1124
*/
836
 
bool Session::lock_table_name_if_not_cached(const TableIdentifier &identifier, Table **table)
 
1125
bool Session::lock_table_name_if_not_cached(TableIdentifier &identifier, Table **table)
837
1126
{
838
1127
  const TableIdentifier::Key &key(identifier.getKey());
839
1128
 
840
 
  boost_unique_lock_t scope_lock(table::Cache::singleton().mutex()); /* Obtain a name lock even though table is not in cache (like for create table)  */
841
 
 
842
 
  table::CacheMap::iterator iter;
843
 
 
844
 
  iter= table::getCache().find(key);
845
 
 
846
 
  if (iter != table::getCache().end())
 
1129
  LOCK_open.lock(); /* Obtain a name lock even though table is not in cache (like for create table)  */
 
1130
 
 
1131
  TableOpenCache::iterator iter;
 
1132
 
 
1133
  iter= get_open_cache().find(key);
 
1134
 
 
1135
  if (iter != get_open_cache().end())
847
1136
  {
 
1137
    LOCK_open.unlock();
848
1138
    *table= 0;
849
1139
    return false;
850
1140
  }
851
1141
 
852
 
  if (not (*table= table_cache_insert_placeholder(identifier)))
 
1142
  if (not (*table= table_cache_insert_placeholder(identifier.getSchemaName().c_str(), identifier.getTableName().c_str())))
853
1143
  {
 
1144
    LOCK_open.unlock();
854
1145
    return true;
855
1146
  }
856
1147
  (*table)->open_placeholder= true;
857
1148
  (*table)->setNext(open_tables);
858
1149
  open_tables= *table;
 
1150
  LOCK_open.unlock();
859
1151
 
860
1152
  return false;
861
1153
}
909
1201
  if (check_stack_overrun(this, STACK_MIN_SIZE_FOR_OPEN, (unsigned char *)&alias))
910
1202
    return NULL;
911
1203
 
912
 
  if (getKilled())
 
1204
  if (killed)
913
1205
    return NULL;
914
1206
 
915
 
  TableIdentifier identifier(table_list->getSchemaName(), table_list->getTableName());
 
1207
  TableIdentifier identifier(table_list->db, table_list->table_name);
916
1208
  const TableIdentifier::Key &key(identifier.getKey());
917
 
  table::CacheRange ppp;
 
1209
  TableOpenCacheRange ppp;
918
1210
 
919
1211
  /*
920
1212
    Unless requested otherwise, try to resolve this table in the list
923
1215
    same name. This block implements the behaviour.
924
1216
    TODO -> move this block into a separate function.
925
1217
  */
926
 
  bool reset= false;
927
 
  for (table= getTemporaryTables(); table ; table=table->getNext())
 
1218
  for (table= temporary_tables; table ; table=table->getNext())
928
1219
  {
929
1220
    if (table->getShare()->getCacheKey() == key)
930
1221
    {
940
1231
        return NULL;
941
1232
      }
942
1233
      table->query_id= getQueryId();
943
 
      reset= true;
 
1234
      goto reset;
 
1235
    }
 
1236
  }
 
1237
 
 
1238
  if (flags & DRIZZLE_OPEN_TEMPORARY_ONLY)
 
1239
  {
 
1240
    my_error(ER_NO_SUCH_TABLE, MYF(0), table_list->db, table_list->table_name);
 
1241
    return NULL;
 
1242
  }
 
1243
 
 
1244
  /*
 
1245
    If it's the first table from a list of tables used in a query,
 
1246
    remember refresh_version (the version of open_cache state).
 
1247
    If the version changes while we're opening the remaining tables,
 
1248
    we will have to back off, close all the tables opened-so-far,
 
1249
    and try to reopen them.
 
1250
 
 
1251
    Note-> refresh_version is currently changed only during FLUSH TABLES.
 
1252
  */
 
1253
  if (!open_tables)
 
1254
  {
 
1255
    version= refresh_version;
 
1256
  }
 
1257
  else if ((version != refresh_version) &&
 
1258
           ! (flags & DRIZZLE_LOCK_IGNORE_FLUSH))
 
1259
  {
 
1260
    /* Someone did a refresh while thread was opening tables */
 
1261
    if (refresh)
 
1262
      *refresh= true;
 
1263
 
 
1264
    return NULL;
 
1265
  }
 
1266
 
 
1267
  /*
 
1268
    Before we test the global cache, we test our local session cache.
 
1269
  */
 
1270
  if (cached_table)
 
1271
  {
 
1272
    assert(false); /* Not implemented yet */
 
1273
  }
 
1274
 
 
1275
  /*
 
1276
    Non pre-locked/LOCK TABLES mode, and the table is not temporary:
 
1277
    this is the normal use case.
 
1278
    Now we should:
 
1279
    - try to find the table in the table cache.
 
1280
    - if one of the discovered Table instances is name-locked
 
1281
    (table->getShare()->version == 0) back off -- we have to wait
 
1282
    until no one holds a name lock on the table.
 
1283
    - if there is no such Table in the name cache, read the table definition
 
1284
    and insert it into the cache.
 
1285
    We perform all of the above under LOCK_open which currently protects
 
1286
    the open cache (also known as table cache) and table definitions stored
 
1287
    on disk.
 
1288
  */
 
1289
 
 
1290
  LOCK_open.lock(); /* Lock for FLUSH TABLES for open table */
 
1291
 
 
1292
  /*
 
1293
    Actually try to find the table in the open_cache.
 
1294
    The cache may contain several "Table" instances for the same
 
1295
    physical table. The instances that are currently "in use" by
 
1296
    some thread have their "in_use" member != NULL.
 
1297
    There is no good reason for having more than one entry in the
 
1298
    hash for the same physical table, except that we use this as
 
1299
    an implicit "pending locks queue" - see
 
1300
    wait_for_locked_table_names for details.
 
1301
  */
 
1302
  ppp= get_open_cache().equal_range(key);
 
1303
 
 
1304
  table= NULL;
 
1305
  for (TableOpenCache::const_iterator iter= ppp.first;
 
1306
       iter != ppp.second; ++iter, table= NULL)
 
1307
  {
 
1308
    table= (*iter).second;
 
1309
 
 
1310
    if (not table->in_use)
944
1311
      break;
945
 
    }
946
 
  }
947
 
 
948
 
  if (not reset)
949
 
  {
950
 
    if (flags & DRIZZLE_OPEN_TEMPORARY_ONLY)
951
 
    {
952
 
      my_error(ER_NO_SUCH_TABLE, MYF(0), table_list->getSchemaName(), table_list->getTableName());
953
 
      return NULL;
954
 
    }
955
 
 
956
1312
    /*
957
 
      If it's the first table from a list of tables used in a query,
958
 
      remember refresh_version (the version of open_cache state).
959
 
      If the version changes while we're opening the remaining tables,
960
 
      we will have to back off, close all the tables opened-so-far,
961
 
      and try to reopen them.
962
 
 
963
 
      Note-> refresh_version is currently changed only during FLUSH TABLES.
 
1313
      Here we flush tables marked for flush.
 
1314
      Normally, table->getShare()->version contains the value of
 
1315
      refresh_version from the moment when this table was
 
1316
      (re-)opened and added to the cache.
 
1317
      If since then we did (or just started) FLUSH TABLES
 
1318
      statement, refresh_version has been increased.
 
1319
      For "name-locked" Table instances, table->getShare()->version is set
 
1320
      to 0 (see lock_table_name for details).
 
1321
      In case there is a pending FLUSH TABLES or a name lock, we
 
1322
      need to back off and re-start opening tables.
 
1323
      If we do not back off now, we may dead lock in case of lock
 
1324
      order mismatch with some other thread:
 
1325
      c1-> name lock t1; -- sort of exclusive lock
 
1326
      c2-> open t2;      -- sort of shared lock
 
1327
      c1-> name lock t2; -- blocks
 
1328
      c2-> open t1; -- blocks
964
1329
    */
965
 
    if (!open_tables)
966
 
    {
967
 
      version= refresh_version;
968
 
    }
969
 
    else if ((version != refresh_version) &&
970
 
             ! (flags & DRIZZLE_LOCK_IGNORE_FLUSH))
971
 
    {
972
 
      /* Someone did a refresh while thread was opening tables */
 
1330
    if (table->needs_reopen_or_name_lock())
 
1331
    {
 
1332
      if (flags & DRIZZLE_LOCK_IGNORE_FLUSH)
 
1333
      {
 
1334
        /* Force close at once after usage */
 
1335
        version= table->getShare()->getVersion();
 
1336
        continue;
 
1337
      }
 
1338
 
 
1339
      /* Avoid self-deadlocks by detecting self-dependencies. */
 
1340
      if (table->open_placeholder && table->in_use == this)
 
1341
      {
 
1342
        LOCK_open.unlock();
 
1343
        my_error(ER_UPDATE_TABLE_USED, MYF(0), table->getMutableShare()->getTableName());
 
1344
        return NULL;
 
1345
      }
 
1346
 
 
1347
      /*
 
1348
        Back off, part 1: mark the table as "unused" for the
 
1349
        purpose of name-locking by setting table->db_stat to 0. Do
 
1350
        that only for the tables in this thread that have an old
 
1351
        table->getShare()->version (this is an optimization (?)).
 
1352
        table->db_stat == 0 signals wait_for_locked_table_names
 
1353
        that the tables in question are not used any more. See
 
1354
        table_is_used call for details.
 
1355
      */
 
1356
      close_old_data_files(false, false);
 
1357
 
 
1358
      /*
 
1359
        Back-off part 2: try to avoid "busy waiting" on the table:
 
1360
        if the table is in use by some other thread, we suspend
 
1361
        and wait till the operation is complete: when any
 
1362
        operation that juggles with table->getShare()->version completes,
 
1363
        it broadcasts COND_refresh condition variable.
 
1364
        If 'old' table we met is in use by current thread we return
 
1365
        without waiting since in this situation it's this thread
 
1366
        which is responsible for broadcasting on COND_refresh
 
1367
        (and this was done already in Session::close_old_data_files()).
 
1368
        Good example of such situation is when we have statement
 
1369
        that needs two instances of table and FLUSH TABLES comes
 
1370
        after we open first instance but before we open second
 
1371
        instance.
 
1372
      */
 
1373
      if (table->in_use != this)
 
1374
      {
 
1375
        /* wait_for_conditionwill unlock LOCK_open for us */
 
1376
        wait_for_condition(LOCK_open, COND_refresh);
 
1377
      }
 
1378
      else
 
1379
      {
 
1380
        LOCK_open.unlock();
 
1381
      }
 
1382
      /*
 
1383
        There is a refresh in progress for this table.
 
1384
        Signal the caller that it has to try again.
 
1385
      */
973
1386
      if (refresh)
974
1387
        *refresh= true;
975
 
 
976
1388
      return NULL;
977
1389
    }
978
 
 
979
 
    /*
980
 
      Before we test the global cache, we test our local session cache.
981
 
    */
982
 
    if (cached_table)
983
 
    {
984
 
      assert(false); /* Not implemented yet */
985
 
    }
986
 
 
987
 
    /*
988
 
      Non pre-locked/LOCK TABLES mode, and the table is not temporary:
989
 
      this is the normal use case.
990
 
      Now we should:
991
 
      - try to find the table in the table cache.
992
 
      - if one of the discovered Table instances is name-locked
993
 
      (table->getShare()->version == 0) back off -- we have to wait
994
 
      until no one holds a name lock on the table.
995
 
      - if there is no such Table in the name cache, read the table definition
996
 
      and insert it into the cache.
997
 
      We perform all of the above under table::Cache::singleton().mutex() which currently protects
998
 
      the open cache (also known as table cache) and table definitions stored
999
 
      on disk.
1000
 
    */
1001
 
 
1002
 
    {
1003
 
      table::Cache::singleton().mutex().lock(); /* Lock for FLUSH TABLES for open table */
1004
 
 
1005
 
      /*
1006
 
        Actually try to find the table in the open_cache.
1007
 
        The cache may contain several "Table" instances for the same
1008
 
        physical table. The instances that are currently "in use" by
1009
 
        some thread have their "in_use" member != NULL.
1010
 
        There is no good reason for having more than one entry in the
1011
 
        hash for the same physical table, except that we use this as
1012
 
        an implicit "pending locks queue" - see
1013
 
        wait_for_locked_table_names for details.
1014
 
      */
1015
 
      ppp= table::getCache().equal_range(key);
1016
 
 
1017
 
      table= NULL;
1018
 
      for (table::CacheMap::const_iterator iter= ppp.first;
1019
 
           iter != ppp.second; ++iter, table= NULL)
 
1390
  }
 
1391
  if (table)
 
1392
  {
 
1393
    unused_tables.unlink(table);
 
1394
    table->in_use= this;
 
1395
  }
 
1396
  else
 
1397
  {
 
1398
    /* Insert a new Table instance into the open cache */
 
1399
    int error;
 
1400
    /* Free cache if too big */
 
1401
    unused_tables.cull();
 
1402
 
 
1403
    if (table_list->isCreate())
 
1404
    {
 
1405
      TableIdentifier  lock_table_identifier(table_list->db, table_list->table_name, message::Table::STANDARD);
 
1406
 
 
1407
      if (not plugin::StorageEngine::doesTableExist(*this, lock_table_identifier))
1020
1408
      {
1021
 
        table= (*iter).second;
1022
 
 
1023
 
        if (not table->in_use)
1024
 
          break;
1025
1409
        /*
1026
 
          Here we flush tables marked for flush.
1027
 
          Normally, table->getShare()->version contains the value of
1028
 
          refresh_version from the moment when this table was
1029
 
          (re-)opened and added to the cache.
1030
 
          If since then we did (or just started) FLUSH TABLES
1031
 
          statement, refresh_version has been increased.
1032
 
          For "name-locked" Table instances, table->getShare()->version is set
1033
 
          to 0 (see lock_table_name for details).
1034
 
          In case there is a pending FLUSH TABLES or a name lock, we
1035
 
          need to back off and re-start opening tables.
1036
 
          If we do not back off now, we may dead lock in case of lock
1037
 
          order mismatch with some other thread:
1038
 
          c1-> name lock t1; -- sort of exclusive lock
1039
 
          c2-> open t2;      -- sort of shared lock
1040
 
          c1-> name lock t2; -- blocks
1041
 
          c2-> open t1; -- blocks
 
1410
          Table to be created, so we need to create placeholder in table-cache.
1042
1411
        */
1043
 
        if (table->needs_reopen_or_name_lock())
 
1412
        if (!(table= table_cache_insert_placeholder(table_list->db, table_list->table_name)))
1044
1413
        {
1045
 
          if (flags & DRIZZLE_LOCK_IGNORE_FLUSH)
1046
 
          {
1047
 
            /* Force close at once after usage */
1048
 
            version= table->getShare()->getVersion();
1049
 
            continue;
1050
 
          }
1051
 
 
1052
 
          /* Avoid self-deadlocks by detecting self-dependencies. */
1053
 
          if (table->open_placeholder && table->in_use == this)
1054
 
          {
1055
 
            table::Cache::singleton().mutex().unlock();
1056
 
            my_error(ER_UPDATE_TABLE_USED, MYF(0), table->getShare()->getTableName());
1057
 
            return NULL;
1058
 
          }
1059
 
 
1060
 
          /*
1061
 
            Back off, part 1: mark the table as "unused" for the
1062
 
            purpose of name-locking by setting table->db_stat to 0. Do
1063
 
            that only for the tables in this thread that have an old
1064
 
            table->getShare()->version (this is an optimization (?)).
1065
 
            table->db_stat == 0 signals wait_for_locked_table_names
1066
 
            that the tables in question are not used any more. See
1067
 
            table_is_used call for details.
1068
 
          */
1069
 
          close_old_data_files(false, false);
1070
 
 
1071
 
          /*
1072
 
            Back-off part 2: try to avoid "busy waiting" on the table:
1073
 
            if the table is in use by some other thread, we suspend
1074
 
            and wait till the operation is complete: when any
1075
 
            operation that juggles with table->getShare()->version completes,
1076
 
            it broadcasts COND_refresh condition variable.
1077
 
            If 'old' table we met is in use by current thread we return
1078
 
            without waiting since in this situation it's this thread
1079
 
            which is responsible for broadcasting on COND_refresh
1080
 
            (and this was done already in Session::close_old_data_files()).
1081
 
            Good example of such situation is when we have statement
1082
 
            that needs two instances of table and FLUSH TABLES comes
1083
 
            after we open first instance but before we open second
1084
 
            instance.
1085
 
          */
1086
 
          if (table->in_use != this)
1087
 
          {
1088
 
            /* wait_for_conditionwill unlock table::Cache::singleton().mutex() for us */
1089
 
            wait_for_condition(table::Cache::singleton().mutex(), COND_refresh);
1090
 
          }
1091
 
          else
1092
 
          {
1093
 
            table::Cache::singleton().mutex().unlock();
1094
 
          }
1095
 
          /*
1096
 
            There is a refresh in progress for this table.
1097
 
            Signal the caller that it has to try again.
1098
 
          */
1099
 
          if (refresh)
1100
 
            *refresh= true;
 
1414
          LOCK_open.unlock();
1101
1415
          return NULL;
1102
1416
        }
1103
 
      }
1104
 
      if (table)
1105
 
      {
1106
 
        table::getUnused().unlink(static_cast<table::Concurrent *>(table));
1107
 
        table->in_use= this;
1108
 
      }
1109
 
      else
1110
 
      {
1111
 
        /* Insert a new Table instance into the open cache */
1112
 
        int error;
1113
 
        /* Free cache if too big */
1114
 
        table::getUnused().cull();
1115
 
 
1116
 
        if (table_list->isCreate())
1117
 
        {
1118
 
          TableIdentifier  lock_table_identifier(table_list->getSchemaName(), table_list->getTableName(), message::Table::STANDARD);
1119
 
 
1120
 
          if (not plugin::StorageEngine::doesTableExist(*this, lock_table_identifier))
1121
 
          {
1122
 
            /*
1123
 
              Table to be created, so we need to create placeholder in table-cache.
1124
 
            */
1125
 
            if (!(table= table_cache_insert_placeholder(lock_table_identifier)))
1126
 
            {
1127
 
              table::Cache::singleton().mutex().unlock();
1128
 
              return NULL;
1129
 
            }
1130
 
            /*
1131
 
              Link placeholder to the open tables list so it will be automatically
1132
 
              removed once tables are closed. Also mark it so it won't be ignored
1133
 
              by other trying to take name-lock.
1134
 
            */
1135
 
            table->open_placeholder= true;
1136
 
            table->setNext(open_tables);
1137
 
            open_tables= table;
1138
 
            table::Cache::singleton().mutex().unlock();
1139
 
 
1140
 
            return table ;
1141
 
          }
1142
 
          /* Table exists. Let us try to open it. */
1143
 
        }
1144
 
 
1145
 
        /* make a new table */
1146
 
        {
1147
 
          table::Concurrent *new_table= new table::Concurrent;
1148
 
          table= new_table;
1149
 
          if (new_table == NULL)
1150
 
          {
1151
 
            table::Cache::singleton().mutex().unlock();
1152
 
            return NULL;
1153
 
          }
1154
 
 
1155
 
          error= new_table->open_unireg_entry(this, alias, identifier);
1156
 
          if (error != 0)
1157
 
          {
1158
 
            delete new_table;
1159
 
            table::Cache::singleton().mutex().unlock();
1160
 
            return NULL;
1161
 
          }
1162
 
          (void)table::Cache::singleton().insert(new_table);
1163
 
        }
1164
 
      }
1165
 
 
1166
 
      table::Cache::singleton().mutex().unlock();
1167
 
    }
1168
 
    if (refresh)
1169
 
    {
1170
 
      table->setNext(open_tables); /* Link into simple list */
1171
 
      open_tables= table;
1172
 
    }
1173
 
    table->reginfo.lock_type= TL_READ; /* Assume read */
1174
 
 
1175
 
  }
 
1417
        /*
 
1418
          Link placeholder to the open tables list so it will be automatically
 
1419
          removed once tables are closed. Also mark it so it won't be ignored
 
1420
          by other trying to take name-lock.
 
1421
        */
 
1422
        table->open_placeholder= true;
 
1423
        table->setNext(open_tables);
 
1424
        open_tables= table;
 
1425
        LOCK_open.unlock();
 
1426
 
 
1427
        return table ;
 
1428
      }
 
1429
      /* Table exists. Let us try to open it. */
 
1430
    }
 
1431
 
 
1432
    /* make a new table */
 
1433
    table= new Table;
 
1434
    if (table == NULL)
 
1435
    {
 
1436
      LOCK_open.unlock();
 
1437
      return NULL;
 
1438
    }
 
1439
 
 
1440
    error= open_unireg_entry(this, table, alias, identifier);
 
1441
    if (error != 0)
 
1442
    {
 
1443
      delete table;
 
1444
      LOCK_open.unlock();
 
1445
      return NULL;
 
1446
    }
 
1447
    (void)add_table(table);
 
1448
  }
 
1449
 
 
1450
  LOCK_open.unlock();
 
1451
  if (refresh)
 
1452
  {
 
1453
    table->setNext(open_tables); /* Link into simple list */
 
1454
    open_tables= table;
 
1455
  }
 
1456
  table->reginfo.lock_type= TL_READ; /* Assume read */
 
1457
 
 
1458
reset:
1176
1459
  assert(table->getShare()->getTableCount() > 0 || table->getShare()->getType() != message::Table::STANDARD);
1177
1460
 
 
1461
  if (lex->need_correct_ident())
 
1462
    table->alias_name_used= my_strcasecmp(table_alias_charset,
 
1463
                                          table->getMutableShare()->getTableName(), alias);
1178
1464
  /* Fix alias if table name changes */
1179
1465
  if (strcmp(table->getAlias(), alias))
1180
1466
  {
1181
 
    table->setAlias(alias);
 
1467
    uint32_t length=(uint32_t) strlen(alias)+1;
 
1468
    table->alias= (char*) realloc((char*) table->alias, length);
 
1469
    memcpy((void*) table->alias, alias, length);
1182
1470
  }
1183
1471
 
1184
1472
  /* These variables are also set in reopen_table() */
1205
1493
}
1206
1494
 
1207
1495
 
 
1496
#if 0
 
1497
/*
 
1498
  Reopen an table because the definition has changed.
 
1499
 
 
1500
  SYNOPSIS
 
1501
  reopen_table()
 
1502
  table Table object
 
1503
 
 
1504
  NOTES
 
1505
  The data cursor for the table is already closed and the share is released
 
1506
  The table has a 'dummy' share that mainly contains database and table name.
 
1507
 
 
1508
  RETURN
 
1509
  0  ok
 
1510
  1  error. The old table object is not changed.
 
1511
*/
 
1512
 
 
1513
bool reopen_table(Table *table)
 
1514
{
 
1515
  Table tmp;
 
1516
  bool error= 1;
 
1517
  Field **field;
 
1518
  uint32_t key,part;
 
1519
  TableList table_list;
 
1520
  Session *session= table->in_use;
 
1521
 
 
1522
  assert(table->getShare()->ref_count == 0);
 
1523
  assert(!table->sort.io_cache);
 
1524
 
 
1525
#ifdef EXTRA_DEBUG
 
1526
  if (table->db_stat)
 
1527
    errmsg_printf(ERRMSG_LVL_ERROR, _("Table %s had a open data Cursor in reopen_table"),
 
1528
                  table->alias);
 
1529
#endif
 
1530
  table_list.db=         const_cast<char *>(table->getShare()->getSchemaName());
 
1531
  table_list.table_name= table->getShare()->getTableName();
 
1532
  table_list.table=      table;
 
1533
 
 
1534
  if (wait_for_locked_table_names(session, &table_list))
 
1535
    return true;                             // Thread was killed
 
1536
 
 
1537
  if (open_unireg_entry(session, &tmp, &table_list,
 
1538
                        table->alias,
 
1539
                        table->getShare()->getCacheKey(),
 
1540
                        table->getShare()->getCacheKeySize()))
 
1541
    goto end;
 
1542
 
 
1543
  /* This list copies variables set by open_table */
 
1544
  tmp.tablenr=          table->tablenr;
 
1545
  tmp.used_fields=      table->used_fields;
 
1546
  tmp.const_table=      table->const_table;
 
1547
  tmp.null_row=         table->null_row;
 
1548
  tmp.maybe_null=       table->maybe_null;
 
1549
  tmp.status=           table->status;
 
1550
 
 
1551
  /* Get state */
 
1552
  tmp.in_use=           session;
 
1553
  tmp.reginfo.lock_type=table->reginfo.lock_type;
 
1554
 
 
1555
  /* Replace table in open list */
 
1556
  tmp.next=             table->next;
 
1557
  tmp.prev=             table->prev;
 
1558
 
 
1559
  if (table->cursor)
 
1560
    table->delete_table(true);          // close cursor, free everything
 
1561
 
 
1562
  *table= tmp;
 
1563
  table->default_column_bitmaps();
 
1564
  table->cursor->change_table_ptr(table, table->s);
 
1565
 
 
1566
  assert(table->alias != 0);
 
1567
  for (field=table->field ; *field ; field++)
 
1568
  {
 
1569
    (*field)->table= (*field)->orig_table= table;
 
1570
    (*field)->table_name= &table->alias;
 
1571
  }
 
1572
  for (key=0 ; key < table->getShare()->keys ; key++)
 
1573
  {
 
1574
    for (part=0 ; part < table->key_info[key].usable_key_parts ; part++)
 
1575
      table->key_info[key].key_part[part].field->table= table;
 
1576
  }
 
1577
 
 
1578
  broadcast_refresh();
 
1579
  error= false;
 
1580
 
 
1581
end:
 
1582
  return(error);
 
1583
}
 
1584
#endif
 
1585
 
 
1586
 
1208
1587
/**
1209
1588
  Close all instances of a table open by this thread and replace
1210
1589
  them with exclusive name-locks.
1222
1601
  the strings are used in a loop even after the share may be freed.
1223
1602
*/
1224
1603
 
1225
 
void Session::close_data_files_and_morph_locks(const TableIdentifier &identifier)
 
1604
void Session::close_data_files_and_morph_locks(TableIdentifier &identifier)
1226
1605
{
1227
 
  safe_mutex_assert_owner(table::Cache::singleton().mutex().native_handle()); /* Adjust locks at the end of ALTER TABLEL */
 
1606
  safe_mutex_assert_owner(LOCK_open.native_handle()); /* Adjust locks at the end of ALTER TABLEL */
1228
1607
 
1229
1608
  if (lock)
1230
1609
  {
1232
1611
      If we are not under LOCK TABLES we should have only one table
1233
1612
      open and locked so it makes sense to remove the lock at once.
1234
1613
    */
1235
 
    unlockTables(lock);
 
1614
    mysql_unlock_tables(this, lock);
1236
1615
    lock= 0;
1237
1616
  }
1238
1617
 
1267
1646
  combination when one needs tables to be reopened (for
1268
1647
  example see openTablesLock()).
1269
1648
 
1270
 
  @note One should have lock on table::Cache::singleton().mutex() when calling this.
 
1649
  @note One should have lock on LOCK_open when calling this.
1271
1650
 
1272
1651
  @return false in case of success, true - otherwise.
1273
1652
*/
1284
1663
  if (open_tables == NULL)
1285
1664
    return false;
1286
1665
 
1287
 
  safe_mutex_assert_owner(table::Cache::singleton().mutex().native_handle());
 
1666
  safe_mutex_assert_owner(LOCK_open.native_handle());
1288
1667
  if (get_locks)
1289
1668
  {
1290
1669
    /*
1311
1690
    next= table->getNext();
1312
1691
 
1313
1692
    my_error(ER_CANT_REOPEN_TABLE, MYF(0), table->getAlias());
1314
 
    table::remove_table(static_cast<table::Concurrent *>(table));
 
1693
    remove_table(table);
1315
1694
    error= 1;
1316
1695
  }
1317
1696
  *prev=0;
1320
1699
    DrizzleLock *local_lock;
1321
1700
    /*
1322
1701
      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
 
1702
      wait_for_tables() as it tries to acquire LOCK_open, which is
1324
1703
      already locked.
1325
1704
    */
1326
1705
    some_tables_deleted= false;
1327
1706
 
1328
 
    if ((local_lock= lockTables(tables, (uint32_t) (tables_ptr - tables),
1329
 
                                       flags, &not_used)))
 
1707
    if ((local_lock= mysql_lock_tables(this, tables, (uint32_t) (tables_ptr - tables),
 
1708
                                 flags, &not_used)))
1330
1709
    {
1331
1710
      /* unused */
1332
1711
    }
1345
1724
  if (get_locks && tables)
1346
1725
    delete [] tables;
1347
1726
 
1348
 
  locking::broadcast_refresh();
 
1727
  broadcast_refresh();
1349
1728
 
1350
1729
  return(error);
1351
1730
}
1392
1771
              lock on it. This will also give them a chance to close their
1393
1772
              instances of this table.
1394
1773
            */
1395
 
            abortLock(ulcktbl);
1396
 
            removeLock(ulcktbl);
 
1774
            mysql_lock_abort(this, ulcktbl);
 
1775
            mysql_lock_remove(this, ulcktbl);
1397
1776
            ulcktbl->lock_count= 0;
1398
1777
          }
1399
1778
          if ((ulcktbl != table) && ulcktbl->db_stat)
1433
1812
    }
1434
1813
  }
1435
1814
  if (found)
1436
 
    locking::broadcast_refresh();
 
1815
    broadcast_refresh();
 
1816
}
 
1817
 
 
1818
 
 
1819
/*
 
1820
  Wait until all threads has closed the tables in the list
 
1821
  We have also to wait if there is thread that has a lock on this table even
 
1822
  if the table is closed
 
1823
*/
 
1824
 
 
1825
bool table_is_used(Table *table, bool wait_for_name_lock)
 
1826
{
 
1827
  do
 
1828
  {
 
1829
    const TableIdentifier::Key &key(table->getShare()->getCacheKey());
 
1830
 
 
1831
    TableOpenCacheRange ppp;
 
1832
    ppp= get_open_cache().equal_range(key);
 
1833
 
 
1834
    for (TableOpenCache::const_iterator iter= ppp.first;
 
1835
         iter != ppp.second; ++iter)
 
1836
    {
 
1837
      Table *search= (*iter).second;
 
1838
      if (search->in_use == table->in_use)
 
1839
        continue;                               // Name locked by this thread
 
1840
      /*
 
1841
        We can't use the table under any of the following conditions:
 
1842
        - There is an name lock on it (Table is to be deleted or altered)
 
1843
        - If we are in flush table and we didn't execute the flush
 
1844
        - If the table engine is open and it's an old version
 
1845
        (We must wait until all engines are shut down to use the table)
 
1846
      */
 
1847
      if ( (search->locked_by_name && wait_for_name_lock) ||
 
1848
           (search->is_name_opened() && search->needs_reopen_or_name_lock()))
 
1849
        return 1;
 
1850
    }
 
1851
  } while ((table=table->getNext()));
 
1852
  return 0;
1437
1853
}
1438
1854
 
1439
1855
 
1444
1860
  bool result;
1445
1861
 
1446
1862
  session->set_proc_info("Waiting for tables");
1447
 
  {
1448
 
    boost_unique_lock_t lock(table::Cache::singleton().mutex());
1449
 
    while (not session->getKilled())
1450
 
    {
1451
 
      session->some_tables_deleted= false;
1452
 
      session->close_old_data_files(false, dropping_tables != 0);
1453
 
      if (not table::Cache::singleton().areTablesUsed(session->open_tables, 1))
1454
 
      {
1455
 
        break;
1456
 
      }
1457
 
      COND_refresh.wait(lock);
1458
 
    }
1459
 
    if (session->getKilled())
1460
 
      result= true;                                     // aborted
1461
 
    else
1462
 
    {
1463
 
      /* Now we can open all tables without any interference */
1464
 
      session->set_proc_info("Reopen tables");
1465
 
      session->version= refresh_version;
1466
 
      result= session->reopen_tables(false, false);
1467
 
    }
1468
 
  }
 
1863
  LOCK_open.lock(); /* Lock for all tables to be refreshed */
 
1864
  while (!session->killed)
 
1865
  {
 
1866
    session->some_tables_deleted= false;
 
1867
    session->close_old_data_files(false, dropping_tables != 0);
 
1868
    if (!table_is_used(session->open_tables, 1))
 
1869
      break;
 
1870
    (void) pthread_cond_wait(COND_refresh.native_handle(),LOCK_open.native_handle());
 
1871
  }
 
1872
  if (session->killed)
 
1873
    result= true;                                       // aborted
 
1874
  else
 
1875
  {
 
1876
    /* Now we can open all tables without any interference */
 
1877
    session->set_proc_info("Reopen tables");
 
1878
    session->version= refresh_version;
 
1879
    result= session->reopen_tables(false, false);
 
1880
  }
 
1881
  LOCK_open.unlock();
1469
1882
  session->set_proc_info(0);
1470
1883
 
1471
1884
  return result;
1502
1915
  prev= &session->open_tables;
1503
1916
 
1504
1917
  /*
1505
 
    Note that we need to hold table::Cache::singleton().mutex() while changing the
 
1918
    Note that we need to hold LOCK_open while changing the
1506
1919
    open_tables list. Another thread may work on it.
1507
 
    (See: table::Cache::singleton().removeTable(), mysql_wait_completed_table())
 
1920
    (See: remove_table_from_cache(), mysql_wait_completed_table())
1508
1921
    Closing a MERGE child before the parent would be fatal if the
1509
1922
    other thread tries to abort the MERGE lock in between.
1510
1923
  */
1513
1926
    next=table->getNext();
1514
1927
    if (table->getShare()->getCacheKey() == identifier.getKey())
1515
1928
    {
1516
 
      session->removeLock(table);
 
1929
      mysql_lock_remove(session, table);
1517
1930
 
1518
1931
      if (!found)
1519
1932
      {
1528
1941
      else
1529
1942
      {
1530
1943
        /* We already have a name lock, remove copy */
1531
 
        table::remove_table(static_cast<table::Concurrent *>(table));
 
1944
        remove_table(table);
1532
1945
      }
1533
1946
    }
1534
1947
    else
1539
1952
  }
1540
1953
  *prev=0;
1541
1954
  if (found)
1542
 
    locking::broadcast_refresh();
 
1955
    broadcast_refresh();
1543
1956
 
1544
1957
  return(found);
1545
1958
}
1559
1972
    if (table->getShare()->getCacheKey() == identifier.getKey())
1560
1973
    {
1561
1974
      /* If MERGE child, forward lock handling to parent. */
1562
 
      session->abortLock(table);
 
1975
      mysql_lock_abort(session, table);
1563
1976
      break;
1564
1977
    }
1565
1978
  }
1566
1979
}
1567
1980
 
 
1981
/*
 
1982
  Load a table definition from cursor and open unireg table
 
1983
 
 
1984
  SYNOPSIS
 
1985
  open_unireg_entry()
 
1986
  session                       Thread handle
 
1987
  entry         Store open table definition here
 
1988
  table_list            TableList with db, table_name
 
1989
  alias         Alias name
 
1990
  cache_key             Key for share_cache
 
1991
  cache_key_length      length of cache_key
 
1992
 
 
1993
  NOTES
 
1994
  Extra argument for open is taken from session->open_options
 
1995
  One must have a lock on LOCK_open when calling this function
 
1996
 
 
1997
  RETURN
 
1998
  0     ok
 
1999
#       Error
 
2000
*/
 
2001
 
 
2002
static int open_unireg_entry(Session *session,
 
2003
                             Table *entry,
 
2004
                             const char *alias,
 
2005
                             TableIdentifier &identifier)
 
2006
{
 
2007
  int error;
 
2008
  TableShare *share;
 
2009
  uint32_t discover_retry_count= 0;
 
2010
 
 
2011
  safe_mutex_assert_owner(LOCK_open.native_handle());
 
2012
retry:
 
2013
  if (not (share= TableShare::getShareCreate(session,
 
2014
                                             identifier,
 
2015
                                             &error)))
 
2016
    return 1;
 
2017
 
 
2018
  while ((error= share->open_table_from_share(session,
 
2019
                                              identifier,
 
2020
                                              alias,
 
2021
                                              (uint32_t) (HA_OPEN_KEYFILE |
 
2022
                                                          HA_OPEN_RNDFILE |
 
2023
                                                          HA_GET_INDEX |
 
2024
                                                          HA_TRY_READ_ONLY),
 
2025
                                              session->open_options, *entry)))
 
2026
  {
 
2027
    if (error == 7)                             // Table def changed
 
2028
    {
 
2029
      share->resetVersion();                        // Mark share as old
 
2030
      if (discover_retry_count++)               // Retry once
 
2031
        goto err;
 
2032
 
 
2033
      /*
 
2034
        TODO->
 
2035
        Here we should wait until all threads has released the table.
 
2036
        For now we do one retry. This may cause a deadlock if there
 
2037
        is other threads waiting for other tables used by this thread.
 
2038
 
 
2039
        Proper fix would be to if the second retry failed:
 
2040
        - Mark that table def changed
 
2041
        - Return from open table
 
2042
        - Close all tables used by this thread
 
2043
        - Start waiting that the share is released
 
2044
        - Retry by opening all tables again
 
2045
      */
 
2046
 
 
2047
      /*
 
2048
        TO BE FIXED
 
2049
        To avoid deadlock, only wait for release if no one else is
 
2050
        using the share.
 
2051
      */
 
2052
      if (share->getTableCount() != 1)
 
2053
        goto err;
 
2054
      /* Free share and wait until it's released by all threads */
 
2055
      TableShare::release(share);
 
2056
 
 
2057
      if (!session->killed)
 
2058
      {
 
2059
        drizzle_reset_errors(session, 1);         // Clear warnings
 
2060
        session->clear_error();                 // Clear error message
 
2061
        goto retry;
 
2062
      }
 
2063
      return 1;
 
2064
    }
 
2065
 
 
2066
    goto err;
 
2067
  }
 
2068
 
 
2069
  return 0;
 
2070
 
 
2071
err:
 
2072
  TableShare::release(share);
 
2073
 
 
2074
  return 1;
 
2075
}
 
2076
 
1568
2077
 
1569
2078
/*
1570
2079
  Open all tables in list
1632
2141
     * to see if it exists so that an unauthorized user cannot phish for
1633
2142
     * table/schema information via error messages
1634
2143
     */
1635
 
    TableIdentifier the_table(tables->getSchemaName(), tables->getTableName());
 
2144
    TableIdentifier the_table(tables->db, tables->table_name);
1636
2145
    if (not plugin::Authorization::isAuthorized(getSecurityContext(),
1637
2146
                                                the_table))
1638
2147
    {
1742
2251
 
1743
2252
    assert(lock == 0);  // You must lock everything at once
1744
2253
    if ((table->reginfo.lock_type= lock_type) != TL_UNLOCK)
1745
 
      if (! (lock= lockTables(&table_list->table, 1, 0, &refresh)))
 
2254
      if (! (lock= mysql_lock_tables(this, &table_list->table, 1, 0, &refresh)))
1746
2255
        table= 0;
1747
2256
  }
1748
2257
 
1805
2314
      *(ptr++)= table->table;
1806
2315
  }
1807
2316
 
1808
 
  if (!(session->lock= session->lockTables(start, (uint32_t) (ptr - start), lock_flag, need_reopen)))
 
2317
  if (!(session->lock= mysql_lock_tables(session, start, (uint32_t) (ptr - start),
 
2318
                                         lock_flag, need_reopen)))
1809
2319
  {
1810
2320
    return -1;
1811
2321
  }
1834
2344
#  Table object
1835
2345
*/
1836
2346
 
1837
 
Table *Open_tables_state::open_temporary_table(const TableIdentifier &identifier,
1838
 
                                               bool link_in_list)
 
2347
Table *Session::open_temporary_table(TableIdentifier &identifier,
 
2348
                                     bool link_in_list)
1839
2349
{
 
2350
  TableShare *share;
 
2351
 
1840
2352
  assert(identifier.isTmp());
1841
 
 
1842
 
 
1843
 
  table::Temporary *new_tmp_table= new table::Temporary(identifier.getType(),
1844
 
                                                        identifier,
1845
 
                                                        const_cast<char *>(const_cast<TableIdentifier&>(identifier).getPath().c_str()),
1846
 
                                                        static_cast<uint32_t>(identifier.getPath().length()));
 
2353
  share= new TableShare(identifier.getType(),
 
2354
                        identifier,
 
2355
                        const_cast<char *>(identifier.getPath().c_str()), static_cast<uint32_t>(identifier.getPath().length()));
 
2356
 
 
2357
 
 
2358
  Table *new_tmp_table= new Table;
1847
2359
  if (not new_tmp_table)
1848
2360
    return NULL;
1849
2361
 
1850
2362
  /*
1851
2363
    First open the share, and then open the table from the share we just opened.
1852
2364
  */
1853
 
  if (new_tmp_table->getMutableShare()->open_table_def(*static_cast<Session *>(this), identifier) ||
1854
 
      new_tmp_table->getMutableShare()->open_table_from_share(static_cast<Session *>(this), identifier, identifier.getTableName().c_str(),
1855
 
                                                              (uint32_t) (HA_OPEN_KEYFILE | HA_OPEN_RNDFILE |
1856
 
                                                                          HA_GET_INDEX),
1857
 
                                                              ha_open_options,
1858
 
                                                              *new_tmp_table))
 
2365
  if (share->open_table_def(*this, identifier) ||
 
2366
      share->open_table_from_share(this, identifier, identifier.getTableName().c_str(),
 
2367
                            (uint32_t) (HA_OPEN_KEYFILE | HA_OPEN_RNDFILE |
 
2368
                                        HA_GET_INDEX),
 
2369
                            ha_open_options,
 
2370
                            *new_tmp_table))
1859
2371
  {
1860
2372
    /* No need to lock share->mutex as this is not needed for tmp tables */
1861
 
    delete new_tmp_table->getMutableShare();
 
2373
    delete share;
1862
2374
    delete new_tmp_table;
1863
2375
 
1864
2376
    return 0;
1900
2412
{
1901
2413
  if (session->mark_used_columns != MARK_COLUMNS_NONE)
1902
2414
  {
1903
 
    boost::dynamic_bitset<> *current_bitmap= NULL;
 
2415
    MyBitmap *current_bitmap, *other_bitmap;
1904
2416
 
1905
2417
    /*
1906
2418
      We always want to register the used keys, as the column bitmap may have
1913
2425
    if (session->mark_used_columns == MARK_COLUMNS_READ)
1914
2426
    {
1915
2427
      current_bitmap= table->read_set;
 
2428
      other_bitmap=   table->write_set;
1916
2429
    }
1917
2430
    else
1918
2431
    {
1919
2432
      current_bitmap= table->write_set;
 
2433
      other_bitmap=   table->read_set;
1920
2434
    }
1921
2435
 
1922
 
    //if (current_bitmap->testAndSet(field->position()))
1923
 
    if (current_bitmap->test(field->position()))
 
2436
    if (current_bitmap->testAndSet(field->field_index))
1924
2437
    {
1925
2438
      if (session->mark_used_columns == MARK_COLUMNS_WRITE)
1926
2439
        session->dup_field= field;
2154
2667
      */
2155
2668
      table_name && table_name[0] &&
2156
2669
      (my_strcasecmp(table_alias_charset, table_list->alias, table_name) ||
2157
 
       (db_name && db_name[0] && table_list->getSchemaName() && table_list->getSchemaName()[0] &&
2158
 
        strcmp(db_name, table_list->getSchemaName()))))
 
2670
       (db_name && db_name[0] && table_list->db && table_list->db[0] &&
 
2671
        strcmp(db_name, table_list->db))))
2159
2672
    return 0;
2160
2673
 
2161
2674
  *actual_table= NULL;
2230
2743
      {
2231
2744
        Table *table= field_to_set->getTable();
2232
2745
        if (session->mark_used_columns == MARK_COLUMNS_READ)
2233
 
          table->setReadSet(field_to_set->position());
 
2746
          table->setReadSet(field_to_set->field_index);
2234
2747
        else
2235
 
          table->setWriteSet(field_to_set->position());
 
2748
          table->setWriteSet(field_to_set->field_index);
2236
2749
      }
2237
2750
    }
2238
2751
  }
2788
3301
    /* true if field_name_1 is a member of using_fields */
2789
3302
    bool is_using_column_1;
2790
3303
    if (!(nj_col_1= it_1.get_or_create_column_ref(leaf_1)))
2791
 
      return(result);
 
3304
      goto err;
2792
3305
    field_name_1= nj_col_1->name();
2793
3306
    is_using_column_1= using_fields &&
2794
3307
      test_if_string_in_list(field_name_1, using_fields);
2806
3319
      Natural_join_column *cur_nj_col_2;
2807
3320
      const char *cur_field_name_2;
2808
3321
      if (!(cur_nj_col_2= it_2.get_or_create_column_ref(leaf_2)))
2809
 
        return(result);
 
3322
        goto err;
2810
3323
      cur_field_name_2= cur_nj_col_2->name();
2811
3324
 
2812
3325
      /*
2826
3339
            (found && (!using_fields || is_using_column_1)))
2827
3340
        {
2828
3341
          my_error(ER_NON_UNIQ_ERROR, MYF(0), field_name_1, session->where);
2829
 
          return(result);
 
3342
          goto err;
2830
3343
        }
2831
3344
        nj_col_2= cur_nj_col_2;
2832
3345
        found= true;
2859
3372
      Item_func_eq *eq_cond;
2860
3373
 
2861
3374
      if (!item_1 || !item_2)
2862
 
        return(result); // out of memory
 
3375
        goto err;                               // out of memory
2863
3376
 
2864
3377
      /*
2865
3378
        In the case of no_wrap_view_item == 0, the created items must be
2884
3397
      */
2885
3398
      if (set_new_item_local_context(session, item_ident_1, nj_col_1->table_ref) ||
2886
3399
          set_new_item_local_context(session, item_ident_2, nj_col_2->table_ref))
2887
 
        return(result);
 
3400
        goto err;
2888
3401
 
2889
3402
      if (!(eq_cond= new Item_func_eq(item_ident_1, item_ident_2)))
2890
 
        return(result);                               /* Out of memory. */
 
3403
        goto err;                               /* Out of memory. */
2891
3404
 
2892
3405
      /*
2893
3406
        Add the new equi-join condition to the ON clause. Notice that
2904
3417
      {
2905
3418
        Table *table_1= nj_col_1->table_ref->table;
2906
3419
        /* Mark field_1 used for table cache. */
2907
 
        table_1->setReadSet(field_1->position());
 
3420
        table_1->setReadSet(field_1->field_index);
2908
3421
        table_1->covering_keys&= field_1->part_of_key;
2909
3422
        table_1->merge_keys|= field_1->part_of_key;
2910
3423
      }
2912
3425
      {
2913
3426
        Table *table_2= nj_col_2->table_ref->table;
2914
3427
        /* Mark field_2 used for table cache. */
2915
 
        table_2->setReadSet(field_2->position());
 
3428
        table_2->setReadSet(field_2->field_index);
2916
3429
        table_2->covering_keys&= field_2->part_of_key;
2917
3430
        table_2->merge_keys|= field_2->part_of_key;
2918
3431
      }
2933
3446
  */
2934
3447
  result= false;
2935
3448
 
 
3449
err:
2936
3450
  return(result);
2937
3451
}
2938
3452
 
2990
3504
 
2991
3505
  if (!(non_join_columns= new List<Natural_join_column>) ||
2992
3506
      !(natural_using_join->join_columns= new List<Natural_join_column>))
2993
 
  {
2994
 
    return(result);
2995
 
  }
 
3507
    goto err;
2996
3508
 
2997
3509
  /* Append the columns of the first join operand. */
2998
3510
  for (it_1.set(table_ref_1); !it_1.end_of_fields(); it_1.next())
3031
3543
        {
3032
3544
          my_error(ER_BAD_FIELD_ERROR, MYF(0), using_field_name_ptr,
3033
3545
                   session->where);
3034
 
          return(result);
 
3546
          goto err;
3035
3547
        }
3036
3548
        if (!my_strcasecmp(system_charset_info,
3037
3549
                           common_field->name(), using_field_name_ptr))
3059
3571
 
3060
3572
  result= false;
3061
3573
 
 
3574
err:
3062
3575
  return(result);
3063
3576
}
3064
3577
 
3144
3657
      if (cur_table_ref->getNestedJoin() &&
3145
3658
          store_top_level_join_columns(session, cur_table_ref,
3146
3659
                                       real_left_neighbor, real_right_neighbor))
3147
 
        return(result);
 
3660
        goto err;
3148
3661
      same_level_right_neighbor= cur_table_ref;
3149
3662
    }
3150
3663
  }
3176
3689
      std::swap(table_ref_1, table_ref_2);
3177
3690
    if (mark_common_columns(session, table_ref_1, table_ref_2,
3178
3691
                            using_fields, &found_using_fields))
3179
 
      return(result);
 
3692
      goto err;
3180
3693
 
3181
3694
    /*
3182
3695
      Swap the join operands back, so that we pick the columns of the second
3188
3701
    if (store_natural_using_join_columns(session, table_ref, table_ref_1,
3189
3702
                                         table_ref_2, using_fields,
3190
3703
                                         found_using_fields))
3191
 
      return(result);
 
3704
      goto err;
3192
3705
 
3193
3706
    /*
3194
3707
      Change NATURAL JOIN to JOIN ... ON. We do this for both operands
3221
3734
  }
3222
3735
  result= false; /* All is OK. */
3223
3736
 
 
3737
err:
3224
3738
  return(result);
3225
3739
}
3226
3740
 
3622
4136
    assert(tables->is_leaf_for_name_resolution());
3623
4137
 
3624
4138
    if ((table_name && my_strcasecmp(table_alias_charset, table_name, tables->alias)) ||
3625
 
        (db_name && strcasecmp(tables->getSchemaName(),db_name)))
 
4139
        (db_name && strcasecmp(tables->db,db_name)))
3626
4140
      continue;
3627
4141
 
3628
4142
    /*
3658
4172
      if ((field= field_iterator.field()))
3659
4173
      {
3660
4174
        /* Mark fields as used to allow storage engine to optimze access */
3661
 
        field->getTable()->setReadSet(field->position());
 
4175
        field->getTable()->setReadSet(field->field_index);
3662
4176
        if (table)
3663
4177
        {
3664
4178
          table->covering_keys&= field->part_of_key;
3865
4379
    if ((value->save_in_field(rfield, 0) < 0) && !ignore_errors)
3866
4380
    {
3867
4381
      my_message(ER_UNKNOWN_ERROR, ER(ER_UNKNOWN_ERROR), MYF(0));
3868
 
      if (table)
3869
 
        table->auto_increment_field_not_null= false;
3870
 
 
3871
 
      return true;
 
4382
      goto err;
3872
4383
    }
3873
4384
  }
3874
4385
 
3875
4386
  return session->is_error();
 
4387
 
 
4388
err:
 
4389
  if (table)
 
4390
    table->auto_increment_field_not_null= false;
 
4391
 
 
4392
  return true;
3876
4393
}
3877
4394
 
3878
4395
 
3922
4439
    if (field == table->next_number_field)
3923
4440
      table->auto_increment_field_not_null= true;
3924
4441
    if (value->save_in_field(field, 0) < 0)
3925
 
    {
3926
 
      if (table)
3927
 
        table->auto_increment_field_not_null= false;
3928
 
 
3929
 
      return true;
3930
 
    }
 
4442
      goto err;
3931
4443
  }
3932
4444
 
3933
4445
  return(session->is_error());
 
4446
 
 
4447
err:
 
4448
  if (table)
 
4449
    table->auto_increment_field_not_null= false;
 
4450
 
 
4451
  return true;
3934
4452
}
3935
4453
 
3936
4454
 
3947
4465
 
3948
4466
  plugin::StorageEngine::removeLostTemporaryTables(*session, drizzle_tmpdir.c_str());
3949
4467
 
 
4468
  session->lockForDelete();
3950
4469
  delete session;
3951
4470
 
3952
4471
  return false;
3958
4477
  unireg support functions
3959
4478
 *****************************************************************************/
3960
4479
 
3961
 
 
 
4480
/*
 
4481
  Invalidate any cache entries that are for some DB
 
4482
 
 
4483
  SYNOPSIS
 
4484
  remove_db_from_cache()
 
4485
  db            Database name. This will be in lower case if
 
4486
  lower_case_table_name is set
 
4487
 
 
4488
NOTE:
 
4489
We can't use hash_delete when looping hash_elements. We mark them first
 
4490
and afterwards delete those marked unused.
 
4491
*/
 
4492
 
 
4493
void remove_db_from_cache(const SchemaIdentifier &schema_identifier)
 
4494
{
 
4495
  safe_mutex_assert_owner(LOCK_open.native_handle());
 
4496
 
 
4497
  for (TableOpenCache::const_iterator iter= get_open_cache().begin();
 
4498
       iter != get_open_cache().end();
 
4499
       iter++)
 
4500
  {
 
4501
    Table *table= (*iter).second;
 
4502
 
 
4503
    if (not schema_identifier.getPath().compare(table->getMutableShare()->getSchemaName()))
 
4504
    {
 
4505
      table->getMutableShare()->resetVersion();                 /* Free when thread is ready */
 
4506
      if (not table->in_use)
 
4507
        unused_tables.relink(table);
 
4508
    }
 
4509
  }
 
4510
 
 
4511
  unused_tables.cullByVersion();
 
4512
}
 
4513
 
 
4514
 
 
4515
/*
 
4516
  Mark all entries with the table as deleted to force an reopen of the table
 
4517
 
 
4518
  The table will be closed (not stored in cache) by the current thread when
 
4519
  close_thread_tables() is called.
 
4520
 
 
4521
  PREREQUISITES
 
4522
  Lock on LOCK_open()
 
4523
 
 
4524
  RETURN
 
4525
  0  This thread now have exclusive access to this table and no other thread
 
4526
  can access the table until close_thread_tables() is called.
 
4527
  1  Table is in use by another thread
 
4528
*/
 
4529
 
 
4530
bool remove_table_from_cache(Session *session, TableIdentifier &identifier, uint32_t flags)
 
4531
{
 
4532
  const TableIdentifier::Key &key(identifier.getKey());
 
4533
  bool result= false; 
 
4534
  bool signalled= false;
 
4535
 
 
4536
  for (;;)
 
4537
  {
 
4538
    result= signalled= false;
 
4539
 
 
4540
    TableOpenCacheRange ppp;
 
4541
    ppp= get_open_cache().equal_range(key);
 
4542
 
 
4543
    for (TableOpenCache::const_iterator iter= ppp.first;
 
4544
         iter != ppp.second; ++iter)
 
4545
    {
 
4546
      Table *table= (*iter).second;
 
4547
      Session *in_use;
 
4548
 
 
4549
      table->getMutableShare()->resetVersion();         /* Free when thread is ready */
 
4550
      if (!(in_use=table->in_use))
 
4551
      {
 
4552
        unused_tables.relink(table);
 
4553
      }
 
4554
      else if (in_use != session)
 
4555
      {
 
4556
        /*
 
4557
          Mark that table is going to be deleted from cache. This will
 
4558
          force threads that are in mysql_lock_tables() (but not yet
 
4559
          in thr_multi_lock()) to abort it's locks, close all tables and retry
 
4560
        */
 
4561
        in_use->some_tables_deleted= true;
 
4562
        if (table->is_name_opened())
 
4563
        {
 
4564
          result= true;
 
4565
        }
 
4566
        /*
 
4567
          Now we must abort all tables locks used by this thread
 
4568
          as the thread may be waiting to get a lock for another table.
 
4569
          Note that we need to hold LOCK_open while going through the
 
4570
          list. So that the other thread cannot change it. The other
 
4571
          thread must also hold LOCK_open whenever changing the
 
4572
          open_tables list. Aborting the MERGE lock after a child was
 
4573
          closed and before the parent is closed would be fatal.
 
4574
        */
 
4575
        for (Table *session_table= in_use->open_tables;
 
4576
             session_table ;
 
4577
             session_table= session_table->getNext())
 
4578
        {
 
4579
          /* Do not handle locks of MERGE children. */
 
4580
          if (session_table->db_stat)   // If table is open
 
4581
            signalled|= mysql_lock_abort_for_thread(session, session_table);
 
4582
        }
 
4583
      }
 
4584
      else
 
4585
        result= result || (flags & RTFC_OWNED_BY_Session_FLAG);
 
4586
    }
 
4587
 
 
4588
    unused_tables.cullByVersion();
 
4589
 
 
4590
    /* Remove table from table definition cache if it's not in use */
 
4591
    TableShare::release(identifier);
 
4592
 
 
4593
    if (result && (flags & RTFC_WAIT_OTHER_THREAD_FLAG))
 
4594
    {
 
4595
      /*
 
4596
        Signal any thread waiting for tables to be freed to
 
4597
        reopen their tables
 
4598
      */
 
4599
      broadcast_refresh();
 
4600
      if (!(flags & RTFC_CHECK_KILLED_FLAG) || !session->killed)
 
4601
      {
 
4602
        dropping_tables++;
 
4603
        if (likely(signalled))
 
4604
          (void) pthread_cond_wait(COND_refresh.native_handle(), LOCK_open.native_handle());
 
4605
        else
 
4606
        {
 
4607
          struct timespec abstime;
 
4608
          /*
 
4609
            It can happen that another thread has opened the
 
4610
            table but has not yet locked any table at all. Since
 
4611
            it can be locked waiting for a table that our thread
 
4612
            has done LOCK Table x WRITE on previously, we need to
 
4613
            ensure that the thread actually hears our signal
 
4614
            before we go to sleep. Thus we wait for a short time
 
4615
            and then we retry another loop in the
 
4616
            remove_table_from_cache routine.
 
4617
          */
 
4618
          set_timespec(abstime, 10);
 
4619
          pthread_cond_timedwait(COND_refresh.native_handle(), LOCK_open.native_handle(), &abstime);
 
4620
        }
 
4621
        dropping_tables--;
 
4622
        continue;
 
4623
      }
 
4624
    }
 
4625
    break;
 
4626
  }
 
4627
 
 
4628
  return result;
 
4629
}
3962
4630
 
3963
4631
 
3964
4632
/**