~drizzle-trunk/drizzle/development

« back to all changes in this revision

Viewing changes to drizzled/sql_base.cc

  • Committer: Joseph Daly
  • Date: 2010-09-16 17:47:44 UTC
  • mto: (1774.1.1 build)
  • mto: This revision was merged to the branch mainline in revision 1775.
  • Revision ID: jdaly@rx7-20100916174744-9myzc6sigk4zrmtn
fix copyright

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 */
53
53
#include "drizzled/internal/iocache.h"
54
54
#include "drizzled/drizzled.h"
55
55
#include "drizzled/plugin/authorization.h"
56
 
#include "drizzled/table/temporary.h"
57
 
#include "drizzled/table/placeholder.h"
58
 
#include "drizzled/table/unused.h"
 
56
#include "drizzled/table_placeholder.h"
59
57
 
60
58
using namespace std;
61
59
 
64
62
 
65
63
extern bool volatile shutdown_in_progress;
66
64
 
 
65
TableOpenCache &get_open_cache()
 
66
{
 
67
  static TableOpenCache open_cache;                             /* Used by mysql_test */
 
68
 
 
69
  return open_cache;
 
70
}
 
71
 
 
72
static void free_cache_entry(Table *entry);
 
73
 
 
74
void remove_table(Table *arg)
 
75
{
 
76
  TableOpenCacheRange ppp;
 
77
  ppp= get_open_cache().equal_range(arg->getShare()->getCacheKey());
 
78
 
 
79
  for (TableOpenCache::const_iterator iter= ppp.first;
 
80
         iter != ppp.second; ++iter)
 
81
  {
 
82
    Table *found_table= (*iter).second;
 
83
 
 
84
    if (found_table == arg)
 
85
    {
 
86
      free_cache_entry(arg);
 
87
      get_open_cache().erase(iter);
 
88
      return;
 
89
    }
 
90
  }
 
91
}
 
92
 
 
93
static bool add_table(Table *arg)
 
94
{
 
95
  TableOpenCache &open_cache(get_open_cache());
 
96
 
 
97
  TableOpenCache::iterator returnable= open_cache.insert(make_pair(arg->getShare()->getCacheKey(), arg));
 
98
 
 
99
  return not (returnable == open_cache.end());
 
100
}
 
101
 
 
102
class UnusedTables {
 
103
  Table *tables;                                /* Used by mysql_test */
 
104
 
 
105
  Table *getTable() const
 
106
  {
 
107
    return tables;
 
108
  }
 
109
 
 
110
  Table *setTable(Table *arg)
 
111
  {
 
112
    return tables= arg;
 
113
  }
 
114
 
 
115
public:
 
116
 
 
117
  void cull()
 
118
  {
 
119
    /* Free cache if too big */
 
120
    while (cached_open_tables() > table_cache_size && getTable())
 
121
      remove_table(getTable());
 
122
  }
 
123
 
 
124
  void cullByVersion()
 
125
  {
 
126
    while (getTable() && not getTable()->getShare()->getVersion())
 
127
      remove_table(getTable());
 
128
  }
 
129
  
 
130
  void link(Table *table)
 
131
  {
 
132
    if (getTable())
 
133
    {
 
134
      table->setNext(getTable());               /* Link in last */
 
135
      table->setPrev(getTable()->getPrev());
 
136
      getTable()->setPrev(table);
 
137
      table->getPrev()->setNext(table);
 
138
    }
 
139
    else
 
140
    {
 
141
      table->setPrev(setTable(table));
 
142
      table->setNext(table->getPrev());
 
143
      assert(table->getNext() == table && table->getPrev() == table);
 
144
    }
 
145
  }
 
146
 
 
147
 
 
148
  void unlink(Table *table)
 
149
  {
 
150
    table->unlink();
 
151
 
 
152
    /* Unlink the table from "unused_tables" list. */
 
153
    if (table == getTable())
 
154
    {  // First unused
 
155
      setTable(getTable()->getNext()); // Remove from link
 
156
      if (table == getTable())
 
157
        setTable(NULL);
 
158
    }
 
159
  }
 
160
 
 
161
/* move table first in unused links */
 
162
 
 
163
  void relink(Table *table)
 
164
  {
 
165
    if (table != getTable())
 
166
    {
 
167
      table->unlink();
 
168
 
 
169
      table->setNext(getTable());                       /* Link in unused tables */
 
170
      table->setPrev(getTable()->getPrev());
 
171
      getTable()->getPrev()->setNext(table);
 
172
      getTable()->setPrev(table);
 
173
      setTable(table);
 
174
    }
 
175
  }
 
176
 
 
177
 
 
178
  void clear()
 
179
  {
 
180
    while (getTable())
 
181
      remove_table(getTable());
 
182
  }
 
183
 
 
184
  UnusedTables():
 
185
    tables(NULL)
 
186
  { }
 
187
 
 
188
  ~UnusedTables()
 
189
  { 
 
190
  }
 
191
};
 
192
 
 
193
static UnusedTables unused_tables;
 
194
static int open_unireg_entry(Session *session,
 
195
                             Table *entry,
 
196
                             const char *alias,
 
197
                             TableIdentifier &identifier);
 
198
 
 
199
unsigned char *table_cache_key(const unsigned char *record,
 
200
                               size_t *length,
 
201
                               bool );
 
202
 
 
203
#if 0
 
204
static bool reopen_table(Table *table);
 
205
#endif
 
206
 
 
207
unsigned char *table_cache_key(const unsigned char *record,
 
208
                               size_t *length,
 
209
                               bool )
 
210
{
 
211
  Table *entry=(Table*) record;
 
212
  *length= entry->getShare()->getCacheKey().size();
 
213
  return (unsigned char*) &entry->getShare()->getCacheKey()[0];
 
214
}
 
215
 
67
216
bool table_cache_init(void)
68
217
{
69
218
  return false;
71
220
 
72
221
uint32_t cached_open_tables(void)
73
222
{
74
 
  return table::getCache().size();
 
223
  return get_open_cache().size();
75
224
}
76
225
 
77
226
void table_cache_free(void)
78
227
{
79
228
  refresh_version++;                            // Force close of open tables
80
229
 
81
 
  table::getUnused().clear();
82
 
  table::getCache().clear();
 
230
  unused_tables.clear();
 
231
  get_open_cache().clear();
83
232
}
84
233
 
85
234
/*
93
242
  By leaving the table in the table cache, it disallows any other thread
94
243
  to open the table
95
244
 
96
 
  session->getKilled() will be set if we run out of memory
 
245
  session->killed will be set if we run out of memory
97
246
 
98
247
  If closing a MERGE child, the calling function has to take care for
99
248
  closing the parent too, if necessary.
102
251
 
103
252
void close_handle_and_leave_table_as_lock(Table *table)
104
253
{
 
254
  TableShare *share, *old_share= table->getMutableShare();
105
255
  assert(table->db_stat);
106
256
  assert(table->getShare()->getType() == message::Table::STANDARD);
107
257
 
112
262
  */
113
263
  TableIdentifier identifier(table->getShare()->getSchemaName(), table->getShare()->getTableName(), message::Table::INTERNAL);
114
264
  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()));
 
265
  share= new TableShare(identifier.getType(),
 
266
                        identifier,
 
267
                        const_cast<char *>(&key[0]),  static_cast<uint32_t>(old_share->getCacheKeySize()));
118
268
 
119
269
  table->cursor->close();
120
270
  table->db_stat= 0;                            // Mark cursor closed
121
271
  TableShare::release(table->getMutableShare());
122
272
  table->setShare(share);
 
273
  table->cursor->change_table_ptr(table, table->getMutableShare());
123
274
}
124
275
 
125
276
 
137
288
  }
138
289
}
139
290
 
 
291
/*
 
292
  Remove table from the open table cache
 
293
 
 
294
  SYNOPSIS
 
295
  free_cache_entry()
 
296
  entry         Table to remove
 
297
 
 
298
  NOTE
 
299
  We need to have a lock on LOCK_open when calling this
 
300
*/
 
301
 
 
302
void free_cache_entry(Table *table)
 
303
{
 
304
  table->intern_close_table();
 
305
  if (not table->in_use)
 
306
  {
 
307
    unused_tables.unlink(table);
 
308
  }
 
309
 
 
310
  delete table;
 
311
}
 
312
 
140
313
/* Free resources allocated by filesort() and read_record() */
141
314
 
