~ubuntu-branches/ubuntu/trusty/drizzle/trusty

« back to all changes in this revision

Viewing changes to drizzled/sql_base.cc

  • Committer: Bazaar Package Importer
  • Author(s): Monty Taylor
  • Date: 2010-10-02 14:17:48 UTC
  • mfrom: (1.1.1 upstream)
  • mto: (2.1.17 sid)
  • mto: This revision was merged to the branch mainline in revision 3.
  • Revision ID: james.westby@ubuntu.com-20101002141748-m6vbfbfjhrw1153e
Tags: 2010.09.1802-1
* New upstream release.
* Removed pid-file argument hack.
* Updated GPL-2 address to be new address.
* Directly copy in drizzledump.1 since debian doesn't have sphinx 1.0 yet.
* Link to jquery from libjs-jquery. Add it as a depend.
* Add drizzled.8 symlink to the install files.

Show diffs side-by-side

added added

removed removed

Lines of Context:
31
31
# endif
32
32
#endif
33
33
#include "drizzled/internal/my_pthread.h"
 
34
#include "drizzled/internal/thread_var.h"
34
35
 
35
36
#include <drizzled/sql_select.h>
36
37
#include <drizzled/error.h>
46
47
#include "drizzled/cached_directory.h"
47
48
#include <drizzled/field/timestamp.h>
48
49
#include <drizzled/field/null.h>
49
 
#include "drizzled/memory/multi_malloc.h"
50
50
#include "drizzled/sql_table.h"
51
51
#include "drizzled/global_charset_info.h"
52
52
#include "drizzled/pthread_globals.h"
53
53
#include "drizzled/internal/iocache.h"
 
54
#include "drizzled/drizzled.h"
54
55
#include "drizzled/plugin/authorization.h"
 
56
#include "drizzled/table_placeholder.h"
55
57
 
56
58
using namespace std;
57
59
 
60
62
 
61
63
extern bool volatile shutdown_in_progress;
62
64
 
63
 
bool drizzle_rm_tmp_tables();
64
 
 
65
 
/**
66
 
  @defgroup Data_Dictionary Data Dictionary
67
 
  @{
68
 
*/
69
 
Table *unused_tables;                           /* Used by mysql_test */
70
 
HASH open_cache;                                /* Used by mysql_test */
71
 
static int open_unireg_entry(Session *session, Table *entry, TableList *table_list,
 
65
TableOpenCache &get_open_cache()
 
66
{
 
67
  static TableOpenCache open_cache;                             /* Used by mysql_test */
 
68
 
 
69
  return open_cache;
 
70
}
 
71
 
 
72
static void free_cache_entry(Table *entry);
 
73
 
 
74
void remove_table(Table *arg)
 
75
{
 
76
  TableOpenCacheRange ppp;
 
77
  ppp= get_open_cache().equal_range(arg->getShare()->getCacheKey());
 
78
 
 
79
  for (TableOpenCache::const_iterator iter= ppp.first;
 
80
         iter != ppp.second; ++iter)
 
81
  {
 
82
    Table *found_table= (*iter).second;
 
83
 
 
84
    if (found_table == arg)
 
85
    {
 
86
      free_cache_entry(arg);
 
87
      get_open_cache().erase(iter);
 
88
      return;
 
89
    }
 
90
  }
 
91
}
 
92
 
 
93
static bool add_table(Table *arg)
 
94
{
 
95
  TableOpenCache &open_cache(get_open_cache());
 
96
 
 
97
  TableOpenCache::iterator returnable= open_cache.insert(make_pair(arg->getShare()->getCacheKey(), arg));
 
98
 
 
99
  return not (returnable == open_cache.end());
 
100
}
 
101
 
 
102
class UnusedTables {
 
103
  Table *tables;                                /* Used by mysql_test */
 
104
 
 
105
  Table *getTable() const
 
106
  {
 
107
    return tables;
 
108
  }
 
109
 
 
110
  Table *setTable(Table *arg)
 
111
  {
 
112
    return tables= arg;
 
113
  }
 
114
 
 
115
public:
 
116
 
 
117
  void cull()
 
118
  {
 
119
    /* Free cache if too big */
 
120
    while (cached_open_tables() > table_cache_size && getTable())
 
121
      remove_table(getTable());
 
122
  }
 
123
 
 
124
  void cullByVersion()
 
125
  {
 
126
    while (getTable() && not getTable()->getShare()->getVersion())
 
127
      remove_table(getTable());
 
128
  }
 
129
  
 
130
  void link(Table *table)
 
131
  {
 
132
    if (getTable())
 
133
    {
 
134
      table->setNext(getTable());               /* Link in last */
 
135
      table->setPrev(getTable()->getPrev());
 
136
      getTable()->setPrev(table);
 
137
      table->getPrev()->setNext(table);
 
138
    }
 
139
    else
 
140
    {
 
141
      table->setPrev(setTable(table));
 
142
      table->setNext(table->getPrev());
 
143
      assert(table->getNext() == table && table->getPrev() == table);
 
144
    }
 
145
  }
 
146
 
 
147
 
 
148
  void unlink(Table *table)
 
149
  {
 
150
    table->unlink();
 
151
 
 
152
    /* Unlink the table from "unused_tables" list. */
 
153
    if (table == getTable())
 
154
    {  // First unused
 
155
      setTable(getTable()->getNext()); // Remove from link
 
156
      if (table == getTable())
 
157
        setTable(NULL);
 
158
    }
 
159
  }
 
160
 
 
161
/* move table first in unused links */
 
162
 
 
163
  void relink(Table *table)
 
164
  {
 
165
    if (table != getTable())
 
166
    {
 
167
      table->unlink();
 
168
 
 
169
      table->setNext(getTable());                       /* Link in unused tables */
 
170
      table->setPrev(getTable()->getPrev());
 
171
      getTable()->getPrev()->setNext(table);
 
172
      getTable()->setPrev(table);
 
173
      setTable(table);
 
174
    }
 
175
  }
 
176
 
 
177
 
 
178
  void clear()
 
179
  {
 
180
    while (getTable())
 
181
      remove_table(getTable());
 
182
  }
 
183
 
 
184
  UnusedTables():
 
185
    tables(NULL)
 
186
  { }
 
187
 
 
188
  ~UnusedTables()
 
189
  { 
 
190
  }
 
191
};
 
192
 
 
193
static UnusedTables unused_tables;
 
194
static int open_unireg_entry(Session *session,
 
195
                             Table *entry,
72
196
                             const char *alias,
73
 
                             char *cache_key, uint32_t cache_key_length);
74
 
void free_cache_entry(void *entry);
 
197
                             TableIdentifier &identifier);
 
198
 
75
199
unsigned char *table_cache_key(const unsigned char *record,
76
200
                               size_t *length,
77
201
                               bool );
78
202
 
79
 
 
80
203
unsigned char *table_cache_key(const unsigned char *record,
81
204
                               size_t *length,
82
205
                               bool )
83
206
{
84
207
  Table *entry=(Table*) record;
85
 
  *length= entry->s->table_cache_key.length;
86
 
  return (unsigned char*) entry->s->table_cache_key.str;
87
 
}
88
 
 
89
 
HASH *get_open_cache()
90
 
{
91
 
  return &open_cache;
92
 
}
93
 
 
 
208
  *length= entry->getShare()->getCacheKey().size();
 
209
  return (unsigned char*) &entry->getShare()->getCacheKey()[0];
 
210
}
94
211
 
95
212
bool table_cache_init(void)
96
213
{
97
 
  return hash_init(&open_cache, &my_charset_bin,
98
 
                   (size_t) table_cache_size+16,
99
 
                   0, 0, table_cache_key,
100
 
                   free_cache_entry, 0);
 
214
  return false;
 
215
}
 
216
 
 
217
uint32_t cached_open_tables(void)
 
218
{
 
219
  return get_open_cache().size();
101
220
}
102
221
 
103
222
void table_cache_free(void)
104
223
{
105
224
  refresh_version++;                            // Force close of open tables
106
225
 
107
 
  while (unused_tables)
108
 
    hash_delete(&open_cache, (unsigned char*) unused_tables);
109
 
 
110
 
  if (not open_cache.records)                   // Safety first
111
 
    hash_free(&open_cache);
112
 
}
113
 
 
114
 
uint32_t cached_open_tables(void)
115
 
{
116
 
  return open_cache.records;
117
 
}
118
 
 
 
226
  unused_tables.clear();
 
227
  get_open_cache().clear();
 
228
}
119
229
 
120
230
/*
121
231
  Close cursor handle, but leave the table in the table cache
137
247
 
138
248
void close_handle_and_leave_table_as_lock(Table *table)
139
249
{
140
 
  TableShare *share, *old_share= table->s;
141
 
  char *key_buff;
142
 
  memory::Root *mem_root= &table->mem_root;
143
 
 
 
250
  TableShare *share, *old_share= table->getMutableShare();
144
251
  assert(table->db_stat);
 
252
  assert(table->getShare()->getType() == message::Table::STANDARD);
145
253
 
146
254
  /*
147
255
    Make a local copy of the table share and free the current one.
148
256
    This has to be done to ensure that the table share is removed from
149
257
    the table defintion cache as soon as the last instance is removed
150
258
  */
151
 
  if (multi_alloc_root(mem_root,
152
 
                       &share, sizeof(*share),
153
 
                       &key_buff, old_share->table_cache_key.length,
154
 
                       NULL))
155
 
  {
156
 
    memset(share, 0, sizeof(*share));
157
 
    share->set_table_cache_key(key_buff, old_share->table_cache_key.str,
158
 
                               old_share->table_cache_key.length);
159
 
    share->tmp_table= INTERNAL_TMP_TABLE;       // for intern_close_table()
160
 
  }
 
259
  TableIdentifier identifier(table->getShare()->getSchemaName(), table->getShare()->getTableName(), message::Table::INTERNAL);
 
260
  const TableIdentifier::Key &key(identifier.getKey());
 
261
  share= new TableShare(identifier.getType(),
 
262
                        identifier,
 
263
                        const_cast<char *>(&key[0]),  static_cast<uint32_t>(old_share->getCacheKeySize()));
161
264
 
162
265
  table->cursor->close();
163
266
  table->db_stat= 0;                            // Mark cursor closed
164
 
  TableShare::release(table->s);
165
 
  table->s= share;
166
 
  table->cursor->change_table_ptr(table, table->s);
 
267
  TableShare::release(table->getMutableShare());
 
268
  table->setShare(share);
 
269
  table->cursor->change_table_ptr(table, table->getMutableShare());
167
270
}
168
271
 
169
272
 
176
279
{                                               // Free all structures
177
280
  free_io_cache();
178
281
  if (cursor)                              // Not true if name lock
179
 
    closefrm(true);                     // close cursor
 
282
  {
 
283
    delete_table(true);                 // close cursor
 
284
  }
180
285
}
181
286
 
182
287
/*
190
295
  We need to have a lock on LOCK_open when calling this
191
296
*/
192
297
 
193
 
void free_cache_entry(void *entry)
 
298
void free_cache_entry(Table *table)
194
299
{
195
 
  Table *table= static_cast<Table *>(entry);
196
300
  table->intern_close_table();
197
301
  if (not table->in_use)
198
302
  {
199
 
    table->next->prev=table->prev;              /* remove from used chain */
200
 
    table->prev->next=table->next;
201
 
    if (table == unused_tables)
202
 
    {
203
 
      unused_tables=unused_tables->next;
204
 
      if (table == unused_tables)
205
 
        unused_tables= NULL;
206
 
    }
 
303
    unused_tables.unlink(table);
207
304
  }
208
 
  free(table);
 
305
 
 
306
  delete table;
209
307
}
210
308
 
211
309
/* Free resources allocated by filesort() and read_record() */
241
339
  bool result= false;
242
340
  Session *session= this;
243
341
 
244
 
  pthread_mutex_lock(&LOCK_open); /* Optionally lock for remove tables from open_cahe if not in use */
245
 
 
246
 
  if (tables == NULL)
