~drizzle-trunk/drizzle/development

« back to all changes in this revision

Viewing changes to drizzled/sql_base.cc

  • Committer: Brian Aker
  • Date: 2010-08-17 01:34:55 UTC
  • mto: (1711.1.23 build)
  • mto: This revision was merged to the branch mainline in revision 1714.
  • Revision ID: brian@tangent.org-20100817013455-zx3nm7qilxvpwrgb
Style on structure cleanup

Show diffs side-by-side

added added

removed removed

Lines of Context:
11
11
 
12
12
  You should have received a copy of the GNU General Public License
13
13
  along with this program; if not, write to the Free Software
14
 
  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA */
 
14
  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA */
15
15
 
16
16
 
17
17
/* Basic functions needed by many modules */
45
45
#include <drizzled/lock.h>
46
46
#include <drizzled/plugin/listen.h>
47
47
#include "drizzled/cached_directory.h"
48
 
#include <drizzled/field/epoch.h>
 
48
#include <drizzled/field/timestamp.h>
49
49
#include <drizzled/field/null.h>
 
50
#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"
59
 
#include "drizzled/plugin/storage_engine.h"
60
 
 
61
 
#include <drizzled/refresh_version.h>
 
57
#include "drizzled/table_placeholder.h"
62
58
 
63
59
using namespace std;
64
60
 
67
63
 
68
64
extern bool volatile shutdown_in_progress;
69
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
 
70
217
bool table_cache_init(void)
71
218
{
72
219
  return false;
74
221
 
75
222
uint32_t cached_open_tables(void)
76
223
{
77
 
  return table::getCache().size();
 
224
  return get_open_cache().size();
78
225
}
79
226
 
80
227
void table_cache_free(void)
81
228
{
82
229
  refresh_version++;                            // Force close of open tables
83
230
 
84
 
  table::getUnused().clear();
85
 
  table::getCache().clear();
 
231
  unused_tables.clear();
 
232
  get_open_cache().clear();
86
233
}
87
234
 
88
235
/*
96
243
  By leaving the table in the table cache, it disallows any other thread
97
244
  to open the table
98
245
 
99
 
  session->getKilled() will be set if we run out of memory
 
246
  session->killed will be set if we run out of memory
100
247
 
101
248
  If closing a MERGE child, the calling function has to take care for
102
249
  closing the parent too, if necessary.
105
252
 
106
253
void close_handle_and_leave_table_as_lock(Table *table)
107
254
{
 
255
  TableShare *share, *old_share= table->getMutableShare();
108
256
  assert(table->db_stat);
109
257
  assert(table->getShare()->getType() == message::Table::STANDARD);
110
258
 
113
261
    This has to be done to ensure that the table share is removed from
114
262
    the table defintion cache as soon as the last instance is removed
115
263
  */
116
 
  identifier::Table identifier(table->getShare()->getSchemaName(), table->getShare()->getTableName(), message::Table::INTERNAL);
117
 
  const identifier::Table::Key &key(identifier.getKey());
118
 
  TableShare *share= new TableShare(identifier.getType(),
119
 
                                    identifier,
120
 
                                    const_cast<char *>(key.vector()),  static_cast<uint32_t>(table->getShare()->getCacheKeySize()));
 
264
  TableIdentifier identifier(table->getShare()->getSchemaName(), table->getShare()->getTableName(), message::Table::INTERNAL);
 
265
  const TableIdentifier::Key &key(identifier.getKey());
 
266
  share= new TableShare(identifier.getType(),
 
267
                        identifier,
 
268
                        const_cast<char *>(&key[0]),  static_cast<uint32_t>(old_share->getCacheKeySize()));
121
269
 
122
270
  table->cursor->close();
123
271
  table->db_stat= 0;                            // Mark cursor closed
124
 
  table::instance::release(table->getMutableShare());
 
272
  TableShare::release(table->getMutableShare());
125
273
  table->setShare(share);
 
274
  table->cursor->change_table_ptr(table, table->getMutableShare());
126
275
}
127
276
 
128
277
 
140
289
  }
141
290
}
142
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
 
143
314
/* Free resources allocated by filesort() and read_record() */
144
315
 
145
316
void Table::free_io_cache()
146
317
{
147
318
  if (sort.io_cache)
148
319
  {
149
 
    sort.io_cache->close_cached_file();
 
320
    close_cached_file(sort.io_cache);
150
321
    delete sort.io_cache;
151
322
    sort.io_cache= 0;
152
323
  }
158
329
 
159
330
  @param session Thread context (may be NULL)
160
331
  @param tables List of tables to remove from the cache
161
 
  @param have_lock If table::Cache::singleton().mutex() is locked
 
332
  @param have_lock If LOCK_open is locked
162
333
  @param wait_for_refresh Wait for a impending flush
163
334
  @param wait_for_placeholders Wait for tables being reopened so that the GRL
164
335
  won't proceed while write-locked tables are being reopened by other
173
344
  bool result= false;
174
345
  Session *session= this;
175
346
 
176
 
  {
177
 
    boost::mutex::scoped_lock scopedLock(table::Cache::singleton().mutex()); /* Optionally lock for remove tables from open_cahe if not in use */
178
 
 
179
 
    if (tables == NULL)
180
 
    {
181
 
      refresh_version++;                                // Force close of open tables
182
 
 
183
 
      table::getUnused().clear();
184
 
 
185
 
      if (wait_for_refresh)
186
 
      {
 
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;
187
445
        /*
188
 
          Other threads could wait in a loop in open_and_lock_tables(),
189
 
          trying to lock one or more of our tables.
190
 
 
191
 
          If they wait for the locks in thr_multi_lock(), their lock
192
 
          request is aborted. They loop in open_and_lock_tables() and
193
 
          enter open_table(). Here they notice the table is refreshed and
194
 
          wait for COND_refresh. Then they loop again in
195
 
          openTablesLock() and this time open_table() succeeds. At
196
 
          this moment, if we (the FLUSH TABLES thread) are scheduled and
197
 
          on another FLUSH TABLES enter close_cached_tables(), they could
198
 
          awake while we sleep below, waiting for others threads (us) to
199
 
          close their open tables. If this happens, the other threads
200
 
          would find the tables unlocked. They would get the locks, one
201
 
          after the other, and could do their destructive work. This is an
202
 
          issue if we have LOCK TABLES in effect.
203
 
 
204
 
          The problem is that the other threads passed all checks in
205
 
          open_table() before we refresh the table.
206
 
 
207
 
          The fix for this problem is to set some_tables_deleted for all
208
 
          threads with open tables. These threads can still get their
209
 
          locks, but will immediately release them again after checking
210
 
          this variable. They will then loop in openTablesLock()
211
 
          again. There they will wait until we update all tables version
212
 
          below.
213
 
 
214
 
          Setting some_tables_deleted is done by table::Cache::singleton().removeTable()
215
 
          in the other branch.
216
 
 
217
 
          In other words (reviewer suggestion): You need this setting of
218
 
          some_tables_deleted for the case when table was opened and all
219
 
          related checks were passed before incrementing refresh_version
220
 
          (which you already have) but attempt to lock the table happened
221
 
          after the call to Session::close_old_data_files() i.e. after removal of
222
 
          current thread locks.
 
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.
223
458
        */
224
 
        for (table::CacheMap::const_iterator iter= table::getCache().begin();
225
 
             iter != table::getCache().end();
226
 
             iter++)
227
 
        {
228
 
          Table *table= (*iter).second;
229
 
          if (table->in_use)
230
 
            table->in_use->some_tables_deleted= false;
231
 
        }
232
 
      }
233
 
    }
234
 
    else
235
 
    {
236
 
      bool found= false;
237
 
      for (TableList *table= tables; table; table= table->next_local)
238
 
      {
239
 
        identifier::Table identifier(table->getSchemaName(), table->getTableName());
240
 
        if (table::Cache::singleton().removeTable(session, identifier,
241
 
                                    RTFC_OWNED_BY_Session_FLAG))
 
459
        if (table->needs_reopen_or_name_lock() && (table->db_stat ||
 
460
                                                   (table->open_placeholder && wait_for_placeholders)))
242
461
        {
243
462
          found= true;
 
463
          pthread_cond_wait(COND_refresh.native_handle(),LOCK_open.native_handle());
 
464
          break;
244
465
        }
245
466
      }
246
 
      if (!found)
247
 
        wait_for_refresh= false;                        // Nothing to wait for
248
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);
249
474
 
250
 
    if (wait_for_refresh)
 
475
    /* Set version for table */
 
476
    for (Table *table= session->open_tables; table ; table= table->getNext())
251
477
    {
252
478
      /*
253
 
        If there is any table that has a lower refresh_version, wait until
254
 
        this is closed (or this thread is killed) before returning
255
 
      */
256
 
      session->mysys_var->current_mutex= &table::Cache::singleton().mutex();
257
 
      session->mysys_var->current_cond= &COND_refresh;
258
 
      session->set_proc_info("Flushing tables");
259
 
 
260
 
      session->close_old_data_files();
261
 
 
262
 
      bool found= true;
263
 
      /* Wait until all threads has closed all the tables we had locked */
264
 
      while (found && ! session->getKilled())
265
 
      {
266
 
        found= false;
267
 
        for (table::CacheMap::const_iterator iter= table::getCache().begin();
268
 
             iter != table::getCache().end();
269
 
             iter++)
270
 
        {
271
 
          Table *table= (*iter).second;
272
 
          /* Avoid a self-deadlock. */
273
 
          if (table->in_use == session)
274
 
            continue;
275
 
          /*
276
 
            Note that we wait here only for tables which are actually open, and
277
 
            not for placeholders with Table::open_placeholder set. Waiting for
278
 
            latter will cause deadlock in the following scenario, for example:
279
 
 
280
 
            conn1-> lock table t1 write;
281
 
            conn2-> lock table t2 write;
282
 
            conn1-> flush tables;
283
 
            conn2-> flush tables;
284
 
 
285
 
            It also does not make sense to wait for those of placeholders that
286
 
            are employed by CREATE TABLE as in this case table simply does not
287
 
            exist yet.
288
 
          */
289
 
          if (table->needs_reopen_or_name_lock() && (table->db_stat ||
290
 
                                                     (table->open_placeholder && wait_for_placeholders)))
291
 
          {
292
 
            found= true;
293
 
            COND_refresh.wait(scopedLock);
294
 
            break;
295
 
          }
296
 
        }
297
 
      }
298
 
      /*
299
 
        No other thread has the locked tables open; reopen them and get the
300
 
        old locks. This should always succeed (unless some external process
301
 
        has removed the tables)
302
 
      */
303
 
      result= session->reopen_tables();
304
 
 
305
 
      /* Set version for table */
306
 
      for (Table *table= session->open_tables; table ; table= table->getNext())
307
 
      {
308
 
        /*
309
 
          Preserve the version (0) of write locked tables so that a impending
310
 
          global read lock won't sneak in.
311
 
        */
312
 
        if (table->reginfo.lock_type < TL_WRITE_ALLOW_WRITE)
313
 
          table->getMutableShare()->refreshVersion();
314
 
      }
 
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();
315
484
    }
316
485
  }
317
486
 
 
487
  LOCK_open.unlock();
 
488
 
318
489
  if (wait_for_refresh)
319
490
  {
320
 
    boost_unique_lock_t scopedLock(session->mysys_var->mutex);
 
491
    pthread_mutex_lock(&session->mysys_var->mutex);
321
492
    session->mysys_var->current_mutex= 0;
322
493
    session->mysys_var->current_cond= 0;
323
494
    session->set_proc_info(0);
 
495
    pthread_mutex_unlock(&session->mysys_var->mutex);
324
496
  }
325
497
 
326
498
  return result;
331
503
  move one table to free list 
332
504
*/
333
505
 
334
 
bool Session::free_cached_table(boost::mutex::scoped_lock &scopedLock)
 
506
bool Session::free_cached_table()
335
507
{
336
508
  bool found_old_table= false;
337
 
 
338
 
  (void)scopedLock;
339
 
 
340
 
  table::Concurrent *table= static_cast<table::Concurrent *>(open_tables);
341
 
 
342
 
  safe_mutex_assert_owner(table::Cache::singleton().mutex().native_handle());
 
509
  Table *table= open_tables;
 
510
 
 
511
  safe_mutex_assert_owner(LOCK_open.native_handle());
343
512
  assert(table->key_read == 0);
344
513
  assert(!table->cursor || table->cursor->inited == Cursor::NONE);
345
514
 
348
517
  if (table->needs_reopen_or_name_lock() ||
349
518
      version != refresh_version || !table->db_stat)
350
519
  {
351
 
    table::remove_table(table);
 
520
    remove_table(table);
352
521
    found_old_table= true;
353
522
  }
354
523
  else
361
530
 
362
531
    /* Free memory and reset for next loop */
363
532
    table->cursor->ha_reset();
364
 
    table->in_use= NULL;
 
533
    table->in_use= false;
365
534
 
366
 
    table::getUnused().link(table);
 
535
    unused_tables.link(table);
367
536
  }
368
537
 
369
538
  return found_old_table;
382
551
{
383
552
  bool found_old_table= false;
384
553
 
385
 
  safe_mutex_assert_not_owner(table::Cache::singleton().mutex().native_handle());
 
554
  safe_mutex_assert_not_owner(LOCK_open.native_handle());
386
555
 
387
 
  boost_unique_lock_t scoped_lock(table::Cache::singleton().mutex()); /* Close all open tables on Session */
 
556
  LOCK_open.lock(); /* Close all open tables on Session */
388
557
 
389
558
  while (open_tables)
390
559
  {
391
 
    found_old_table|= free_cached_table(scoped_lock);
 
560
    found_old_table|= free_cached_table();
392
561
  }
393
562
  some_tables_deleted= false;
394
563
 
395
564
  if (found_old_table)
396
565
  {
397
566
    /* Tell threads waiting for refresh that something has happened */
398
 
    locking::broadcast_refresh();
 
567
    broadcast_refresh();
399
568
  }
 
569
 
 
570
  LOCK_open.unlock();
400
571
}
401
572
 
402
573
/*
424
595
{
425
596
  for (; table; table= table->*link )
426
597
  {
427
 
    if ((table->table == 0 || table->table->getShare()->getType() == message::Table::STANDARD) and
428
 
        my_strcasecmp(system_charset_info, table->getSchemaName(), db_name) == 0 and
429
 
        my_strcasecmp(system_charset_info, table->getTableName(), table_name) == 0)
430
 
    {
 
598
    if ((table->table == 0 || table->table->getShare()->getType() == message::Table::STANDARD) &&
 
599
        strcasecmp(table->db, db_name) == 0 &&
 
600
        strcasecmp(table->table_name, table_name) == 0)
431
601
      break;
432
 
    }
433
602
  }
434
603
  return table;
435
604
}
499
668
    */
500
669
    assert(table);
501
670
  }