142
315
void Table::free_io_cache()
143
316
{
144
317
  if (sort.io_cache)
145
318
  {
146
 
    sort.io_cache->close_cached_file();
 
319
    close_cached_file(sort.io_cache);
147
320
    delete sort.io_cache;
148
321
    sort.io_cache= 0;
149
322
  }
155
328
 
156
329
  @param session Thread context (may be NULL)
157
330
  @param tables List of tables to remove from the cache
158
 
  @param have_lock If table::Cache::singleton().mutex() is locked
 
331
  @param have_lock If LOCK_open is locked
159
332
  @param wait_for_refresh Wait for a impending flush
160
333
  @param wait_for_placeholders Wait for tables being reopened so that the GRL
161
334
  won't proceed while write-locked tables are being reopened by other
170
343
  bool result= false;
171
344
  Session *session= this;
172
345
 
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
 
      {
 
346
  LOCK_open.lock(); /* Optionally lock for remove tables from open_cahe if not in use */
 
347
 
 
348
  if (tables == NULL)
 
349
  {
 
350
    refresh_version++;                          // Force close of open tables
 
351
 
 
352
    unused_tables.clear();
 
353
 
 
354
    if (wait_for_refresh)
 
355
    {
 
356
      /*
 
357
        Other threads could wait in a loop in open_and_lock_tables(),
 
358
        trying to lock one or more of our tables.
 
359
 
 
360
        If they wait for the locks in thr_multi_lock(), their lock
 
361
        request is aborted. They loop in open_and_lock_tables() and
 
362
        enter open_table(). Here they notice the table is refreshed and
 
363
        wait for COND_refresh. Then they loop again in
 
364
        openTablesLock() and this time open_table() succeeds. At
 
365
        this moment, if we (the FLUSH TABLES thread) are scheduled and
 
366
        on another FLUSH TABLES enter close_cached_tables(), they could
 
367
        awake while we sleep below, waiting for others threads (us) to
 
368
        close their open tables. If this happens, the other threads
 
369
        would find the tables unlocked. They would get the locks, one
 
370
        after the other, and could do their destructive work. This is an
 
371
        issue if we have LOCK TABLES in effect.
 
372
 
 
373
        The problem is that the other threads passed all checks in
 
374
        open_table() before we refresh the table.
 
375
 
 
376
        The fix for this problem is to set some_tables_deleted for all
 
377
        threads with open tables. These threads can still get their
 
378
        locks, but will immediately release them again after checking
 
379
        this variable. They will then loop in openTablesLock()
 
380
        again. There they will wait until we update all tables version
 
381
        below.
 
382
 
 
383
        Setting some_tables_deleted is done by remove_table_from_cache()
 
384
        in the other branch.
 
385
 
 
386
        In other words (reviewer suggestion): You need this setting of
 
387
        some_tables_deleted for the case when table was opened and all
 
388
        related checks were passed before incrementing refresh_version
 
389
        (which you already have) but attempt to lock the table happened
 
390
        after the call to Session::close_old_data_files() i.e. after removal of
 
391
        current thread locks.
 
392
      */
 
393
      for (TableOpenCache::const_iterator iter= get_open_cache().begin();
 
394
           iter != get_open_cache().end();
 
395
           iter++)
 
396
      {
 
397
        Table *table= (*iter).second;
 
398
        if (table->in_use)
 
399
          table->in_use->some_tables_deleted= false;
 
400
      }
 
401
    }
 
402
  }
 
403
  else
 
404
  {
 
405
    bool found= false;
 
406
    for (TableList *table= tables; table; table= table->next_local)
 
407
    {
 
408
      TableIdentifier identifier(table->db, table->table_name);
 
409
      if (remove_table_from_cache(session, identifier,
 
410
                                  RTFC_OWNED_BY_Session_FLAG))
 
411
      {
 
412
        found= true;
 
413
      }
 
414
    }
 
415
    if (!found)
 
416
      wait_for_refresh= false;                  // Nothing to wait for
 
417
  }
 
418
 
 
419
  if (wait_for_refresh)
 
420
  {
 
421
    /*
 
422
      If there is any table that has a lower refresh_version, wait until
 
423
      this is closed (or this thread is killed) before returning
 
424
    */
 
425
    session->mysys_var->current_mutex= LOCK_open.native_handle();
 
426
    session->mysys_var->current_cond= COND_refresh.native_handle();
 
427
    session->set_proc_info("Flushing tables");
 
428
 
 
429
    session->close_old_data_files();
 
430
 
 
431
    bool found= true;
 
432
    /* Wait until all threads has closed all the tables we had locked */
 
433
    while (found && ! session->killed)
 
434
    {
 
435
      found= false;
 
436
      for (TableOpenCache::const_iterator iter= get_open_cache().begin();
 
437
           iter != get_open_cache().end();
 
438
           iter++)
 
439
      {
 
440
        Table *table= (*iter).second;
 
441
        /* Avoid a self-deadlock. */
 
442
        if (table->in_use == session)
 
443
          continue;
184
444
        /*
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.
 
445
          Note that we wait here only for tables which are actually open, and
 
446
          not for placeholders with Table::open_placeholder set. Waiting for
 
447
          latter will cause deadlock in the following scenario, for example:
 
448
 
 
449
          conn1-> lock table t1 write;
 
450
          conn2-> lock table t2 write;
 
451
          conn1-> flush tables;
 
452
          conn2-> flush tables;
 
453
 
 
454
          It also does not make sense to wait for those of placeholders that
 
455
          are employed by CREATE TABLE as in this case table simply does not
 
456
          exist yet.
220
457
        */
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))
 
458
        if (table->needs_reopen_or_name_lock() && (table->db_stat ||
 
459
                                                   (table->open_placeholder && wait_for_placeholders)))
239
460
        {
240
461
          found= true;
 
462
          pthread_cond_wait(COND_refresh.native_handle(),LOCK_open.native_handle());
 
463
          break;
241
464
        }
242
465
      }
243
 
      if (!found)
244
 
        wait_for_refresh= false;                        // Nothing to wait for
245
466
    }
 
467
    /*
 
468
      No other thread has the locked tables open; reopen them and get the
 
469
      old locks. This should always succeed (unless some external process
 
470
      has removed the tables)
 
471
    */
 
472
    result= session->reopen_tables(true, true);
246
473
 
247
 
    if (wait_for_refresh)
 
474
    /* Set version for table */
 
475
    for (Table *table= session->open_tables; table ; table= table->getNext())
248
476
    {
249
477
      /*
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
 
      }
 
478
        Preserve the version (0) of write locked tables so that a impending
 
479
        global read lock won't sneak in.
 
480
      */
 
481
      if (table->reginfo.lock_type < TL_WRITE_ALLOW_WRITE)
 
482
        table->getMutableShare()->refreshVersion();
314
483
    }
315
 
 
316
 
    table::Cache::singleton().mutex().unlock();
317
484
  }
318
485
 
 
486
  LOCK_open.unlock();
 
487
 
319
488
  if (wait_for_refresh)
320
489
  {
321
 
    boost_unique_lock_t scopedLock(session->mysys_var->mutex);
 
490
    pthread_mutex_lock(&session->mysys_var->mutex);
322
491
    session->mysys_var->current_mutex= 0;
323
492
    session->mysys_var->current_cond= 0;
324
493
    session->set_proc_info(0);
 
494
    pthread_mutex_unlock(&session->mysys_var->mutex);
325
495
  }
326
496
 
327
497
  return result;
335
505
bool Session::free_cached_table()
336
506
{
337
507
  bool found_old_table= false;
338
 
  table::Concurrent *table= static_cast<table::Concurrent *>(open_tables);
 
508
  Table *table= open_tables;
339
509
 
340
 
  safe_mutex_assert_owner(table::Cache::singleton().mutex().native_handle());
 
510
  safe_mutex_assert_owner(LOCK_open.native_handle());
341
511
  assert(table->key_read == 0);
342
512
  assert(!table->cursor || table->cursor->inited == Cursor::NONE);
343
513
 
346
516
  if (table->needs_reopen_or_name_lock() ||
347
517
      version != refresh_version || !table->db_stat)
348
518
  {
349
 
    table::remove_table(table);
 
519
    remove_table(table);
350
520
    found_old_table= true;
351
521
  }
352
522
  else
359
529
 
360
530
    /* Free memory and reset for next loop */
361
531
    table->cursor->ha_reset();
362
 
    table->in_use= NULL;
 
532
    table->in_use= false;
363
533
 
364
 
    table::getUnused().link(table);
 
534
    unused_tables.link(table);
365
535
  }
366
536
 
367
537
  return found_old_table;
380
550
{
381
551
  bool found_old_table= false;
382
552
 
383
 
  safe_mutex_assert_not_owner(table::Cache::singleton().mutex().native_handle());
 
553
  safe_mutex_assert_not_owner(LOCK_open.native_handle());
384
554
 
385
 
  boost_unique_lock_t scoped_lock(table::Cache::singleton().mutex()); /* Close all open tables on Session */
 
555
  boost::mutex::scoped_lock scoped_lock(LOCK_open); /* Close all open tables on Session */
386
556
 
387
557
  while (open_tables)
388
558
  {
393
563
  if (found_old_table)
394
564
  {
395
565
    /* Tell threads waiting for refresh that something has happened */
396
 
    locking::broadcast_refresh();
 
566
    broadcast_refresh();
397
567
  }
398
568
}
399
569
 
423
593
  for (; table; table= table->*link )
424
594
  {
425
595
    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)
 
596
        strcasecmp(table->db, db_name) == 0 &&
 
597
        strcasecmp(table->table_name, table_name) == 0)
428
598
      break;
429
599
  }
430
600
  return table;
495
665
    */
496
666
    assert(table);
497
667
  }
498
 
  d_name= table->getSchemaName();
499
 
  t_name= table->getTableName();
 
668
  d_name= table->db;
 
669
  t_name= table->table_name;
500
670
  t_alias= table->alias;
501
671
 
502
672
  for (;;)
517
687
}
518
688
 
519
689
 
520
 
void Open_tables_state::doGetTableNames(const SchemaIdentifier &schema_identifier,
521
 
                                        std::set<std::string>& set_of_names)
 
690
void Session::doGetTableNames(const SchemaIdentifier &schema_identifier,
 
691
                              std::set<std::string>& set_of_names)