247
342
  {
248
 
    refresh_version++;                          // Force close of open tables
249
 
    while (unused_tables)
250
 
      hash_delete(&open_cache,(unsigned char*) unused_tables);
 
343
    LOCK_open.lock(); /* Optionally lock for remove tables from open_cahe if not in use */
 
344
 
 
345
    if (tables == NULL)
 
346
    {
 
347
      refresh_version++;                                // Force close of open tables
 
348
 
 
349
      unused_tables.clear();
 
350
 
 
351
      if (wait_for_refresh)
 
352
      {
 
353
        /*
 
354
          Other threads could wait in a loop in open_and_lock_tables(),
 
355
          trying to lock one or more of our tables.
 
356
 
 
357
          If they wait for the locks in thr_multi_lock(), their lock
 
358
          request is aborted. They loop in open_and_lock_tables() and
 
359
          enter open_table(). Here they notice the table is refreshed and
 
360
          wait for COND_refresh. Then they loop again in
 
361
          openTablesLock() and this time open_table() succeeds. At
 
362
          this moment, if we (the FLUSH TABLES thread) are scheduled and
 
363
          on another FLUSH TABLES enter close_cached_tables(), they could
 
364
          awake while we sleep below, waiting for others threads (us) to
 
365
          close their open tables. If this happens, the other threads
 
366
          would find the tables unlocked. They would get the locks, one
 
367
          after the other, and could do their destructive work. This is an
 
368
          issue if we have LOCK TABLES in effect.
 
369
 
 
370
          The problem is that the other threads passed all checks in
 
371
          open_table() before we refresh the table.
 
372
 
 
373
          The fix for this problem is to set some_tables_deleted for all
 
374
          threads with open tables. These threads can still get their
 
375
          locks, but will immediately release them again after checking
 
376
          this variable. They will then loop in openTablesLock()
 
377
          again. There they will wait until we update all tables version
 
378
          below.
 
379
 
 
380
          Setting some_tables_deleted is done by remove_table_from_cache()
 
381
          in the other branch.
 
382
 
 
383
          In other words (reviewer suggestion): You need this setting of
 
384
          some_tables_deleted for the case when table was opened and all
 
385
          related checks were passed before incrementing refresh_version
 
386
          (which you already have) but attempt to lock the table happened
 
387
          after the call to Session::close_old_data_files() i.e. after removal of
 
388
          current thread locks.
 
389
        */
 
390
        for (TableOpenCache::const_iterator iter= get_open_cache().begin();
 
391
             iter != get_open_cache().end();
 
392
             iter++)
 
393
        {
 
394
          Table *table= (*iter).second;
 
395
          if (table->in_use)
 
396
            table->in_use->some_tables_deleted= false;
 
397
        }
 
398
      }
 
399
    }
 
400
    else
 
401
    {
 
402
      bool found= false;
 
403
      for (TableList *table= tables; table; table= table->next_local)
 
404
      {
 
405
        TableIdentifier identifier(table->db, table->table_name);
 
406
        if (remove_table_from_cache(session, identifier,
 
407
                                    RTFC_OWNED_BY_Session_FLAG))
 
408
        {
 
409
          found= true;
 
410
        }
 
411
      }
 
412
      if (!found)
 
413
        wait_for_refresh= false;                        // Nothing to wait for
 
414
    }
251
415
 
252
416
    if (wait_for_refresh)
253
417
    {
254
418
      /*
255
 
        Other threads could wait in a loop in open_and_lock_tables(),
256
 
        trying to lock one or more of our tables.
257
 
 
258
 
        If they wait for the locks in thr_multi_lock(), their lock
259
 
        request is aborted. They loop in open_and_lock_tables() and
260
 
        enter open_table(). Here they notice the table is refreshed and
261
 
        wait for COND_refresh. Then they loop again in
262
 
        openTablesLock() and this time open_table() succeeds. At
263
 
        this moment, if we (the FLUSH TABLES thread) are scheduled and
264
 
        on another FLUSH TABLES enter close_cached_tables(), they could
265
 
        awake while we sleep below, waiting for others threads (us) to
266
 
        close their open tables. If this happens, the other threads
267
 
        would find the tables unlocked. They would get the locks, one
268
 
        after the other, and could do their destructive work. This is an
269
 
        issue if we have LOCK TABLES in effect.
270
 
 
271
 
        The problem is that the other threads passed all checks in
272
 
        open_table() before we refresh the table.
273
 
 
274
 
        The fix for this problem is to set some_tables_deleted for all
275
 
        threads with open tables. These threads can still get their
276
 
        locks, but will immediately release them again after checking
277
 
        this variable. They will then loop in openTablesLock()
278
 
        again. There they will wait until we update all tables version
279
 
        below.
280
 
 
281
 
        Setting some_tables_deleted is done by remove_table_from_cache()
282
 
        in the other branch.
283
 
 
284
 
        In other words (reviewer suggestion): You need this setting of
285
 
        some_tables_deleted for the case when table was opened and all
286
 
        related checks were passed before incrementing refresh_version
287
 
        (which you already have) but attempt to lock the table happened
288
 
        after the call to Session::close_old_data_files() i.e. after removal of
289
 
        current thread locks.
 
419
        If there is any table that has a lower refresh_version, wait until
 
420
        this is closed (or this thread is killed) before returning
290
421
      */
291
 
      for (uint32_t idx=0 ; idx < open_cache.records ; idx++)
 
422
      session->mysys_var->current_mutex= &LOCK_open;
 
423
      session->mysys_var->current_cond= &COND_refresh;
 
424
      session->set_proc_info("Flushing tables");
 
425
 
 
426
      session->close_old_data_files();
 
427
 
 
428
      bool found= true;
 
429
      /* Wait until all threads has closed all the tables we had locked */
 
430
      while (found && ! session->killed)
292
431
      {
293
 
        Table *table=(Table*) hash_element(&open_cache,idx);
294
 
        if (table->in_use)
295
 
          table->in_use->some_tables_deleted= false;
 
432
        found= false;
 
433
        for (TableOpenCache::const_iterator iter= get_open_cache().begin();
 
434
             iter != get_open_cache().end();
 
435
             iter++)
 
436
        {
 
437
          Table *table= (*iter).second;
 
438
          /* Avoid a self-deadlock. */
 
439
          if (table->in_use == session)
 
440
            continue;
 
441
          /*
 
442
            Note that we wait here only for tables which are actually open, and
 
443
            not for placeholders with Table::open_placeholder set. Waiting for
 
444
            latter will cause deadlock in the following scenario, for example:
 
445
 
 
446
            conn1-> lock table t1 write;
 
447
            conn2-> lock table t2 write;
 
448
            conn1-> flush tables;
 
449
            conn2-> flush tables;
 
450
 
 
451
            It also does not make sense to wait for those of placeholders that
 
452
            are employed by CREATE TABLE as in this case table simply does not
 
453
            exist yet.
 
454
          */
 
455
          if (table->needs_reopen_or_name_lock() && (table->db_stat ||
 
456
                                                     (table->open_placeholder && wait_for_placeholders)))
 
457
          {
 
458
            found= true;
 
459
            boost::mutex::scoped_lock scoped(LOCK_open, boost::adopt_lock_t());
 
460
            COND_refresh.wait(scoped);
 
461
            scoped.release();
 
462
            break;
 
463
          }
 
464
        }
296
465
      }
297
 
    }
298
 
  }
299
 
  else
300
 
  {
301
 
    bool found= false;
302
 
    for (TableList *table= tables; table; table= table->next_local)
303
 
    {
304
 
      if (remove_table_from_cache(session, table->db, table->table_name,
305
 
                                  RTFC_OWNED_BY_Session_FLAG))
306
 
        found= true;
307
 
    }
308
 
    if (!found)
309
 
      wait_for_refresh= false;                  // Nothing to wait for
310
 
  }
311
 
 
312
 
  if (wait_for_refresh)
313
 
  {
314
 
    /*
315
 
      If there is any table that has a lower refresh_version, wait until
316
 
      this is closed (or this thread is killed) before returning
317
 
    */
318
 
    session->mysys_var->current_mutex= &LOCK_open;
319
 
    session->mysys_var->current_cond= &COND_refresh;
320
 
    session->set_proc_info("Flushing tables");
321
 
 
322
 
    session->close_old_data_files();
323
 
 
324
 
    bool found= true;
325
 
    /* Wait until all threads has closed all the tables we had locked */
326
 
    while (found && ! session->killed)
327
 
    {
328
 
      found= false;
329
 
      for (uint32_t idx=0 ; idx < open_cache.records ; idx++)
 
466
      /*
 
467
        No other thread has the locked tables open; reopen them and get the
 
468
        old locks. This should always succeed (unless some external process
 
469
        has removed the tables)
 
470
      */
 
471
      result= session->reopen_tables(true, true);
 
472
 
 
473
      /* Set version for table */
 
474
      for (Table *table= session->open_tables; table ; table= table->getNext())
330
475
      {
331
 
        Table *table=(Table*) hash_element(&open_cache,idx);
332
 
        /* Avoid a self-deadlock. */
333
 
        if (table->in_use == session)
334
 
          continue;
335
476
        /*
336
 
          Note that we wait here only for tables which are actually open, and
337
 
          not for placeholders with Table::open_placeholder set. Waiting for
338
 
          latter will cause deadlock in the following scenario, for example:
339
 
 
340
 
conn1: lock table t1 write;
341
 
conn2: lock table t2 write;
342
 
conn1: flush tables;
343
 
conn2: flush tables;
344
 
 
345
 
It also does not make sense to wait for those of placeholders that
346
 
are employed by CREATE TABLE as in this case table simply does not
347
 
exist yet.
 
477
          Preserve the version (0) of write locked tables so that a impending
 
478
          global read lock won't sneak in.
348
479
        */
349
 
        if (table->needs_reopen_or_name_lock() && (table->db_stat ||
350
 
                                                   (table->open_placeholder && wait_for_placeholders)))
351
 
        {
352
 
          found= true;
353
 
          pthread_cond_wait(&COND_refresh,&LOCK_open);
354
 
          break;
355
 
        }
 
480
        if (table->reginfo.lock_type < TL_WRITE_ALLOW_WRITE)
 
481
          table->getMutableShare()->refreshVersion();
356
482
      }
357
483
    }
358
 
    /*
359
 
      No other thread has the locked tables open; reopen them and get the
360
 
      old locks. This should always succeed (unless some external process
361
 
      has removed the tables)
362
 
    */
363
 
    result= session->reopen_tables(true, true);
364
484
 
365
 
    /* Set version for table */
366
 
    for (Table *table= session->open_tables; table ; table= table->next)
367
 
    {
368
 
      /*
369
 
        Preserve the version (0) of write locked tables so that a impending
370
 
        global read lock won't sneak in.
371
 
      */
372
 
      if (table->reginfo.lock_type < TL_WRITE_ALLOW_WRITE)
373
 
        table->s->version= refresh_version;
374
 
    }
 
485
    LOCK_open.unlock();
375
486
  }
376
487
 
377
 
  pthread_mutex_unlock(&LOCK_open);
378
 
 
379
488
  if (wait_for_refresh)
380
489
  {
381
 
    pthread_mutex_lock(&session->mysys_var->mutex);
 
490
    boost::mutex::scoped_lock scopedLock(session->mysys_var->mutex);
382
491
    session->mysys_var->current_mutex= 0;
383
492
    session->mysys_var->current_cond= 0;
384
493
    session->set_proc_info(0);
385
 
    pthread_mutex_unlock(&session->mysys_var->mutex);
386
494
  }
387
495
 
388
496
  return result;
398
506
  bool found_old_table= false;
399
507
  Table *table= open_tables;
400
508
 
401
 
  safe_mutex_assert_owner(&LOCK_open);
 
509
  safe_mutex_assert_owner(LOCK_open.native_handle());
402
510
  assert(table->key_read == 0);
403
511
  assert(!table->cursor || table->cursor->inited == Cursor::NONE);
404
512
 
405
 
  open_tables= table->next;
 
513
  open_tables= table->getNext();
406
514
 
407
515
  if (table->needs_reopen_or_name_lock() ||
408
516
      version != refresh_version || !table->db_stat)
409
517
  {
410
 
    hash_delete(&open_cache,(unsigned char*) table);
 
518
    remove_table(table);
411
519
    found_old_table= true;
412
520
  }
413
521
  else
416
524
      Open placeholders have Table::db_stat set to 0, so they should be
417
525
      handled by the first alternative.
418
526
    */
419
 
    assert(!table->open_placeholder);
 
527
    assert(not table->open_placeholder);
420
528
 
421
529
    /* Free memory and reset for next loop */
422
530
    table->cursor->ha_reset();
423
531
    table->in_use= false;
424
532
 
425
 
    if (unused_tables)
426
 
    {
427
 
      table->next= unused_tables;               /* Link in last */
428
 
      table->prev= unused_tables->prev;
429
 
      unused_tables->prev= table;
430
 
      table->prev->next= table;
431
 
    }
432
 
    else
433
 
      unused_tables= table->next=table->prev=table;
 
533
    unused_tables.link(table);
434
534
  }
435
535
 
436
536
  return found_old_table;
449
549
{
450
550
  bool found_old_table= false;
451
551
 
452
 
  safe_mutex_assert_not_owner(&LOCK_open);
 
552
  safe_mutex_assert_not_owner(LOCK_open.native_handle());
453
553
 
454
 
  pthread_mutex_lock(&LOCK_open); /* Close all open tables on Session */
 
554
  boost::mutex::scoped_lock scoped_lock(LOCK_open); /* Close all open tables on Session */
455
555
 
456
556
  while (open_tables)
 
557
  {
457
558
    found_old_table|= free_cached_table();
 
559
  }
458
560
  some_tables_deleted= false;
459
561
 
460
562
  if (found_old_table)
462
564
    /* Tell threads waiting for refresh that something has happened */
463
565
    broadcast_refresh();
464
566
  }
465
 
 
466
 
  pthread_mutex_unlock(&LOCK_open);
467
567
}
468
568
 
469
569
/*
491
591
{
492
592
  for (; table; table= table->*link )
493
593
  {
494
 
    if ((table->table == 0 || table->table->s->tmp_table == STANDARD_TABLE) &&
495
 
        strcmp(table->db, db_name) == 0 &&
496
 
        strcmp(table->table_name, table_name) == 0)
 
594
    if ((table->table == 0 || table->table->getShare()->getType() == message::Table::STANDARD) &&
 
595
        strcasecmp(table->db, db_name) == 0 &&
 
596
        strcasecmp(table->table_name, table_name) == 0)
497
597
      break;
498
598
  }
499
599
  return table;
555
655
  if (table->table)
556
656
  {
557
657
    /* temporary table is always unique */
558
 
    if (table->table && table->table->s->tmp_table != STANDARD_TABLE)
 
658
    if (table->table && table->table->getShare()->getType() != message::Table::STANDARD)
559
659
      return 0;
560
660
    table= table->find_underlying_table(table->table);