502
 
  d_name= table->getSchemaName();
503
 
  t_name= table->getTableName();
 
671
  d_name= table->db;
 
672
  t_name= table->table_name;
504
673
  t_alias= table->alias;
505
674
 
506
675
  for (;;)
521
690
}
522
691
 
523
692
 
524
 
void Open_tables_state::doGetTableNames(const identifier::Schema &schema_identifier,
525
 
                                        std::set<std::string>& set_of_names)
 
693
void Session::doGetTableNames(const SchemaIdentifier &schema_identifier,
 
694
                              std::set<std::string>& set_of_names)
526
695
{
527
 
  for (Table *table= getTemporaryTables() ; table ; table= table->getNext())
 
696
  for (Table *table= temporary_tables ; table ; table= table->getNext())
528
697
  {
529
698
    if (schema_identifier.compare(table->getShare()->getSchemaName()))
530
699
    {
533
702
  }
534
703
}
535
704
 
536
 
void Open_tables_state::doGetTableNames(CachedDirectory &,
537
 
                                        const identifier::Schema &schema_identifier,
538
 
                                        std::set<std::string> &set_of_names)
 
705
void Session::doGetTableNames(CachedDirectory &,
 
706
                              const SchemaIdentifier &schema_identifier,
 
707
                              std::set<std::string> &set_of_names)
539
708
{
540
709
  doGetTableNames(schema_identifier, set_of_names);
541
710
}
542
711
 
543
 
void Open_tables_state::doGetTableIdentifiers(const identifier::Schema &schema_identifier,
544
 
                                              identifier::Table::vector &set_of_identifiers)
 
712
void Session::doGetTableIdentifiers(const SchemaIdentifier &schema_identifier,
 
713
                                    TableIdentifiers &set_of_identifiers)
545
714
{
546
 
  for (Table *table= getTemporaryTables() ; table ; table= table->getNext())
 
715
  for (Table *table= temporary_tables ; table ; table= table->getNext())
547
716
  {
548
717
    if (schema_identifier.compare(table->getShare()->getSchemaName()))
549
718
    {
550
 
      set_of_identifiers.push_back(identifier::Table(table->getShare()->getSchemaName(),
 
719
      set_of_identifiers.push_back(TableIdentifier(table->getShare()->getSchemaName(),
551
720
                                                   table->getShare()->getTableName(),
552
721
                                                   table->getShare()->getPath()));
553
722
    }
554
723
  }
555
724
}
556
725
 
557
 
void Open_tables_state::doGetTableIdentifiers(CachedDirectory &,
558
 
                                              const identifier::Schema &schema_identifier,
559
 
                                              identifier::Table::vector &set_of_identifiers)
 
726
void Session::doGetTableIdentifiers(CachedDirectory &,
 
727
                                    const SchemaIdentifier &schema_identifier,
 
728
                                    TableIdentifiers &set_of_identifiers)
560
729
{
561
730
  doGetTableIdentifiers(schema_identifier, set_of_identifiers);
562
731
}
563
732
 
564
 
bool Open_tables_state::doDoesTableExist(const identifier::Table &identifier)
 
733
bool Session::doDoesTableExist(const TableIdentifier &identifier)
565
734
{
566
 
  for (Table *table= getTemporaryTables() ; table ; table= table->getNext())
 
735
  for (Table *table= temporary_tables ; table ; table= table->getNext())
567
736
  {
568
737
    if (table->getShare()->getType() == message::Table::TEMPORARY)
569
738
    {
577
746
  return false;
578
747
}
579
748
 
580
 
int Open_tables_state::doGetTableDefinition(const identifier::Table &identifier,
581
 
                                            message::Table &table_proto)
 
749
int Session::doGetTableDefinition(const TableIdentifier &identifier,
 
750
                                  message::Table &table_proto)
582
751
{
583
 
  for (Table *table= getTemporaryTables() ; table ; table= table->getNext())
 
752
  for (Table *table= temporary_tables ; table ; table= table->getNext())
584
753
  {
585
754
    if (table->getShare()->getType() == message::Table::TEMPORARY)
586
755
    {
587
756
      if (identifier.getKey() == table->getShare()->getCacheKey())
588
757
      {
589
 
        table_proto.CopyFrom(*(table->getShare()->getTableMessage()));
 
758
        table_proto.CopyFrom(*(table->getShare()->getTableProto()));
590
759
 
591
760
        return EEXIST;
592
761
      }
596
765
  return ENOENT;
597
766
}
598
767
 
599
 
Table *Open_tables_state::find_temporary_table(const identifier::Table &identifier)
 
768
Table *Session::find_temporary_table(const char *new_db, const char *table_name)
 
769
{
 
770
  char  key[MAX_DBKEY_LENGTH];
 
771
  uint  key_length;
 
772
 
 
773
  key_length= TableIdentifier::createKey(key, new_db, table_name);
 
774
 
 
775
  for (Table *table= temporary_tables ; table ; table= table->getNext())
 
776
  {
 
777
    const TableIdentifier::Key &share_key(table->getShare()->getCacheKey());
 
778
    if (share_key.size() == key_length &&
 
779
        not memcmp(&share_key[0], key, key_length))
 
780
    {
 
781
      return table;
 
782
    }
 
783
  }
 
784
  return NULL;                               // Not a temporary table
 
785
}
 
786
 
 
787
Table *Session::find_temporary_table(TableList *table_list)
 
788
{
 
789
  return find_temporary_table(table_list->db, table_list->table_name);
 
790
}
 
791
 
 
792
Table *Session::find_temporary_table(TableIdentifier &identifier)
600
793
{
601
794
  for (Table *table= temporary_tables ; table ; table= table->getNext())
602
795
  {
634
827
  @retval -1  the table is in use by a outer query
635
828
*/
636
829
 
637
 
int Open_tables_state::drop_temporary_table(const drizzled::identifier::Table &identifier)
 
830
int Session::drop_temporary_table(TableList *table_list)
638
831
{
639
832
  Table *table;
640
833
 
641
 
  if (not (table= find_temporary_table(identifier)))
 
834
  if (not (table= find_temporary_table(table_list)))
642
835
    return 1;
643
836
 
644
837
  /* Table might be in use by some outer statement. */
645
 
  if (table->query_id && table->query_id != getQueryId())
 
838
  if (table->query_id && table->query_id != query_id)
646
839
  {
647
840
    my_error(ER_CANT_REOPEN_TABLE, MYF(0), table->getAlias());
648
841
    return -1;
660
853
 
661
854
  @param  session     Thread context
662
855
  @param  find    Table to remove
663
 
 
664
 
  @note because we risk the chance of deleting the share, we can't assume that it will exist past, this should be modified once we can use a TableShare::shared_ptr here.
665
856
*/
666
857
 
667
858
void Session::unlink_open_table(Table *find)
668
859
{
669
 
  const identifier::Table::Key find_key(find->getShare()->getCacheKey());
670
 
  Table **prev;
671
 
  safe_mutex_assert_owner(table::Cache::singleton().mutex().native_handle());
 
860
  char key[MAX_DBKEY_LENGTH];
 
861
  uint32_t key_length= find->getShare()->getCacheKeySize();
 
862
  Table *list, **prev;
 
863
  safe_mutex_assert_owner(LOCK_open.native_handle());
672
864
 
 
865
  memcpy(key, &find->getMutableShare()->getCacheKey()[0], key_length);
673
866
  /*
674
 
    Note that we need to hold table::Cache::singleton().mutex() while changing the
 
867
    Note that we need to hold LOCK_open while changing the
675
868
    open_tables list. Another thread may work on it.
676
 
    (See: table::Cache::singleton().removeTable(), wait_completed_table())
 
869
    (See: remove_table_from_cache(), mysql_wait_completed_table())
677
870
    Closing a MERGE child before the parent would be fatal if the
678
871
    other thread tries to abort the MERGE lock in between.
679
872
  */
680
873
  for (prev= &open_tables; *prev; )
681
874
  {
682
 
    Table *list= *prev;
 
875
    list= *prev;
683
876
 
684
 
    if (list->getShare()->getCacheKey() == find_key)
 
877
    if (list->getShare()->getCacheKeySize() == key_length &&
 
878
        not memcmp(&list->getShare()->getCacheKey()[0], key, key_length))
685
879
    {
686
880
      /* Remove table from open_tables list. */
687
881
      *prev= list->getNext();
688
882
 
689
883
      /* Close table. */
690
 
      table::remove_table(static_cast<table::Concurrent *>(list));
 
884
      remove_table(list);
691
885
    }
692
886
    else
693
887
    {
697
891
  }
698
892
 
699
893
  // Notify any 'refresh' threads
700
 
  locking::broadcast_refresh();
 
894
  broadcast_refresh();
701
895
}
702
896
 
703
897
 
720
914
  table that was locked with LOCK TABLES.
721
915
*/
722
916
 
723
 
void Session::drop_open_table(Table *table, const identifier::Table &identifier)
 
917
void Session::drop_open_table(Table *table, TableIdentifier &identifier)
724
918
{
725
919
  if (table->getShare()->getType())
726
920
  {
728
922
  }
729
923
  else
730
924
  {
731
 
    boost_unique_lock_t scoped_lock(table::Cache::singleton().mutex()); /* Close and drop a table (AUX routine) */
 
925
    LOCK_open.lock(); /* Close and drop a table (AUX routine) */
732
926
    /*
733
927
      unlink_open_table() also tells threads waiting for refresh or close
734
928
      that something has happened.
735
929
    */
736
930
    unlink_open_table(table);
737
 
    (void)plugin::StorageEngine::dropTable(*this, identifier);
 
931
    quick_rm_table(*this, identifier);
 
932
    LOCK_open.unlock();
738
933
  }
739
934
}
740
935
 
750
945
  cond  Condition to wait for
751
946
*/
752
947
 
753
 
void Session::wait_for_condition(boost::mutex &mutex, boost::condition_variable_any &cond)
 
948
void Session::wait_for_condition(boost::mutex &mutex, boost::condition_variable &cond)
754
949
{
755
950
  /* Wait until the current table is up to date */
756
951
  const char *saved_proc_info;
757
 
  mysys_var->current_mutex= &mutex;
758
 
  mysys_var->current_cond= &cond;
 
952
  mysys_var->current_mutex= mutex.native_handle();
 
953
  mysys_var->current_cond= cond.native_handle();
759
954
  saved_proc_info= get_proc_info();
760
955
  set_proc_info("Waiting for table");
761
 
  {
762
 
    /*
763
 
      We must unlock mutex first to avoid deadlock becasue conditions are
764
 
      sent to this thread by doing locks in the following order:
765
 
      lock(mysys_var->mutex)
766
 
      lock(mysys_var->current_mutex)
767
 
 
768
 
      One by effect of this that one can only use wait_for_condition with
769
 
      condition variables that are guranteed to not disapper (freed) even if this
770
 
      mutex is unlocked
771
 
    */
772
 
    boost_unique_lock_t scopedLock(mutex, boost::adopt_lock_t());
773
 
    if (not getKilled())
774
 
    {
775
 
      cond.wait(scopedLock);
776
 
    }
777
 
  }
778
 
  boost_unique_lock_t mysys_scopedLock(mysys_var->mutex);
 
956
  if (!killed)
 
957
    (void) pthread_cond_wait(cond.native_handle(), mutex.native_handle());
 
958
 
 
959
  /*
 
960
    We must unlock mutex first to avoid deadlock becasue conditions are
 
961
    sent to this thread by doing locks in the following order:
 
962
    lock(mysys_var->mutex)
 
963
    lock(mysys_var->current_mutex)
 
964
 
 
965
    One by effect of this that one can only use wait_for_condition with
 
966
    condition variables that are guranteed to not disapper (freed) even if this
 
967
    mutex is unlocked
 
968
  */
 
969
 
 
970
  pthread_mutex_unlock(mutex.native_handle());
 
971
  pthread_mutex_lock(&mysys_var->mutex);
779
972
  mysys_var->current_mutex= 0;
780
973
  mysys_var->current_cond= 0;
781
974
  set_proc_info(saved_proc_info);
 
975
  pthread_mutex_unlock(&mysys_var->mutex);
 
976
}
 
977
 
 
978
 
 
979
/*
 
980
  Open table which is already name-locked by this thread.
 
981
 
 
982
  SYNOPSIS
 
983
  reopen_name_locked_table()
 
984
  session         Thread handle
 
985
  table_list  TableList object for table to be open, TableList::table
 
986
  member should point to Table object which was used for
 
987
  name-locking.
 
988
  link_in     true  - if Table object for table to be opened should be
 
989
  linked into Session::open_tables list.
 
990
  false - placeholder used for name-locking is already in
 
991
  this list so we only need to preserve Table::next
 
992
  pointer.
 
993
 
 
994
  NOTE
 
995
  This function assumes that its caller already acquired LOCK_open mutex.
 
996
 
 
997
  RETURN VALUE
 
998
  false - Success
 
999
  true  - Error
 
1000
*/
 
1001
 
 
1002
bool Session::reopen_name_locked_table(TableList* table_list, bool link_in)
 
1003
{
 
1004
  Table *table= table_list->table;
 
1005
  TableShare *share;
 
1006
  char *table_name= table_list->table_name;
 
1007
  Table orig_table;
 
1008
 
 
1009
  safe_mutex_assert_owner(LOCK_open.native_handle());
 
1010
 
 
1011
  if (killed || !table)
 
1012
    return true;
 
1013
 
 
1014
  orig_table= *table;
 
1015
 
 
1016
  TableIdentifier identifier(table_list->db, table_list->table_name);
 
1017
  if (open_unireg_entry(this, table, table_name, identifier))
 
1018
  {
 
1019
    table->intern_close_table();
 
1020
    /*
 
1021
      If there was an error during opening of table (for example if it
 
1022
      does not exist) '*table' object can be wiped out. To be able
 
1023
      properly release name-lock in this case we should restore this
 
1024
      object to its original state.
 
1025
    */
 
1026
    *table= orig_table;
 
1027
    return true;
 
1028
  }
 
1029
 
 
1030
  share= table->getMutableShare();
 
1031
  /*
 
1032
    We want to prevent other connections from opening this table until end
 
1033
    of statement as it is likely that modifications of table's metadata are
 
1034
    not yet finished (for example CREATE TRIGGER have to change .TRG cursor,
 
1035
    or we might want to drop table if CREATE TABLE ... SELECT fails).
 
1036
    This also allows us to assume that no other connection will sneak in
 
1037
    before we will get table-level lock on this table.
 
1038
  */
 
1039
  share->resetVersion();
 
1040
  table->in_use = this;
 
1041
 
 
1042
  if (link_in)
 
1043
  {
 
1044
    table->setNext(open_tables);
 
1045
    open_tables= table;
 
1046
  }
 
1047
  else
 
1048
  {
 
1049
    /*
 
1050
      Table object should be already in Session::open_tables list so we just
 
1051
      need to set Table::next correctly.
 
1052
    */
 
1053
    table->setNext(orig_table.getNext());
 
1054
  }
 
1055
 
 
1056
  table->tablenr= current_tablenr++;
 
1057
  table->used_fields= 0;
 
1058
  table->const_table= 0;
 
1059
  table->null_row= false;
 
1060
  table->maybe_null= false;
 
1061
  table->force_index= false;
 
1062
  table->status= STATUS_NO_RECORD;
 
1063
 
 
1064
  return false;
782
1065
}
783
1066
 
784
1067
 
795
1078
  case of failure.
796
1079
*/
797
1080
 
798
 
table::Placeholder *Session::table_cache_insert_placeholder(const drizzled::identifier::Table &arg)
 
1081
Table *Session::table_cache_insert_placeholder(const char *db_name, const char *table_name)
799
1082
{
800
 
  safe_mutex_assert_owner(table::Cache::singleton().mutex().native_handle());
 
1083
  safe_mutex_assert_owner(LOCK_open.native_handle());
801
1084
 
802
1085
  /*
803
1086
    Create a table entry with the right key and with an old refresh version
 
1087
    Note that we must use multi_malloc() here as this is freed by the
 
1088
    table cache
804
1089
  */
805
 
  identifier::Table identifier(arg.getSchemaName(), arg.getTableName(), message::Table::INTERNAL);
806
 
  table::Placeholder *table= new table::Placeholder(this, identifier);
 
1090
  TableIdentifier identifier(db_name, table_name, message::Table::INTERNAL);
 
1091
  TablePlaceholder *table= new TablePlaceholder(this, identifier);
807
1092
 
808
 
  if (not table::Cache::singleton().insert(table))
 
1093
  if (not add_table(table))
809
1094
  {
810
1095
    delete table;
811
1096
 
837
1122
  @retval  true   Error occured (OOM)
838
1123
  @retval  false  Success. 'table' parameter set according to above rules.
839
1124
*/
840
 
bool Session::lock_table_name_if_not_cached(const identifier::Table &identifier, Table **table)
 
1125
bool Session::lock_table_name_if_not_cached(TableIdentifier &identifier, Table **table)
841
1126
{
842
 
  const identifier::Table::Key &key(identifier.getKey());
843
 
 
844
 
  boost_unique_lock_t scope_lock(table::Cache::singleton().mutex()); /* Obtain a name lock even though table is not in cache (like for create table)  */
845
 
 
846
 
  table::CacheMap::iterator iter;
847
 
 
848
 
  iter= table::getCache().find(key);
849
 
 
850
 
  if (iter != table::getCache().end())
 
1127
  const TableIdentifier::Key &key(identifier.getKey());
 
1128
 
 
1129
  LOCK_open.lock(); /* Obtain a name lock even though table is not in cache (like for create table)  */
 
1130
 
 
1131
  TableOpenCache::iterator iter;
 
1132
 
 
1133
  iter= get_open_cache().find(key);
 
1134
 
 
1135
  if (iter != get_open_cache().end())
851
1136
  {
 
1137
    LOCK_open.unlock();
852
1138
    *table= 0;
853
1139
    return false;
854
1140
  }
855
1141
 
856
 
  if (not (*table= table_cache_insert_placeholder(identifier)))
 
1142
  if (not (*table= table_cache_insert_placeholder(identifier.getSchemaName().c_str(), identifier.getTableName().c_str())))
857
1143
  {
 
1144
    LOCK_open.unlock();
858
1145
    return true;
859
1146
  }
860
1147
  (*table)->open_placeholder= true;
861
1148
  (*table)->setNext(open_tables);
862
1149
  open_tables= *table;
 
1150
  LOCK_open.unlock();
863
1151
 
864
1152
  return false;
865
1153
}
913
1201
  if (check_stack_overrun(this, STACK_MIN_SIZE_FOR_OPEN, (unsigned char *)&alias))
914
1202
    return NULL;
915
1203
 
916
 
  if (getKilled())
 
1204
  if (killed)
917
1205
    return NULL;
918
1206
 
919
 
  identifier::Table identifier(table_list->getSchemaName(), table_list->getTableName());
920
 
  const identifier::Table::Key &key(identifier.getKey());
921
 
  table::CacheRange ppp;
 
1207
  TableIdentifier identifier(table_list->db, table_list->table_name);
 
1208
  const TableIdentifier::Key &key(identifier.getKey());
 
1209
  TableOpenCacheRange ppp;
922
1210
 
923
1211
  /*
924
1212
    Unless requested otherwise, try to resolve this table in the list
927
1215
    same name. This block implements the behaviour.
928
1216
    TODO -> move this block into a separate function.
929
1217
  */
930
 
  bool reset= false;
931
 
  for (table= getTemporaryTables(); table ; table=table->getNext())
 
1218
  for (table= temporary_tables; table ; table=table->getNext())
932
1219
  {
933
1220
    if (table->getShare()->getCacheKey() == key)
934
1221
    {
944
1231
        return NULL;
945
1232
      }
946
1233
      table->query_id= getQueryId();
947
 
      reset= true;
 
1234
      goto reset;
 
1235
    }
 
1236
  }
 
1237
 
 
1238
  if (flags & DRIZZLE_OPEN_TEMPORARY_ONLY)
 
1239
  {
 
1240
    my_error(ER_NO_SUCH_TABLE, MYF(0), table_list->db, table_list->table_name);
 
1241
    return NULL;
 
1242
  }
 
1243
 
 
1244
  /*
 
1245
    If it's the first table from a list of tables used in a query,
 
1246
    remember refresh_version (the version of open_cache state).
 
1247
    If the version changes while we're opening the remaining tables,
 
1248
    we will have to back off, close all the tables opened-so-far,
 
1249
    and try to reopen them.
 
1250
 
 
1251
    Note-> refresh_version is currently changed only during FLUSH TABLES.
 
1252
  */
 
1253
  if (!open_tables)
 
1254
  {
 
1255
    version= refresh_version;
 
1256
  }
 
1257
  else if ((version != refresh_version) &&
 
1258
           ! (flags & DRIZZLE_LOCK_IGNORE_FLUSH))
 
1259
  {
 
1260
    /* Someone did a refresh while thread was opening tables */
 
1261
    if (refresh)
 
1262
      *refresh= true;
 
1263
 
 
1264
    return NULL;
 
1265
  }
 
1266
 
 
1267
  /*
 
1268
    Before we test the global cache, we test our local session cache.
 
1269
  */
 
1270
  if (cached_table)
 
1271
  {
 
1272
    assert(false); /* Not implemented yet */
 
1273
  }
 
1274
 
 
1275
  /*
 
1276
    Non pre-locked/LOCK TABLES mode, and the table is not temporary:
 
1277
    this is the normal use case.
 
1278
    Now we should:
 
1279
    - try to find the table in the table cache.
 
1280
    - if one of the discovered Table instances is name-locked
 
1281
    (table->getShare()->version == 0) back off -- we have to wait
 
1282
    until no one holds a name lock on the table.
 
1283
    - if there is no such Table in the name cache, read the table definition
 
1284
    and insert it into the cache.
 
1285
    We perform all of the above under LOCK_open which currently protects
 
1286
    the open cache (also known as table cache) and table definitions stored
 
1287
    on disk.
 
1288
  */
 
1289
 
 
1290
  LOCK_open.lock(); /* Lock for FLUSH TABLES for open table */
 
1291
 
 
1292
  /*
 
1293
    Actually try to find the table in the open_cache.
 
1294
    The cache may contain several "Table" instances for the same
 
1295
    physical table. The instances that are currently "in use" by
 
1296
    some thread have their "in_use" member != NULL.
 
1297
    There is no good reason for having more than one entry in the
 
1298
    hash for the same physical table, except that we use this as
 
1299
    an implicit "pending locks queue" - see
 
1300
    wait_for_locked_table_names for details.
 
1301
  */
 
1302
  ppp= get_open_cache().equal_range(key);
 
1303
 
 
1304
  table= NULL;
 
1305
  for (TableOpenCache::const_iterator iter= ppp.first;
 
1306
       iter != ppp.second; ++iter, table= NULL)
 
1307
  {
 
1308
    table= (*iter).second;
 
1309
 
 
1310
    if (not table->in_use)
948
1311
      break;
949
 
    }
950
 
  }
951
 
 
952
 
  if (not reset)
953
 
  {
954
 
    if (flags & DRIZZLE_OPEN_TEMPORARY_ONLY)
955
 
    {
956
 
      my_error(ER_TABLE_UNKNOWN, identifier);
957
 
      return NULL;
958
 
    }
959
 
 
960
1312
    /*
961
 
      If it's the first table from a list of tables used in a query,
962
 
      remember refresh_version (the version of open_cache state).
963
 
      If the version changes while we're opening the remaining tables,
964
 
      we will have to back off, close all the tables opened-so-far,
965
 
      and try to reopen them.
966
 
 
967
 
      Note-> refresh_version is currently changed only during FLUSH TABLES.
 
1313
      Here we flush tables marked for flush.
 
1314
      Normally, table->getShare()->version contains the value of
 
1315
      refresh_version from the moment when this table was
 
1316
      (re-)opened and added to the cache.
 
1317
      If since then we did (or just started) FLUSH TABLES
 
1318
      statement, refresh_version has been increased.
 
1319
      For "name-locked" Table instances, table->getShare()->version is set
 
1320
      to 0 (see lock_table_name for details).
 
1321
      In case there is a pending FLUSH TABLES or a name lock, we
 
1322
      need to back off and re-start opening tables.
 
1323
      If we do not back off now, we may dead lock in case of lock
 
1324
      order mismatch with some other thread:
 
1325
      c1-> name lock t1; -- sort of exclusive lock
 
1326
      c2-> open t2;      -- sort of shared lock
 
1327
      c1-> name lock t2; -- blocks
 
1328
      c2-> open t1; -- blocks
968
1329
    */
969
 
    if (!open_tables)
970
 
    {
971
 
      version= refresh_version;
972
 
    }
973
 
    else if ((version != refresh_version) &&
974
 
             ! (flags & DRIZZLE_LOCK_IGNORE_FLUSH))
975
 
    {
976
 
      /* Someone did a refresh while thread was opening tables */
 
1330
    if (table->needs_reopen_or_name_lock())
 
1331
    {
 
1332
      if (flags & DRIZZLE_LOCK_IGNORE_FLUSH)
 
1333
      {
 
1334
        /* Force close at once after usage */
 
1335
        version= table->getShare()->getVersion();
 
1336
        continue;
 
1337
      }
 
1338
 
 
1339
      /* Avoid self-deadlocks by detecting self-dependencies. */
 
1340
      if (table->open_placeholder && table->in_use == this)
 
1341
      {
 
1342
        LOCK_open.unlock();
 
1343
        my_error(ER_UPDATE_TABLE_USED, MYF(0), table->getMutableShare()->getTableName());
 
1344
        return NULL;
 
1345
      }
 
1346
 
 
1347
      /*
 
1348
        Back off, part 1: mark the table as "unused" for the
 
1349
        purpose of name-locking by setting table->db_stat to 0. Do
 
1350
        that only for the tables in this thread that have an old
 
1351
        table->getShare()->version (this is an optimization (?)).
 
1352
        table->db_stat == 0 signals wait_for_locked_table_names
 
1353
        that the tables in question are not used any more. See
 
1354
        table_is_used call for details.
 
1355
      */
 
1356
      close_old_data_files(false, false);
 
1357
 
 
1358
      /*
 
1359
        Back-off part 2: try to avoid "busy waiting" on the table:
 
1360
        if the table is in use by some other thread, we suspend
 
1361
        and wait till the operation is complete: when any
 
1362
        operation that juggles with table->getShare()->version completes,
 
1363
        it broadcasts COND_refresh condition variable.
 
1364
        If 'old' table we met is in use by current thread we return
 
1365
        without waiting since in this situation it's this thread
 
1366
        which is responsible for broadcasting on COND_refresh
 
1367
        (and this was done already in Session::close_old_data_files()).
 
1368
        Good example of such situation is when we have statement
 
1369
        that needs two instances of table and FLUSH TABLES comes
 
1370
        after we open first instance but before we open second
 
1371
        instance.
 
1372
      */
 
1373
      if (table->in_use != this)
 
1374
      {
 
1375
        /* wait_for_conditionwill unlock LOCK_open for us */
 
1376
        wait_for_condition(LOCK_open, COND_refresh);
 
1377
      }
 
1378
      else
 
1379
      {
 
1380
        LOCK_open.unlock();
 
1381
      }
 
1382
      /*
 
1383
        There is a refresh in progress for this table.
 
1384
        Signal the caller that it has to try again.
 
1385
      */
977
1386
      if (refresh)
978
1387
        *refresh= true;
979
 
 
980
1388
      return NULL;
981
1389
    }
982
 
 
983
 
    /*
984
 
      Before we test the global cache, we test our local session cache.
985
 
    */
986
 
    if (cached_table)
987
 
    {
988
 
      assert(false); /* Not implemented yet */
989
 
    }
990
 
 
991
 
    /*
992
 
      Non pre-locked/LOCK TABLES mode, and the table is not temporary:
993
 
      this is the normal use case.
994
 
      Now we should:
995
 
      - try to find the table in the table cache.
996
 
      - if one of the discovered Table instances is name-locked
997
 
      (table->getShare()->version == 0) back off -- we have to wait
998
 
      until no one holds a name lock on the table.
999
 
      - if there is no such Table in the name cache, read the table definition
1000
 
      and insert it into the cache.
1001
 
      We perform all of the above under table::Cache::singleton().mutex() which currently protects
1002
 
      the open cache (also known as table cache) and table definitions stored
1003
 
      on disk.
1004
 
    */
1005
 
 
1006
 
    {
1007
 
      boost::mutex::scoped_lock scopedLock(table::Cache::singleton().mutex());
1008
 
 
1009
 
      /*
1010
 
        Actually try to find the table in the open_cache.
1011
 
        The cache may contain several "Table" instances for the same
1012
 
        physical table. The instances that are currently "in use" by
1013
 
        some thread have their "in_use" member != NULL.
1014
 
        There is no good reason for having more than one entry in the
1015
 
        hash for the same physical table, except that we use this as
1016
 
        an implicit "pending locks queue" - see
1017
 
        wait_for_locked_table_names for details.
1018
 
      */
1019
 
      ppp= table::getCache().equal_range(key);
1020
 
 
1021
 
      table= NULL;
1022
 
      for (table::CacheMap::const_iterator iter= ppp.first;
1023
 
           iter != ppp.second; ++iter, table= NULL)
 
1390
  }
 
1391
  if (table)
 
1392
  {
 
1393
    unused_tables.unlink(table);
 
1394
    table->in_use= this;
 
1395
  }
 
1396
  else
 
1397
  {
 
1398
    /* Insert a new Table instance into the open cache */
 
1399
    int error;
 
1400
    /* Free cache if too big */
 
1401
    unused_tables.cull();
 
1402
 
 
1403
    if (table_list->isCreate())
 
1404
    {
 
1405
      TableIdentifier  lock_table_identifier(table_list->db, table_list->table_name, message::Table::STANDARD);
 
1406
 
 
1407
      if (not plugin::StorageEngine::doesTableExist(*this, lock_table_identifier))
1024
1408
      {
1025
 
        table= (*iter).second;
1026
 
 
1027
 
        if (not table->in_use)
1028
 
          break;
1029
1409
        /*
1030
 
          Here we flush tables marked for flush.
1031
 
          Normally, table->getShare()->version contains the value of
1032
 
          refresh_version from the moment when this table was
1033
 
          (re-)opened and added to the cache.
1034
 
          If since then we did (or just started) FLUSH TABLES
1035
 
          statement, refresh_version has been increased.
1036
 
          For "name-locked" Table instances, table->getShare()->version is set
1037
 
          to 0 (see lock_table_name for details).
1038
 
          In case there is a pending FLUSH TABLES or a name lock, we
1039
 
          need to back off and re-start opening tables.
1040
 
          If we do not back off now, we may dead lock in case of lock
1041
 
          order mismatch with some other thread:
1042
 
          c1-> name lock t1; -- sort of exclusive lock
1043
 
          c2-> open t2;      -- sort of shared lock
1044
 
          c1-> name lock t2; -- blocks
1045
 
          c2-> open t1; -- blocks
 
1410
          Table to be created, so we need to create placeholder in table-cache.
1046
1411
        */
1047
 
        if (table->needs_reopen_or_name_lock())
 
1412
        if (!(table= table_cache_insert_placeholder(table_list->db, table_list->table_name)))
1048
1413
        {
1049
 
          if (flags & DRIZZLE_LOCK_IGNORE_FLUSH)
1050
 
          {
1051
 
            /* Force close at once after usage */
1052
 
            version= table->getShare()->getVersion();
1053
 
            continue;
1054
 
          }
1055
 
 
1056
 
          /* Avoid self-deadlocks by detecting self-dependencies. */
1057
 
          if (table->open_placeholder && table->in_use == this)
1058
 
          {
1059
 
            my_error(ER_UPDATE_TABLE_USED, MYF(0), table->getShare()->getTableName());
1060
 
            return NULL;
1061
 
          }
1062
 
 
1063
 
          /*
1064
 
            Back off, part 1: mark the table as "unused" for the
1065
 
            purpose of name-locking by setting table->db_stat to 0. Do
1066
 
            that only for the tables in this thread that have an old
1067
 
            table->getShare()->version (this is an optimization (?)).
1068
 
            table->db_stat == 0 signals wait_for_locked_table_names
1069
 
            that the tables in question are not used any more. See
1070
 
            table_is_used call for details.
1071
 
          */
1072
 
          close_old_data_files(false, false);
1073
 
 
1074
 
          /*
1075
 
            Back-off part 2: try to avoid "busy waiting" on the table:
1076
 
            if the table is in use by some other thread, we suspend
1077
 
            and wait till the operation is complete: when any
1078
 
            operation that juggles with table->getShare()->version completes,
1079
 
            it broadcasts COND_refresh condition variable.
1080
 
            If 'old' table we met is in use by current thread we return
1081
 
            without waiting since in this situation it's this thread
1082
 
            which is responsible for broadcasting on COND_refresh
1083
 
            (and this was done already in Session::close_old_data_files()).
1084
 
            Good example of such situation is when we have statement
1085
 
            that needs two instances of table and FLUSH TABLES comes
1086
 
            after we open first instance but before we open second
1087
 
            instance.
1088
 
          */
1089
 
          if (table->in_use != this)
1090
 
          {
1091
 
            /* wait_for_conditionwill unlock table::Cache::singleton().mutex() for us */
1092
 
            wait_for_condition(table::Cache::singleton().mutex(), COND_refresh);
1093
 
            scopedLock.release();
1094
 
          }
1095
 
          else
1096
 
          {
1097
 
            scopedLock.unlock();
1098
 
          }
1099
 
 
1100
 
          /*
1101
 
            There is a refresh in progress for this table.
1102
 
            Signal the caller that it has to try again.
1103
 
          */
1104
 
          if (refresh)
1105
 
            *refresh= true;
1106
 
 
 
1414
          LOCK_open.unlock();
1107
1415
          return NULL;
1108
1416
        }
1109
 
      }
1110
 
 
1111
 
      if (table)
1112
 
      {
1113
 
        table::getUnused().unlink(static_cast<table::Concurrent *>(table));
1114
 
        table->in_use= this;
1115
 
      }
1116
 
      else
1117
 
      {
1118
 
        /* Insert a new Table instance into the open cache */
1119
 
        int error;
1120
 
        /* Free cache if too big */
1121
 
        table::getUnused().cull();
1122
 
 
1123
 
        if (table_list->isCreate())
1124
 
        {
1125
 
          identifier::Table  lock_table_identifier(table_list->getSchemaName(), table_list->getTableName(), message::Table::STANDARD);
1126
 
 
1127
 
          if (not plugin::StorageEngine::doesTableExist(*this, lock_table_identifier))
1128
 
          {
1129
 
            /*
1130
 
              Table to be created, so we need to create placeholder in table-cache.
1131
 
            */
1132
 
            if (!(table= table_cache_insert_placeholder(lock_table_identifier)))
1133
 
            {
1134
 
              return NULL;
1135
 
            }
1136
 
            /*
1137
 
              Link placeholder to the open tables list so it will be automatically
1138
 
              removed once tables are closed. Also mark it so it won't be ignored
1139
 
              by other trying to take name-lock.
1140
 
            */
1141
 
            table->open_placeholder= true;
1142
 
            table->setNext(open_tables);
1143
 
            open_tables= table;
1144
 
 
1145
 
            return table ;
1146
 
          }
1147
 
          /* Table exists. Let us try to open it. */
1148
 
        }
1149
 
 
1150
 
        /* make a new table */
1151
 
        {
1152
 
          table::Concurrent *new_table= new table::Concurrent;
1153
 
          table= new_table;
1154
 
          if (new_table == NULL)
1155
 
          {
1156
 
            return NULL;
1157
 
          }
1158
 
 
1159
 
          error= new_table->open_unireg_entry(this, alias, identifier);
1160
 
          if (error != 0)
1161
 
          {
1162
 
            delete new_table;
1163
 
            return NULL;
1164
 
          }
1165
 
          (void)table::Cache::singleton().insert(new_table);
1166
 
        }
1167
 
      }
1168
 
    }
1169
 
 
1170
 
    if (refresh)
1171
 
    {
1172
 
      table->setNext(open_tables); /* Link into simple list */
1173
 
      open_tables= table;
1174
 
    }
1175
 
    table->reginfo.lock_type= TL_READ; /* Assume read */
1176
 
 
1177
 
  }
 
1417
        /*
 
1418
          Link placeholder to the open tables list so it will be automatically
 
1419
          removed once tables are closed. Also mark it so it won't be ignored
 
1420
          by other trying to take name-lock.
 
1421
        */
 
1422
        table->open_placeholder= true;
 
1423
        table->setNext(open_tables);
 
1424
        open_tables= table;
 
1425
        LOCK_open.unlock();
 
1426
 
 
1427
        return table ;
 
1428
      }
 
1429
      /* Table exists. Let us try to open it. */
 
1430
    }
 
1431
 
 
1432
    /* make a new table */
 
1433
    table= new Table;
 
1434
    if (table == NULL)
 
1435
    {
 
1436
      LOCK_open.unlock();
 
1437
      return NULL;
 
1438
    }
 
1439
 
 
1440
    error= open_unireg_entry(this, table, alias, identifier);
 
1441
    if (error != 0)
 
1442
    {
 
1443
      delete table;
 
1444
      LOCK_open.unlock();
 
1445
      return NULL;
 
1446
    }
 
1447
    (void)add_table(table);
 
1448
  }
 
1449
 
 
1450
  LOCK_open.unlock();
 
1451
  if (refresh)
 
1452
  {
 
1453
    table->setNext(open_tables); /* Link into simple list */
 
1454
    open_tables= table;
 
1455
  }
 
1456
  table->reginfo.lock_type= TL_READ; /* Assume read */
 
1457
 
 
1458
reset:
1178
1459
  assert(table->getShare()->getTableCount() > 0 || table->getShare()->getType() != message::Table::STANDARD);
1179
1460
 
 
1461
  if (lex->need_correct_ident())
 
1462
    table->alias_name_used= my_strcasecmp(table_alias_charset,
 
1463
                                          table->getMutableShare()->getTableName(), alias);
1180
1464
  /* Fix alias if table name changes */
1181
1465
  if (strcmp(table->getAlias(), alias))
1182
1466
  {
1183
 
    table->setAlias(alias);
 
1467
    uint32_t length=(uint32_t) strlen(alias)+1;
 
1468
    table->alias= (char*) realloc((char*) table->alias, length);
 
1469
    memcpy((void*) table->alias, alias, length);
1184
1470
  }
1185
1471
 
1186
1472
  /* These variables are also set in reopen_table() */
1207
1493
}
1208
1494
 
1209
1495
 
 
1496
#if 0
 
1497
/*
 
1498
  Reopen an table because the definition has changed.
 
1499
 
 
1500
  SYNOPSIS
 
1501
  reopen_table()
 
1502
  table Table object
 
1503
 
 
1504
  NOTES
 
1505
  The data cursor for the table is already closed and the share is released
 
1506
  The table has a 'dummy' share that mainly contains database and table name.
 
1507
 
 
1508
  RETURN
 
1509
  0  ok
 
1510
  1  error. The old table object is not changed.
 
1511
*/
 
1512
 
 
1513
bool reopen_table(Table *table)
 
1514
{
 
1515
  Table tmp;
 
1516
  bool error= 1;
 
1517
  Field **field;
 
1518
  uint32_t key,part;
 
1519
  TableList table_list;
 
1520
  Session *session= table->in_use;
 
1521
 
 
1522
  assert(table->getShare()->ref_count == 0);
 
1523
  assert(!table->sort.io_cache);
 
1524
 
 
1525
#ifdef EXTRA_DEBUG
 
1526
  if (table->db_stat)
 
1527
    errmsg_printf(ERRMSG_LVL_ERROR, _("Table %s had a open data Cursor in reopen_table"),
 
1528
                  table->alias);
 
1529
#endif
 
1530
  table_list.db=         const_cast<char *>(table->getShare()->getSchemaName());
 
1531
  table_list.table_name= table->getShare()->getTableName();
 
1532
  table_list.table=      table;
 
1533
 
 
1534
  if (wait_for_locked_table_names(session, &table_list))
 
1535
    return true;                             // Thread was killed
 
1536
 
 
1537
  if (open_unireg_entry(session, &tmp, &table_list,
 
1538
                        table->alias,
 
1539
                        table->getShare()->getCacheKey(),
 
1540
                        table->getShare()->getCacheKeySize()))
 
1541
    goto end;
 
1542
 
 
1543
  /* This list copies variables set by open_table */
 
1544
  tmp.tablenr=          table->tablenr;
 
1545
  tmp.used_fields=      table->used_fields;
 
1546
  tmp.const_table=      table->const_table;
 
1547
  tmp.null_row=         table->null_row;
 
1548
  tmp.maybe_null=       table->maybe_null;
 
1549
  tmp.status=           table->status;
 
1550
 
 
1551
  /* Get state */
 
1552
  tmp.in_use=           session;
 
1553
  tmp.reginfo.lock_type=table->reginfo.lock_type;
 
1554
 
 
1555
  /* Replace table in open list */
 
1556
  tmp.next=             table->next;
 
1557
  tmp.prev=             table->prev;
 
1558
 
 
1559
  if (table->cursor)
 
1560
    table->delete_table(true);          // close cursor, free everything
 
1561
 
 
1562
  *table= tmp;
 
1563
  table->default_column_bitmaps();
 
1564
  table->cursor->change_table_ptr(table, table->s);
 
1565
 
 
1566
  assert(table->alias != 0);
 
1567
  for (field=table->field ; *field ; field++)
 
1568
  {
 
1569
    (*field)->table= (*field)->orig_table= table;
 
1570
    (*field)->table_name= &table->alias;
 
1571
  }
 
1572
  for (key=0 ; key < table->getShare()->keys ; key++)
 
1573
  {
 
1574
    for (part=0 ; part < table->key_info[key].usable_key_parts ; part++)
 
1575
      table->key_info[key].key_part[part].field->table= table;
 
1576
  }
 
1577
 
 
1578
  broadcast_refresh();
 
1579
  error= false;
 
1580
 
 
1581
end:
 
1582
  return(error);
 
1583
}
 
1584
#endif
 
1585
 
 
1586
 
1210
1587
/**
1211
1588
  Close all instances of a table open by this thread and replace
1212
1589
  them with exclusive name-locks.
1224
1601
  the strings are used in a loop even after the share may be freed.
1225
1602
*/
1226
1603
 
1227
 
void Session::close_data_files_and_morph_locks(const identifier::Table &identifier)
 
1604
void Session::close_data_files_and_morph_locks(TableIdentifier &identifier)
1228
1605
{
1229
 
  safe_mutex_assert_owner(table::Cache::singleton().mutex().native_handle()); /* Adjust locks at the end of ALTER TABLEL */
 
1606
  safe_mutex_assert_owner(LOCK_open.native_handle()); /* Adjust locks at the end of ALTER TABLEL */
1230
1607
 
1231
1608
  if (lock)
1232
1609
  {
1234
1611
      If we are not under LOCK TABLES we should have only one table
1235
1612
      open and locked so it makes sense to remove the lock at once.
1236
1613
    */
1237
 
    unlockTables(lock);
 
1614
    mysql_unlock_tables(this, lock);
1238
1615
    lock= 0;
1239
1616
  }
1240
1617
 
1269
1646
  combination when one needs tables to be reopened (for
1270
1647
  example see openTablesLock()).
1271
1648
 
1272
 
  @note One should have lock on table::Cache::singleton().mutex() when calling this.
 
1649
  @note One should have lock on LOCK_open when calling this.
1273
1650
 
1274
1651
  @return false in case of success, true - otherwise.
1275
1652
*/
1276
1653
 
1277
 
bool Session::reopen_tables()
 
1654
bool Session::reopen_tables(bool get_locks, bool)
1278
1655
{
1279
1656
  Table *table,*next,**prev;
1280
 
  Table **tables= 0;                    // For locks
1281
 
  Table **tables_ptr= 0;                        // For locks
1282
 
  bool error= false;
 
1657
  Table **tables,**tables_ptr;                  // For locks
 
1658
  bool error=0, not_used;
1283
1659
  const uint32_t flags= DRIZZLE_LOCK_NOTIFY_IF_NEED_REOPEN |
1284
1660
    DRIZZLE_LOCK_IGNORE_GLOBAL_READ_LOCK |
1285
1661
    DRIZZLE_LOCK_IGNORE_FLUSH;
1287
1663
  if (open_tables == NULL)
1288
1664
    return false;
1289
1665
 
1290
 
  safe_mutex_assert_owner(table::Cache::singleton().mutex().native_handle());
 
1666
  safe_mutex_assert_owner(LOCK_open.native_handle());
 
1667
  if (get_locks)
1291
1668
  {
1292
1669
    /*
1293
1670
      The ptr is checked later
1301
1678
    }
1302
1679
    tables= new Table *[opens];
1303
1680
  }
1304
 
 
 
1681
  else
 
1682
  {
 
1683
    tables= &open_tables;
 
1684
  }
1305
1685
  tables_ptr =tables;
1306
1686
 
1307
1687
  prev= &open_tables;
1310
1690
    next= table->getNext();
1311
1691
 
1312
1692
    my_error(ER_CANT_REOPEN_TABLE, MYF(0), table->getAlias());
1313
 
    table::remove_table(static_cast<table::Concurrent *>(table));
 
1693
    remove_table(table);
1314
1694
    error= 1;
1315
1695
  }
1316
1696
  *prev=0;
1317
 
 
1318
1697
  if (tables != tables_ptr)                     // Should we get back old locks
1319
1698
  {
1320
1699
    DrizzleLock *local_lock;
1321
1700
    /*
1322
1701
      We should always get these locks. Anyway, we must not go into
1323
 
      wait_for_tables() as it tries to acquire table::Cache::singleton().mutex(), which is
 
1702
      wait_for_tables() as it tries to acquire LOCK_open, which is
1324
1703
      already locked.
1325
1704
    */
1326
1705
    some_tables_deleted= false;
1327
1706
 
1328
 
    if ((local_lock= lockTables(tables, (uint32_t) (tables_ptr - tables), flags)))
 
1707
    if ((local_lock= mysql_lock_tables(this, tables, (uint32_t) (tables_ptr - tables),
 
1708
                                 flags, &not_used)))
1329
1709
    {
1330
1710
      /* unused */
1331
1711
    }
1341
1721
    }
1342
1722
  }
1343
1723
 
1344
 
  delete [] tables;
1345
 
 
1346
 
  locking::broadcast_refresh();
1347
 
 
1348
 
  return error;
 
1724
  if (get_locks && tables)
 
1725
    delete [] tables;
 
1726
 
 
1727
  broadcast_refresh();
 
1728
 
 
1729
  return(error);
1349
1730
}
1350
1731
 
1351
1732
 
1376
1757
    */
1377
1758
    if (table->needs_reopen_or_name_lock())
1378
1759
    {
1379
 
      found= true;
 
1760
      found=1;
1380
1761
      if (table->db_stat)
1381
1762
      {
1382
1763
        if (morph_locks)
1390
1771
              lock on it. This will also give them a chance to close their
1391
1772
              instances of this table.
1392
1773
            */
1393
 
            abortLock(ulcktbl);
1394
 
            removeLock(ulcktbl);
 
1774
            mysql_lock_abort(this, ulcktbl);
 
1775
            mysql_lock_remove(this, ulcktbl);
1395
1776
            ulcktbl->lock_count= 0;
1396
1777
          }
1397
1778
          if ((ulcktbl != table) && ulcktbl->db_stat)
1431
1812
    }
1432
1813
  }
1433
1814
  if (found)
1434
 
    locking::broadcast_refresh();
 
1815
    broadcast_refresh();
 
1816
}
 
1817
 
 
1818
 
 
1819
/*
 
1820
  Wait until all threads has closed the tables in the list
 
1821
  We have also to wait if there is thread that has a lock on this table even
 
1822
  if the table is closed
 
1823
*/
 
1824
 
 
1825
bool table_is_used(Table *table, bool wait_for_name_lock)
 
1826
{
 
1827
  do
 
1828
  {
 
1829
    const TableIdentifier::Key &key(table->getShare()->getCacheKey());
 
1830
 
 
1831
    TableOpenCacheRange ppp;
 
1832
    ppp= get_open_cache().equal_range(key);
 
1833
 
 
1834
    for (TableOpenCache::const_iterator iter= ppp.first;
 
1835
         iter != ppp.second; ++iter)
 
1836
    {
 
1837
      Table *search= (*iter).second;
 
1838
      if (search->in_use == table->in_use)
 
1839
        continue;                               // Name locked by this thread
 
1840
      /*
 
1841
        We can't use the table under any of the following conditions:
 
1842
        - There is an name lock on it (Table is to be deleted or altered)
 
1843
        - If we are in flush table and we didn't execute the flush
 
1844
        - If the table engine is open and it's an old version
 
1845
        (We must wait until all engines are shut down to use the table)
 
1846
      */
 
1847
      if ( (search->locked_by_name && wait_for_name_lock) ||
 
1848
           (search->is_name_opened() && search->needs_reopen_or_name_lock()))
 
1849
        return 1;
 
1850
    }
 
1851
  } while ((table=table->getNext()));
 
1852
  return 0;
 
1853
}
 
1854
 
 
1855
 
 
1856
/* Wait until all used tables are refreshed */
 
1857
 
 
1858
bool wait_for_tables(Session *session)
 
1859
{
 
1860
  bool result;
 
1861
 
 
1862
  session->set_proc_info("Waiting for tables");
 
1863
  LOCK_open.lock(); /* Lock for all tables to be refreshed */
 
1864
  while (!session->killed)
 
1865
  {
 
1866
    session->some_tables_deleted= false;
 
1867
    session->close_old_data_files(false, dropping_tables != 0);
 
1868
    if (!table_is_used(session->open_tables, 1))
 
1869
      break;
 
1870
    (void) pthread_cond_wait(COND_refresh.native_handle(),LOCK_open.native_handle());
 
1871
  }
 
1872
  if (session->killed)
 
1873
    result= true;                                       // aborted
 
1874
  else
 
1875
  {
 
1876
    /* Now we can open all tables without any interference */
 
1877
    session->set_proc_info("Reopen tables");
 
1878
    session->version= refresh_version;
 
1879
    result= session->reopen_tables(false, false);
 
1880
  }
 
1881
  LOCK_open.unlock();
 
1882
  session->set_proc_info(0);
 
1883
 
 
1884
  return result;
1435
1885
}
1436
1886
 
1437
1887
 
1459
1909
*/
1460
1910
 
1461
1911
 
1462
 
Table *drop_locked_tables(Session *session, const drizzled::identifier::Table &identifier)
 
1912
Table *drop_locked_tables(Session *session, const drizzled::TableIdentifier &identifier)
1463
1913
{
1464
1914
  Table *table,*next,**prev, *found= 0;
1465
1915
  prev= &session->open_tables;
1466
1916
 
1467
1917
  /*
1468
 
    Note that we need to hold table::Cache::singleton().mutex() while changing the
 
1918
    Note that we need to hold LOCK_open while changing the
1469
1919
    open_tables list. Another thread may work on it.
1470
 
    (See: table::Cache::singleton().removeTable(), wait_completed_table())
 
1920
    (See: remove_table_from_cache(), mysql_wait_completed_table())
1471
1921
    Closing a MERGE child before the parent would be fatal if the
1472
1922
    other thread tries to abort the MERGE lock in between.
1473
1923
  */
1476
1926
    next=table->getNext();
1477
1927
    if (table->getShare()->getCacheKey() == identifier.getKey())
1478
1928
    {
1479
 
      session->removeLock(table);
 
1929
      mysql_lock_remove(session, table);
1480
1930
 
1481
1931
      if (!found)
1482
1932
      {
1491
1941
      else
1492
1942
      {
1493
1943
        /* We already have a name lock, remove copy */
1494
 
        table::remove_table(static_cast<table::Concurrent *>(table));
 
1944
        remove_table(table);
1495
1945
      }
1496
1946
    }
1497
1947
    else
1501
1951
    }
1502
1952
  }
1503
1953
  *prev=0;
1504
 
 
1505
1954
  if (found)
1506
 
    locking::broadcast_refresh();
 
1955
    broadcast_refresh();
1507
1956
 
1508
 
  return found;
 
1957
  return(found);
1509
1958
}
1510
1959
 
1511
1960
 
1515
1964
  other threads trying to get the lock.
1516
1965
*/
1517
1966
 
1518
 
void abort_locked_tables(Session *session, const drizzled::identifier::Table &identifier)
 
1967
void abort_locked_tables(Session *session, const drizzled::TableIdentifier &identifier)
1519
1968
{
1520
1969
  Table *table;
1521
1970
  for (table= session->open_tables; table ; table= table->getNext())
1523
1972
    if (table->getShare()->getCacheKey() == identifier.getKey())
1524
1973
    {
1525
1974
      /* If MERGE child, forward lock handling to parent. */
1526
 
      session->abortLock(table);
1527
 
      assert(0);
 
1975
      mysql_lock_abort(session, table);
1528
1976
      break;
1529
1977
    }
1530
1978
  }
1531
1979
}
1532
1980
 
 
1981
/*
 
1982
  Load a table definition from cursor and open unireg table
 
1983
 
 
1984
  SYNOPSIS
 
1985
  open_unireg_entry()
 
1986
  session                       Thread handle
 
1987
  entry         Store open table definition here
 
1988
  table_list            TableList with db, table_name
 
1989
  alias         Alias name
 
1990
  cache_key             Key for share_cache
 
1991
  cache_key_length      length of cache_key
 
1992
 
 
1993
  NOTES
 
1994
  Extra argument for open is taken from session->open_options
 
1995
  One must have a lock on LOCK_open when calling this function
 
1996
 
 
1997
  RETURN
 
1998
  0     ok
 
1999
#       Error
 
2000
*/
 
2001
 
 
2002
static int open_unireg_entry(Session *session,
 
2003
                             Table *entry,
 
2004
                             const char *alias,
 
2005
                             TableIdentifier &identifier)
 
2006
{
 
2007
  int error;
 
2008
  TableShare *share;
 
2009
  uint32_t discover_retry_count= 0;
 
2010
 
 
2011
  safe_mutex_assert_owner(LOCK_open.native_handle());
 
2012
retry:
 
2013
  if (not (share= TableShare::getShareCreate(session,
 
2014
                                             identifier,
 
2015
                                             &error)))
 
2016
    return 1;
 
2017
 
 
2018
  while ((error= share->open_table_from_share(session,
 
2019
                                              identifier,
 
2020
                                              alias,
 
2021
                                              (uint32_t) (HA_OPEN_KEYFILE |
 
2022
                                                          HA_OPEN_RNDFILE |
 
2023
                                                          HA_GET_INDEX |
 
2024
                                                          HA_TRY_READ_ONLY),
 
2025
                                              session->open_options, *entry)))
 
2026
  {
 
2027
    if (error == 7)                             // Table def changed
 
2028
    {
 
2029
      share->resetVersion();                        // Mark share as old
 
2030
      if (discover_retry_count++)               // Retry once
 
2031
        goto err;
 
2032
 
 
2033
      /*
 
2034
        TODO->
 
2035
        Here we should wait until all threads has released the table.
 
2036
        For now we do one retry. This may cause a deadlock if there
 
2037
        is other threads waiting for other tables used by this thread.
 
2038
 
 
2039
        Proper fix would be to if the second retry failed:
 
2040
        - Mark that table def changed
 
2041
        - Return from open table
 
2042
        - Close all tables used by this thread
 
2043
        - Start waiting that the share is released
 
2044
        - Retry by opening all tables again
 
2045
      */
 
2046
 
 
2047
      /*
 
2048
        TO BE FIXED
 
2049
        To avoid deadlock, only wait for release if no one else is
 
2050
        using the share.
 
2051
      */
 
2052
      if (share->getTableCount() != 1)
 
2053
        goto err;
 
2054
      /* Free share and wait until it's released by all threads */
 
2055
      TableShare::release(share);
 
2056
 
 
2057
      if (!session->killed)
 
2058
      {
 
2059
        drizzle_reset_errors(session, 1);         // Clear warnings
 
2060
        session->clear_error();                 // Clear error message
 
2061
        goto retry;
 
2062
      }
 
2063
      return 1;
 
2064
    }
 
2065
 
 
2066
    goto err;
 
2067
  }
 
2068
 
 
2069
  return 0;
 
2070
 
 
2071
err:
 
2072
  TableShare::release(share);
 
2073
 
 
2074
  return 1;
 
2075
}
 
2076
 
1533
2077
 
1534
2078
/*
1535
2079
  Open all tables in list
1597
2141
     * to see if it exists so that an unauthorized user cannot phish for
1598
2142
     * table/schema information via error messages
1599
2143
     */
1600
 
    identifier::Table the_table(tables->getSchemaName(), tables->getTableName());
1601
 
    if (not plugin::Authorization::isAuthorized(user(), the_table))
 
2144
    TableIdentifier the_table(tables->db, tables->table_name);
 
2145
    if (not plugin::Authorization::isAuthorized(getSecurityContext(),
 
2146
                                                the_table))
1602
2147
    {
1603
2148
      result= -1;                               // Fatal error
1604
2149
      break;
1695
2240
 
1696
2241
  set_proc_info("Opening table");
1697
2242
  current_tablenr= 0;
1698
 
  while (!(table= openTable(table_list, &refresh)) && refresh) ;
 
2243
  while (!(table= openTable(table_list, &refresh)) &&
 
2244
         refresh)
 
2245
    ;
1699
2246
 
1700
2247
  if (table)
1701
2248
  {
1704
2251
 
1705
2252
    assert(lock == 0);  // You must lock everything at once
1706
2253
    if ((table->reginfo.lock_type= lock_type) != TL_UNLOCK)
1707
 
    {
1708
 
      if (not (lock= lockTables(&table_list->table, 1, 0)))
1709
 
        table= NULL;
1710
 
    }
 
2254
      if (! (lock= mysql_lock_tables(this, &table_list->table, 1, 0, &refresh)))
 
2255
        table= 0;
1711
2256
  }
1712
2257
 
1713
2258
  set_proc_info(0);
1761
2306
  Table **start,**ptr;
1762
2307
  uint32_t lock_flag= DRIZZLE_LOCK_NOTIFY_IF_NEED_REOPEN;
1763
2308
 
1764
 
  if (!(ptr=start=(Table**) session->getMemRoot()->allocate(sizeof(Table*)*count)))
 
2309
  if (!(ptr=start=(Table**) session->alloc(sizeof(Table*)*count)))
1765
2310
    return -1;
1766
 
 
1767
2311
  for (table= tables; table; table= table->next_global)
1768
2312
  {
1769
2313
    if (!table->placeholder())
1770
2314
      *(ptr++)= table->table;
1771
2315
  }
1772
2316
 
1773
 
  if (not (session->lock= session->lockTables(start, (uint32_t) (ptr - start), lock_flag)))
 
2317
  if (!(session->lock= mysql_lock_tables(session, start, (uint32_t) (ptr - start),
 
2318
                                         lock_flag, need_reopen)))
1774
2319
  {
1775
2320
    return -1;
1776
2321
  }
1799
2344
#  Table object
1800
2345
*/
1801
2346
 
1802
 
Table *Open_tables_state::open_temporary_table(const identifier::Table &identifier,
1803
 
                                               bool link_in_list)
 
2347
Table *Session::open_temporary_table(TableIdentifier &identifier,
 
2348
                                     bool link_in_list)
1804
2349
{
 
2350
  TableShare *share;
 
2351
 
1805
2352
  assert(identifier.isTmp());
1806
 
 
1807
 
 
1808
 
  table::Temporary *new_tmp_table= new table::Temporary(identifier.getType(),
1809
 
                                                        identifier,
1810
 
                                                        const_cast<char *>(const_cast<identifier::Table&>(identifier).getPath().c_str()),
1811
 
                                                        static_cast<uint32_t>(identifier.getPath().length()));
 
2353
  share= new TableShare(identifier.getType(),
 
2354
                        identifier,
 
2355
                        const_cast<char *>(identifier.getPath().c_str()), static_cast<uint32_t>(identifier.getPath().length()));
 
2356
 
 
2357
 
 
2358
  Table *new_tmp_table= new Table;
1812
2359
  if (not new_tmp_table)
1813
2360
    return NULL;
1814
2361
 
1815
2362
  /*
1816
2363
    First open the share, and then open the table from the share we just opened.
1817
2364
  */
1818
 
  if (new_tmp_table->getMutableShare()->open_table_def(*static_cast<Session *>(this), identifier) ||
1819
 
      new_tmp_table->getMutableShare()->open_table_from_share(static_cast<Session *>(this), identifier, identifier.getTableName().c_str(),
1820
 
                                                              (uint32_t) (HA_OPEN_KEYFILE | HA_OPEN_RNDFILE |
1821
 
                                                                          HA_GET_INDEX),
1822
 
                                                              ha_open_options,
1823
 
                                                              *new_tmp_table))
 
2365
  if (share->open_table_def(*this, identifier) ||
 
2366
      share->open_table_from_share(this, identifier, identifier.getTableName().c_str(),
 
2367
                            (uint32_t) (HA_OPEN_KEYFILE | HA_OPEN_RNDFILE |
 
2368
                                        HA_GET_INDEX),
 
2369
                            ha_open_options,
 
2370
                            *new_tmp_table))
1824
2371
  {
1825
2372
    /* No need to lock share->mutex as this is not needed for tmp tables */
1826
 
    delete new_tmp_table->getMutableShare();
 
2373
    delete share;
1827
2374
    delete new_tmp_table;
1828
2375
 
1829
2376
    return 0;
1865
2412
{
1866
2413
  if (session->mark_used_columns != MARK_COLUMNS_NONE)
1867
2414
  {
1868
 
    boost::dynamic_bitset<> *current_bitmap= NULL;
 
2415
    MyBitmap *current_bitmap, *other_bitmap;
1869
2416
 
1870
2417
    /*
1871
2418
      We always want to register the used keys, as the column bitmap may have
1878
2425
    if (session->mark_used_columns == MARK_COLUMNS_READ)
1879
2426
    {
1880
2427
      current_bitmap= table->read_set;
 
2428
      other_bitmap=   table->write_set;
1881
2429
    }
1882
2430
    else
1883
2431
    {
1884
2432
      current_bitmap= table->write_set;
 
2433
      other_bitmap=   table->read_set;
1885
2434
    }
1886
2435
 
1887
 
    //if (current_bitmap->testAndSet(field->position()))
1888
 
    if (current_bitmap->test(field->position()))
 
2436
    if (current_bitmap->testAndSet(field->field_index))
1889
2437
    {
1890
2438
      if (session->mark_used_columns == MARK_COLUMNS_WRITE)
1891
2439
        session->dup_field= field;
1944
2492
    {
1945
2493
      if (nj_col)
1946
2494
      {
1947
 
        my_error(ER_NON_UNIQ_ERROR, MYF(0), name, session->where());
 
2495
        my_error(ER_NON_UNIQ_ERROR, MYF(0), name, session->where);
1948
2496
        return NULL;
1949
2497
      }
1950
2498
      nj_col= curr_nj_col;
2119
2667
      */
2120
2668
      table_name && table_name[0] &&
2121
2669
      (my_strcasecmp(table_alias_charset, table_list->alias, table_name) ||
2122
 
       (db_name && db_name[0] && table_list->getSchemaName() && table_list->getSchemaName()[0] &&
2123
 
        strcmp(db_name, table_list->getSchemaName()))))
 
2670
       (db_name && db_name[0] && table_list->db && table_list->db[0] &&
 
2671
        strcmp(db_name, table_list->db))))
2124
2672
    return 0;
2125
2673
 
2126
2674
  *actual_table= NULL;
2195
2743
      {
2196
2744
        Table *table= field_to_set->getTable();
2197
2745
        if (session->mark_used_columns == MARK_COLUMNS_READ)
2198
 
          table->setReadSet(field_to_set->position());
 
2746
          table->setReadSet(field_to_set->field_index);
2199
2747
        else
2200
 
          table->setWriteSet(field_to_set->position());
 
2748
          table->setWriteSet(field_to_set->field_index);
2201
2749
      }
2202
2750
    }
2203
2751
  }
2341
2889
      */
2342
2890
      item->cached_table= found ?  0 : actual_table;
2343
2891
 
2344
 
      assert(session->where());
 
2892
      assert(session->where);
2345
2893
      /*
2346
2894
        If we found a fully qualified field we return it directly as it can't
2347
2895
        have duplicates.
2354
2902
        if (report_error == REPORT_ALL_ERRORS ||
2355
2903
            report_error == IGNORE_EXCEPT_NON_UNIQUE)
2356
2904
          my_error(ER_NON_UNIQ_ERROR, MYF(0),
2357
 
                   table_name ? item->full_name() : name, session->where());
 
2905
                   table_name ? item->full_name() : name, session->where);
2358
2906
        return (Field*) 0;
2359
2907
      }
2360
2908
      found= cur_field;
2387
2935
      strcat(buff, table_name);
2388
2936
      table_name=buff;
2389
2937
    }
2390
 
    my_error(ER_UNKNOWN_TABLE, MYF(0), table_name, session->where());
 
2938
    my_error(ER_UNKNOWN_TABLE, MYF(0), table_name, session->where);
2391
2939
  }
2392
2940
  else
2393
2941
  {
2394
2942
    if (report_error == REPORT_ALL_ERRORS ||
2395
2943
        report_error == REPORT_EXCEPT_NON_UNIQUE)
2396
 
      my_error(ER_BAD_FIELD_ERROR, MYF(0), item->full_name(), session->where());
 
2944
      my_error(ER_BAD_FIELD_ERROR, MYF(0), item->full_name(), session->where);
2397
2945
    else
2398
2946
      found= not_found_field;
2399
2947
  }
2520
3068
            */
2521
3069
            if (report_error != IGNORE_ERRORS)
2522
3070
              my_error(ER_NON_UNIQ_ERROR, MYF(0),
2523
 
                       find->full_name(), session->where());
 
3071
                       find->full_name(), session->where);
2524
3072
            return (Item**) 0;
2525
3073
          }
2526
3074
          found_unaliased= li.ref();
2551
3099
              continue;                           // Same field twice
2552
3100
            if (report_error != IGNORE_ERRORS)
2553
3101
              my_error(ER_NON_UNIQ_ERROR, MYF(0),
2554
 
                       find->full_name(), session->where());
 
3102
                       find->full_name(), session->where);
2555
3103
            return (Item**) 0;
2556
3104
          }
2557
3105
          found= li.ref();
2603
3151
    {
2604
3152
      if (report_error != IGNORE_ERRORS)
2605
3153
        my_error(ER_NON_UNIQ_ERROR, MYF(0),
2606
 
                 find->full_name(), session->where());
 
3154
                 find->full_name(), session->where);
2607
3155
      return (Item **) 0;
2608
3156
    }
2609
3157
    if (found_unaliased)
2619
3167
  {
2620
3168
    if (report_error == REPORT_ALL_ERRORS)
2621
3169
      my_error(ER_BAD_FIELD_ERROR, MYF(0),
2622
 
               find->full_name(), session->where());
 
3170
               find->full_name(), session->where);
2623
3171
    return (Item **) 0;
2624
3172
  }