522
692
{
523
 
  for (Table *table= getTemporaryTables() ; table ; table= table->getNext())
 
693
  for (Table *table= temporary_tables ; table ; table= table->getNext())
524
694
  {
525
695
    if (schema_identifier.compare(table->getShare()->getSchemaName()))
526
696
    {
529
699
  }
530
700
}
531
701
 
532
 
void Open_tables_state::doGetTableNames(CachedDirectory &,
533
 
                                        const SchemaIdentifier &schema_identifier,
534
 
                                        std::set<std::string> &set_of_names)
 
702
void Session::doGetTableNames(CachedDirectory &,
 
703
                              const SchemaIdentifier &schema_identifier,
 
704
                              std::set<std::string> &set_of_names)
535
705
{
536
706
  doGetTableNames(schema_identifier, set_of_names);
537
707
}
538
708
 
539
 
void Open_tables_state::doGetTableIdentifiers(const SchemaIdentifier &schema_identifier,
540
 
                                              TableIdentifier::vector &set_of_identifiers)
 
709
void Session::doGetTableIdentifiers(const SchemaIdentifier &schema_identifier,
 
710
                                    TableIdentifiers &set_of_identifiers)
541
711
{
542
 
  for (Table *table= getTemporaryTables() ; table ; table= table->getNext())
 
712
  for (Table *table= temporary_tables ; table ; table= table->getNext())
543
713
  {
544
714
    if (schema_identifier.compare(table->getShare()->getSchemaName()))
545
715
    {
550
720
  }
551
721
}
552
722
 
553
 
void Open_tables_state::doGetTableIdentifiers(CachedDirectory &,
554
 
                                              const SchemaIdentifier &schema_identifier,
555
 
                                              TableIdentifier::vector &set_of_identifiers)
 
723
void Session::doGetTableIdentifiers(CachedDirectory &,
 
724
                                    const SchemaIdentifier &schema_identifier,
 
725
                                    TableIdentifiers &set_of_identifiers)
556
726
{
557
727
  doGetTableIdentifiers(schema_identifier, set_of_identifiers);
558
728
}
559
729
 
560
 
bool Open_tables_state::doDoesTableExist(const TableIdentifier &identifier)
 
730
bool Session::doDoesTableExist(const TableIdentifier &identifier)
561
731
{
562
 
  for (Table *table= getTemporaryTables() ; table ; table= table->getNext())
 
732
  for (Table *table= temporary_tables ; table ; table= table->getNext())
563
733
  {
564
734
    if (table->getShare()->getType() == message::Table::TEMPORARY)
565
735
    {
573
743
  return false;
574
744
}
575
745
 
576
 
int Open_tables_state::doGetTableDefinition(const TableIdentifier &identifier,
 
746
int Session::doGetTableDefinition(const TableIdentifier &identifier,
577
747
                                  message::Table &table_proto)
578
748
{
579
 
  for (Table *table= getTemporaryTables() ; table ; table= table->getNext())
 
749
  for (Table *table= temporary_tables ; table ; table= table->getNext())
580
750
  {
581
751
    if (table->getShare()->getType() == message::Table::TEMPORARY)
582
752
    {
592
762
  return ENOENT;
593
763
}
594
764
 
595
 
Table *Open_tables_state::find_temporary_table(const TableIdentifier &identifier)
 
765
Table *Session::find_temporary_table(const char *new_db, const char *table_name)
 
766
{
 
767
  char  key[MAX_DBKEY_LENGTH];
 
768
  uint  key_length;
 
769
 
 
770
  key_length= TableIdentifier::createKey(key, new_db, table_name);
 
771
 
 
772
  for (Table *table= temporary_tables ; table ; table= table->getNext())
 
773
  {
 
774
    const TableIdentifier::Key &share_key(table->getShare()->getCacheKey());
 
775
    if (share_key.size() == key_length &&
 
776
        not memcmp(&share_key[0], key, key_length))
 
777
    {
 
778
      return table;
 
779
    }
 
780
  }
 
781
  return NULL;                               // Not a temporary table
 
782
}
 
783
 
 
784
Table *Session::find_temporary_table(TableList *table_list)
 
785
{
 
786
  return find_temporary_table(table_list->db, table_list->table_name);
 
787
}
 
788
 
 
789
Table *Session::find_temporary_table(TableIdentifier &identifier)
596
790
{
597
791
  for (Table *table= temporary_tables ; table ; table= table->getNext())
598
792
  {
630
824
  @retval -1  the table is in use by a outer query
631
825
*/
632
826
 
633
 
int Open_tables_state::drop_temporary_table(const drizzled::TableIdentifier &identifier)
 
827
int Session::drop_temporary_table(TableList *table_list)
634
828
{
635
829
  Table *table;
636
830
 
637
 
  if (not (table= find_temporary_table(identifier)))
 
831
  if (not (table= find_temporary_table(table_list)))
638
832
    return 1;
639
833
 
640
834
  /* Table might be in use by some outer statement. */
641
 
  if (table->query_id && table->query_id != getQueryId())
 
835
  if (table->query_id && table->query_id != query_id)
642
836
  {
643
837
    my_error(ER_CANT_REOPEN_TABLE, MYF(0), table->getAlias());
644
838
    return -1;
656
850
 
657
851
  @param  session     Thread context
658
852
  @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
853
*/
662
854
 
663
855
void Session::unlink_open_table(Table *find)
664
856
{
665
 
  const TableIdentifier::Key find_key(find->getShare()->getCacheKey());
666
 
  Table **prev;
667
 
  safe_mutex_assert_owner(table::Cache::singleton().mutex().native_handle());
 
857
  char key[MAX_DBKEY_LENGTH];
 
858
  uint32_t key_length= find->getShare()->getCacheKeySize();
 
859
  Table *list, **prev;
 
860
  safe_mutex_assert_owner(LOCK_open.native_handle());
668
861
 
 
862
  memcpy(key, &find->getMutableShare()->getCacheKey()[0], key_length);
669
863
  /*
670
 
    Note that we need to hold table::Cache::singleton().mutex() while changing the
 
864
    Note that we need to hold LOCK_open while changing the
671
865
    open_tables list. Another thread may work on it.
672
 
    (See: table::Cache::singleton().removeTable(), mysql_wait_completed_table())
 
866
    (See: remove_table_from_cache(), mysql_wait_completed_table())
673
867
    Closing a MERGE child before the parent would be fatal if the
674
868
    other thread tries to abort the MERGE lock in between.
675
869
  */
676
870
  for (prev= &open_tables; *prev; )
677
871
  {
678
 
    Table *list= *prev;
 
872
    list= *prev;
679
873
 
680
 
    if (list->getShare()->getCacheKey() == find_key)
 
874
    if (list->getShare()->getCacheKeySize() == key_length &&
 
875
        not memcmp(&list->getShare()->getCacheKey()[0], key, key_length))
681
876
    {
682
877
      /* Remove table from open_tables list. */
683
878
      *prev= list->getNext();
684
879
 
685
880
      /* Close table. */
686
 
      table::remove_table(static_cast<table::Concurrent *>(list));
 
881
      remove_table(list);
687
882
    }
688
883
    else
689
884
    {
693
888
  }
694
889
 
695
890
  // Notify any 'refresh' threads
696
 
  locking::broadcast_refresh();
 
891
  broadcast_refresh();
697
892
}
698
893
 
699
894
 
716
911
  table that was locked with LOCK TABLES.
717
912
*/
718
913
 
719
 
void Session::drop_open_table(Table *table, const TableIdentifier &identifier)
 
914
void Session::drop_open_table(Table *table, TableIdentifier &identifier)
720
915
{
721
916
  if (table->getShare()->getType())
722
917
  {
724
919
  }
725
920
  else
726
921
  {
727
 
    boost_unique_lock_t scoped_lock(table::Cache::singleton().mutex()); /* Close and drop a table (AUX routine) */
 
922
    boost::mutex::scoped_lock scoped_lock(LOCK_open); /* Close and drop a table (AUX routine) */
728
923
    /*
729
924
      unlink_open_table() also tells threads waiting for refresh or close
730
925
      that something has happened.
731
926
    */
732
927
    unlink_open_table(table);
733
 
    plugin::StorageEngine::dropTable(*this, identifier);
 
928
    quick_rm_table(*this, identifier);
734
929
  }
735
930
}
736
931
 
746
941
  cond  Condition to wait for
747
942
*/
748
943
 
749
 
void Session::wait_for_condition(boost::mutex &mutex, boost::condition_variable_any &cond)
 
944
void Session::wait_for_condition(boost::mutex &mutex, boost::condition_variable &cond)
750
945
{
751
946
  /* Wait until the current table is up to date */
752
947
  const char *saved_proc_info;
753
 
  mysys_var->current_mutex= &mutex;
754
 
  mysys_var->current_cond= &cond;
 
948
  mysys_var->current_mutex= mutex.native_handle();
 
949
  mysys_var->current_cond= cond.native_handle();
755
950
  saved_proc_info= get_proc_info();
756
951
  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);
 
952
  if (!killed)
 
953
    (void) pthread_cond_wait(cond.native_handle(), mutex.native_handle());
 
954
 
 
955
  /*
 
956
    We must unlock mutex first to avoid deadlock becasue conditions are
 
957
    sent to this thread by doing locks in the following order:
 
958
    lock(mysys_var->mutex)
 
959
    lock(mysys_var->current_mutex)
 
960
 
 
961
    One by effect of this that one can only use wait_for_condition with
 
962
    condition variables that are guranteed to not disapper (freed) even if this
 
963
    mutex is unlocked
 
964
  */
 
965
 
 
966
  pthread_mutex_unlock(mutex.native_handle());
 
967
  pthread_mutex_lock(&mysys_var->mutex);
775
968
  mysys_var->current_mutex= 0;
776
969
  mysys_var->current_cond= 0;
777
970
  set_proc_info(saved_proc_info);
 
971
  pthread_mutex_unlock(&mysys_var->mutex);
 
972
}
 
973
 
 
974
 
 
975
/*
 
976
  Open table which is already name-locked by this thread.
 
977
 
 
978
  SYNOPSIS
 
979
  reopen_name_locked_table()
 
980
  session         Thread handle
 
981
  table_list  TableList object for table to be open, TableList::table
 
982
  member should point to Table object which was used for
 
983
  name-locking.
 
984
  link_in     true  - if Table object for table to be opened should be
 
985
  linked into Session::open_tables list.
 
986
  false - placeholder used for name-locking is already in
 
987
  this list so we only need to preserve Table::next
 
988
  pointer.
 
989
 
 
990
  NOTE
 
991
  This function assumes that its caller already acquired LOCK_open mutex.
 
992
 
 
993
  RETURN VALUE
 
994
  false - Success
 
995
  true  - Error
 
996
*/
 
997
 
 
998
bool Session::reopen_name_locked_table(TableList* table_list, bool link_in)
 
999
{
 
1000
  Table *table= table_list->table;
 
1001
  TableShare *share;
 
1002
  char *table_name= table_list->table_name;
 
1003
  Table orig_table;
 
1004
 
 
1005
  safe_mutex_assert_owner(LOCK_open.native_handle());
 
1006
 
 
1007
  if (killed || !table)
 
1008
    return true;
 
1009
 
 
1010
  orig_table= *table;
 
1011
 
 
1012
  TableIdentifier identifier(table_list->db, table_list->table_name);
 
1013
  if (open_unireg_entry(this, table, table_name, identifier))
 
1014
  {
 
1015
    table->intern_close_table();
 
1016
    /*
 
1017
      If there was an error during opening of table (for example if it
 
1018
      does not exist) '*table' object can be wiped out. To be able
 
1019
      properly release name-lock in this case we should restore this
 
1020
      object to its original state.
 
1021
    */
 
1022
    *table= orig_table;
 
1023
    return true;
 
1024
  }
 
1025
 
 
1026
  share= table->getMutableShare();
 
1027
  /*
 
1028
    We want to prevent other connections from opening this table until end
 
1029
    of statement as it is likely that modifications of table's metadata are
 
1030
    not yet finished (for example CREATE TRIGGER have to change .TRG cursor,
 
1031
    or we might want to drop table if CREATE TABLE ... SELECT fails).
 
1032
    This also allows us to assume that no other connection will sneak in
 
1033
    before we will get table-level lock on this table.
 
1034
  */
 
1035
  share->resetVersion();
 
1036
  table->in_use = this;
 
1037
 
 
1038
  if (link_in)
 
1039
  {
 
1040
    table->setNext(open_tables);
 
1041
    open_tables= table;
 
1042
  }
 
1043
  else
 
1044
  {
 
1045
    /*
 
1046
      Table object should be already in Session::open_tables list so we just
 
1047
      need to set Table::next correctly.
 
1048
    */
 
1049
    table->setNext(orig_table.getNext());
 
1050
  }
 
1051
 
 
1052
  table->tablenr= current_tablenr++;
 
1053
  table->used_fields= 0;
 
1054
  table->const_table= 0;
 
1055
  table->null_row= false;
 
1056
  table->maybe_null= false;
 
1057
  table->force_index= false;
 
1058
  table->status= STATUS_NO_RECORD;
 
1059
 
 
1060
  return false;
778
1061
}
779
1062
 
780
1063
 
791
1074
  case of failure.
792
1075
*/
793
1076
 
794
 
table::Placeholder *Session::table_cache_insert_placeholder(const drizzled::TableIdentifier &arg)
 
1077
Table *Session::table_cache_insert_placeholder(const char *db_name, const char *table_name)
795
1078
{
796
 
  safe_mutex_assert_owner(table::Cache::singleton().mutex().native_handle());
 
1079
  safe_mutex_assert_owner(LOCK_open.native_handle());
797
1080
 
798
1081
  /*
799
1082
    Create a table entry with the right key and with an old refresh version
800
1083
  */
801
 
  TableIdentifier identifier(arg.getSchemaName(), arg.getTableName(), message::Table::INTERNAL);
802
 
  table::Placeholder *table= new table::Placeholder(this, identifier);
 
1084
  TableIdentifier identifier(db_name, table_name, message::Table::INTERNAL);
 
1085
  TablePlaceholder *table= new TablePlaceholder(this, identifier);
803
1086
 
804
 
  if (not table::Cache::singleton().insert(table))
 
1087
  if (not add_table(table))
805
1088
  {
806
1089
    delete table;
807
1090
 
833
1116
  @retval  true   Error occured (OOM)
834
1117
  @retval  false  Success. 'table' parameter set according to above rules.
835
1118
*/
836
 
bool Session::lock_table_name_if_not_cached(const TableIdentifier &identifier, Table **table)
 
1119
bool Session::lock_table_name_if_not_cached(TableIdentifier &identifier, Table **table)
837
1120
{
838
1121
  const TableIdentifier::Key &key(identifier.getKey());
839
1122
 
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())
 
1123
  boost::mutex::scoped_lock scope_lock(LOCK_open); /* Obtain a name lock even though table is not in cache (like for create table)  */
 
1124
 
 
1125
  TableOpenCache::iterator iter;
 
1126
 
 
1127
  iter= get_open_cache().find(key);
 
1128
 
 
1129
  if (iter != get_open_cache().end())
847
1130
  {
848
1131
    *table= 0;
849
1132
    return false;
850
1133
  }
851
1134
 
852
 
  if (not (*table= table_cache_insert_placeholder(identifier)))
 
1135
  if (not (*table= table_cache_insert_placeholder(identifier.getSchemaName().c_str(), identifier.getTableName().c_str())))
853
1136
  {
854
1137
    return true;
855
1138
  }
909
1192
  if (check_stack_overrun(this, STACK_MIN_SIZE_FOR_OPEN, (unsigned char *)&alias))
910
1193
    return NULL;
911
1194
 
912
 
  if (getKilled())
 
1195
  if (killed)
913
1196
    return NULL;
914
1197
 
915
 
  TableIdentifier identifier(table_list->getSchemaName(), table_list->getTableName());
 
1198
  TableIdentifier identifier(table_list->db, table_list->table_name);
916
1199
  const TableIdentifier::Key &key(identifier.getKey());
917
 
  table::CacheRange ppp;
 
1200
  TableOpenCacheRange ppp;
918
1201
 
919
1202
  /*
920
1203
    Unless requested otherwise, try to resolve this table in the list
923
1206
    same name. This block implements the behaviour.
924
1207
    TODO -> move this block into a separate function.
925
1208
  */
926
 
  bool reset= false;
927
 
  for (table= getTemporaryTables(); table ; table=table->getNext())
 
1209
  for (table= temporary_tables; table ; table=table->getNext())
928
1210
  {
929
1211
    if (table->getShare()->getCacheKey() == key)
930
1212
    {
940
1222
        return NULL;
941
1223
      }
942
1224
      table->query_id= getQueryId();
943
 
      reset= true;
 
1225
      goto reset;
 
1226
    }
 
1227
  }
 
1228
 
 
1229
  if (flags & DRIZZLE_OPEN_TEMPORARY_ONLY)
 
1230
  {
 
1231
    my_error(ER_NO_SUCH_TABLE, MYF(0), table_list->db, table_list->table_name);
 
1232
    return NULL;
 
1233
  }
 
1234
 
 
1235
  /*
 
1236
    If it's the first table from a list of tables used in a query,
 
1237
    remember refresh_version (the version of open_cache state).
 
1238
    If the version changes while we're opening the remaining tables,
 
1239
    we will have to back off, close all the tables opened-so-far,
 
1240
    and try to reopen them.
 
1241
 
 
1242
    Note-> refresh_version is currently changed only during FLUSH TABLES.
 
1243
  */
 
1244
  if (!open_tables)
 
1245
  {
 
1246
    version= refresh_version;
 
1247
  }
 
1248
  else if ((version != refresh_version) &&
 
1249
           ! (flags & DRIZZLE_LOCK_IGNORE_FLUSH))
 
1250
  {
 
1251
    /* Someone did a refresh while thread was opening tables */
 
1252
    if (refresh)
 
1253
      *refresh= true;
 
1254
 
 
1255
    return NULL;
 
1256
  }
 
1257
 
 
1258
  /*
 
1259
    Before we test the global cache, we test our local session cache.
 
1260
  */
 
1261
  if (cached_table)
 
1262
  {
 
1263
    assert(false); /* Not implemented yet */
 
1264
  }
 
1265
 
 
1266
  /*
 
1267
    Non pre-locked/LOCK TABLES mode, and the table is not temporary:
 
1268
    this is the normal use case.
 
1269
    Now we should:
 
1270
    - try to find the table in the table cache.
 
1271
    - if one of the discovered Table instances is name-locked
 
1272
    (table->getShare()->version == 0) back off -- we have to wait
 
1273
    until no one holds a name lock on the table.
 
1274
    - if there is no such Table in the name cache, read the table definition
 
1275
    and insert it into the cache.
 
1276
    We perform all of the above under LOCK_open which currently protects
 
1277
    the open cache (also known as table cache) and table definitions stored
 
1278
    on disk.
 
1279
  */
 
1280
 
 
1281
  LOCK_open.lock(); /* Lock for FLUSH TABLES for open table */
 
1282
 
 
1283
  /*
 
1284
    Actually try to find the table in the open_cache.
 
1285
    The cache may contain several "Table" instances for the same
 
1286
    physical table. The instances that are currently "in use" by
 
1287
    some thread have their "in_use" member != NULL.
 
1288
    There is no good reason for having more than one entry in the
 
1289
    hash for the same physical table, except that we use this as
 
1290
    an implicit "pending locks queue" - see
 
1291
    wait_for_locked_table_names for details.
 
1292
  */
 
1293
  ppp= get_open_cache().equal_range(key);
 
1294
 
 
1295
  table= NULL;
 
1296
  for (TableOpenCache::const_iterator iter= ppp.first;
 
1297
       iter != ppp.second; ++iter, table= NULL)
 
1298
  {
 
1299
    table= (*iter).second;
 
1300
 
 
1301
    if (not table->in_use)
944
1302
      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
1303
    /*
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.
 
1304
      Here we flush tables marked for flush.
 
1305
      Normally, table->getShare()->version contains the value of
 
1306
      refresh_version from the moment when this table was
 
1307
      (re-)opened and added to the cache.
 
1308
      If since then we did (or just started) FLUSH TABLES
 
1309
      statement, refresh_version has been increased.
 
1310
      For "name-locked" Table instances, table->getShare()->version is set
 
1311
      to 0 (see lock_table_name for details).
 
1312
      In case there is a pending FLUSH TABLES or a name lock, we
 
1313
      need to back off and re-start opening tables.
 
1314
      If we do not back off now, we may dead lock in case of lock
 
1315
      order mismatch with some other thread:
 
1316
      c1-> name lock t1; -- sort of exclusive lock
 
1317
      c2-> open t2;      -- sort of shared lock
 
1318
      c1-> name lock t2; -- blocks
 
1319
      c2-> open t1; -- blocks
964
1320
    */
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 */
 
1321
    if (table->needs_reopen_or_name_lock())
 
1322
    {
 
1323
      if (flags & DRIZZLE_LOCK_IGNORE_FLUSH)
 
1324
      {
 
1325
        /* Force close at once after usage */
 
1326
        version= table->getShare()->getVersion();
 
1327
        continue;
 
1328
      }
 
1329
 
 
1330
      /* Avoid self-deadlocks by detecting self-dependencies. */
 
1331
      if (table->open_placeholder && table->in_use == this)
 
1332
      {
 
1333
        LOCK_open.unlock();
 
1334
        my_error(ER_UPDATE_TABLE_USED, MYF(0), table->getMutableShare()->getTableName());
 
1335
        return NULL;
 
1336
      }
 
1337
 
 
1338
      /*
 
1339
        Back off, part 1: mark the table as "unused" for the
 
1340
        purpose of name-locking by setting table->db_stat to 0. Do
 
1341
        that only for the tables in this thread that have an old
 
1342
        table->getShare()->version (this is an optimization (?)).
 
1343
        table->db_stat == 0 signals wait_for_locked_table_names
 
1344
        that the tables in question are not used any more. See
 
1345
        table_is_used call for details.
 
1346
      */
 
1347
      close_old_data_files(false, false);
 
1348
 
 
1349
      /*
 
1350
        Back-off part 2: try to avoid "busy waiting" on the table:
 
1351
        if the table is in use by some other thread, we suspend
 
1352
        and wait till the operation is complete: when any
 
1353
        operation that juggles with table->getShare()->version completes,
 
1354
        it broadcasts COND_refresh condition variable.
 
1355
        If 'old' table we met is in use by current thread we return
 
1356
        without waiting since in this situation it's this thread
 
1357
        which is responsible for broadcasting on COND_refresh
 
1358
        (and this was done already in Session::close_old_data_files()).
 
1359
        Good example of such situation is when we have statement
 
1360
        that needs two instances of table and FLUSH TABLES comes
 
1361
        after we open first instance but before we open second
 
1362
        instance.
 
1363
      */
 
1364
      if (table->in_use != this)
 
1365
      {
 
1366
        /* wait_for_conditionwill unlock LOCK_open for us */
 
1367
        wait_for_condition(LOCK_open, COND_refresh);
 
1368
      }
 
1369
      else
 
1370
      {
 
1371
        LOCK_open.unlock();
 
1372
      }
 
1373
      /*
 
1374
        There is a refresh in progress for this table.
 
1375
        Signal the caller that it has to try again.
 
1376
      */
973
1377
      if (refresh)
974
1378
        *refresh= true;
975
 
 
976
1379
      return NULL;
977
1380
    }
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)
 
1381
  }
 
1382
  if (table)
 
1383
  {
 
1384
    unused_tables.unlink(table);
 
1385
    table->in_use= this;
 
1386
  }
 
1387
  else
 
1388
  {
 
1389
    /* Insert a new Table instance into the open cache */
 
1390
    int error;
 
1391
    /* Free cache if too big */
 
1392
    unused_tables.cull();
 
1393
 
 
1394
    if (table_list->isCreate())
 
1395
    {
 
1396
      TableIdentifier  lock_table_identifier(table_list->db, table_list->table_name, message::Table::STANDARD);
 
1397
 
 
1398
      if (not plugin::StorageEngine::doesTableExist(*this, lock_table_identifier))
1020
1399
      {
1021
 
        table= (*iter).second;
1022
 
 
1023
 
        if (not table->in_use)
1024
 
          break;
1025
1400
        /*
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
 
1401
          Table to be created, so we need to create placeholder in table-cache.
1042
1402
        */
1043
 
        if (table->needs_reopen_or_name_lock())
 
1403
        if (!(table= table_cache_insert_placeholder(table_list->db, table_list->table_name)))
1044
1404
        {
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;
 
1405
          LOCK_open.unlock();
1101
1406
          return NULL;
1102
1407
        }
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
 
  }
 
1408
        /*
 
1409
          Link placeholder to the open tables list so it will be automatically
 
1410
          removed once tables are closed. Also mark it so it won't be ignored
 
1411
          by other trying to take name-lock.
 
1412
        */
 
1413
        table->open_placeholder= true;
 
1414
        table->setNext(open_tables);
 
1415
        open_tables= table;
 
1416
        LOCK_open.unlock();
 
1417
 
 
1418
        return table ;
 
1419
      }
 
1420
      /* Table exists. Let us try to open it. */
 
1421
    }
 
1422
 
 
1423
    /* make a new table */
 
1424
    table= new Table;
 
1425
    if (table == NULL)
 
1426
    {
 
1427
      LOCK_open.unlock();
 
1428
      return NULL;
 
1429
    }
 
1430
 
 
1431
    error= open_unireg_entry(this, table, alias, identifier);
 
1432
    if (error != 0)
 
1433
    {
 
1434
      delete table;
 
1435
      LOCK_open.unlock();
 
1436
      return NULL;
 
1437
    }
 
1438
    (void)add_table(table);
 
1439
  }
 
1440
 
 
1441
  LOCK_open.unlock();
 
1442
  if (refresh)
 
1443
  {
 
1444
    table->setNext(open_tables); /* Link into simple list */
 
1445
    open_tables= table;
 
1446
  }
 
1447
  table->reginfo.lock_type= TL_READ; /* Assume read */
 
1448
 
 
1449
reset:
1176
1450
  assert(table->getShare()->getTableCount() > 0 || table->getShare()->getType() != message::Table::STANDARD);
1177
1451
 
 
1452
  if (lex->need_correct_ident())
 
1453
    table->alias_name_used= my_strcasecmp(table_alias_charset,
 
1454
                                          table->getMutableShare()->getTableName(), alias);
1178
1455
  /* Fix alias if table name changes */
1179
1456
  if (strcmp(table->getAlias(), alias))
1180
1457
  {
1181
 
    table->setAlias(alias);
 
1458
    uint32_t length=(uint32_t) strlen(alias)+1;
 
1459
    table->alias= (char*) realloc((char*) table->alias, length);
 
1460
    memcpy((void*) table->alias, alias, length);
1182
1461
  }
1183
1462
 
1184
1463
  /* These variables are also set in reopen_table() */
1205
1484
}
1206
1485
 
1207
1486
 
 
1487
#if 0
 
1488
/*
 
1489
  Reopen an table because the definition has changed.
 
1490
 
 
1491
  SYNOPSIS
 
1492
  reopen_table()
 
1493
  table Table object
 
1494
 
 
1495
  NOTES
 
1496
  The data cursor for the table is already closed and the share is released
 
1497
  The table has a 'dummy' share that mainly contains database and table name.
 
1498
 
 
1499
  RETURN
 
1500
  0  ok
 
1501
  1  error. The old table object is not changed.
 
1502
*/
 
1503
 
 
1504
bool reopen_table(Table *table)
 
1505
{
 
1506
  Table tmp;
 
1507
  bool error= 1;
 
1508
  Field **field;
 
1509
  uint32_t key,part;
 
1510
  TableList table_list;
 
1511
  Session *session= table->in_use;
 
1512
 
 
1513
  assert(table->getShare()->ref_count == 0);
 
1514
  assert(!table->sort.io_cache);
 
1515
 
 
1516
#ifdef EXTRA_DEBUG
 
1517
  if (table->db_stat)
 
1518
    errmsg_printf(ERRMSG_LVL_ERROR, _("Table %s had a open data Cursor in reopen_table"),
 
1519
                  table->alias);
 
1520
#endif
 
1521
  table_list.db=         const_cast<char *>(table->getShare()->getSchemaName());
 
1522
  table_list.table_name= table->getShare()->getTableName();
 
1523
  table_list.table=      table;
 
1524
 
 
1525
  if (wait_for_locked_table_names(session, &table_list))
 
1526
    return true;                             // Thread was killed
 
1527
 
 
1528
  if (open_unireg_entry(session, &tmp, &table_list,
 
1529
                        table->alias,
 
1530
                        table->getShare()->getCacheKey(),
 
1531
                        table->getShare()->getCacheKeySize()))
 
1532
    goto end;
 
1533
 
 
1534
  /* This list copies variables set by open_table */
 
1535
  tmp.tablenr=          table->tablenr;
 
1536
  tmp.used_fields=      table->used_fields;
 
1537
  tmp.const_table=      table->const_table;
 
1538
  tmp.null_row=         table->null_row;
 
1539
  tmp.maybe_null=       table->maybe_null;
 
1540
  tmp.status=           table->status;
 
1541
 
 
1542
  /* Get state */
 
1543
  tmp.in_use=           session;
 
1544
  tmp.reginfo.lock_type=table->reginfo.lock_type;
 
1545
 
 
1546
  /* Replace table in open list */
 
1547
  tmp.next=             table->next;
 
1548
  tmp.prev=             table->prev;
 
1549
 
 
1550
  if (table->cursor)
 
1551
    table->delete_table(true);          // close cursor, free everything
 
1552
 
 
1553
  *table= tmp;
 
1554
  table->default_column_bitmaps();
 
1555
  table->cursor->change_table_ptr(table, table->s);
 
1556
 
 
1557
  assert(table->alias != 0);
 
1558
  for (field=table->field ; *field ; field++)
 
1559
  {
 
1560
    (*field)->table= (*field)->orig_table= table;
 
1561
    (*field)->table_name= &table->alias;
 
1562
  }
 
1563
  for (key=0 ; key < table->getShare()->keys ; key++)
 
1564
  {
 
1565
    for (part=0 ; part < table->key_info[key].usable_key_parts ; part++)
 
1566
      table->key_info[key].key_part[part].field->table= table;
 
1567
  }
 
1568
 
 
1569
  broadcast_refresh();
 
1570
  error= false;
 
1571
 
 
1572
end:
 
1573
  return(error);
 
1574
}
 
1575
#endif
 
1576
 
 
1577
 
1208
1578
/**
1209
1579
  Close all instances of a table open by this thread and replace
1210
1580
  them with exclusive name-locks.
1222
1592
  the strings are used in a loop even after the share may be freed.
1223
1593
*/
1224
1594
 
1225
 
void Session::close_data_files_and_morph_locks(const TableIdentifier &identifier)
 
1595
void Session::close_data_files_and_morph_locks(TableIdentifier &identifier)
1226
1596
{
1227
 
  safe_mutex_assert_owner(table::Cache::singleton().mutex().native_handle()); /* Adjust locks at the end of ALTER TABLEL */
 
1597
  safe_mutex_assert_owner(LOCK_open.native_handle()); /* Adjust locks at the end of ALTER TABLEL */
1228
1598
 
1229
1599
  if (lock)
1230
1600
  {
1232
1602
      If we are not under LOCK TABLES we should have only one table
1233
1603
      open and locked so it makes sense to remove the lock at once.
1234
1604
    */
1235
 
    unlockTables(lock);
 
1605
    mysql_unlock_tables(this, lock);
1236
1606
    lock= 0;
1237
1607
  }
1238
1608
 
1267
1637
  combination when one needs tables to be reopened (for
1268
1638
  example see openTablesLock()).
1269
1639
 
1270
 
  @note One should have lock on table::Cache::singleton().mutex() when calling this.
 
1640
  @note One should have lock on LOCK_open when calling this.
1271
1641
 
1272
1642
  @return false in case of success, true - otherwise.
1273
1643
*/
1284
1654
  if (open_tables == NULL)
1285
1655
    return false;
1286
1656
 
1287
 
  safe_mutex_assert_owner(table::Cache::singleton().mutex().native_handle());
 
1657
  safe_mutex_assert_owner(LOCK_open.native_handle());
1288
1658
  if (get_locks)
1289
1659
  {
1290
1660
    /*
1311
1681
    next= table->getNext();
1312
1682
 
1313
1683
    my_error(ER_CANT_REOPEN_TABLE, MYF(0), table->getAlias());
1314
 
    table::remove_table(static_cast<table::Concurrent *>(table));
 
1684
    remove_table(table);
1315
1685
    error= 1;
1316
1686
  }
1317
1687
  *prev=0;
1320
1690
    DrizzleLock *local_lock;
1321
1691
    /*
1322
1692
      We should always get these locks. Anyway, we must not go into
1323
 
      wait_for_tables() as it tries to acquire table::Cache::singleton().mutex(), which is
 
1693
      wait_for_tables() as it tries to acquire LOCK_open, which is
1324
1694
      already locked.
1325
1695
    */
1326
1696
    some_tables_deleted= false;
1327
1697
 
1328
 
    if ((local_lock= lockTables(tables, (uint32_t) (tables_ptr - tables),
1329
 
                                       flags, &not_used)))
 
1698
    if ((local_lock= mysql_lock_tables(this, tables, (uint32_t) (tables_ptr - tables),
 
1699
                                 flags, &not_used)))
1330
1700
    {
1331
1701
      /* unused */
1332
1702
    }
1345
1715
  if (get_locks && tables)
1346
1716
    delete [] tables;
1347
1717
 
1348
 
  locking::broadcast_refresh();
 
1718
  broadcast_refresh();
1349
1719
 
1350
1720
  return(error);
1351
1721
}
1392
1762
              lock on it. This will also give them a chance to close their
1393
1763
              instances of this table.
1394
1764
            */
1395
 
            abortLock(ulcktbl);
1396
 
            removeLock(ulcktbl);
 
1765
            mysql_lock_abort(this, ulcktbl);
 
1766
            mysql_lock_remove(this, ulcktbl);
1397
1767
            ulcktbl->lock_count= 0;
1398
1768
          }
1399
1769
          if ((ulcktbl != table) && ulcktbl->db_stat)
1433
1803
    }
1434
1804
  }
1435
1805
  if (found)
1436
 
    locking::broadcast_refresh();
 
1806
    broadcast_refresh();
 
1807
}
 
1808
 
 
1809
 
 
1810
/*
 
1811
  Wait until all threads has closed the tables in the list
 
1812
  We have also to wait if there is thread that has a lock on this table even
 
1813
  if the table is closed
 
1814
*/
 
1815
 
 
1816
bool table_is_used(Table *table, bool wait_for_name_lock)
 
1817
{
 
1818
  do
 
1819
  {
 
1820
    const TableIdentifier::Key &key(table->getShare()->getCacheKey());
 
1821
 
 
1822
    TableOpenCacheRange ppp;
 
1823
    ppp= get_open_cache().equal_range(key);
 
1824
 
 
1825
    for (TableOpenCache::const_iterator iter= ppp.first;
 
1826
         iter != ppp.second; ++iter)
 
1827
    {
 
1828
      Table *search= (*iter).second;
 
1829
      if (search->in_use == table->in_use)
 
1830
        continue;                               // Name locked by this thread
 
1831
      /*
 
1832
        We can't use the table under any of the following conditions:
 
1833
        - There is an name lock on it (Table is to be deleted or altered)
 
1834
        - If we are in flush table and we didn't execute the flush
 
1835
        - If the table engine is open and it's an old version
 
1836
        (We must wait until all engines are shut down to use the table)
 
1837
      */
 
1838
      if ( (search->locked_by_name && wait_for_name_lock) ||
 
1839
           (search->is_name_opened() && search->needs_reopen_or_name_lock()))
 
1840
        return 1;
 
1841
    }
 
1842
  } while ((table=table->getNext()));
 
1843
  return 0;
1437
1844
}
1438
1845
 
1439
1846
 
1445
1852
 
1446
1853
  session->set_proc_info("Waiting for tables");
1447
1854
  {
1448
 
    boost_unique_lock_t lock(table::Cache::singleton().mutex());
1449
 
    while (not session->getKilled())
 
1855
    boost::mutex::scoped_lock lock(LOCK_open);
 
1856
    while (!session->killed)
1450
1857
    {
1451
1858
      session->some_tables_deleted= false;
1452
1859
      session->close_old_data_files(false, dropping_tables != 0);
1453
 
      if (not table::Cache::singleton().areTablesUsed(session->open_tables, 1))
1454
 
      {
 
1860
      if (!table_is_used(session->open_tables, 1))
1455
1861
        break;
1456
 
      }
1457
1862
      COND_refresh.wait(lock);
1458
1863
    }
1459
 
    if (session->getKilled())
 
1864
    if (session->killed)
1460
1865
      result= true;                                     // aborted
1461
1866
    else
1462
1867
    {
1502
1907
  prev= &session->open_tables;
1503
1908
 
1504
1909
  /*
1505
 
    Note that we need to hold table::Cache::singleton().mutex() while changing the
 
1910
    Note that we need to hold LOCK_open while changing the
1506
1911
    open_tables list. Another thread may work on it.
1507
 
    (See: table::Cache::singleton().removeTable(), mysql_wait_completed_table())
 
1912
    (See: remove_table_from_cache(), mysql_wait_completed_table())
1508
1913
    Closing a MERGE child before the parent would be fatal if the
1509
1914
    other thread tries to abort the MERGE lock in between.
1510
1915
  */
1513
1918
    next=table->getNext();
1514
1919
    if (table->getShare()->getCacheKey() == identifier.getKey())
1515
1920
    {
1516
 
      session->removeLock(table);
 
1921
      mysql_lock_remove(session, table);
1517
1922
 
1518
1923
      if (!found)
1519
1924
      {
1528
1933
      else
1529
1934
      {
1530
1935
        /* We already have a name lock, remove copy */
1531
 
        table::remove_table(static_cast<table::Concurrent *>(table));
 
1936
        remove_table(table);
1532
1937
      }
1533
1938
    }
1534
1939
    else
1539
1944
  }
1540
1945
  *prev=0;
1541
1946
  if (found)
1542
 
    locking::broadcast_refresh();
 
1947
    broadcast_refresh();
1543
1948
 
1544
1949
  return(found);
1545
1950
}
1559
1964
    if (table->getShare()->getCacheKey() == identifier.getKey())
1560
1965
    {
1561
1966
      /* If MERGE child, forward lock handling to parent. */
1562
 
      session->abortLock(table);
 
1967
      mysql_lock_abort(session, table);
1563
1968
      break;
1564
1969
    }
1565
1970
  }
1566
1971
}
1567
1972
 
 
1973
/*
 
1974
  Load a table definition from cursor and open unireg table
 
1975
 
 
1976
  SYNOPSIS
 
1977
  open_unireg_entry()
 
1978
  session                       Thread handle
 
1979
  entry         Store open table definition here
 
1980
  table_list            TableList with db, table_name
 
1981
  alias         Alias name
 
1982
  cache_key             Key for share_cache
 
1983
  cache_key_length      length of cache_key
 
1984
 
 
1985
  NOTES
 
1986
  Extra argument for open is taken from session->open_options
 
1987
  One must have a lock on LOCK_open when calling this function
 
1988
 
 
1989
  RETURN
 
1990
  0     ok
 
1991
#       Error
 
1992
*/
 
1993
 
 
1994
static int open_unireg_entry(Session *session,
 
1995
                             Table *entry,
 
1996
                             const char *alias,
 
1997
                             TableIdentifier &identifier)
 
1998
{
 
1999
  int error;
 
2000
  TableShare *share;
 
2001
  uint32_t discover_retry_count= 0;
 
2002
 
 
2003
  safe_mutex_assert_owner(LOCK_open.native_handle());
 
2004
retry:
 
2005
  if (not (share= TableShare::getShareCreate(session,
 
2006
                                             identifier,
 
2007
                                             &error)))
 
2008
    return 1;
 
2009
 
 
2010
  while ((error= share->open_table_from_share(session,
 
2011
                                              identifier,
 
2012
                                              alias,
 
2013
                                              (uint32_t) (HA_OPEN_KEYFILE |
 
2014
                                                          HA_OPEN_RNDFILE |
 
2015
                                                          HA_GET_INDEX |
 
2016
                                                          HA_TRY_READ_ONLY),
 
2017
                                              session->open_options, *entry)))
 
2018
  {
 
2019
    if (error == 7)                             // Table def changed
 
2020
    {
 
2021
      share->resetVersion();                        // Mark share as old
 
2022
      if (discover_retry_count++)               // Retry once
 
2023
        goto err;
 
2024
 
 
2025
      /*
 
2026
        TODO->
 
2027
        Here we should wait until all threads has released the table.
 
2028
        For now we do one retry. This may cause a deadlock if there
 
2029
        is other threads waiting for other tables used by this thread.
 
2030
 
 
2031
        Proper fix would be to if the second retry failed:
 
2032
        - Mark that table def changed
 
2033
        - Return from open table
 
2034
        - Close all tables used by this thread
 
2035
        - Start waiting that the share is released
 
2036
        - Retry by opening all tables again
 
2037
      */
 
2038
 
 
2039
      /*
 
2040
        TO BE FIXED
 
2041
        To avoid deadlock, only wait for release if no one else is
 
2042
        using the share.
 
2043
      */
 
2044
      if (share->getTableCount() != 1)
 
2045
        goto err;
 
2046
      /* Free share and wait until it's released by all threads */
 
2047
      TableShare::release(share);
 
2048
 
 
2049
      if (!session->killed)
 
2050
      {
 
2051
        drizzle_reset_errors(session, 1);         // Clear warnings
 
2052
        session->clear_error();                 // Clear error message
 
2053
        goto retry;
 
2054
      }
 
2055
      return 1;
 
2056
    }
 
2057
 
 
2058
    goto err;
 
2059
  }
 
2060
 
 
2061
  return 0;
 
2062
 
 
2063
err:
 
2064
  TableShare::release(share);
 
2065
 
 
2066
  return 1;
 
2067
}
 
2068
 
1568
2069
 
1569
2070
/*
1570
2071
  Open all tables in list
1632
2133
     * to see if it exists so that an unauthorized user cannot phish for
1633
2134
     * table/schema information via error messages
1634
2135
     */
1635
 
    TableIdentifier the_table(tables->getSchemaName(), tables->getTableName());
 
2136
    TableIdentifier the_table(tables->db, tables->table_name);
1636
2137
    if (not plugin::Authorization::isAuthorized(getSecurityContext(),
1637
2138
                                                the_table))
1638
2139
    {
1742
2243
 
1743
2244
    assert(lock == 0);  // You must lock everything at once
1744
2245
    if ((table->reginfo.lock_type= lock_type) != TL_UNLOCK)
1745
 
      if (! (lock= lockTables(&table_list->table, 1, 0, &refresh)))
 
2246
      if (! (lock= mysql_lock_tables(this, &table_list->table, 1, 0, &refresh)))
1746
2247
        table= 0;
1747
2248
  }
1748
2249
 
1805
2306
      *(ptr++)= table->table;
1806
2307
  }
1807
2308
 
1808
 
  if (!(session->lock= session->lockTables(start, (uint32_t) (ptr - start), lock_flag, need_reopen)))
 
2309
  if (!(session->lock= mysql_lock_tables(session, start, (uint32_t) (ptr - start),
 
2310
                                         lock_flag, need_reopen)))
1809
2311
  {
1810
2312
    return -1;
1811
2313
  }
1834
2336
#  Table object
1835
2337
*/
1836
2338
 
1837
 
Table *Open_tables_state::open_temporary_table(const TableIdentifier &identifier,
1838
 
                                               bool link_in_list)
 
2339
Table *Session::open_temporary_table(TableIdentifier &identifier,
 
2340
                                     bool link_in_list)
1839
2341
{
 
2342
  TableShare *share;
 
2343
 
1840
2344
  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()));
 
2345
  share= new TableShare(identifier.getType(),
 
2346
                        identifier,
 
2347
                        const_cast<char *>(identifier.getPath().c_str()), static_cast<uint32_t>(identifier.getPath().length()));
 
2348
 
 
2349
 
 
2350
  Table *new_tmp_table= new Table;
1847
2351
  if (not new_tmp_table)
1848
2352
    return NULL;
1849
2353
 
1850
2354
  /*
1851
2355
    First open the share, and then open the table from the share we just opened.
1852
2356
  */
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))
 
2357
  if (share->open_table_def(*this, identifier) ||
 
2358
      share->open_table_from_share(this, identifier, identifier.getTableName().c_str(),
 
2359
                            (uint32_t) (HA_OPEN_KEYFILE | HA_OPEN_RNDFILE |
 
2360
                                        HA_GET_INDEX),
 
2361
                            ha_open_options,
 
2362
                            *new_tmp_table))
1859
2363
  {
1860
2364
    /* No need to lock share->mutex as this is not needed for tmp tables */
1861
 
    delete new_tmp_table->getMutableShare();
 
2365
    delete share;
1862
2366
    delete new_tmp_table;
1863
2367
 
1864
2368
    return 0;
1900
2404
{
1901
2405
  if (session->mark_used_columns != MARK_COLUMNS_NONE)
1902
2406
  {
1903
 
    boost::dynamic_bitset<> *current_bitmap= NULL;
 
2407
    MyBitmap *current_bitmap, *other_bitmap;
1904
2408
 
1905
2409
    /*
1906
2410
      We always want to register the used keys, as the column bitmap may have
1913
2417
    if (session->mark_used_columns == MARK_COLUMNS_READ)
1914
2418
    {
1915
2419
      current_bitmap= table->read_set;
 
2420
      other_bitmap=   table->write_set;
1916
2421
    }
1917
2422
    else
1918
2423
    {
1919
2424
      current_bitmap= table->write_set;
 
2425
      other_bitmap=   table->read_set;
1920
2426
    }
1921
2427
 
1922
 
    //if (current_bitmap->testAndSet(field->position()))
1923
 
    if (current_bitmap->test(field->position()))
 
2428
    if (current_bitmap->testAndSet(field->field_index))
1924
2429
    {
1925
2430
      if (session->mark_used_columns == MARK_COLUMNS_WRITE)
1926
2431
        session->dup_field= field;
2154
2659
      */
2155
2660
      table_name && table_name[0] &&
2156
2661
      (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()))))
 
2662
       (db_name && db_name[0] && table_list->db && table_list->db[0] &&
 
2663
        strcmp(db_name, table_list->db))))