561
661
    /*
586
686
}
587
687
 
588
688
 
 
689
void Session::doGetTableNames(const SchemaIdentifier &schema_identifier,
 
690
                              std::set<std::string>& set_of_names)
 
691
{
 
692
  for (Table *table= temporary_tables ; table ; table= table->getNext())
 
693
  {
 
694
    if (schema_identifier.compare(table->getShare()->getSchemaName()))
 
695
    {
 
696
      set_of_names.insert(table->getShare()->getTableName());
 
697
    }
 
698
  }
 
699
}
 
700
 
589
701
void Session::doGetTableNames(CachedDirectory &,
590
 
                              const std::string& db_name,
591
 
                              std::set<std::string>& set_of_names)
592
 
{
593
 
  for (Table *table= temporary_tables ; table ; table= table->next)
594
 
  {
595
 
    if (not db_name.compare(table->s->getSchemaName()))
596
 
    {
597
 
      set_of_names.insert(table->s->table_name.str);
598
 
    }
599
 
  }
600
 
}
601
 
 
602
 
int Session::doGetTableDefinition(const char *,
603
 
                                  const char *db_arg,
604
 
                                  const char *table_name_arg,
605
 
                                  const bool ,
606
 
                                  message::Table *table_proto)
607
 
{
608
 
  for (Table *table= temporary_tables ; table ; table= table->next)
609
 
  {
610
 
    if (table->s->tmp_table == TEMP_TABLE)
611
 
    {
612
 
      if (not strcmp(db_arg, table->s->getSchemaName()))
613
 
      {
614
 
        if (not strcmp(table_name_arg, table->s->table_name.str))
615
 
        {
616
 
          if (table_proto)
617
 
            table_proto->CopyFrom(*(table->s->getTableProto()));
618
 
 
619
 
          return EEXIST;
620
 
        }
 
702
                              const SchemaIdentifier &schema_identifier,
 
703
                              std::set<std::string> &set_of_names)
 
704
{
 
705
  doGetTableNames(schema_identifier, set_of_names);
 
706
}
 
707
 
 
708
void Session::doGetTableIdentifiers(const SchemaIdentifier &schema_identifier,
 
709
                                    TableIdentifiers &set_of_identifiers)
 
710
{
 
711
  for (Table *table= temporary_tables ; table ; table= table->getNext())
 
712
  {
 
713
    if (schema_identifier.compare(table->getShare()->getSchemaName()))
 
714
    {
 
715
      set_of_identifiers.push_back(TableIdentifier(table->getShare()->getSchemaName(),
 
716
                                                   table->getShare()->getTableName(),
 
717
                                                   table->getShare()->getPath()));
 
718
    }
 
719
  }
 
720
}
 
721
 
 
722
void Session::doGetTableIdentifiers(CachedDirectory &,
 
723
                                    const SchemaIdentifier &schema_identifier,
 
724
                                    TableIdentifiers &set_of_identifiers)
 
725
{
 
726
  doGetTableIdentifiers(schema_identifier, set_of_identifiers);
 
727
}
 
728
 
 
729
bool Session::doDoesTableExist(const TableIdentifier &identifier)
 
730
{
 
731
  for (Table *table= temporary_tables ; table ; table= table->getNext())
 
732
  {
 
733
    if (table->getShare()->getType() == message::Table::TEMPORARY)
 
734
    {
 
735
      if (identifier.getKey() == table->getShare()->getCacheKey())
 
736
      {
 
737
        return true;
 
738
      }
 
739
    }
 
740
  }
 
741
 
 
742
  return false;
 
743
}
 
744
 
 
745
int Session::doGetTableDefinition(const TableIdentifier &identifier,
 
746
                                  message::Table &table_proto)
 
747
{
 
748
  for (Table *table= temporary_tables ; table ; table= table->getNext())
 
749
  {
 
750
    if (table->getShare()->getType() == message::Table::TEMPORARY)
 
751
    {
 
752
      if (identifier.getKey() == table->getShare()->getCacheKey())
 
753
      {
 
754
        table_proto.CopyFrom(*(table->getShare()->getTableProto()));
 
755
 
 
756
        return EEXIST;
621
757
      }
622
758
    }
623
759
  }
629
765
{
630
766
  char  key[MAX_DBKEY_LENGTH];
631
767
  uint  key_length;
632
 
  Table *table;
633
 
 
634
 
  key_length= TableShare::createKey(key, new_db, table_name);
635
 
 
636
 
  for (table= temporary_tables ; table ; table= table->next)
 
768
 
 
769
  key_length= TableIdentifier::createKey(key, new_db, table_name);
 
770
 
 
771
  for (Table *table= temporary_tables ; table ; table= table->getNext())
637
772
  {
638
 
    if (table->s->table_cache_key.length == key_length &&
639
 
        !memcmp(table->s->table_cache_key.str, key, key_length))
 
773
    const TableIdentifier::Key &share_key(table->getShare()->getCacheKey());
 
774
    if (share_key.size() == key_length &&
 
775
        not memcmp(&share_key[0], key, key_length))
 
776
    {
640
777
      return table;
 
778
    }
641
779
  }
642
780
  return NULL;                               // Not a temporary table
643
781
}
647
785
  return find_temporary_table(table_list->db, table_list->table_name);
648
786
}
649
787
 
 
788
Table *Session::find_temporary_table(TableIdentifier &identifier)
 
789
{
 
790
  for (Table *table= temporary_tables ; table ; table= table->getNext())
 
791
  {
 
792
    if (identifier.getKey() == table->getShare()->getCacheKey())
 
793
      return table;
 
794
  }
 
795
 
 
796
  return NULL;                               // Not a temporary table
 
797
}
 
798
 
650
799
 
651
800
/**
652
801
  Drop a temporary table.
678
827
{
679
828
  Table *table;
680
829
 
681
 
  if (!(table= find_temporary_table(table_list)))
 
830
  if (not (table= find_temporary_table(table_list)))
682
831
    return 1;
683
832
 
684
833
  /* Table might be in use by some outer statement. */
685
834
  if (table->query_id && table->query_id != query_id)
686
835
  {
687
 
    my_error(ER_CANT_REOPEN_TABLE, MYF(0), table->alias);
 
836
    my_error(ER_CANT_REOPEN_TABLE, MYF(0), table->getAlias());
688
837
    return -1;
689
838
  }
690
839
 
694
843
}
695
844
 
696
845
 
697
 
/* move table first in unused links */
698
 
 
699
 
static void relink_unused(Table *table)
700
 
{
701
 
  if (table != unused_tables)
702
 
  {
703
 
    table->prev->next=table->next;              /* Remove from unused list */
704
 
    table->next->prev=table->prev;
705
 
    table->next=unused_tables;                  /* Link in unused tables */
706
 
    table->prev=unused_tables->prev;
707
 
    unused_tables->prev->next=table;
708
 
    unused_tables->prev=table;
709
 
    unused_tables=table;
710
 
  }
711
 
}
712
 
 
713
 
 
714
846
/**
715
847
  Remove all instances of table from thread's open list and
716
848
  table cache.
722
854
void Session::unlink_open_table(Table *find)
723
855
{
724
856
  char key[MAX_DBKEY_LENGTH];
725
 
  uint32_t key_length= find->s->table_cache_key.length;
 
857
  uint32_t key_length= find->getShare()->getCacheKeySize();
726
858
  Table *list, **prev;
727
 
 
728
 
  safe_mutex_assert_owner(&LOCK_open);
729
 
 
730
 
  memcpy(key, find->s->table_cache_key.str, key_length);
 
859
  safe_mutex_assert_owner(LOCK_open.native_handle());
 
860
 
 
861
  memcpy(key, &find->getMutableShare()->getCacheKey()[0], key_length);
731
862
  /*
732
863
    Note that we need to hold LOCK_open while changing the
733
864
    open_tables list. Another thread may work on it.
739
870
  {
740
871
    list= *prev;
741
872
 
742
 
    if (list->s->table_cache_key.length == key_length &&
743
 
        !memcmp(list->s->table_cache_key.str, key, key_length))
 
873
    if (list->getShare()->getCacheKeySize() == key_length &&
 
874
        not memcmp(&list->getShare()->getCacheKey()[0], key, key_length))
744
875
    {
745
876
      /* Remove table from open_tables list. */
746
 
      *prev= list->next;
 
877
      *prev= list->getNext();
 
878
 
747
879
      /* Close table. */
748
 
      hash_delete(&open_cache,(unsigned char*) list); // Close table
 
880
      remove_table(list);
749
881
    }
750
882
    else
751
883
    {
752
884
      /* Step to next entry in open_tables list. */
753
 
      prev= &list->next;
 
885
      prev= list->getNextPtr();
754
886
    }
755
887
  }
756
888
 
778
910
  table that was locked with LOCK TABLES.
779
911
*/
780
912
 
781
 
void Session::drop_open_table(Table *table, const char *db_name,
782
 
                              const char *table_name)
 
913
void Session::drop_open_table(Table *table, TableIdentifier &identifier)
783
914
{
784
 
  if (table->s->tmp_table)
 
915
  if (table->getShare()->getType())
785
916
  {
786
917
    close_temporary_table(table);
787
918
  }
788
919
  else
789
920
  {
790
 
    pthread_mutex_lock(&LOCK_open); /* Close and drop a table (AUX routine) */
 
921
    boost::mutex::scoped_lock scoped_lock(LOCK_open); /* Close and drop a table (AUX routine) */
791
922
    /*
792
923
      unlink_open_table() also tells threads waiting for refresh or close
793
924
      that something has happened.
794
925
    */
795
926
    unlink_open_table(table);
796
 
    TableIdentifier identifier(db_name, table_name, STANDARD_TABLE);
797
927
    quick_rm_table(*this, identifier);
798
 
    pthread_mutex_unlock(&LOCK_open);
799
928
  }
800
929
}
801
930
 
811
940
  cond  Condition to wait for
812
941
*/
813
942
 
814
 
void Session::wait_for_condition(pthread_mutex_t *mutex, pthread_cond_t *cond)
 
943
void Session::wait_for_condition(boost::mutex &mutex, boost::condition_variable &cond)
815
944
{
816
945
  /* Wait until the current table is up to date */
817
946
  const char *saved_proc_info;
818
 
  mysys_var->current_mutex= mutex;
819
 
  mysys_var->current_cond= cond;
 
947
  mysys_var->current_mutex= &mutex;
 
948
  mysys_var->current_cond= &cond;
820
949
  saved_proc_info= get_proc_info();
821
950
  set_proc_info("Waiting for table");
822
 
  if (!killed)
823
 
    (void) pthread_cond_wait(cond, mutex);
824
 
 
825
 
  /*
826
 
    We must unlock mutex first to avoid deadlock becasue conditions are
827
 
    sent to this thread by doing locks in the following order:
828
 
    lock(mysys_var->mutex)
829
 
    lock(mysys_var->current_mutex)
830
 
 
831
 
    One by effect of this that one can only use wait_for_condition with
832
 
    condition variables that are guranteed to not disapper (freed) even if this
833
 
    mutex is unlocked
834
 
  */
835
 
 
836
 
  pthread_mutex_unlock(mutex);
837
 
  pthread_mutex_lock(&mysys_var->mutex);
 
951
  {
 
952
    /*
 
953
      We must unlock mutex first to avoid deadlock becasue conditions are
 
954
      sent to this thread by doing locks in the following order:
 
955
      lock(mysys_var->mutex)
 
956
      lock(mysys_var->current_mutex)
 
957
 
 
958
      One by effect of this that one can only use wait_for_condition with
 
959
      condition variables that are guranteed to not disapper (freed) even if this
 
960
      mutex is unlocked
 
961
    */
 
962
    boost::mutex::scoped_lock scopedLock(mutex, boost::adopt_lock_t());
 
963
    if (not killed)
 
964
    {
 
965
      cond.wait(scopedLock);
 
966
    }
 
967
  }
 
968
  boost::mutex::scoped_lock (mysys_var->mutex);
838
969
  mysys_var->current_mutex= 0;
839
970
  mysys_var->current_cond= 0;
840
971
  set_proc_info(saved_proc_info);
841
 
  pthread_mutex_unlock(&mysys_var->mutex);
842
972
}
843
973
 
844
974
 
872
1002
  char *table_name= table_list->table_name;
873
1003
  Table orig_table;
874
1004
 
875
 
  safe_mutex_assert_owner(&LOCK_open);
 
1005
  safe_mutex_assert_owner(LOCK_open.native_handle());
876
1006
 
877
1007
  if (killed || !table)
878
1008
    return true;
879
1009
 
880
1010
  orig_table= *table;
881
1011
 
882
 
  if (open_unireg_entry(this, table, table_list, table_name,
883
 
                        table->s->table_cache_key.str,
884
 
                        table->s->table_cache_key.length))
 
1012
  TableIdentifier identifier(table_list->db, table_list->table_name);
 
1013
  if (open_unireg_entry(this, table, table_name, identifier))
885
1014
  {
886
1015
    table->intern_close_table();
887
1016
    /*
894
1023
    return true;
895
1024
  }
896
1025
 
897
 
  share= table->s;
 
1026
  share= table->getMutableShare();
898
1027
  /*
899
1028
    We want to prevent other connections from opening this table until end
900
1029
    of statement as it is likely that modifications of table's metadata are
903
1032
    This also allows us to assume that no other connection will sneak in
904
1033
    before we will get table-level lock on this table.
905
1034
  */
906
 
  share->version=0;
 
1035
  share->resetVersion();
907
1036
  table->in_use = this;
908
1037
 
909
1038
  if (link_in)
910
1039
  {
911
 
    table->next= open_tables;
 
1040
    table->setNext(open_tables);
912
1041
    open_tables= table;
913
1042
  }
914
1043
  else
917
1046
      Table object should be already in Session::open_tables list so we just
918
1047
      need to set Table::next correctly.
919
1048
    */
920
 
    table->next= orig_table.next;
 
1049
    table->setNext(orig_table.getNext());
921
1050
  }
922
1051
 
923
1052
  table->tablenr= current_tablenr++;
945
1074
  case of failure.
946
1075
*/
947
1076
 
948
 