2625
3173
  else
2753
3301
    /* true if field_name_1 is a member of using_fields */
2754
3302
    bool is_using_column_1;
2755
3303
    if (!(nj_col_1= it_1.get_or_create_column_ref(leaf_1)))
2756
 
      return(result);
 
3304
      goto err;
2757
3305
    field_name_1= nj_col_1->name();
2758
3306
    is_using_column_1= using_fields &&
2759
3307
      test_if_string_in_list(field_name_1, using_fields);
2771
3319
      Natural_join_column *cur_nj_col_2;
2772
3320
      const char *cur_field_name_2;
2773
3321
      if (!(cur_nj_col_2= it_2.get_or_create_column_ref(leaf_2)))
2774
 
        return(result);
 
3322
        goto err;
2775
3323
      cur_field_name_2= cur_nj_col_2->name();
2776
3324
 
2777
3325
      /*
2790
3338
        if (cur_nj_col_2->is_common ||
2791
3339
            (found && (!using_fields || is_using_column_1)))
2792
3340
        {
2793
 
          my_error(ER_NON_UNIQ_ERROR, MYF(0), field_name_1, session->where());
2794
 
          return(result);
 
3341
          my_error(ER_NON_UNIQ_ERROR, MYF(0), field_name_1, session->where);
 
3342
          goto err;
2795
3343
        }
2796
3344
        nj_col_2= cur_nj_col_2;
2797
3345
        found= true;
2824
3372
      Item_func_eq *eq_cond;
2825
3373
 
2826
3374
      if (!item_1 || !item_2)
2827
 
        return(result); // out of memory
 
3375
        goto err;                               // out of memory
2828
3376
 
2829
3377
      /*
2830
3378
        In the case of no_wrap_view_item == 0, the created items must be
2849
3397
      */