2159
2664
    return 0;
2160
2665
 
2161
2666
  *actual_table= NULL;
2230
2735
      {
2231
2736
        Table *table= field_to_set->getTable();
2232
2737
        if (session->mark_used_columns == MARK_COLUMNS_READ)
2233
 
          table->setReadSet(field_to_set->position());
 
2738
          table->setReadSet(field_to_set->field_index);
2234
2739
        else
2235
 
          table->setWriteSet(field_to_set->position());
 
2740
          table->setWriteSet(field_to_set->field_index);
2236
2741
      }
2237
2742
    }
2238
2743
  }
2788
3293
    /* true if field_name_1 is a member of using_fields */
2789
3294
    bool is_using_column_1;
2790
3295
    if (!(nj_col_1= it_1.get_or_create_column_ref(leaf_1)))
2791
 
      return(result);
 
3296
      goto err;
2792
3297
    field_name_1= nj_col_1->name();
2793
3298
    is_using_column_1= using_fields &&
2794
3299
      test_if_string_in_list(field_name_1, using_fields);
2806
3311
      Natural_join_column *cur_nj_col_2;
2807
3312
      const char *cur_field_name_2;
2808
3313
      if (!(cur_nj_col_2= it_2.get_or_create_column_ref(leaf_2)))
2809
 
        return(result);
 
