~drizzle-trunk/drizzle/development

« back to all changes in this revision

Viewing changes to drizzled/sql_base.cc

  • Committer: Brian Aker
  • Date: 2010-09-12 01:42:27 UTC
  • mto: (1759.2.1 build)
  • mto: This revision was merged to the branch mainline in revision 1762.
  • Revision ID: brian@tangent.org-20100912014227-krt6d9z5ohqrokhb
Add two plugins to handle the string and math functions.

Show diffs side-by-side

added added

removed removed

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