Table *Session::table_cache_insert_placeholder(const char *key, uint32_t key_length)
 
1077
Table *Session::table_cache_insert_placeholder(const char *db_name, const char *table_name)
949
1078
{
950
 
  Table *table;
951
 
  TableShare *share;
952
 
  char *key_buff;
953
 
 
954
 
  safe_mutex_assert_owner(&LOCK_open);
 
1079
  safe_mutex_assert_owner(LOCK_open.native_handle());
955
1080
 
956
1081
  /*
957
1082
    Create a table entry with the right key and with an old refresh version
958
 
    Note that we must use multi_malloc() here as this is freed by the
959
 
    table cache
960
1083
  */
961
 
  if (! memory::multi_malloc(true,
962
 
                             &table, sizeof(*table),
963
 
                             &share, sizeof(*share),
964
 
                             &key_buff, key_length,
965
 
                             NULL))
966
 
    return NULL;
967
 
 
968
 
  table->s= share;
969
 
  share->set_table_cache_key(key_buff, key, key_length);
970
 
  share->tmp_table= INTERNAL_TMP_TABLE;  // for intern_close_table
971
 
  table->in_use= this;
972
 
  table->locked_by_name=1;
973
 
 
974
 
  if (my_hash_insert(&open_cache, (unsigned char*)table))
 
1084
  TableIdentifier identifier(db_name, table_name, message::Table::INTERNAL);
 
1085
  TablePlaceholder *table= new TablePlaceholder(this, identifier);
 
1086
 
 
1087
  if (not add_table(table))
975
1088
  {
976
 
    free((unsigned char*) table);
 
1089
    delete table;
 
1090
 
977
1091
    return NULL;
978
1092
  }
979
1093
 
1002
1116
  @retval  true   Error occured (OOM)
1003
1117
  @retval  false  Success. 'table' parameter set according to above rules.
1004
1118
*/
1005
 
 
1006
 
bool Session::lock_table_name_if_not_cached(const char *new_db,
1007
 
                                            const char *table_name, Table **table)
 
1119
bool Session::lock_table_name_if_not_cached(TableIdentifier &identifier, Table **table)
1008
1120
{
1009
 
  char key[MAX_DBKEY_LENGTH];
1010
 
  char *key_pos= key;
1011
 
  uint32_t key_length;
1012
 
 
1013
 
  key_pos= strcpy(key_pos, new_db) + strlen(new_db);
1014
 
  key_pos= strcpy(key_pos+1, table_name) + strlen(table_name);
1015
 
  key_length= (uint32_t) (key_pos-key)+1;
1016
 
 
1017
 
  pthread_mutex_lock(&LOCK_open); /* Obtain a name lock even though table is not in cache (like for create table)  */
1018
 
 
1019
 
  if (hash_search(&open_cache, (unsigned char *)key, key_length))
 
1121
  const TableIdentifier::Key &key(identifier.getKey());
 
1122
 
 
1123
  boost::mutex::scoped_lock scope_lock(LOCK_open); /* Obtain a name lock even though table is not in cache (like for create table)  */
 
1124
 
 
1125
  TableOpenCache::iterator iter;
 
1126
 
 
1127
  iter= get_open_cache().find(key);
 
1128
 
 
1129
  if (iter != get_open_cache().end())
1020
1130
  {
1021
 
    pthread_mutex_unlock(&LOCK_open);
1022
1131
    *table= 0;
1023
1132
    return false;
1024
1133
  }
1025
 
  if (!(*table= table_cache_insert_placeholder(key, key_length)))
 
1134
 
 
1135
  if (not (*table= table_cache_insert_placeholder(identifier.getSchemaName().c_str(), identifier.getTableName().c_str())))
1026
1136
  {
1027
 
    pthread_mutex_unlock(&LOCK_open);
1028
1137
    return true;
1029
1138
  }
1030
1139
  (*table)->open_placeholder= true;
1031
 
  (*table)->next= open_tables;
 
1140
  (*table)->setNext(open_tables);
1032
1141
  open_tables= *table;
1033
 
  pthread_mutex_unlock(&LOCK_open);
1034
1142
 
1035
1143
  return false;
1036
1144
}
1071
1179
Table *Session::openTable(TableList *table_list, bool *refresh, uint32_t flags)
1072
1180
{
1073
1181
  Table *table;
1074
 
  char key[MAX_DBKEY_LENGTH];
1075
 
  unsigned int key_length;
1076
1182
  const char *alias= table_list->alias;
1077
 
  HASH_SEARCH_STATE state;
1078
1183
 
1079
1184
  /* Parsing of partitioning information from .frm needs session->lex set up. */
1080
1185
  assert(lex->is_lex_started);
1090
1195
  if (killed)
1091
1196
    return NULL;
1092
1197
 
1093
 
  key_length= table_list->create_table_def_key(key);
 
1198
  TableIdentifier identifier(table_list->db, table_list->table_name);
 
1199
  const TableIdentifier::Key &key(identifier.getKey());
 
1200
  TableOpenCacheRange ppp;
1094
1201
 
1095
1202
  /*
1096
1203
    Unless requested otherwise, try to resolve this table in the list
1099
1206
    same name. This block implements the behaviour.
1100
1207
    TODO -> move this block into a separate function.
1101
1208
  */
1102
 
  for (table= temporary_tables; table ; table=table->next)
 
1209
  bool reset= false;
 
1210
  for (table= temporary_tables; table ; table=table->getNext())
1103
1211
  {
1104
 
    if (table->s->table_cache_key.length == key_length && !memcmp(table->s->table_cache_key.str, key, key_length))
 
1212
    if (table->getShare()->getCacheKey() == key)
1105
1213
    {
1106
1214
      /*
1107
1215
        We're trying to use the same temporary table twice in a query.
1111
1219
      */
1112
1220
      if (table->query_id)
1113
1221
      {
1114
 
        my_error(ER_CANT_REOPEN_TABLE, MYF(0), table->alias);
 
1222
        my_error(ER_CANT_REOPEN_TABLE, MYF(0), table->getAlias());
1115
1223
        return NULL;
1116
1224
      }
1117
1225
      table->query_id= getQueryId();
1118
 
      goto reset;
1119
 
    }
1120
 
  }
1121
 
 
1122
 
  if (flags & DRIZZLE_OPEN_TEMPORARY_ONLY)
1123
 
  {
1124
 
    my_error(ER_NO_SUCH_TABLE, MYF(0), table_list->db, table_list->table_name);
1125
 
    return NULL;
1126
 
  }
1127
 
 
1128
 
  /*
1129
 
    If it's the first table from a list of tables used in a query,
1130
 
    remember refresh_version (the version of open_cache state).
1131
 
    If the version changes while we're opening the remaining tables,
1132
 
    we will have to back off, close all the tables opened-so-far,
1133
 
    and try to reopen them.
1134
 
 
1135
 
    Note-> refresh_version is currently changed only during FLUSH TABLES.
1136
 
  */
1137
 
  if (!open_tables)
1138
 
    version= refresh_version;
1139
 
  else if ((version != refresh_version) &&
1140
 
           ! (flags & DRIZZLE_LOCK_IGNORE_FLUSH))
1141
 
  {
1142
 
    /* Someone did a refresh while thread was opening tables */
1143
 
    if (refresh)
1144
 
      *refresh= true;
1145
 
 
1146
 
    return NULL;
1147
 
  }
1148
 
 
1149
 
  /*
1150
 
    Before we test the global cache, we test our local session cache.
1151
 
  */
1152
 
  if (cached_table)
1153
 
  {
1154
 
    assert(false); /* Not implemented yet */
1155
 
  }
1156
 
 
1157
 
  /*
1158
 
    Non pre-locked/LOCK TABLES mode, and the table is not temporary:
1159
 
    this is the normal use case.
1160
 
    Now we should:
1161
 
    - try to find the table in the table cache.
1162
 
    - if one of the discovered Table instances is name-locked
1163
 
    (table->s->version == 0) back off -- we have to wait
1164
 
    until no one holds a name lock on the table.
1165
 
    - if there is no such Table in the name cache, read the table definition
1166
 
    and insert it into the cache.
1167
 
    We perform all of the above under LOCK_open which currently protects
1168
 
    the open cache (also known as table cache) and table definitions stored
1169
 
    on disk.
1170
 
  */
1171
 
 
1172
 
  pthread_mutex_lock(&LOCK_open); /* Lock for FLUSH TABLES for open table */
1173
 
 
1174
 
  /*
1175
 
    Actually try to find the table in the open_cache.
1176
 
    The cache may contain several "Table" instances for the same
1177
 
    physical table. The instances that are currently "in use" by
1178
 
    some thread have their "in_use" member != NULL.
1179
 
    There is no good reason for having more than one entry in the
1180
 
    hash for the same physical table, except that we use this as
1181
 
    an implicit "pending locks queue" - see
1182
 
    wait_for_locked_table_names for details.
1183
 
  */
1184
 
  for (table= (Table*) hash_first(&open_cache, (unsigned char*) key, key_length,
1185
 
                                  &state);
1186
 
       table && table->in_use ;
1187
 
       table= (Table*) hash_next(&open_cache, (unsigned char*) key, key_length,
1188
 
                                 &state))
1189
 
  {
 
1226
      reset= true;
 
1227
      break;
 
1228
    }
 
1229
  }
 
1230
 
 
1231
  if (not reset)
 
1232
  {
 
1233
    if (flags & DRIZZLE_OPEN_TEMPORARY_ONLY)
 
1234
    {
 
1235
      my_error(ER_NO_SUCH_TABLE, MYF(0), table_list->db, table_list->table_name);
 
1236
      return NULL;
 
1237
    }
 
1238
 
1190
1239
    /*
1191
 
      Here we flush tables marked for flush.
1192
 
      Normally, table->s->version contains the value of
1193
 
      refresh_version from the moment when this table was
1194
 
      (re-)opened and added to the cache.
1195
 
      If since then we did (or just started) FLUSH TABLES
1196
 
      statement, refresh_version has been increased.
1197
 
      For "name-locked" Table instances, table->s->version is set
1198
 
      to 0 (see lock_table_name for details).
1199
 
      In case there is a pending FLUSH TABLES or a name lock, we
1200
 
      need to back off and re-start opening tables.
1201
 
      If we do not back off now, we may dead lock in case of lock
1202
 
      order mismatch with some other thread:
1203
 
c1: name lock t1; -- sort of exclusive lock
1204
 
c2: open t2;      -- sort of shared lock
1205
 
c1: name lock t2; -- blocks
1206
 
c2: open t1; -- blocks
 
1240
      If it's the first table from a list of tables used in a query,
 
1241
      remember refresh_version (the version of open_cache state).
 
1242
      If the version changes while we're opening the remaining tables,
 
1243
      we will have to back off, close all the tables opened-so-far,
 
1244
      and try to reopen them.
 
1245
 
 
1246
      Note-> refresh_version is currently changed only during FLUSH TABLES.
1207
1247
    */
1208
 
    if (table->needs_reopen_or_name_lock())
1209
 
    {
1210
 
      if (flags & DRIZZLE_LOCK_IGNORE_FLUSH)
1211
 
      {
1212
 
        /* Force close at once after usage */
1213
 
        version= table->s->version;
1214
 
        continue;
1215
 
      }
1216
 
 
1217
 
      /* Avoid self-deadlocks by detecting self-dependencies. */
1218
 
      if (table->open_placeholder && table->in_use == this)
1219
 
      {
1220
 
        pthread_mutex_unlock(&LOCK_open);
1221
 
        my_error(ER_UPDATE_TABLE_USED, MYF(0), table->s->table_name.str);
1222
 
        return NULL;
1223
 
      }
1224
 
 
1225
 
      /*
1226
 
        Back off, part 1: mark the table as "unused" for the
1227
 
        purpose of name-locking by setting table->db_stat to 0. Do
1228
 
        that only for the tables in this thread that have an old
1229
 
        table->s->version (this is an optimization (?)).
1230
 
        table->db_stat == 0 signals wait_for_locked_table_names
1231
 
        that the tables in question are not used any more. See
1232
 
        table_is_used call for details.
1233
 
      */
1234
 
      close_old_data_files(false, false);
1235
 
 
1236
 
      /*
1237
 
        Back-off part 2: try to avoid "busy waiting" on the table:
1238
 
        if the table is in use by some other thread, we suspend
1239
 
        and wait till the operation is complete: when any
1240
 
        operation that juggles with table->s->version completes,
1241
 
        it broadcasts COND_refresh condition variable.
1242
 
        If 'old' table we met is in use by current thread we return
1243
 
        without waiting since in this situation it's this thread
1244
 
        which is responsible for broadcasting on COND_refresh
1245
 
        (and this was done already in Session::close_old_data_files()).
1246
 
        Good example of such situation is when we have statement
1247
 
        that needs two instances of table and FLUSH TABLES comes
1248
 
        after we open first instance but before we open second
1249
 
        instance.
1250
 
      */
1251
 
      if (table->in_use != this)
1252
 
      {
1253
 
        /* wait_for_conditionwill unlock LOCK_open for us */
1254
 
        wait_for_condition(&LOCK_open, &COND_refresh);
1255
 
      }
1256
 
      else
1257
 
      {
1258
 
        pthread_mutex_unlock(&LOCK_open);
1259
 
      }
1260
 
      /*
1261
 
        There is a refresh in progress for this table.
1262
 
        Signal the caller that it has to try again.
1263
 
      */
 
1248
    if (!open_tables)
 
1249
    {
 
1250
      version= refresh_version;
 
1251
    }
 
1252
    else if ((version != refresh_version) &&
 
1253
             ! (flags & DRIZZLE_LOCK_IGNORE_FLUSH))
 
1254
    {
 
1255
      /* Someone did a refresh while thread was opening tables */
1264
1256
      if (refresh)
1265
1257
        *refresh= true;
1266
 
      return NULL;
1267
 
    }
1268
 
  }
1269
 
  if (table)
1270
 
  {
1271
 
    /* Unlink the table from "unused_tables" list. */
1272
 
    if (table == unused_tables)
1273
 
    {  // First unused
1274
 
      unused_tables=unused_tables->next; // Remove from link
1275
 
      if (table == unused_tables)
1276
 
        unused_tables= NULL;
1277
 
    }
1278
 
    table->prev->next=table->next; /* Remove from unused list */
1279
 
    table->next->prev=table->prev;
1280
 
    table->in_use= this;
1281
 
  }
1282
 
  else
1283
 
  {
1284
 
    /* Insert a new Table instance into the open cache */
1285
 
    int error;
1286
 
    /* Free cache if too big */
1287
 
    while (open_cache.records > table_cache_size && unused_tables)
1288
 
      hash_delete(&open_cache,(unsigned char*) unused_tables);
1289
 
 
1290
 
    if (table_list->create)
1291
 
    {
1292
 
      TableIdentifier  lock_table_identifier(table_list->db, table_list->table_name, STANDARD_TABLE);
1293
 
 
1294
 
      if (not plugin::StorageEngine::doesTableExist(*this, lock_table_identifier))
1295
 
      {
1296
 
        /*
1297
 
          Table to be created, so we need to create placeholder in table-cache.
1298
 
        */
1299
 
        if (!(table= table_cache_insert_placeholder(key, key_length)))
1300
 
        {
1301
 
          pthread_mutex_unlock(&LOCK_open);
1302
 
          return NULL;
1303
 
        }
1304
 
        /*
1305
 
          Link placeholder to the open tables list so it will be automatically
1306
 
          removed once tables are closed. Also mark it so it won't be ignored
1307
 
          by other trying to take name-lock.
1308
 
        */
1309
 
        table->open_placeholder= true;
1310
 
        table->next= open_tables;
1311
 
        open_tables= table;
1312
 
        pthread_mutex_unlock(&LOCK_open);
1313
 
 
1314
 
        return table ;
1315
 
      }
1316
 
      /* Table exists. Let us try to open it. */
1317
 
    }
1318
 
 
1319
 
    /* make a new table */
1320
 
    table= (Table *)malloc(sizeof(Table));
1321
 
    if (table == NULL)
1322
 
    {
1323
 
      pthread_mutex_unlock(&LOCK_open);
1324
 
      return NULL;
1325
 
    }
1326
 
 
1327
 
    error= open_unireg_entry(this, table, table_list, alias, key, key_length);
1328
 
    if (error != 0)
1329
 
    {
1330
 
      free(table);
1331
 
      pthread_mutex_unlock(&LOCK_open);
1332
 
      return NULL;
1333
 
    }
1334
 
    my_hash_insert(&open_cache, (unsigned char*) table);
1335
 
  }
1336
 
 
1337
 
  pthread_mutex_unlock(&LOCK_open);
1338
 
  if (refresh)
1339
 
  {
1340
 
    table->next= open_tables; /* Link into simple list */
1341
 
    open_tables=table;
1342
 
  }
1343
 
  table->reginfo.lock_type= TL_READ; /* Assume read */
1344
 
 
1345
 
reset:
1346
 
  assert(table->s->ref_count > 0 || table->s->tmp_table != STANDARD_TABLE);
 
1258
 
 
1259
      return NULL;
 
1260
    }
 
1261
 
 
1262
    /*
 
1263
      Before we test the global cache, we test our local session cache.
 
1264
    */
 
1265
    if (cached_table)
 
1266
    {
 
1267
      assert(false); /* Not implemented yet */
 
1268
    }
 
1269
 
 
1270
    /*
 
1271
      Non pre-locked/LOCK TABLES mode, and the table is not temporary:
 
1272
      this is the normal use case.
 
1273
      Now we should:
 
1274
      - try to find the table in the table cache.
 
1275
      - if one of the discovered Table instances is name-locked
 
1276
      (table->getShare()->version == 0) back off -- we have to wait
 
1277
      until no one holds a name lock on the table.
 
1278
      - if there is no such Table in the name cache, read the table definition
 
1279
      and insert it into the cache.
 
1280
      We perform all of the above under LOCK_open which currently protects
 
1281
      the open cache (also known as table cache) and table definitions stored
 
1282
      on disk.
 
1283
    */
 
1284
 
 
1285
    {
 
1286
      LOCK_open.lock(); /* Lock for FLUSH TABLES for open table */
 
1287
 
 
1288
      /*
 
1289
        Actually try to find the table in the open_cache.
 
1290
        The cache may contain several "Table" instances for the same
 
1291
        physical table. The instances that are currently "in use" by
 
1292
        some thread have their "in_use" member != NULL.
 
1293
        There is no good reason for having more than one entry in the
 
1294
        hash for the same physical table, except that we use this as
 
1295
        an implicit "pending locks queue" - see
 
1296
        wait_for_locked_table_names for details.
 
1297
      */
 
1298
      ppp= get_open_cache().equal_range(key);
 
1299
 
 
1300
      table= NULL;
 
1301
      for (TableOpenCache::const_iterator iter= ppp.first;
 
1302
           iter != ppp.second; ++iter, table= NULL)
 
1303
      {
 
1304
        table= (*iter).second;
 
1305
 
 
1306
        if (not table->in_use)
 
1307
          break;
 
1308
        /*
 
1309
          Here we flush tables marked for flush.
 
1310
          Normally, table->getShare()->version contains the value of
 
1311
          refresh_version from the moment when this table was
 
1312
          (re-)opened and added to the cache.
 
1313
          If since then we did (or just started) FLUSH TABLES
 
1314
          statement, refresh_version has been increased.
 
1315
          For "name-locked" Table instances, table->getShare()->version is set
 
1316
          to 0 (see lock_table_name for details).
 
1317
          In case there is a pending FLUSH TABLES or a name lock, we
 
1318
          need to back off and re-start opening tables.
 
1319
          If we do not back off now, we may dead lock in case of lock
 
1320
          order mismatch with some other thread:
 
1321
          c1-> name lock t1; -- sort of exclusive lock
 
1322
          c2-> open t2;      -- sort of shared lock
 
1323
          c1-> name lock t2; -- blocks
 
1324
          c2-> open t1; -- blocks
 
1325
        */
 
1326
        if (table->needs_reopen_or_name_lock())
 
1327
        {
 
1328
          if (flags & DRIZZLE_LOCK_IGNORE_FLUSH)
 
1329
          {
 
1330
            /* Force close at once after usage */
 
1331
            version= table->getShare()->getVersion();
 
1332
            continue;
 
1333
          }
 
1334
 
 
1335
          /* Avoid self-deadlocks by detecting self-dependencies. */
 
1336
          if (table->open_placeholder && table->in_use == this)
 
1337
          {
 
1338
            LOCK_open.unlock();
 
1339
            my_error(ER_UPDATE_TABLE_USED, MYF(0), table->getMutableShare()->getTableName());
 
1340
            return NULL;
 
1341
          }
 
1342
 
 
1343
          /*
 
1344
            Back off, part 1: mark the table as "unused" for the
 
1345
            purpose of name-locking by setting table->db_stat to 0. Do
 
1346
            that only for the tables in this thread that have an old
 
1347
            table->getShare()->version (this is an optimization (?)).
 
1348
            table->db_stat == 0 signals wait_for_locked_table_names
 
1349
            that the tables in question are not used any more. See
 
1350
            table_is_used call for details.
 
1351
          */
 
1352
          close_old_data_files(false, false);
 
1353
 
 
1354
          /*
 
1355
            Back-off part 2: try to avoid "busy waiting" on the table:
 
1356
            if the table is in use by some other thread, we suspend
 
1357
            and wait till the operation is complete: when any
 
1358
            operation that juggles with table->getShare()->version completes,
 
1359
            it broadcasts COND_refresh condition variable.
 
1360
            If 'old' table we met is in use by current thread we return
 
1361
            without waiting since in this situation it's this thread
 
1362
            which is responsible for broadcasting on COND_refresh
 
1363
            (and this was done already in Session::close_old_data_files()).
 
1364
            Good example of such situation is when we have statement
 
1365
            that needs two instances of table and FLUSH TABLES comes
 
1366
            after we open first instance but before we open second
 
1367
            instance.
 
1368
          */
 
1369
          if (table->in_use != this)
 
1370
          {
 
1371
            /* wait_for_conditionwill unlock LOCK_open for us */
 
1372
            wait_for_condition(LOCK_open, COND_refresh);
 
1373
          }
 
1374
          else
 
1375
          {
 
1376
            LOCK_open.unlock();
 
1377
          }
 
1378
          /*
 
1379
            There is a refresh in progress for this table.
 
1380
            Signal the caller that it has to try again.
 
1381
          */
 
1382
          if (refresh)
 
1383
            *refresh= true;
 
1384
          return NULL;
 
1385
        }
 
1386
      }
 
1387
      if (table)
 
1388
      {
 
1389
        unused_tables.unlink(table);
 
1390
        table->in_use= this;
 
1391
      }
 
1392
      else
 
1393
      {
 
1394
        /* Insert a new Table instance into the open cache */
 
1395
        int error;
 
1396
        /* Free cache if too big */
 
1397
        unused_tables.cull();
 
1398
 
 
1399
        if (table_list->isCreate())
 
1400
        {
 
1401
          TableIdentifier  lock_table_identifier(table_list->db, table_list->table_name, message::Table::STANDARD);
 
1402
 
 
1403
          if (not plugin::StorageEngine::doesTableExist(*this, lock_table_identifier))
 
1404
          {
 
1405
            /*
 
1406
              Table to be created, so we need to create placeholder in table-cache.
 
1407
            */
 
1408
            if (!(table= table_cache_insert_placeholder(table_list->db, table_list->table_name)))
 
1409
            {
 
1410
              LOCK_open.unlock();
 
1411
              return NULL;
 
1412
            }
 
1413
            /*
 
1414
              Link placeholder to the open tables list so it will be automatically
 
1415
              removed once tables are closed. Also mark it so it won't be ignored
 
1416
              by other trying to take name-lock.
 
1417
            */
 
1418
            table->open_placeholder= true;
 
1419
            table->setNext(open_tables);
 
1420
            open_tables= table;
 
1421
            LOCK_open.unlock();
 
1422
 
 
1423
            return table ;
 
1424
          }
 
1425
          /* Table exists. Let us try to open it. */
 
1426
        }
 
1427
 
 
1428
        /* make a new table */
 
1429
        table= new Table;
 
1430
        if (table == NULL)
 
1431
        {
 
1432
          LOCK_open.unlock();
 
1433
          return NULL;
 
1434
        }
 
1435
 
 
1436
        error= open_unireg_entry(this, table, alias, identifier);
 
1437
        if (error != 0)
 
1438
        {
 
1439
          delete table;
 
1440
          LOCK_open.unlock();
 
1441
          return NULL;
 
1442
        }
 
1443
        (void)add_table(table);
 
1444
      }
 
1445
 
 
1446
      LOCK_open.unlock();
 
1447
    }
 
1448
    if (refresh)
 
1449
    {
 
1450
      table->setNext(open_tables); /* Link into simple list */
 
1451
      open_tables= table;
 
1452
    }
 
1453
    table->reginfo.lock_type= TL_READ; /* Assume read */
 
1454
 
 
1455
  }
 