3314
        goto err;
2810
3315
      cur_field_name_2= cur_nj_col_2->name();
2811
3316
 
2812
3317
      /*
2826
3331
            (found && (!using_fields || is_using_column_1)))
2827
3332
        {
2828
3333
          my_error(ER_NON_UNIQ_ERROR, MYF(0), field_name_1, session->where);
2829
 
          return(result);
 
3334
          goto err;
2830
3335
        }
2831
3336
        nj_col_2= cur_nj_col_2;
2832
3337
        found= true;
2859
3364
      Item_func_eq *eq_cond;
2860
3365
 
2861
3366
      if (!item_1 || !item_2)
2862
 
        return(result); // out of memory
 
3367
        goto err;                               // out of memory
2863
3368
 
2864
3369
      /*
2865
3370
        In the case of no_wrap_view_item == 0, the created items must be
2884
3389
      */
2885
3390
      if (set_new_item_local_context(session, item_ident_1, nj_col_1->table_ref) ||
2886
3391
          set_new_item_local_context(session, item_ident_2, nj_col_2->table_ref))
2887
 
        return(result);
 
3392
        goto err;
2888
3393
 
2889
3394
      if (!(eq_cond= new Item_func_eq(item_ident_1, item_ident_2)))
2890
 
        return(result);                               /* Out of memory. */
 