2850
3398
      if (set_new_item_local_context(session, item_ident_1, nj_col_1->table_ref) ||
2851
3399
          set_new_item_local_context(session, item_ident_2, nj_col_2->table_ref))
2852
 
        return(result);
 
3400
        goto err;
2853
3401
 
2854
3402
      if (!(eq_cond= new Item_func_eq(item_ident_1, item_ident_2)))
2855
 
        return(result);                               /* Out of memory. */
 
3403
        goto err;                               /* Out of memory. */
2856
3404
 
2857
3405
      /*
2858
3406
        Add the new equi-join condition to the ON clause. Notice that
2869
3417
      {
2870
3418
        Table *table_1= nj_col_1->table_ref->table;
2871
3419
        /* Mark field_1 used for table cache. */
2872
 
        table_1->setReadSet(field_1->position());
 
3420
        table_1->setReadSet(field_1->field_index);
2873
3421
        table_1->covering_keys&= field_1->part_of_key;
2874
3422
        table_1->merge_keys|= field_1->part_of_key;
2875
3423
      }
2877
3425
      {
2878
3426
        Table *table_2= nj_col_2->table_ref->table;
2879
3427
        /* Mark field_2 used for table cache. */
2880
 
        table_2->setReadSet(field_2->position());
 
3428
        table_2->setReadSet(field_2->field_index);
2881
3429
        table_2->covering_keys&= field_2->part_of_key;
2882
3430
        table_2->merge_keys|= field_2->part_of_key;
2883
3431
      }