1456
  assert(table->getShare()->getTableCount() > 0 || table->getShare()->getType() != message::Table::STANDARD);
1347
1457
 
1348
1458
  if (lex->need_correct_ident())
1349
1459
    table->alias_name_used= my_strcasecmp(table_alias_charset,
1350
 
                                          table->s->table_name.str, alias);
 
1460
                                          table->getMutableShare()->getTableName(), alias);
1351
1461
  /* Fix alias if table name changes */
1352
 
  if (strcmp(table->alias, alias))
 
1462
  if (strcmp(table->getAlias(), alias))
1353
1463
  {
1354
1464
    uint32_t length=(uint32_t) strlen(alias)+1;
1355
1465
    table->alias= (char*) realloc((char*) table->alias, length);
1364
1474
  table->maybe_null= false;
1365
1475
  table->force_index= false;
1366
1476
  table->status=STATUS_NO_RECORD;
1367
 
  table->insert_values= 0;
 
1477
  table->insert_values.clear();
1368
1478
  /* Catch wrong handling of the auto_increment_field_not_null. */
1369
1479
  assert(!table->auto_increment_field_not_null);
1370
1480
  table->auto_increment_field_not_null= false;
1371
1481
  if (table->timestamp_field)
 
1482
  {
1372
1483
    table->timestamp_field_type= table->timestamp_field->get_auto_set_type();
 
1484
  }
1373
1485
  table->pos_in_table_list= table_list;
1374
1486
  table->clear_column_bitmaps();
1375
1487
  assert(table->key_read == 0);
1378
1490
}
1379
1491
 
1380
1492
 
1381
 
/*
1382
 
  Reopen an table because the definition has changed.
1383
 
 
1384
 
  SYNOPSIS
1385
 
  reopen_table()
1386
 
  table Table object
1387
 
 
1388
 
  NOTES
1389
 
  The data cursor for the table is already closed and the share is released
1390
 
  The table has a 'dummy' share that mainly contains database and table name.
1391
 
 
1392
 
  RETURN
1393
 
  0  ok
1394
 
  1  error. The old table object is not changed.
1395
 
*/
1396
 
 
1397
 
bool reopen_table(Table *table)
1398
 