3395
        goto err;                               /* Out of memory. */
2891
3396
 
2892
3397
      /*
2893
3398
        Add the new equi-join condition to the ON clause. Notice that
2904
3409
      {
2905
3410
        Table *table_1= nj_col_1->table_ref->table;
2906
3411
        /* Mark field_1 used for table cache. */
2907
 
        table_1->setReadSet(field_1->position());
 
3412
        table_1->setReadSet(field_1->field_index);
2908
3413
        table_1->covering_keys&= field_1->part_of_key;
2909
3414
        table_1->merge_keys|= field_1->part_of_key;
2910
3415
      }
2912
3417
      {
2913
3418
        Table *table_2= nj_col_2->table_ref->table;
2914
3419
        /* Mark field_2 used for table cache. */
2915
 
        table_2->setReadSet(field_2->position());
 
3420
        table_2->setReadSet(field_2->field_index);
2916
3421
        table_2->covering_keys&= field_2->part_of_key;
2917
3422
        table_2->merge_keys|= field_2->part_of_key;
2918
3423
      }
2933
3438
  */
2934
3439
  result= false;
2935
3440
 
 
3441
err:
2936
3442
  return(result);
2937
3443
}
2938
3444
 
2990
3496
 
2991
3497
  if (!(non_join_columns= new List<Natural_join_column>) ||
2992
3498
      !(natural_using_join->join_columns= new List<Natural_join_column>))