2898
3446
  */
2899
3447
  result= false;
2900
3448
 
 
3449
err:
2901
3450
  return(result);
2902
3451
}
2903
3452
 
2955
3504
 
2956
3505
  if (!(non_join_columns= new List<Natural_join_column>) ||
2957
3506
      !(natural_using_join->join_columns= new List<Natural_join_column>))
2958
 
  {
2959
 
    return(result);
2960
 
  }
 
3507
    goto err;
2961
3508
 
2962
3509
  /* Append the columns of the first join operand. */
2963
3510
  for (it_1.set(table_ref_1); !it_1.end_of_fields(); it_1.next())
2995
3542
        if (!(common_field= it++))
2996
3543
        {
2997
3544
          my_error(ER_BAD_FIELD_ERROR, MYF(0), using_field_name_ptr,
2998
 
                   session->where());
2999
 
          return(result);
 
3545
                   session->where);
 
3546
          goto err;
3000
3547
        }
3001
3548
        if (!my_strcasecmp(system_charset_info,
3002
3549
                           common_field->name(), using_field_name_ptr))
3024
3571
 
3025
3572
  result= false;
3026
3573
 
 
3574
err:
3027
3575
  return(result);
3028
3576
}
3029
3577
 
3109
3657
      if (cur_table_ref->getNestedJoin() &&
3110
3658
          store_top_level_join_columns(session, cur_table_ref,
3111
3659
                                       real_left_neighbor, real_right_neighbor))