{
1399
 
  Table tmp;
1400
 
  bool error= 1;
1401
 
  Field **field;
1402
 
  uint32_t key,part;
1403
 
  TableList table_list;
1404
 
  Session *session= table->in_use;
1405
 
 
1406
 
  assert(table->s->ref_count == 0);
1407
 
  assert(!table->sort.io_cache);
1408
 
 
1409
 
#ifdef EXTRA_DEBUG
1410
 
  if (table->db_stat)
1411
 
    errmsg_printf(ERRMSG_LVL_ERROR, _("Table %s had a open data Cursor in reopen_table"),
1412
 
                  table->alias);
1413
 
#endif
1414
 
  table_list.db=         const_cast<char *>(table->s->getSchemaName());
1415
 
  table_list.table_name= table->s->table_name.str;
1416
 
  table_list.table=      table;
1417
 
 
1418
 
  if (wait_for_locked_table_names(session, &table_list))
1419
 
    return true;                             // Thread was killed
1420
 
 
1421
 
  if (open_unireg_entry(session, &tmp, &table_list,
1422
 
                        table->alias,
1423
 
                        table->s->table_cache_key.str,
1424
 
                        table->s->table_cache_key.length))
1425
 
    goto end;
1426
 
 
1427
 
  /* This list copies variables set by open_table */
1428
 
  tmp.tablenr=          table->tablenr;
1429
 
  tmp.used_fields=      table->used_fields;
1430
 
  tmp.const_table=      table->const_table;
1431
 
  tmp.null_row=         table->null_row;
1432
 
  tmp.maybe_null=       table->maybe_null;
1433
 
  tmp.status=           table->status;
1434
 
 
1435
 
  /* Get state */
1436
 
  tmp.in_use=           session;
1437
 
  tmp.reginfo.lock_type=table->reginfo.lock_type;
1438
 
 
1439
 
  /* Replace table in open list */
1440
 
  tmp.next=             table->next;
1441
 
  tmp.prev=             table->prev;
1442
 
 
1443
 
  if (table->cursor)
1444
 
    table->closefrm(true);              // close cursor, free everything
1445
 
 
1446
 
  *table= tmp;
1447
 
  table->default_column_bitmaps();
1448
 
  table->cursor->change_table_ptr(table, table->s);
1449
 
 
1450
 
  assert(table->alias != 0);
1451
 
  for (field=table->field ; *field ; field++)
1452
 
  {
1453
 
    (*field)->table= (*field)->orig_table= table;
1454
 
    (*field)->table_name= &table->alias;
1455
 
  }
1456
 
  for (key=0 ; key < table->s->keys ; key++)
1457
 
  {
1458
 
    for (part=0 ; part < table->key_info[key].usable_key_parts ; part++)
1459
 
      table->key_info[key].key_part[part].field->table= table;
1460
 
  }
1461
 
 
1462
 
  broadcast_refresh();
1463
 
  error= false;
1464
 
 
1465
 
end:
1466
 
  return(error);
1467
 
}
1468
 
 
1469
 
 
1470
1493
/**
1471
1494
  Close all instances of a table open by this thread and replace
1472
1495
  them with exclusive name-locks.
1484
1507
  the strings are used in a loop even after the share may be freed.
1485
1508
*/
1486
1509
 
1487
 
void Session::close_data_files_and_morph_locks(const char *new_db, const char *new_table_name)
 