2993
 
  {
2994
 
    return(result);
2995
 
  }
 
3499
    goto err;
2996
3500
 
2997
3501
  /* Append the columns of the first join operand. */
2998
3502
  for (it_1.set(table_ref_1); !it_1.end_of_fields(); it_1.next())
3031
3535
        {
3032
3536
          my_error(ER_BAD_FIELD_ERROR, MYF(0), using_field_name_ptr,
3033
3537
                   session->where);
3034
 
          return(result);
 
3538
          goto err;
3035
3539
        }
3036
3540
        if (!my_strcasecmp(system_charset_info,
3037
3541
                           common_field->name(), using_field_name_ptr))
3059
3563
 
3060
3564
  result= false;
3061
3565
 
 
3566
err:
3062
3567
  return(result);
3063
3568
}
3064
3569
 
3144
3649
      if (cur_table_ref->getNestedJoin() &&
3145
3650
          store_top_level_join_columns(session, cur_table_ref,
3146
3651
                                       real_left_neighbor, real_right_neighbor))
3147
 
        return(result);
 
3652
        goto err;
3148
3653
      same_level_right_neighbor= cur_table_ref;
3149
3654
    }
3150
3655
  }
3176
3681
      std::swap(table_ref_1, table_ref_2);
3177
3682
    if (mark_common_columns(session, table_ref_1, table_ref_2,
3178
3683
                            using_fields, &found_using_fields))