3112
 
        return(result);
 
3660
        goto err;
3113
3661
      same_level_right_neighbor= cur_table_ref;
3114
3662
    }
3115
3663
  }
3141
3689
      std::swap(table_ref_1, table_ref_2);
3142
3690
    if (mark_common_columns(session, table_ref_1, table_ref_2,
3143
3691
                            using_fields, &found_using_fields))
3144
 
      return(result);
 
3692
      goto err;
3145
3693
 
3146
3694
    /*
3147
3695
      Swap the join operands back, so that we pick the columns of the second
3153
3701
    if (store_natural_using_join_columns(session, table_ref, table_ref_1,
3154
3702
                                         table_ref_2, using_fields,
3155
3703
                                         found_using_fields))
3156
 
      return(result);
 
3704
      goto err;
3157
3705
 
3158
3706
    /*
3159
3707
      Change NATURAL JOIN to JOIN ... ON. We do this for both operands
3186
3734
  }
3187
3735
  result= false; /* All is OK. */
3188
3736
 
 
3737
err:
3189
3738
  return(result);
3190
3739
}
3191
3740
 
3218
3767
                                         List<TableList> *from_clause,
3219
3768
                                         Name_resolution_context *context)
3220
3769
{
3221
 
  session->setWhere("from clause");
 
3770
  session->where= "from clause";
3222
3771
  if (from_clause->elements == 0)
3223
3772
    return false; /* We come here in the case of UNIONs. */
3224
3773
 
3339
3888
  session->mark_used_columns= mark_used_columns;
3340
3889
  if (allow_sum_func)
3341
3890
    session->lex->allow_sum_func|= 1 << session->lex->current_select->nest_level;
3342
 
  session->setWhere(Session::DEFAULT_WHERE);
 
3891
  session->where= Session::DEFAULT_WHERE;
3343
3892
  save_is_item_list_lookup= session->lex->current_select->is_item_list_lookup;
3344
3893
  session->lex->current_select->is_item_list_lookup= 0;
3345
3894
 
3351
3900
    There is other way to solve problem: fill array with pointers to list,
3352
3901
    but it will be slower.
3353
3902
 
3354
 
    TODO-> remove it when (if) we made one list for allfields and ref_pointer_array
 
3903
TODO: remove it when (if) we made one list for allfields and
 
3904
ref_pointer_array
3355
3905
  */
3356
3906
  if (ref_pointer_array)
3357
 
  {
3358
3907
    memset(ref_pointer_array, 0, sizeof(Item *) * fields.elements);
3359
 
  }
3360
3908
 
3361
3909
  Item **ref= ref_pointer_array;
3362
3910
  session->lex->current_select->cur_pos_in_select_list= 0;
3588
4136
    assert(tables->is_leaf_for_name_resolution());
3589
4137
 
3590
4138
    if ((table_name && my_strcasecmp(table_alias_charset, table_name, tables->alias)) ||
3591
 
        (db_name && my_strcasecmp(system_charset_info, tables->getSchemaName(),db_name)))
 
4139
        (db_name && strcasecmp(tables->db,db_name)))