1510
void Session::close_data_files_and_morph_locks(TableIdentifier &identifier)
1488
1511
{
1489
 
  Table *table;
1490
 
 
1491
 
  safe_mutex_assert_owner(&LOCK_open); /* Adjust locks at the end of ALTER TABLEL */
 
1512
  safe_mutex_assert_owner(LOCK_open.native_handle()); /* Adjust locks at the end of ALTER TABLEL */
1492
1513
 
1493
1514
  if (lock)
1494
1515
  {
1505
1526
    for target table name if we process ALTER Table ... RENAME.
1506
1527
    So loop below makes sense even if we are not under LOCK TABLES.
1507
1528
  */
1508
 
  for (table= open_tables; table ; table=table->next)
 
1529
  for (Table *table= open_tables; table ; table=table->getNext())
1509
1530
  {
1510
 
    if (!strcmp(table->s->table_name.str, new_table_name) &&
1511
 
        !strcmp(table->s->getSchemaName(), new_db))
 
1531
    if (table->getShare()->getCacheKey() == identifier.getKey())
1512
1532
    {
1513
1533
      table->open_placeholder= true;
1514
1534
      close_handle_and_leave_table_as_lock(table);
1537
1557
  @return false in case of success, true - otherwise.
1538
1558
*/
1539
1559
 
1540
 
bool Session::reopen_tables(bool get_locks, bool mark_share_as_old)
 
1560
bool Session::reopen_tables(bool get_locks, bool)
1541
1561
{
1542
1562
  Table *table,*next,**prev;
1543
1563
  Table **tables,**tables_ptr;                  // For locks
1549
1569
  if (open_tables == NULL)
1550
1570
    return false;
1551
1571
 
1552
 
  safe_mutex_assert_owner(&LOCK_open);
 
1572
  safe_mutex_assert_owner(LOCK_open.native_handle());
1553
1573
  if (get_locks)
1554
1574
  {
1555
1575
    /*
1558
1578
    */
1559
1579
    uint32_t opens= 0;
1560
1580
 
1561
 
    for (table= open_tables; table ; table=table->next)
 
1581
    for (table= open_tables; table ; table=table->getNext())
 
1582
    {
1562
1583
      opens++;
 
1584
    }
1563
1585
    tables= new Table *[opens];
1564
1586
  }
1565
1587
  else
 
1588
  {
1566
1589
    tables= &open_tables;
 
1590
  }
1567
1591
  tables_ptr =tables;
1568
1592
 
1569
1593
  prev= &open_tables;
1570
1594
  for (table= open_tables; table ; table=next)
1571
1595
  {
1572
 
    uint32_t db_stat= table->db_stat;
1573
 
    next= table->next;
1574
 
    if (!tables || (!db_stat && reopen_table(table)))
1575
 
    {
1576
 
      my_error(ER_CANT_REOPEN_TABLE, MYF(0), table->alias);
1577
 
      hash_delete(&open_cache,(unsigned char*) table);
1578
 
      error= 1;
1579
 
    }
1580
 
    else
1581
 
    {
1582
 
      *prev= table;
1583
 
      prev= &table->next;
1584
 
      /* Do not handle locks of MERGE children. */
1585
 
      if (get_locks && !db_stat)
1586
 
        *tables_ptr++= table;                   // need new lock on this
1587
 
      if (mark_share_as_old)
1588
 
      {
1589
 
        table->s->version= 0;
1590
 
        table->open_placeholder= false;
1591
 
      }
1592
 
    }
 
1596
    next= table->getNext();
 
1597
 
 
1598
    my_error(ER_CANT_REOPEN_TABLE, MYF(0), table->getAlias());
 
1599
    remove_table(table);
 
1600
    error= 1;
1593
1601
  }
1594
1602
  *prev=0;
1595
1603
  if (tables != tables_ptr)                     // Should we get back old locks
1596
1604
  {
1597
 
    DRIZZLE_LOCK *local_lock;
 
1605
    DrizzleLock *local_lock;
1598
1606
    /*
1599
1607
      We should always get these locks. Anyway, we must not go into
1600
1608
      wait_for_tables() as it tries to acquire LOCK_open, which is
1648
1656
 
1649
1657
  Table *table= open_tables;
1650
1658
 
1651
 
  for (; table ; table=table->next)
 
1659
  for (; table ; table=table->getNext())
1652
1660
  {
1653
1661
    /*
1654
1662
      Reopen marked for flush.
1724
1732
{
1725
1733
  do
1726
1734
  {
1727
 
    char *key= table->s->table_cache_key.str;
1728
 
    uint32_t key_length= table->s->table_cache_key.length;
1729
 
 
1730
 
    HASH_SEARCH_STATE state;
1731
 
    for (Table *search= (Table*) hash_first(&open_cache, (unsigned char*) key,
1732
 
                                            key_length, &state);
1733
 
         search ;
1734
 
         search= (Table*) hash_next(&open_cache, (unsigned char*) key,
1735
 
                                    key_length, &state))
 
1735
    const TableIdentifier::Key &key(table->getShare()->getCacheKey());
 
1736
 
 
1737
    TableOpenCacheRange ppp;
 
1738
    ppp= get_open_cache().equal_range(key);
 
1739
 
 
1740
    for (TableOpenCache::const_iterator iter= ppp.first;
 
1741
         iter != ppp.second; ++iter)
1736
1742
    {
 
1743
      Table *search= (*iter).second;
1737
1744
      if (search->in_use == table->in_use)
1738
1745
        continue;                               // Name locked by this thread
1739
1746
      /*
1747
1754
           (search->is_name_opened() && search->needs_reopen_or_name_lock()))
1748
1755
        return 1;
1749
1756
    }
1750
 
  } while ((table=table->next));
 
1757
  } while ((table=table->getNext()));
1751
1758
  return 0;
1752
1759
}
1753
1760
 
1759
1766
  bool result;
1760
1767
 
1761
1768
  session->set_proc_info("Waiting for tables");
1762
 
  pthread_mutex_lock(&LOCK_open); /* Lock for all tables to be refreshed */
1763
 
  while (!session->killed)
1764
 
  {
1765
 
    session->some_tables_deleted= false;
1766
 
    session->close_old_data_files(false, dropping_tables != 0);
1767
 
    if (!table_is_used(session->open_tables, 1))
1768
 
      break;
1769
 
    (void) pthread_cond_wait(&COND_refresh,&LOCK_open);
1770
 
  }
1771
 
  if (session->killed)
1772
 
    result= true;                                       // aborted
1773
 
  else
1774
 
  {
1775
 
    /* Now we can open all tables without any interference */
1776
 
    session->set_proc_info("Reopen tables");
1777
 
    session->version= refresh_version;
1778
 
    result= session->reopen_tables(false, false);
1779
 
  }
1780
 
  pthread_mutex_unlock(&LOCK_open);
 
1769
  {
 
1770
    boost::mutex::scoped_lock lock(LOCK_open);
 
1771
    while (!session->killed)
 
1772
    {
 
1773
      session->some_tables_deleted= false;
 
1774
      session->close_old_data_files(false, dropping_tables != 0);
 
1775
      if (!table_is_used(session->open_tables, 1))
 
1776
        break;
 
1777
      COND_refresh.wait(lock);
 
1778
    }
 
1779
    if (session->killed)
 
1780
      result= true;                                     // aborted
 
1781
    else
 
1782
    {
 
1783
      /* Now we can open all tables without any interference */
 
1784
      session->set_proc_info("Reopen tables");
 
1785
      session->version= refresh_version;
 
1786
      result= session->reopen_tables(false, false);
 
1787
    }
 
1788
  }
1781
1789
  session->set_proc_info(0);
1782
1790
 
1783
1791
  return result;
1808
1816
*/
1809
1817
 
1810
1818
 
1811
 
Table *drop_locked_tables(Session *session,const char *db, const char *table_name)
 
1819
Table *drop_locked_tables(Session *session, const drizzled::TableIdentifier &identifier)
1812
1820
{
1813
1821
  Table *table,*next,**prev, *found= 0;
1814
1822
  prev= &session->open_tables;
1822
1830
  */
1823
1831
  for (table= session->open_tables; table ; table=next)
1824
1832
  {
1825
 
    next=table->next;
1826
 
    if (!strcmp(table->s->table_name.str, table_name) &&
1827
 
        !strcmp(table->s->getSchemaName(), db))
 
1833
    next=table->getNext();
 
1834
    if (table->getShare()->getCacheKey() == identifier.getKey())
1828
1835
    {
1829
1836
      mysql_lock_remove(session, table);
1830
1837
 
1841
1848
      else
1842
1849
      {
1843
1850
        /* We already have a name lock, remove copy */
1844
 
        hash_delete(&open_cache,(unsigned char*) table);
 
1851
        remove_table(table);
1845
1852
      }
1846
1853
    }
1847
1854
    else
1848
1855
    {
1849
1856
      *prev=table;
1850
 
      prev= &table->next;
 
1857
      prev= table->getNextPtr();
1851
1858
    }
1852
1859
  }
1853
1860
  *prev=0;
1864
1871
  other threads trying to get the lock.
1865
1872
*/
1866
1873
 
1867
 
void abort_locked_tables(Session *session,const char *db, const char *table_name)
 
1874
void abort_locked_tables(Session *session, const drizzled::TableIdentifier &identifier)
1868
1875
{
1869
1876
  Table *table;
1870
 
  for (table= session->open_tables; table ; table= table->next)
 
1877
  for (table= session->open_tables; table ; table= table->getNext())
1871
1878
  {
1872
 
    if (!strcmp(table->s->table_name.str, table_name) &&
1873
 
        !strcmp(table->s->getSchemaName(), db))
 
1879
    if (table->getShare()->getCacheKey() == identifier.getKey())
1874
1880
    {
1875
1881
      /* If MERGE child, forward lock handling to parent. */
1876
1882
      mysql_lock_abort(session, table);
1900
1906
#       Error
1901
1907
*/
1902
1908
 
1903
 
static int open_unireg_entry(Session *session, Table *entry, TableList *table_list,
 
1909
static int open_unireg_entry(Session *session,
 
1910
                             Table *entry,
1904
1911
                             const char *alias,
1905
 
                             char *cache_key, uint32_t cache_key_length)
 
1912
                             TableIdentifier &identifier)
1906
1913
{
1907
1914
  int error;
1908
1915
  TableShare *share;
1909
1916
  uint32_t discover_retry_count= 0;
1910
1917
 
1911
 
  safe_mutex_assert_owner(&LOCK_open);
 
1918
  safe_mutex_assert_owner(LOCK_open.native_handle());
1912
1919
retry:
1913
 
  if (!(share= TableShare::getShare(session, table_list, cache_key,
1914
 
                                    cache_key_length,
1915
 
                                    table_list->i_s_requested_object,
1916
 
                                    &error)))
 
1920
  if (not (share= TableShare::getShareCreate(session,
 
1921
                                             identifier,
 
1922
                                             &error)))
1917
1923
    return 1;
1918
1924
 
1919
 
  while ((error= open_table_from_share(session, share, alias,
1920
 
                                       (uint32_t) (HA_OPEN_KEYFILE |
1921
 
                                                   HA_OPEN_RNDFILE |
1922
 
                                                   HA_GET_INDEX |
1923
 
                                                   HA_TRY_READ_ONLY),
1924
 
                                       session->open_options, entry)))
 
1925
  while ((error= share->open_table_from_share(session,
 
1926
                                              identifier,
 
1927
                                              alias,
 
1928
                                              (uint32_t) (HA_OPEN_KEYFILE |
 
1929
                                                          HA_OPEN_RNDFILE |
 
1930
                                                          HA_GET_INDEX |
 
1931
                                                          HA_TRY_READ_ONLY),
 
1932
                                              session->open_options, *entry)))
1925
1933
  {
1926
1934
    if (error == 7)                             // Table def changed
1927
1935
    {
1928
 
      share->version= 0;                        // Mark share as old
 
1936
      share->resetVersion();                        // Mark share as old
1929
1937
      if (discover_retry_count++)               // Retry once
1930
1938
        goto err;
1931
1939
 
1948
1956
        To avoid deadlock, only wait for release if no one else is
1949
1957
        using the share.
1950
1958
      */
1951
 
      if (share->ref_count != 1)
 
1959
      if (share->getTableCount() != 1)
1952
1960
        goto err;
1953
1961
      /* Free share and wait until it's released by all threads */
1954
1962
      TableShare::release(share);
2040
2048
     * to see if it exists so that an unauthorized user cannot phish for
2041
2049
     * table/schema information via error messages
2042
2050
     */
 
2051
    TableIdentifier the_table(tables->db, tables->table_name);
2043
2052
    if (not plugin::Authorization::isAuthorized(getSecurityContext(),
2044
 
                                                string(tables->db),
2045
 
                                                string(tables->table_name)))
 
2053
                                                the_table))
2046
2054
    {
2047
2055
      result= -1;                               // Fatal error
2048
2056
      break;
2088
2096
    {
2089
2097
      if (tables->lock_type == TL_WRITE_DEFAULT)
2090
2098
        tables->table->reginfo.lock_type= update_lock_default;
2091
 
      else if (tables->table->s->tmp_table == STANDARD_TABLE)
 
2099
      else if (tables->table->getShare()->getType() == message::Table::STANDARD)
2092
2100
        tables->table->reginfo.lock_type= tables->lock_type;
2093
2101
    }
2094
2102
  }
2246
2254
Table *Session::open_temporary_table(TableIdentifier &identifier,
2247
2255
                                     bool link_in_list)
2248
2256
{
2249
 
  Table *new_tmp_table;
2250
2257
  TableShare *share;
2251
 
  char cache_key[MAX_DBKEY_LENGTH], *saved_cache_key, *tmp_path;
2252
 
  uint32_t key_length, path_length;
2253
 
  TableList table_list;
2254
 
 
2255
 
  table_list.db=         (char*) identifier.getDBName();
2256
 
  table_list.table_name= (char*) identifier.getTableName();
2257
 
  /* Create the cache_key for temporary tables */
2258
 
  key_length= table_list.create_table_def_key(cache_key);
2259
 
  path_length= strlen(identifier.getPath());
2260
 
 
2261
 
  if (!(new_tmp_table= (Table*) malloc(sizeof(*new_tmp_table) + sizeof(*share) +
2262
 
                                       path_length + 1 + key_length)))
 
2258
 
 
2259
  assert(identifier.isTmp());
 
2260
  share= new TableShare(identifier.getType(),
 
2261
                        identifier,
 
2262
                        const_cast<char *>(identifier.getPath().c_str()), static_cast<uint32_t>(identifier.getPath().length()));
 
2263
 
 
2264
 
 
2265
  Table *new_tmp_table= new Table;
 
2266
  if (not new_tmp_table)
2263
2267
    return NULL;
2264
2268
 
2265
 
  share= (TableShare*) (new_tmp_table+1);
2266
 
  tmp_path= (char*) (share+1);
2267
 
  saved_cache_key= strcpy(tmp_path, identifier.getPath())+path_length+1;
2268
 
  memcpy(saved_cache_key, cache_key, key_length);
2269
 
 
2270
 
  share->init(saved_cache_key, key_length, strchr(saved_cache_key, '\0')+1, tmp_path);
2271
 
 
2272
2269
  /*
2273
2270
    First open the share, and then open the table from the share we just opened.
2274
2271
  */
2275
 
  if (open_table_def(*this, share) ||
2276
 
      open_table_from_share(this, share, identifier.getTableName(),
 
2272
  if (share->open_table_def(*this, identifier) ||
 
2273
      share->open_table_from_share(this, identifier, identifier.getTableName().c_str(),
2277
2274
                            (uint32_t) (HA_OPEN_KEYFILE | HA_OPEN_RNDFILE |
2278
2275
                                        HA_GET_INDEX),
2279
2276
                            ha_open_options,
2280
 
                            new_tmp_table))
 
2277
                            *new_tmp_table))
2281
2278
  {
2282
2279
    /* No need to lock share->mutex as this is not needed for tmp tables */
2283
 
    share->free_table_share();
2284
 
    free((char*) new_tmp_table);
 
2280
    delete share;
 
2281
    delete new_tmp_table;
 
2282
 
2285
2283
    return 0;
2286
2284
  }
2287
2285
 
2288
2286
  new_tmp_table->reginfo.lock_type= TL_WRITE;    // Simulate locked
2289
 
  share->tmp_table= TEMP_TABLE;
2290
2287
 
2291
2288
  if (link_in_list)
2292
2289
  {
2293
2290
    /* growing temp list at the head */
2294
 
    new_tmp_table->next= this->temporary_tables;
2295
 
    if (new_tmp_table->next)
2296
 
      new_tmp_table->next->prev= new_tmp_table;
 
2291
    new_tmp_table->setNext(this->temporary_tables);
 
2292
    if (new_tmp_table->getNext())
 
2293
    {
 
2294
      new_tmp_table->getNext()->setPrev(new_tmp_table);
 
2295
    }
2297
2296
    this->temporary_tables= new_tmp_table;
2298
 
    this->temporary_tables->prev= 0;
 
2297
    this->temporary_tables->setPrev(0);
2299
2298
  }
2300
2299
  new_tmp_table->pos_in_table_list= 0;
2301
2300
 
2410
2409
    return NULL;
2411
2410
  {
2412
2411
    /* This is a base table. */
2413
 
    assert(nj_col->table_ref->table == nj_col->table_field->table);
 
2412
    assert(nj_col->table_ref->table == nj_col->table_field->getTable());
2414
2413
    found_field= nj_col->table_field;
2415
2414
    update_field_dependencies(session, found_field, nj_col->table_ref->table);
2416
2415
  }
2447
2446
  uint32_t cached_field_index= *cached_field_index_ptr;
2448
2447
 
2449
2448
  /* We assume here that table->field < NO_CACHED_FIELD_INDEX = UINT_MAX */
2450
 
  if (cached_field_index < table->s->fields &&
 
2449
  if (cached_field_index < table->getShare()->sizeFields() &&
2451
2450
      !my_strcasecmp(system_charset_info,
2452
 
                     table->field[cached_field_index]->field_name, name))
2453
 
    field_ptr= table->field + cached_field_index;
2454
 
  else if (table->s->name_hash.records)
2455
 
  {
2456
 
    field_ptr= (Field**) hash_search(&table->s->name_hash, (unsigned char*) name,
2457
 
                                     length);
 
2451
                     table->getField(cached_field_index)->field_name, name))
 
2452
  {
 
2453
    field_ptr= table->getFields() + cached_field_index;
 
2454
  }
 
2455
  else if (table->getShare()->getNamedFieldSize())
 
2456
  {
 
2457
    field_ptr= table->getMutableShare()->getNamedField(std::string(name, length));
2458
2458
    if (field_ptr)
2459
2459
    {
2460
2460
      /*
2461
2461
        field_ptr points to field in TableShare. Convert it to the matching
2462
2462
        field in table
2463
2463
      */
2464
 
      field_ptr= (table->field + (field_ptr - table->s->field));
 
2464
      field_ptr= (table->getFields() + table->getShare()->positionFields(field_ptr));
2465
2465
    }
2466
2466
  }
2467
2467
  else
2468
2468
  {
2469
 
    if (!(field_ptr= table->field))
 
2469
    if (!(field_ptr= table->getFields()))
2470
2470
      return((Field *)0);
2471
2471
    for (; *field_ptr; ++field_ptr)
2472
2472
      if (!my_strcasecmp(system_charset_info, (*field_ptr)->field_name, name))
2475
2475
 
2476
2476
  if (field_ptr && *field_ptr)
2477
2477
  {
2478
 
    *cached_field_index_ptr= field_ptr - table->field;
 
2478
    *cached_field_index_ptr= field_ptr - table->getFields();
2479
2479
    field= *field_ptr;
2480
2480
  }
2481
2481
  else
2482
2482
  {
2483
2483
    if (!allow_rowid ||
2484
2484
        my_strcasecmp(system_charset_info, name, "_rowid") ||
2485
 
        table->s->rowid_field_offset == 0)
 
2485
        table->getShare()->rowid_field_offset == 0)
2486
2486
      return((Field*) 0);
2487
 
    field= table->field[table->s->rowid_field_offset-1];
 
2487
    field= table->getField(table->getShare()->rowid_field_offset-1);
2488
2488
  }
2489
2489
 
2490
2490
  update_field_dependencies(session, field, table);
2563
2563
    inside the view, but we want to search directly in the view columns
2564
2564
    which are represented as a 'field_translation'.
2565
2565
 
2566
 
TODO: Ensure that table_name, db_name and tables->db always points to
2567
 
something !
 
2566
    TODO-> Ensure that table_name, db_name and tables->db always points to something !
2568
2567
  */
2569
2568
  if (/* Exclude nested joins. */
2570
 
      (!table_list->nested_join) &&
 
2569
      (!table_list->getNestedJoin()) &&
2571
2570
      /* Include merge views and information schema tables. */
2572
2571
      /*
2573
2572
        Test if the field qualifiers match the table reference we plan
2581
2580
 
2582
2581
  *actual_table= NULL;
2583
2582
 
2584
 
  if (!table_list->nested_join)
 
2583
  if (!table_list->getNestedJoin())
2585
2584
  {
2586
2585
    /* 'table_list' is a stored table. */
2587
2586
    assert(table_list->table);
2601
2600
    */
2602
2601
    if (table_name && table_name[0])
2603
2602
    {
2604
 
      List_iterator<TableList> it(table_list->nested_join->join_list);
 
2603
      List_iterator<TableList> it(table_list->getNestedJoin()->join_list);
2605
2604
      TableList *table;
2606
2605
      while ((table= it++))
2607
2606
      {
2649
2648
        field_to_set= fld;
2650
2649
      if (field_to_set)
2651
2650
      {
2652
 
        Table *table= field_to_set->table;
 
2651
        Table *table= field_to_set->getTable();
2653
2652
        if (session->mark_used_columns == MARK_COLUMNS_READ)
2654
2653
          table->setReadSet(field_to_set->field_index);
2655
2654
        else
2895
2894
 
2896
2895
 
2897
2896
Item **
2898
 
find_item_in_list(Item *find, List<Item> &items, uint32_t *counter,
 
2897
find_item_in_list(Session *session,
 
2898
                  Item *find, List<Item> &items, uint32_t *counter,
2899
2899
                  find_item_error_report_type report_error,
2900
2900
                  enum_resolution_type *resolution)
2901
2901
{
2975
2975
            */
2976
2976
            if (report_error != IGNORE_ERRORS)
2977
2977
              my_error(ER_NON_UNIQ_ERROR, MYF(0),
2978
 
                       find->full_name(), current_session->where);
 
2978
                       find->full_name(), session->where);
2979
2979
            return (Item**) 0;
2980
2980
          }
2981
2981
          found_unaliased= li.ref();
3006
3006
              continue;                           // Same field twice
3007
3007
            if (report_error != IGNORE_ERRORS)
3008
3008
              my_error(ER_NON_UNIQ_ERROR, MYF(0),
3009
 
                       find->full_name(), current_session->where);
 
3009
                       find->full_name(), session->where);
3010
3010
            return (Item**) 0;
3011
3011
          }
3012
3012
          found= li.ref();
3058
3058
    {
3059
3059
      if (report_error != IGNORE_ERRORS)
3060
3060
        my_error(ER_NON_UNIQ_ERROR, MYF(0),
3061
 
                 find->full_name(), current_session->where);
 
3061
                 find->full_name(), session->where);
3062
3062
      return (Item **) 0;
3063
3063
    }
3064
3064
    if (found_unaliased)
3074
3074
  {
3075
3075
    if (report_error == REPORT_ALL_ERRORS)
3076
3076
      my_error(ER_BAD_FIELD_ERROR, MYF(0),
3077
 
               find->full_name(), current_session->where);
 
3077
               find->full_name(), session->where);
3078
3078
    return (Item **) 0;
3079
3079
  }
3080
3080
  else
3192
3192
    Leaf table references to which new natural join columns are added
3193
3193
    if the leaves are != NULL.
3194
3194
  */
3195
 
  TableList *leaf_1= (table_ref_1->nested_join &&
3196
 
                      !table_ref_1->is_natural_join) ?
 
3195
  TableList *leaf_1= (table_ref_1->getNestedJoin() &&
 
3196
                      ! table_ref_1->is_natural_join) ?
3197
3197
    NULL : table_ref_1;
3198
 
  TableList *leaf_2= (table_ref_2->nested_join &&
3199
 
                      !table_ref_2->is_natural_join) ?
 
3198
  TableList *leaf_2= (table_ref_2->getNestedJoin() &&
 
3199
                      ! table_ref_2->is_natural_join) ?
3200
3200
    NULL : table_ref_2;
3201
3201
 
3202
3202
  *found_using_fields= 0;
3395
3395
*/
3396
3396
 
3397
3397
static bool
3398
 
store_natural_using_join_columns(Session *,
 
3398
store_natural_using_join_columns(Session *session,
3399
3399
                                 TableList *natural_using_join,
3400
3400
                                 TableList *table_ref_1,
3401
3401
                                 TableList *table_ref_2,
3449
3449
        if (!(common_field= it++))
3450
3450
        {
3451
3451
          my_error(ER_BAD_FIELD_ERROR, MYF(0), using_field_name_ptr,
3452
 
                   current_session->where);
 
3452
                   session->where);
3453
3453
          goto err;
3454
3454
        }
3455
3455
        if (!my_strcasecmp(system_charset_info,
3521
3521
  bool result= true;
3522
3522
 
3523
3523
  /* Call the procedure recursively for each nested table reference. */
3524
 
  if (table_ref->nested_join)
 
3524
  if (table_ref->getNestedJoin())
3525
3525
  {
3526
 
    List_iterator_fast<TableList> nested_it(table_ref->nested_join->join_list);
 
3526
    List_iterator_fast<TableList> nested_it(table_ref->getNestedJoin()->join_list);
3527
3527
    TableList *same_level_left_neighbor= nested_it++;
3528
3528
    TableList *same_level_right_neighbor= NULL;
3529
3529
    /* Left/right-most neighbors, possibly at higher levels in the join tree. */
3548
3548
          cur_table_ref->outer_join & JOIN_TYPE_RIGHT)
3549
3549
      {
3550
3550
        /* This can happen only for JOIN ... ON. */
3551
 
        assert(table_ref->nested_join->join_list.elements == 2);
 
3551
        assert(table_ref->getNestedJoin()->join_list.elements == 2);
3552
3552
        std::swap(same_level_left_neighbor, cur_table_ref);
3553
3553
      }
3554
3554
 
3561
3561
      real_right_neighbor= (same_level_right_neighbor) ?
3562
3562
        same_level_right_neighbor : right_neighbor;
3563
3563
 
3564
 
      if (cur_table_ref->nested_join &&
 
3564
      if (cur_table_ref->getNestedJoin() &&
3565
3565
          store_top_level_join_columns(session, cur_table_ref,
3566
3566
                                       real_left_neighbor, real_right_neighbor))
3567
3567
        goto err;
3575
3575
  */
3576
3576
  if (table_ref->is_natural_join)
3577
3577
  {
3578
 
    assert(table_ref->nested_join &&
3579
 
           table_ref->nested_join->join_list.elements == 2);
3580
 
    List_iterator_fast<TableList> operand_it(table_ref->nested_join->join_list);
 
3578
    assert(table_ref->getNestedJoin() &&
 
3579
           table_ref->getNestedJoin()->join_list.elements == 2);
 
3580
    List_iterator_fast<TableList> operand_it(table_ref->getNestedJoin()->join_list);
3581
3581
    /*
3582
3582
      Notice that the order of join operands depends on whether table_ref
3583
3583
      represents a LEFT or a RIGHT join. In a RIGHT join, the operands are
4043
4043
    assert(tables->is_leaf_for_name_resolution());
4044
4044
 
4045
4045
    if ((table_name && my_strcasecmp(table_alias_charset, table_name, tables->alias)) ||
4046
 
        (db_name && strcmp(tables->db,db_name)))
 
4046
        (db_name && strcasecmp(tables->db,db_name)))
4047
4047
      continue;
4048
4048
 
4049
4049
    /*
4079
4079
      if ((field= field_iterator.field()))
4080
4080
      {
4081
4081
        /* Mark fields as used to allow storage engine to optimze access */
4082
 
        field->table->setReadSet(field->field_index);
 
4082
        field->getTable()->setReadSet(field->field_index);
4083
4083
        if (table)
4084
4084
        {
4085
4085
          table->covering_keys&= field->part_of_key;
4117
4117
      For NATURAL joins, used_tables is updated in the IF above.
4118
4118
    */
4119
4119
    if (table)
4120
 
      table->used_fields= table->s->fields;
 
4120
      table->used_fields= table->getShare()->sizeFields();
4121
4121
  }
4122
4122
  if (found)
4123
4123
    return false;
4207
4207
          goto err_no_arena;
4208
4208
        select_lex->cond_count++;
4209
4209
      }
4210
 
      embedding= embedded->embedding;
 
4210
      embedding= embedded->getEmbedding();
4211
4211
    }
4212
4212
    while (embedding &&
4213
 
           embedding->nested_join->join_list.head() == embedded);
 
4213
           embedding->getNestedJoin()->join_list.head() == embedded);
4214
4214
 
4215
4215
  }
4216
4216
  session->session_marker= save_session_marker;
4269
4269
      thus we safely can take table from the first field.
4270
4270
    */
4271
4271
    field= static_cast<Item_field *>(f++);
4272
 
    table= field->field->table;
 
4272
    table= field->field->getTable();
4273
4273
    table->auto_increment_field_not_null= false;
4274
4274
    f.rewind();
4275
4275
  }
4279
4279
    value= v++;
4280
4280
 
4281
4281
    Field *rfield= field->field;
4282
 
    table= rfield->table;
 
4282
    table= rfield->getTable();
4283
4283
 
4284
4284
    if (rfield == table->next_number_field)
4285
4285
      table->auto_increment_field_not_null= true;
4336
4336
      On INSERT or UPDATE fields are checked to be from the same table,
4337
4337
      thus we safely can take table from the first field.
4338
4338
    */
4339
 
    table= (*ptr)->table;
 
4339
    table= (*ptr)->getTable();
4340
4340
    table->auto_increment_field_not_null= false;
4341
4341
  }
4342
4342
  while ((field = *ptr++) && ! session->is_error())
4343
4343
  {
4344
4344
    value=v++;
4345
 
    table= field->table;
 
4345
    table= field->getTable();
4346
4346
    if (field == table->next_number_field)
4347
4347
      table->auto_increment_field_not_null= true;
4348
4348
    if (value->save_in_field(field, 0) < 0)
4363
4363
{
4364
4364
  Session *session;
4365
4365
 
4366
 
  assert(drizzle_tmpdir);
 
4366
  assert(drizzle_tmpdir.size());
4367
4367
 
4368
4368
  if (!(session= new Session(plugin::Listen::getNullClient())))
4369
4369
    return true;
4370
4370
  session->thread_stack= (char*) &session;
4371
4371
  session->storeGlobals();
4372
4372
 
4373
 
  plugin::StorageEngine::removeLostTemporaryTables(*session, drizzle_tmpdir);
 
4373
  plugin::StorageEngine::removeLostTemporaryTables(*session, drizzle_tmpdir.c_str());
4374
4374
 
 
4375
  session->lockForDelete();
4375
4376
  delete session;
4376
4377
 
4377
4378
  return false;
4396
4397
and afterwards delete those marked unused.
4397
4398
*/
4398
4399
 
4399
 
void remove_db_from_cache(const std::string schema_name)
 
4400
void remove_db_from_cache(const SchemaIdentifier &schema_identifier)
4400
4401
{
4401
 
  safe_mutex_assert_owner(&LOCK_open);
 
4402
  safe_mutex_assert_owner(LOCK_open.native_handle());
4402
4403
 
4403
 
  for (uint32_t idx=0 ; idx < open_cache.records ; idx++)
 
4404
  for (TableOpenCache::const_iterator iter= get_open_cache().begin();
 
4405
       iter != get_open_cache().end();
 
4406
       iter++)
4404
4407
  {
4405
 
    Table *table=(Table*) hash_element(&open_cache,idx);
4406
 
    if (not strcmp(table->s->getSchemaName(), schema_name.c_str()))
 
4408
    Table *table= (*iter).second;
 
4409
 
 
4410
    if (not schema_identifier.getPath().compare(table->getMutableShare()->getSchemaName()))
4407
4411
    {
4408
 
      table->s->version= 0L;                    /* Free when thread is ready */
 
4412
      table->getMutableShare()->resetVersion();                 /* Free when thread is ready */
4409
4413
      if (not table->in_use)
4410
 
        relink_unused(table);
 
4414
        unused_tables.relink(table);
4411
4415
    }
4412
4416
  }
4413
 
  while (unused_tables && !unused_tables->s->version)
4414
 
    hash_delete(&open_cache,(unsigned char*) unused_tables);
 
4417
 
 
4418
  unused_tables.cullByVersion();
4415
4419
}
4416
4420
 
4417
4421
 
4430
4434
  1  Table is in use by another thread
4431
4435
*/
4432
4436
 
4433
 
bool remove_table_from_cache(Session *session, const char *db, const char *table_name,
4434
 
                             uint32_t flags)
 
4437
bool remove_table_from_cache(Session *session, TableIdentifier &identifier, uint32_t flags)
4435
4438
{
4436
 
  char key[MAX_DBKEY_LENGTH];
4437
 
  char *key_pos= key;
4438
 
  uint32_t key_length;
4439
 
  Table *table;
 
4439
  const TableIdentifier::Key &key(identifier.getKey());
4440
4440
  bool result= false; 
4441
4441
  bool signalled= false;
4442
4442
 
4443
 
  key_pos= strcpy(key_pos, db) + strlen(db);
4444
 
  key_pos= strcpy(key_pos+1, table_name) + strlen(table_name);
4445
 
  key_length= (uint32_t) (key_pos-key)+1;
4446
 
 
4447
4443
  for (;;)
4448
4444
  {
4449
 
    HASH_SEARCH_STATE state;
4450
4445
    result= signalled= false;
4451
4446
 
4452
 
    for (table= (Table*) hash_first(&open_cache, (unsigned char*) key, key_length,
4453
 
                                    &state);
4454
 
         table;
4455
 
         table= (Table*) hash_next(&open_cache, (unsigned char*) key, key_length,
4456
 
                                   &state))
 
4447
    TableOpenCacheRange ppp;
 
4448
    ppp= get_open_cache().equal_range(key);
 
4449
 
 
4450
    for (TableOpenCache::const_iterator iter= ppp.first;
 
4451
         iter != ppp.second; ++iter)
4457
4452
    {
 
4453
      Table *table= (*iter).second;
4458
4454
      Session *in_use;
4459
4455
 
4460
 
      table->s->version=0L;             /* Free when thread is ready */
 
4456
      table->getMutableShare()->resetVersion();         /* Free when thread is ready */
4461
4457
      if (!(in_use=table->in_use))
4462
4458
      {
4463
 
        relink_unused(table);
 
4459
        unused_tables.relink(table);
4464
4460
      }
4465
4461
      else if (in_use != session)
4466
4462
      {
4485
4481
        */
4486
4482
        for (Table *session_table= in_use->open_tables;
4487
4483
             session_table ;
4488
 
             session_table= session_table->next)
 
4484
             session_table= session_table->getNext())
4489
4485
        {
4490
4486
          /* Do not handle locks of MERGE children. */
4491
4487
          if (session_table->db_stat)   // If table is open
4495
4491
      else
4496
4492
        result= result || (flags & RTFC_OWNED_BY_Session_FLAG);
4497
4493
    }
4498
 
    while (unused_tables && !unused_tables->s->version)
4499
 
      hash_delete(&open_cache,(unsigned char*) unused_tables);
 
4494
 
 
4495
    unused_tables.cullByVersion();
4500
4496
 
4501
4497
    /* Remove table from table definition cache if it's not in use */
4502
 
    TableShare::release(key, key_length);
 
4498
    TableShare::release(identifier);
4503
4499
 
4504
4500
    if (result && (flags & RTFC_WAIT_OTHER_THREAD_FLAG))
4505
4501
    {
4512
4508
      {
4513
4509
        dropping_tables++;
4514
4510
        if (likely(signalled))
4515
 
          (void) pthread_cond_wait(&COND_refresh, &LOCK_open);
 
4511
        {
 
4512
          boost::mutex::scoped_lock scoped(LOCK_open, boost::adopt_lock_t());
 
4513
          COND_refresh.wait(scoped);
 
4514
          scoped.release();
 
4515
        }
4516
4516
        else
4517
4517
        {
4518
 
          struct timespec abstime;
4519
4518
          /*
4520
4519
            It can happen that another thread has opened the
4521
4520
            table but has not yet locked any table at all. Since
4526
4525
            and then we retry another loop in the
4527
4526
            remove_table_from_cache routine.
4528
4527
          */
4529
 
          set_timespec(abstime, 10);
4530
 
          pthread_cond_timedwait(&COND_refresh, &LOCK_open, &abstime);
 
4528
          boost::xtime xt; 
 
4529
          xtime_get(&xt, boost::TIME_UTC); 
 
4530
          xt.sec += 10; 
 
4531
          boost::mutex::scoped_lock scoped(LOCK_open, boost::adopt_lock_t());
 
4532
          COND_refresh.timed_wait(scoped, xt);
 
4533
          scoped.release();
4531
4534
        }
4532
4535
        dropping_tables--;
4533
4536
        continue;
4535
4538
    }
4536
4539
    break;
4537
4540
  }
 
4541
 
4538
4542
  return result;
4539
4543
}
4540
4544