3179
 
      return(result);
 
3684
      goto err;
3180
3685
 
3181
3686
    /*
3182
3687
      Swap the join operands back, so that we pick the columns of the second
3188
3693
    if (store_natural_using_join_columns(session, table_ref, table_ref_1,
3189
3694
                                         table_ref_2, using_fields,
3190
3695
                                         found_using_fields))
3191
 
      return(result);
 
3696
      goto err;
3192
3697
 
3193
3698
    /*
3194
3699
      Change NATURAL JOIN to JOIN ... ON. We do this for both operands
3221
3726
  }
3222
3727
  result= false; /* All is OK. */
3223
3728
 
 
3729
err:
3224
3730
  return(result);
3225
3731
}
3226
3732
 
3622
4128
    assert(tables->is_leaf_for_name_resolution());
3623
4129
 
3624
4130
    if ((table_name && my_strcasecmp(table_alias_charset, table_name, tables->alias)) ||
3625
 
        (db_name && strcasecmp(tables->getSchemaName(),db_name)))
 
4131
        (db_name && strcasecmp(tables->db,db_name)))
3626
4132
      continue;
3627
4133
 
3628
4134
    /*
3658
4164
      if ((field= field_iterator.field()))
3659
4165
      {
3660
4166
        /* Mark fields as used to allow storage engine to optimze access */
3661
 
        field->getTable()->setReadSet(field->position());
 
4167
        field->getTable()->setReadSet(field->field_index);
3662
4168
        if (table)
3663
4169
        {
3664
4170
          table->covering_keys&= field->part_of_key;
3865
4371
    if ((value->save_in_field(rfield, 0) < 0) && !ignore_errors)
3866
4372
    {
3867
4373
      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;
 
4374
      goto err;
3872
4375
    }
3873
4376
  }
3874
4377
 
3875
4378
  return session->is_error();
 
4379
 
 
4380
err:
 
4381
  if (table)
 
4382
    table->auto_increment_field_not_null= false;
 
4383
 
 
4384
  return true;
3876
4385
}
3877
4386
 
3878
4387
 
3922
4431
    if (field == table->next_number_field)
3923
4432
      table->auto_increment_field_not_null= true;
3924
4433
    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
 
    }
 
4434
      goto err;
3931
4435
  }
3932
4436
 
3933
4437
  return(session->is_error());
 
4438
 
 
4439
err:
 
4440
  if (table)
 
4441
    table->auto_increment_field_not_null= false;
 
4442
 
 
4443
  return true;
3934
4444
}
3935
4445
 
3936
4446
 
3947
4457
 
3948
4458
  plugin::StorageEngine::removeLostTemporaryTables(*session, drizzle_tmpdir.c_str());
3949
4459
 
 
4460
  session->lockForDelete();
3950
4461
  delete session;
3951
4462
 
3952
4463
  return false;
3958
4469
  unireg support functions
3959
4470
 *****************************************************************************/
3960
4471
 
3961
 
 
 
4472
/*
 
4473
  Invalidate any cache entries that are for some DB
 
4474
 
 
4475
  SYNOPSIS
 
4476
  remove_db_from_cache()
 
4477
  db            Database name. This will be in lower case if
 
4478
  lower_case_table_name is set
 
4479
 
 
4480
NOTE:
 
4481
We can't use hash_delete when looping hash_elements. We mark them first
 
4482
and afterwards delete those marked unused.
 
4483
*/
 
4484
 
 
4485
void remove_db_from_cache(const SchemaIdentifier &schema_identifier)
 
4486
{
 
4487
  safe_mutex_assert_owner(LOCK_open.native_handle());
 
4488
 
 
4489
  for (TableOpenCache::const_iterator iter= get_open_cache().begin();
 
4490
       iter != get_open_cache().end();
 
4491
       iter++)
 
4492
  {
 
4493
    Table *table= (*iter).second;
 
4494
 
 
4495
    if (not schema_identifier.getPath().compare(table->getMutableShare()->getSchemaName()))
 
4496
    {
 
4497
      table->getMutableShare()->resetVersion();                 /* Free when thread is ready */
 
4498
      if (not table->in_use)
 
4499
        unused_tables.relink(table);
 
4500
    }
 
4501
  }
 
4502
 
 
4503
  unused_tables.cullByVersion();
 
4504
}
 
4505
 
 
4506
 
 
4507
/*
 
4508
  Mark all entries with the table as deleted to force an reopen of the table
 
4509
 
 
4510
  The table will be closed (not stored in cache) by the current thread when
 
4511
  close_thread_tables() is called.
 
4512
 
 
4513
  PREREQUISITES
 
4514
  Lock on LOCK_open()
 
4515
 
 
4516
  RETURN
 
4517
  0  This thread now have exclusive access to this table and no other thread
 
4518
  can access the table until close_thread_tables() is called.
 
4519
  1  Table is in use by another thread
 
4520
*/
 
4521
 
 
4522
bool remove_table_from_cache(Session *session, TableIdentifier &identifier, uint32_t flags)
 
4523
{
 
4524
  const TableIdentifier::Key &key(identifier.getKey());
 
4525
  bool result= false; 
 
4526
  bool signalled= false;
 
4527
 
 
4528
  for (;;)
 
4529
  {
 
4530
    result= signalled= false;
 
4531
 
 
4532
    TableOpenCacheRange ppp;
 
4533
    ppp= get_open_cache().equal_range(key);
 
4534
 
 
4535
    for (TableOpenCache::const_iterator iter= ppp.first;
 
4536
         iter != ppp.second; ++iter)
 
4537
    {
 
4538
      Table *table= (*iter).second;
 
4539
      Session *in_use;
 
4540
 
 
4541
      table->getMutableShare()->resetVersion();         /* Free when thread is ready */
 
4542
      if (!(in_use=table->in_use))
 
4543
      {
 
4544
        unused_tables.relink(table);
 
4545
      }
 
4546
      else if (in_use != session)
 
4547
      {
 
4548
        /*
 
4549
          Mark that table is going to be deleted from cache. This will
 
4550
          force threads that are in mysql_lock_tables() (but not yet
 
4551
          in thr_multi_lock()) to abort it's locks, close all tables and retry
 
4552
        */
 
4553
        in_use->some_tables_deleted= true;
 
4554
        if (table->is_name_opened())
 
4555
        {
 
4556
          result= true;
 
4557
        }
 
4558
        /*
 
4559
          Now we must abort all tables locks used by this thread
 
4560
          as the thread may be waiting to get a lock for another table.
 
4561
          Note that we need to hold LOCK_open while going through the
 
4562
          list. So that the other thread cannot change it. The other
 
4563
          thread must also hold LOCK_open whenever changing the
 
4564
          open_tables list. Aborting the MERGE lock after a child was
 
4565
          closed and before the parent is closed would be fatal.
 
4566
        */
 
4567
        for (Table *session_table= in_use->open_tables;
 
4568
             session_table ;
 
4569
             session_table= session_table->getNext())
 
4570
        {
 
4571
          /* Do not handle locks of MERGE children. */
 
4572
          if (session_table->db_stat)   // If table is open
 
4573
            signalled|= mysql_lock_abort_for_thread(session, session_table);
 
4574
        }
 
4575
      }
 
4576
      else
 
4577
        result= result || (flags & RTFC_OWNED_BY_Session_FLAG);
 
4578
    }
 
4579
 
 
4580
    unused_tables.cullByVersion();
 
4581
 
 
4582
    /* Remove table from table definition cache if it's not in use */
 
4583
    TableShare::release(identifier);
 
4584
 
 
4585
    if (result && (flags & RTFC_WAIT_OTHER_THREAD_FLAG))
 
4586
    {
 
4587
      /*
 
4588
        Signal any thread waiting for tables to be freed to
 
4589
        reopen their tables
 
4590
      */
 
4591
      broadcast_refresh();
 
4592
      if (!(flags & RTFC_CHECK_KILLED_FLAG) || !session->killed)
 
4593
      {
 
4594
        dropping_tables++;
 
4595
        if (likely(signalled))
 
4596
          (void) pthread_cond_wait(COND_refresh.native_handle(), LOCK_open.native_handle());
 
4597
        else
 
4598
        {
 
4599
          struct timespec abstime;
 
4600
          /*
 
4601
            It can happen that another thread has opened the
 
4602
            table but has not yet locked any table at all. Since
 
4603
            it can be locked waiting for a table that our thread
 
4604
            has done LOCK Table x WRITE on previously, we need to
 
4605
            ensure that the thread actually hears our signal
 
4606
            before we go to sleep. Thus we wait for a short time
 
4607
            and then we retry another loop in the
 
4608
            remove_table_from_cache routine.
 
4609
          */
 
4610
          set_timespec(abstime, 10);
 
4611
          pthread_cond_timedwait(COND_refresh.native_handle(), LOCK_open.native_handle(), &abstime);
 
4612
        }
 
4613
        dropping_tables--;
 
4614
        continue;
 
4615
      }
 
4616
    }
 
4617
    break;
 
4618
  }
 
4619
 
 
4620
  return result;
 
4621
}
3962
4622
 
3963
4623
 
3964
4624
/**