3592
4140
      continue;
3593
4141
 
3594
4142
    /*
3624
4172
      if ((field= field_iterator.field()))
3625
4173
      {
3626
4174
        /* Mark fields as used to allow storage engine to optimze access */
3627
 
        field->getTable()->setReadSet(field->position());
 
4175
        field->getTable()->setReadSet(field->field_index);
3628
4176
        if (table)
3629
4177
        {
3630
4178
          table->covering_keys&= field->part_of_key;
3652
4200
        }
3653
4201
      }
3654
4202
      else
3655
 
      {
3656
4203
        session->used_tables|= item->used_tables();
3657
 
      }
3658
 
 
3659
4204
      session->lex->current_select->cur_pos_in_select_list++;
3660
4205
    }
3661
4206
    /*
3675
4220
    qualified '*', and all columns were coalesced, we have to give a more
3676
4221
    meaningful message than ER_BAD_TABLE_ERROR.
3677
4222
  */
3678
 
  if (not table_name)
3679
 
  {
 
4223
  if (!table_name)
3680
4224
    my_message(ER_NO_TABLES_USED, ER(ER_NO_TABLES_USED), MYF(0));
3681
 
  }
3682
4225
  else
3683
 
  {
3684
4226
    my_error(ER_BAD_TABLE_ERROR, MYF(0), table_name);
3685
 
  }
3686
4227
 
3687
4228
  return true;
3688
4229
}
3731
4272
  session->session_marker= (void*)1;
3732
4273
  if (*conds)
3733
4274
  {
3734
 
    session->setWhere("where clause");
 
4275
    session->where="where clause";
3735
4276
    if ((!(*conds)->fixed && (*conds)->fix_fields(session, conds)) ||
3736
4277
        (*conds)->check_cols(1))
3737
4278
      goto err_no_arena;
3753
4294
      {
3754
4295
        /* Make a join an a expression */
3755
4296
        session->session_marker= (void*)embedded;
3756
 
        session->setWhere("on clause");
 
4297
        session->where="on clause";
3757
4298
        if ((!embedded->on_expr->fixed && embedded->on_expr->fix_fields(session, &embedded->on_expr)) ||
3758
4299
            embedded->on_expr->check_cols(1))
3759
4300
          goto err_no_arena;
3838
4379
    if ((value->save_in_field(rfield, 0) < 0) && !ignore_errors)
3839
4380
    {
3840
4381
      my_message(ER_UNKNOWN_ERROR, ER(ER_UNKNOWN_ERROR), MYF(0));
3841
 
      if (table)
3842
 
        table->auto_increment_field_not_null= false;
3843
 
 
3844
 
      return true;
 
4382
      goto err;
3845
4383
    }
3846
4384
  }
3847
4385
 
3848
4386
  return session->is_error();
 
4387
 
 
4388
err:
 
4389
  if (table)
 
4390
    table->auto_increment_field_not_null= false;
 
4391
 
 
4392
  return true;
3849
4393
}
3850
4394
 
3851
4395
 
3888
4432
    table= (*ptr)->getTable();
3889
4433
    table->auto_increment_field_not_null= false;
3890
4434
  }
3891
 
 
3892
4435
  while ((field = *ptr++) && ! session->is_error())
3893
4436
  {
3894
4437
    value=v++;
3895
4438
    table= field->getTable();
3896
 
 
3897
4439
    if (field == table->next_number_field)
3898
4440
      table->auto_increment_field_not_null= true;
3899
 
 
3900
4441
    if (value->save_in_field(field, 0) < 0)
3901
 
    {
3902
 
      if (table)
3903
 
        table->auto_increment_field_not_null= false;
3904
 
 
3905
 
      return true;
3906
 
    }
 
4442
      goto err;
3907
4443
  }
3908
4444
 
3909
4445
  return(session->is_error());
 
4446
 
 
4447
err:
 
4448
  if (table)
 
4449
    table->auto_increment_field_not_null= false;
 
4450
 
 
4451
  return true;
3910
4452
}
3911
4453
 
3912
4454
 
3913
4455
bool drizzle_rm_tmp_tables()
3914
4456
{
 
4457
  Session *session;
3915
4458
 
3916
4459
  assert(drizzle_tmpdir.size());
3917
 
  Session::shared_ptr session= Session::make_shared(plugin::Listen::getNullClient(), catalog::local());
3918
4460
 
3919
 
  if (not session)
 
4461
  if (!(session= new Session(plugin::Listen::getNullClient())))
3920
4462
    return true;
3921
 
  session->thread_stack= (char*) session.get();
 
4463
  session->thread_stack= (char*) &session;
3922
4464
  session->storeGlobals();
3923
4465
 
3924
4466
  plugin::StorageEngine::removeLostTemporaryTables(*session, drizzle_tmpdir.c_str());
3925
4467
 
 
4468
  session->lockForDelete();
 
4469
  delete session;
 
4470
 
3926
4471
  return false;
3927
4472
}
3928
4473
 
3932
4477
  unireg support functions
3933
4478
 *****************************************************************************/
3934
4479
 
3935
 
 
 
4480
/*
 
4481
  Invalidate any cache entries that are for some DB
 
4482
 
 
4483
  SYNOPSIS
 
4484
  remove_db_from_cache()
 
4485
  db            Database name. This will be in lower case if
 
4486
  lower_case_table_name is set
 
4487
 
 
4488
NOTE:
 
4489
We can't use hash_delete when looping hash_elements. We mark them first
 
4490
and afterwards delete those marked unused.
 
4491
*/
 
4492
 
 
4493
void remove_db_from_cache(const SchemaIdentifier &schema_identifier)
 
4494
{
 
4495
  safe_mutex_assert_owner(LOCK_open.native_handle());
 
4496
 
 
4497
  for (TableOpenCache::const_iterator iter= get_open_cache().begin();
 
4498
       iter != get_open_cache().end();
 
4499
       iter++)
 
4500
  {
 
4501
    Table *table= (*iter).second;
 
4502
 
 
4503
    if (not schema_identifier.getPath().compare(table->getMutableShare()->getSchemaName()))
 
4504
    {
 
4505
      table->getMutableShare()->resetVersion();                 /* Free when thread is ready */
 
4506
      if (not table->in_use)
 
4507
        unused_tables.relink(table);
 
4508
    }
 
4509
  }
 
4510
 
 
4511
  unused_tables.cullByVersion();
 
4512
}
 
4513
 
 
4514
 
 
4515
/*
 
4516
  Mark all entries with the table as deleted to force an reopen of the table
 
4517
 
 
4518
  The table will be closed (not stored in cache) by the current thread when
 
4519
  close_thread_tables() is called.
 
4520
 
 
4521
  PREREQUISITES
 
4522
  Lock on LOCK_open()
 
4523
 
 
4524
  RETURN
 
4525
  0  This thread now have exclusive access to this table and no other thread
 
4526
  can access the table until close_thread_tables() is called.
 
4527
  1  Table is in use by another thread
 
4528
*/
 
4529
 
 
4530
bool remove_table_from_cache(Session *session, TableIdentifier &identifier, uint32_t flags)
 
4531
{
 
4532
  const TableIdentifier::Key &key(identifier.getKey());
 
4533
  bool result= false; 
 
4534
  bool signalled= false;
 
4535
 
 
4536
  for (;;)
 
4537
  {
 
4538
    result= signalled= false;
 
4539
 
 
4540
    TableOpenCacheRange ppp;
 
4541
    ppp= get_open_cache().equal_range(key);
 
4542
 
 
4543
    for (TableOpenCache::const_iterator iter= ppp.first;
 
4544
         iter != ppp.second; ++iter)
 
4545
    {
 
4546
      Table *table= (*iter).second;
 
4547
      Session *in_use;
 
4548
 
 
4549
      table->getMutableShare()->resetVersion();         /* Free when thread is ready */
 
4550
      if (!(in_use=table->in_use))
 
4551
      {
 
4552
        unused_tables.relink(table);
 
4553
      }
 
4554
      else if (in_use != session)
 
4555
      {
 
4556
        /*
 
4557
          Mark that table is going to be deleted from cache. This will
 
4558
          force threads that are in mysql_lock_tables() (but not yet
 
4559
          in thr_multi_lock()) to abort it's locks, close all tables and retry
 
4560
        */
 
4561
        in_use->some_tables_deleted= true;
 
4562
        if (table->is_name_opened())
 
4563
        {
 
4564
          result= true;
 
4565
        }
 
4566
        /*
 
4567
          Now we must abort all tables locks used by this thread
 
4568
          as the thread may be waiting to get a lock for another table.
 
4569
          Note that we need to hold LOCK_open while going through the
 
4570
          list. So that the other thread cannot change it. The other
 
4571
          thread must also hold LOCK_open whenever changing the
 
4572
          open_tables list. Aborting the MERGE lock after a child was
 
4573
          closed and before the parent is closed would be fatal.
 
4574
        */
 
4575
        for (Table *session_table= in_use->open_tables;
 
4576
             session_table ;
 
4577
             session_table= session_table->getNext())
 
4578
        {
 
4579
          /* Do not handle locks of MERGE children. */
 
4580
          if (session_table->db_stat)   // If table is open
 
4581
            signalled|= mysql_lock_abort_for_thread(session, session_table);
 
4582
        }
 
4583
      }
 
4584
      else
 
4585
        result= result || (flags & RTFC_OWNED_BY_Session_FLAG);
 
4586
    }
 
4587
 
 
4588
    unused_tables.cullByVersion();
 
4589
 
 
4590
    /* Remove table from table definition cache if it's not in use */
 
4591
    TableShare::release(identifier);
 
4592
 
 
4593
    if (result && (flags & RTFC_WAIT_OTHER_THREAD_FLAG))
 
4594
    {
 
4595
      /*
 
4596
        Signal any thread waiting for tables to be freed to
 
4597
        reopen their tables
 
4598
      */
 
4599
      broadcast_refresh();
 
4600
      if (!(flags & RTFC_CHECK_KILLED_FLAG) || !session->killed)
 
4601
      {
 
4602
        dropping_tables++;
 
4603
        if (likely(signalled))
 
4604
          (void) pthread_cond_wait(COND_refresh.native_handle(), LOCK_open.native_handle());
 
4605
        else
 
4606
        {
 
4607
          struct timespec abstime;
 
4608
          /*
 
4609
            It can happen that another thread has opened the
 
4610
            table but has not yet locked any table at all. Since
 
4611
            it can be locked waiting for a table that our thread
 
4612
            has done LOCK Table x WRITE on previously, we need to
 
4613
            ensure that the thread actually hears our signal
 
4614
            before we go to sleep. Thus we wait for a short time
 
4615
            and then we retry another loop in the
 
4616
            remove_table_from_cache routine.
 
4617
          */
 
4618
          set_timespec(abstime, 10);
 
4619
          pthread_cond_timedwait(COND_refresh.native_handle(), LOCK_open.native_handle(), &abstime);
 
4620
        }
 
4621
        dropping_tables--;
 
4622
        continue;
 
4623
      }
 
4624
    }
 
4625
    break;
 
4626
  }
 
4627
 
 
4628
  return result;
 
4629
}
3936
4630
 
3937
4631
 
3938
4632
/**