~drizzle-trunk/drizzle/development

« back to all changes in this revision

Viewing changes to drizzled/sql_base.cc

  • Committer: Andrew Hutchings
  • Date: 2010-09-06 20:47:28 UTC
  • mto: (1747.1.3 build)
  • mto: This revision was merged to the branch mainline in revision 1748.
  • Revision ID: andrew@linuxjedi.co.uk-20100906204728-8qjwkx638e5lsm1q
Timestamp cannot reliably store leap seconds, so don't try.  Leave that to datetime only

Show diffs side-by-side

added added

removed removed

Lines of Context:
11
11
 
12
12
  You should have received a copy of the GNU General Public License
13
13
  along with this program; if not, write to the Free Software
14
 
  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA */
 
14
  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA */
15
15
 
16
16
 
17
17
/* Basic functions needed by many modules */
18
 
#include <config.h>
 
18
#include "config.h"
19
19
#include <assert.h>
20
20
 
21
21
#include <signal.h>
30
30
#  include <time.h>
31
31
# endif
32
32
#endif
33
 
#include <drizzled/internal/my_pthread.h>
34
 
#include <drizzled/internal/thread_var.h>
 
33
#include "drizzled/internal/my_pthread.h"
 
34
#include "drizzled/internal/thread_var.h"
35
35
 
36
36
#include <drizzled/sql_select.h>
37
37
#include <drizzled/error.h>
44
44
#include <drizzled/check_stack_overrun.h>
45
45
#include <drizzled/lock.h>
46
46
#include <drizzled/plugin/listen.h>
47
 
#include <drizzled/cached_directory.h>
48
 
#include <drizzled/field/epoch.h>
 
47
#include "drizzled/cached_directory.h"
 
48
#include <drizzled/field/timestamp.h>
49
49
#include <drizzled/field/null.h>
50
 
#include <drizzled/sql_table.h>
51
 
#include <drizzled/global_charset_info.h>
52
 
#include <drizzled/pthread_globals.h>
53
 
#include <drizzled/internal/iocache.h>
54
 
#include <drizzled/drizzled.h>
55
 
#include <drizzled/plugin/authorization.h>
56
 
#include <drizzled/table/temporary.h>
57
 
#include <drizzled/table/placeholder.h>
58
 
#include <drizzled/table/unused.h>
59
 
#include <drizzled/plugin/storage_engine.h>
60
 
#include <drizzled/session.h>
61
 
 
62
 
#include <drizzled/refresh_version.h>
 
50
#include "drizzled/memory/multi_malloc.h"
 
51
#include "drizzled/sql_table.h"
 
52
#include "drizzled/global_charset_info.h"
 
53
#include "drizzled/pthread_globals.h"
 
54
#include "drizzled/internal/iocache.h"
 
55
#include "drizzled/drizzled.h"
 
56
#include "drizzled/plugin/authorization.h"
 
57
#include "drizzled/table_placeholder.h"
63
58
 
64
59
using namespace std;
65
60
 
68
63
 
69
64
extern bool volatile shutdown_in_progress;
70
65
 
 
66
TableOpenCache &get_open_cache()
 
67
{
 
68
  static TableOpenCache open_cache;                             /* Used by mysql_test */
 
69
 
 
70
  return open_cache;
 
71
}
 
72
 
 
73
static void free_cache_entry(Table *entry);
 
74
 
 
75
void remove_table(Table *arg)
 
76
{
 
77
  TableOpenCacheRange ppp;
 
78
  ppp= get_open_cache().equal_range(arg->getShare()->getCacheKey());
 
79
 
 
80
  for (TableOpenCache::const_iterator iter= ppp.first;
 
81
         iter != ppp.second; ++iter)
 
82
  {
 
83
    Table *found_table= (*iter).second;
 
84
 
 
85
    if (found_table == arg)
 
86
    {
 
87
      free_cache_entry(arg);
 
88
      get_open_cache().erase(iter);
 
89
      return;
 
90
    }
 
91
  }
 
92
}
 
93
 
 
94
static bool add_table(Table *arg)
 
95
{
 
96
  TableOpenCache &open_cache(get_open_cache());
 
97
 
 
98
  TableOpenCache::iterator returnable= open_cache.insert(make_pair(arg->getShare()->getCacheKey(), arg));
 
99
 
 
100
  return not (returnable == open_cache.end());
 
101
}
 
102
 
 
103
class UnusedTables {
 
104
  Table *tables;                                /* Used by mysql_test */
 
105
 
 
106
  Table *getTable() const
 
107
  {
 
108
    return tables;
 
109
  }
 
110
 
 
111
  Table *setTable(Table *arg)
 
112
  {
 
113
    return tables= arg;
 
114
  }
 
115
 
 
116
public:
 
117
 
 
118
  void cull()
 
119
  {
 
120
    /* Free cache if too big */
 
121
    while (cached_open_tables() > table_cache_size && getTable())
 
122
      remove_table(getTable());
 
123
  }
 
124
 
 
125
  void cullByVersion()
 
126
  {
 
127
    while (getTable() && not getTable()->getShare()->getVersion())
 
128
      remove_table(getTable());
 
129
  }
 
130
  
 
131
  void link(Table *table)
 
132
  {
 
133
    if (getTable())
 
134
    {
 
135
      table->setNext(getTable());               /* Link in last */
 
136
      table->setPrev(getTable()->getPrev());
 
137
      getTable()->setPrev(table);
 
138
      table->getPrev()->setNext(table);
 
139
    }
 
140
    else
 
141
    {
 
142
      table->setPrev(setTable(table));
 
143
      table->setNext(table->getPrev());
 
144
      assert(table->getNext() == table && table->getPrev() == table);
 
145
    }
 
146
  }
 
147
 
 
148
 
 
149
  void unlink(Table *table)
 
150
  {
 
151
    table->unlink();
 
152
 
 
153
    /* Unlink the table from "unused_tables" list. */
 
154
    if (table == getTable())
 
155
    {  // First unused
 
156
      setTable(getTable()->getNext()); // Remove from link
 
157
      if (table == getTable())
 
158
        setTable(NULL);
 
159
    }
 
160
  }
 
161
 
 
162
/* move table first in unused links */
 
163
 
 
164
  void relink(Table *table)
 
165
  {
 
166
    if (table != getTable())
 
167
    {
 
168
      table->unlink();
 
169
 
 
170
      table->setNext(getTable());                       /* Link in unused tables */
 
171
      table->setPrev(getTable()->getPrev());
 
172
      getTable()->getPrev()->setNext(table);
 
173
      getTable()->setPrev(table);
 
174
      setTable(table);
 
175
    }
 
176
  }
 
177
 
 
178
 
 
179
  void clear()
 
180
  {
 
181
    while (getTable())
 
182
      remove_table(getTable());
 
183
  }
 
184
 
 
185
  UnusedTables():
 
186
    tables(NULL)
 
187
  { }
 
188
 
 
189
  ~UnusedTables()
 
190
  { 
 
191
  }
 
192
};
 
193
 
 
194
static UnusedTables unused_tables;
 
195
static int open_unireg_entry(Session *session,
 
196
                             Table *entry,
 
197
                             const char *alias,
 
198
                             TableIdentifier &identifier);
 
199
 
 
200
unsigned char *table_cache_key(const unsigned char *record,
 
201
                               size_t *length,
 
202
                               bool );
 
203
 
 
204
#if 0
 
205
static bool reopen_table(Table *table);
 
206
#endif
 
207
 
 
208
unsigned char *table_cache_key(const unsigned char *record,
 
209
                               size_t *length,
 
210
                               bool )
 
211
{
 
212
  Table *entry=(Table*) record;
 
213
  *length= entry->getShare()->getCacheKey().size();
 
214
  return (unsigned char*) &entry->getShare()->getCacheKey()[0];
 
215
}
 
216
 
71
217
bool table_cache_init(void)
72
218
{
73
219
  return false;
75
221
 
76
222
uint32_t cached_open_tables(void)
77
223
{
78
 
  return table::getCache().size();
 
224
  return get_open_cache().size();
79
225
}
80
226
 
81
227
void table_cache_free(void)
82
228
{
83
229
  refresh_version++;                            // Force close of open tables
84
230
 
85
 
  table::getUnused().clear();
86
 
  table::getCache().clear();
 
231
  unused_tables.clear();
 
232
  get_open_cache().clear();
87
233
}
88
234
 
89
235
/*
97
243
  By leaving the table in the table cache, it disallows any other thread
98
244
  to open the table
99
245
 
100
 
  session->getKilled() will be set if we run out of memory
 
246
  session->killed will be set if we run out of memory
101
247
 
102
248
  If closing a MERGE child, the calling function has to take care for
103
249
  closing the parent too, if necessary.
106
252
 
107
253
void close_handle_and_leave_table_as_lock(Table *table)
108
254
{
 
255
  TableShare *share, *old_share= table->getMutableShare();
109
256
  assert(table->db_stat);
110
257
  assert(table->getShare()->getType() == message::Table::STANDARD);
111
258
 
114
261
    This has to be done to ensure that the table share is removed from
115
262
    the table defintion cache as soon as the last instance is removed
116
263
  */
117
 
  identifier::Table identifier(table->getShare()->getSchemaName(), table->getShare()->getTableName(), message::Table::INTERNAL);
118
 
  const identifier::Table::Key &key(identifier.getKey());
119
 
  TableShare *share= new TableShare(identifier.getType(),
120
 
                                    identifier,
121
 
                                    const_cast<char *>(key.vector()),  static_cast<uint32_t>(table->getShare()->getCacheKeySize()));
 
264
  TableIdentifier identifier(table->getShare()->getSchemaName(), table->getShare()->getTableName(), message::Table::INTERNAL);
 
265
  const TableIdentifier::Key &key(identifier.getKey());
 
266
  share= new TableShare(identifier.getType(),
 
267
                        identifier,
 
268
                        const_cast<char *>(&key[0]),  static_cast<uint32_t>(old_share->getCacheKeySize()));
122
269
 
123
270
  table->cursor->close();
124
271
  table->db_stat= 0;                            // Mark cursor closed
125
 
  table::instance::release(table->getMutableShare());
 
272
  TableShare::release(table->getMutableShare());
126
273
  table->setShare(share);
 
274
  table->cursor->change_table_ptr(table, table->getMutableShare());
127
275
}
128
276
 
129
277
 
141
289
  }
142
290
}
143
291
 
 
292
/*
 
293
  Remove table from the open table cache
 
294
 
 
295
  SYNOPSIS
 
296
  free_cache_entry()
 
297
  entry         Table to remove
 
298
 
 
299
  NOTE
 
300
  We need to have a lock on LOCK_open when calling this
 
301
*/
 
302
 
 
303
void free_cache_entry(Table *table)
 
304
{
 
305
  table->intern_close_table();
 
306
  if (not table->in_use)
 
307
  {
 
308
    unused_tables.unlink(table);
 
309
  }
 
310
 
 
311
  delete table;
 
312
}
 
313
 
144
314
/* Free resources allocated by filesort() and read_record() */
145
315
 
146
316
void Table::free_io_cache()
147
317
{
148
318
  if (sort.io_cache)
149
319
  {
150
 
    sort.io_cache->close_cached_file();
151
 
    safe_delete(sort.io_cache);
 
320
    close_cached_file(sort.io_cache);
 
321
    delete sort.io_cache;
 
322
    sort.io_cache= 0;
152
323
  }
153
324
}
154
325
 
158
329
 
159
330
  @param session Thread context (may be NULL)
160
331
  @param tables List of tables to remove from the cache
161
 
  @param have_lock If table::Cache::singleton().mutex() is locked
 
332
  @param have_lock If LOCK_open is locked
162
333
  @param wait_for_refresh Wait for a impending flush
163
334
  @param wait_for_placeholders Wait for tables being reopened so that the GRL
164
335
  won't proceed while write-locked tables are being reopened by other
173
344
  bool result= false;
174
345
  Session *session= this;
175
346
 
176
 
  {
177
 
    boost::mutex::scoped_lock scopedLock(table::Cache::singleton().mutex()); /* Optionally lock for remove tables from open_cahe if not in use */
178
 
 
179
 
    if (tables == NULL)
180
 
    {
181
 
      refresh_version++;                                // Force close of open tables
182
 
 
183
 
      table::getUnused().clear();
184
 
 
185
 
      if (wait_for_refresh)
186
 
      {
 
347
  LOCK_open.lock(); /* Optionally lock for remove tables from open_cahe if not in use */
 
348
 
 
349
  if (tables == NULL)
 
350
  {
 
351
    refresh_version++;                          // Force close of open tables
 
352
 
 
353
    unused_tables.clear();
 
354
 
 
355
    if (wait_for_refresh)
 
356
    {
 
357
      /*
 
358
        Other threads could wait in a loop in open_and_lock_tables(),
 
359
        trying to lock one or more of our tables.
 
360
 
 
361
        If they wait for the locks in thr_multi_lock(), their lock
 
362
        request is aborted. They loop in open_and_lock_tables() and
 
363
        enter open_table(). Here they notice the table is refreshed and
 
364
        wait for COND_refresh. Then they loop again in
 
365
        openTablesLock() and this time open_table() succeeds. At
 
366
        this moment, if we (the FLUSH TABLES thread) are scheduled and
 
367
        on another FLUSH TABLES enter close_cached_tables(), they could
 
368
        awake while we sleep below, waiting for others threads (us) to
 
369
        close their open tables. If this happens, the other threads
 
370
        would find the tables unlocked. They would get the locks, one
 
371
        after the other, and could do their destructive work. This is an
 
372
        issue if we have LOCK TABLES in effect.
 
373
 
 
374
        The problem is that the other threads passed all checks in
 
375
        open_table() before we refresh the table.
 
376
 
 
377
        The fix for this problem is to set some_tables_deleted for all
 
378
        threads with open tables. These threads can still get their
 
379
        locks, but will immediately release them again after checking
 
380
        this variable. They will then loop in openTablesLock()
 
381
        again. There they will wait until we update all tables version
 
382
        below.
 
383
 
 
384
        Setting some_tables_deleted is done by remove_table_from_cache()
 
385
        in the other branch.
 
386
 
 
387
        In other words (reviewer suggestion): You need this setting of
 
388
        some_tables_deleted for the case when table was opened and all
 
389
        related checks were passed before incrementing refresh_version
 
390
        (which you already have) but attempt to lock the table happened
 
391
        after the call to Session::close_old_data_files() i.e. after removal of
 
392
        current thread locks.
 
393
      */
 
394
      for (TableOpenCache::const_iterator iter= get_open_cache().begin();
 
395
           iter != get_open_cache().end();
 
396
           iter++)
 
397
      {
 
398
        Table *table= (*iter).second;
 
399
        if (table->in_use)
 
400
          table->in_use->some_tables_deleted= false;
 
401
      }
 
402
    }
 
403
  }
 
404
  else
 
405
  {
 
406
    bool found= false;
 
407
    for (TableList *table= tables; table; table= table->next_local)
 
408
    {
 
409
      TableIdentifier identifier(table->db, table->table_name);
 
410
      if (remove_table_from_cache(session, identifier,
 
411
                                  RTFC_OWNED_BY_Session_FLAG))
 
412
      {
 
413
        found= true;
 
414
      }
 
415
    }
 
416
    if (!found)
 
417
      wait_for_refresh= false;                  // Nothing to wait for
 
418
  }
 
419
 
 
420
  if (wait_for_refresh)
 
421
  {
 
422
    /*
 
423
      If there is any table that has a lower refresh_version, wait until
 
424
      this is closed (or this thread is killed) before returning
 
425
    */
 
426
    session->mysys_var->current_mutex= LOCK_open.native_handle();
 
427
    session->mysys_var->current_cond= COND_refresh.native_handle();
 
428
    session->set_proc_info("Flushing tables");
 
429
 
 
430
    session->close_old_data_files();
 
431
 
 
432
    bool found= true;
 
433
    /* Wait until all threads has closed all the tables we had locked */
 
434
    while (found && ! session->killed)
 
435
    {
 
436
      found= false;
 
437
      for (TableOpenCache::const_iterator iter= get_open_cache().begin();
 
438
           iter != get_open_cache().end();
 
439
           iter++)
 
440
      {
 
441
        Table *table= (*iter).second;
 
442
        /* Avoid a self-deadlock. */
 
443
        if (table->in_use == session)
 
444
          continue;
187
445
        /*
188
 
          Other threads could wait in a loop in open_and_lock_tables(),
189
 
          trying to lock one or more of our tables.
190
 
 
191
 
          If they wait for the locks in thr_multi_lock(), their lock
192
 
          request is aborted. They loop in open_and_lock_tables() and
193
 
          enter open_table(). Here they notice the table is refreshed and
194
 
          wait for COND_refresh. Then they loop again in
195
 
          openTablesLock() and this time open_table() succeeds. At
196
 
          this moment, if we (the FLUSH TABLES thread) are scheduled and
197
 
          on another FLUSH TABLES enter close_cached_tables(), they could
198
 
          awake while we sleep below, waiting for others threads (us) to
199
 
          close their open tables. If this happens, the other threads
200
 
          would find the tables unlocked. They would get the locks, one
201
 
          after the other, and could do their destructive work. This is an
202
 
          issue if we have LOCK TABLES in effect.
203
 
 
204
 
          The problem is that the other threads passed all checks in
205
 
          open_table() before we refresh the table.
206
 
 
207
 
          The fix for this problem is to set some_tables_deleted for all
208
 
          threads with open tables. These threads can still get their
209
 
          locks, but will immediately release them again after checking
210
 
          this variable. They will then loop in openTablesLock()
211
 
          again. There they will wait until we update all tables version
212
 
          below.
213
 
 
214
 
          Setting some_tables_deleted is done by table::Cache::singleton().removeTable()
215
 
          in the other branch.
216
 
 
217
 
          In other words (reviewer suggestion): You need this setting of
218
 
          some_tables_deleted for the case when table was opened and all
219
 
          related checks were passed before incrementing refresh_version
220
 
          (which you already have) but attempt to lock the table happened
221
 
          after the call to Session::close_old_data_files() i.e. after removal of
222
 
          current thread locks.
 
446
          Note that we wait here only for tables which are actually open, and
 
447
          not for placeholders with Table::open_placeholder set. Waiting for
 
448
          latter will cause deadlock in the following scenario, for example:
 
449
 
 
450
          conn1-> lock table t1 write;
 
451
          conn2-> lock table t2 write;
 
452
          conn1-> flush tables;
 
453
          conn2-> flush tables;
 
454
 
 
455
          It also does not make sense to wait for those of placeholders that
 
456
          are employed by CREATE TABLE as in this case table simply does not
 
457
          exist yet.
223
458
        */
224
 
        for (table::CacheMap::const_iterator iter= table::getCache().begin();
225
 
             iter != table::getCache().end();
226
 
             iter++)
227
 
        {
228
 
          Table *table= (*iter).second;
229
 
          if (table->in_use)
230
 
            table->in_use->some_tables_deleted= false;
231
 
        }
232
 
      }
233
 
    }
234
 
    else
235
 
    {
236
 
      bool found= false;
237
 
      for (TableList *table= tables; table; table= table->next_local)
238
 
      {
239
 
        identifier::Table identifier(table->getSchemaName(), table->getTableName());
240
 
        if (table::Cache::singleton().removeTable(session, identifier,
241
 
                                    RTFC_OWNED_BY_Session_FLAG))
 
459
        if (table->needs_reopen_or_name_lock() && (table->db_stat ||
 
460
                                                   (table->open_placeholder && wait_for_placeholders)))
242
461
        {
243
462
          found= true;
 
463
          pthread_cond_wait(COND_refresh.native_handle(),LOCK_open.native_handle());
 
464
          break;
244
465
        }
245
466
      }
246
 
      if (!found)
247
 
        wait_for_refresh= false;                        // Nothing to wait for
248
467
    }
 
468
    /*
 
469
      No other thread has the locked tables open; reopen them and get the
 
470
      old locks. This should always succeed (unless some external process
 
471
      has removed the tables)
 
472
    */
 
473
    result= session->reopen_tables(true, true);
249
474
 
250
 
    if (wait_for_refresh)
 
475
    /* Set version for table */
 
476
    for (Table *table= session->open_tables; table ; table= table->getNext())
251
477
    {
252
478
      /*
253
 
        If there is any table that has a lower refresh_version, wait until
254
 
        this is closed (or this thread is killed) before returning
255
 
      */
256
 
      session->mysys_var->current_mutex= &table::Cache::singleton().mutex();
257
 
      session->mysys_var->current_cond= &COND_refresh;
258
 
      session->set_proc_info("Flushing tables");
259
 
 
260
 
      session->close_old_data_files();
261
 
 
262
 
      bool found= true;
263
 
      /* Wait until all threads has closed all the tables we had locked */
264
 
      while (found && ! session->getKilled())
265
 
      {
266
 
        found= false;
267
 
        for (table::CacheMap::const_iterator iter= table::getCache().begin();
268
 
             iter != table::getCache().end();
269
 
             iter++)
270
 
        {
271
 
          Table *table= (*iter).second;
272
 
          /* Avoid a self-deadlock. */
273
 
          if (table->in_use == session)
274
 
            continue;
275
 
          /*
276
 
            Note that we wait here only for tables which are actually open, and
277
 
            not for placeholders with Table::open_placeholder set. Waiting for
278
 
            latter will cause deadlock in the following scenario, for example:
279
 
 
280
 
            conn1-> lock table t1 write;
281
 
            conn2-> lock table t2 write;
282
 
            conn1-> flush tables;
283
 
            conn2-> flush tables;
284
 
 
285
 
            It also does not make sense to wait for those of placeholders that
286
 
            are employed by CREATE TABLE as in this case table simply does not
287
 
            exist yet.
288
 
          */
289
 
          if (table->needs_reopen_or_name_lock() && (table->db_stat ||
290
 
                                                     (table->open_placeholder && wait_for_placeholders)))
291
 
          {
292
 
            found= true;
293
 
            COND_refresh.wait(scopedLock);
294
 
            break;
295
 
          }
296
 
        }
297
 
      }
298
 
      /*
299
 
        No other thread has the locked tables open; reopen them and get the
300
 
        old locks. This should always succeed (unless some external process
301
 
        has removed the tables)
302
 
      */
303
 
      result= session->reopen_tables();
304
 
 
305
 
      /* Set version for table */
306
 
      for (Table *table= session->open_tables; table ; table= table->getNext())
307
 
      {
308
 
        /*
309
 
          Preserve the version (0) of write locked tables so that a impending
310
 
          global read lock won't sneak in.
311
 
        */
312
 
        if (table->reginfo.lock_type < TL_WRITE_ALLOW_WRITE)
313
 
          table->getMutableShare()->refreshVersion();
314
 
      }
 
479
        Preserve the version (0) of write locked tables so that a impending
 
480
        global read lock won't sneak in.
 
481
      */
 
482
      if (table->reginfo.lock_type < TL_WRITE_ALLOW_WRITE)
 
483
        table->getMutableShare()->refreshVersion();
315
484
    }
316
485
  }
317
486
 
 
487
  LOCK_open.unlock();
 
488
 
318
489
  if (wait_for_refresh)
319
490
  {
320
 
    boost_unique_lock_t scopedLock(session->mysys_var->mutex);
 
491
    pthread_mutex_lock(&session->mysys_var->mutex);
321
492
    session->mysys_var->current_mutex= 0;
322
493
    session->mysys_var->current_cond= 0;
323
494
    session->set_proc_info(0);
 
495
    pthread_mutex_unlock(&session->mysys_var->mutex);
324
496
  }
325
497
 
326
498
  return result;
331
503
  move one table to free list 
332
504
*/
333
505
 
334
 
bool Session::free_cached_table(boost::mutex::scoped_lock &scopedLock)
 
506
bool Session::free_cached_table()
335
507
{
336
508
  bool found_old_table= false;
337
 
 
338
 
  (void)scopedLock;
339
 
 
340
 
  table::Concurrent *table= static_cast<table::Concurrent *>(open_tables);
341
 
 
342
 
  safe_mutex_assert_owner(table::Cache::singleton().mutex().native_handle());
 
509
  Table *table= open_tables;
 
510
 
 
511
  safe_mutex_assert_owner(LOCK_open.native_handle());
343
512
  assert(table->key_read == 0);
344
513
  assert(!table->cursor || table->cursor->inited == Cursor::NONE);
345
514
 
348
517
  if (table->needs_reopen_or_name_lock() ||
349
518
      version != refresh_version || !table->db_stat)
350
519
  {
351
 
    table::remove_table(table);
 
520
    remove_table(table);
352
521
    found_old_table= true;
353
522
  }
354
523
  else
361
530
 
362
531
    /* Free memory and reset for next loop */
363
532
    table->cursor->ha_reset();
364
 
    table->in_use= NULL;
 
533
    table->in_use= false;
365
534
 
366
 
    table::getUnused().link(table);
 
535
    unused_tables.link(table);
367
536
  }
368
537
 
369
538
  return found_old_table;
382
551
{
383
552
  bool found_old_table= false;
384
553
 
385
 
  safe_mutex_assert_not_owner(table::Cache::singleton().mutex().native_handle());
 
554
  safe_mutex_assert_not_owner(LOCK_open.native_handle());
386
555
 
387
 
  boost_unique_lock_t scoped_lock(table::Cache::singleton().mutex()); /* Close all open tables on Session */
 
556
  boost::mutex::scoped_lock scoped_lock(LOCK_open); /* Close all open tables on Session */
388
557
 
389
558
  while (open_tables)
390
559
  {
391
 
    found_old_table|= free_cached_table(scoped_lock);
 
560
    found_old_table|= free_cached_table();
392
561
  }
393
562
  some_tables_deleted= false;
394
563
 
395
564
  if (found_old_table)
396
565
  {
397
566
    /* Tell threads waiting for refresh that something has happened */
398
 
    locking::broadcast_refresh();
 
567
    broadcast_refresh();
399
568
  }
400
569
}
401
570
 
424
593
{
425
594
  for (; table; table= table->*link )
426
595
  {
427
 
    if ((table->table == 0 || table->table->getShare()->getType() == message::Table::STANDARD) and
428
 
        my_strcasecmp(system_charset_info, table->getSchemaName(), db_name) == 0 and
429
 
        my_strcasecmp(system_charset_info, table->getTableName(), table_name) == 0)
430
 
    {
 
596
    if ((table->table == 0 || table->table->getShare()->getType() == message::Table::STANDARD) &&
 
597
        strcasecmp(table->db, db_name) == 0 &&
 
598
        strcasecmp(table->table_name, table_name) == 0)
431
599
      break;
432
 
    }
433
600
  }
434
601
  return table;
435
602
}
499
666
    */
500
667
    assert(table);
501
668
  }
502
 
  d_name= table->getSchemaName();
503
 
  t_name= table->getTableName();
 
669
  d_name= table->db;
 
670
  t_name= table->table_name;
504
671
  t_alias= table->alias;
505
672
 
506
673
  for (;;)
521
688
}
522
689
 
523
690
 
524
 
void Open_tables_state::doGetTableNames(const identifier::Schema &schema_identifier,
525
 
                                        std::set<std::string>& set_of_names)
 
691
void Session::doGetTableNames(const SchemaIdentifier &schema_identifier,
 
692
                              std::set<std::string>& set_of_names)
526
693
{
527
 
  for (Table *table= getTemporaryTables() ; table ; table= table->getNext())
 
694
  for (Table *table= temporary_tables ; table ; table= table->getNext())
528
695
  {
529
696
    if (schema_identifier.compare(table->getShare()->getSchemaName()))
530
697
    {
533
700
  }
534
701
}
535
702
 
536
 
void Open_tables_state::doGetTableNames(CachedDirectory &,
537
 
                                        const identifier::Schema &schema_identifier,
538
 
                                        std::set<std::string> &set_of_names)
 
703
void Session::doGetTableNames(CachedDirectory &,
 
704
                              const SchemaIdentifier &schema_identifier,
 
705
                              std::set<std::string> &set_of_names)
539
706
{
540
707
  doGetTableNames(schema_identifier, set_of_names);
541
708
}
542
709
 
543
 
void Open_tables_state::doGetTableIdentifiers(const identifier::Schema &schema_identifier,
544
 
                                              identifier::Table::vector &set_of_identifiers)
 
710
void Session::doGetTableIdentifiers(const SchemaIdentifier &schema_identifier,
 
711
                                    TableIdentifiers &set_of_identifiers)
545
712
{
546
 
  for (Table *table= getTemporaryTables() ; table ; table= table->getNext())
 
713
  for (Table *table= temporary_tables ; table ; table= table->getNext())
547
714
  {
548
715
    if (schema_identifier.compare(table->getShare()->getSchemaName()))
549
716
    {
550
 
      set_of_identifiers.push_back(identifier::Table(table->getShare()->getSchemaName(),
 
717
      set_of_identifiers.push_back(TableIdentifier(table->getShare()->getSchemaName(),
551
718
                                                   table->getShare()->getTableName(),
552
719
                                                   table->getShare()->getPath()));
553
720
    }
554
721
  }
555
722
}
556
723
 
557
 
void Open_tables_state::doGetTableIdentifiers(CachedDirectory &,
558
 
                                              const identifier::Schema &schema_identifier,
559
 
                                              identifier::Table::vector &set_of_identifiers)
 
724
void Session::doGetTableIdentifiers(CachedDirectory &,
 
725
                                    const SchemaIdentifier &schema_identifier,
 
726
                                    TableIdentifiers &set_of_identifiers)
560
727
{
561
728
  doGetTableIdentifiers(schema_identifier, set_of_identifiers);
562
729
}
563
730
 
564
 
bool Open_tables_state::doDoesTableExist(const identifier::Table &identifier)
 
731
bool Session::doDoesTableExist(const TableIdentifier &identifier)
565
732
{
566
 
  for (Table *table= getTemporaryTables() ; table ; table= table->getNext())
 
733
  for (Table *table= temporary_tables ; table ; table= table->getNext())
567
734
  {
568
735
    if (table->getShare()->getType() == message::Table::TEMPORARY)
569
736
    {
577
744
  return false;
578
745
}
579
746
 
580
 
int Open_tables_state::doGetTableDefinition(const identifier::Table &identifier,
581
 
                                            message::Table &table_proto)
 
747
int Session::doGetTableDefinition(const TableIdentifier &identifier,
 
748
                                  message::Table &table_proto)
582
749
{
583
 
  for (Table *table= getTemporaryTables() ; table ; table= table->getNext())
 
750
  for (Table *table= temporary_tables ; table ; table= table->getNext())
584
751
  {
585
752
    if (table->getShare()->getType() == message::Table::TEMPORARY)
586
753
    {
587
754
      if (identifier.getKey() == table->getShare()->getCacheKey())
588
755
      {
589
 
        table_proto.CopyFrom(*(table->getShare()->getTableMessage()));
 
756
        table_proto.CopyFrom(*(table->getShare()->getTableProto()));
590
757
 
591
758
        return EEXIST;
592
759
      }
596
763
  return ENOENT;
597
764
}
598
765
 
599
 
Table *Open_tables_state::find_temporary_table(const identifier::Table &identifier)
 
766
Table *Session::find_temporary_table(const char *new_db, const char *table_name)
 
767
{
 
768
  char  key[MAX_DBKEY_LENGTH];
 
769
  uint  key_length;
 
770
 
 
771
  key_length= TableIdentifier::createKey(key, new_db, table_name);
 
772
 
 
773
  for (Table *table= temporary_tables ; table ; table= table->getNext())
 
774
  {
 
775
    const TableIdentifier::Key &share_key(table->getShare()->getCacheKey());
 
776
    if (share_key.size() == key_length &&
 
777
        not memcmp(&share_key[0], key, key_length))
 
778
    {
 
779
      return table;
 
780
    }
 
781
  }
 
782
  return NULL;                               // Not a temporary table
 
783
}
 
784
 
 
785
Table *Session::find_temporary_table(TableList *table_list)
 
786
{
 
787
  return find_temporary_table(table_list->db, table_list->table_name);
 
788
}
 
789
 
 
790
Table *Session::find_temporary_table(TableIdentifier &identifier)
600
791
{
601
792
  for (Table *table= temporary_tables ; table ; table= table->getNext())
602
793
  {
634
825
  @retval -1  the table is in use by a outer query
635
826
*/
636
827
 
637
 
int Open_tables_state::drop_temporary_table(const drizzled::identifier::Table &identifier)
 
828
int Session::drop_temporary_table(TableList *table_list)
638
829
{
639
830
  Table *table;
640
831
 
641
 
  if (not (table= find_temporary_table(identifier)))
 
832
  if (not (table= find_temporary_table(table_list)))
642
833
    return 1;
643
834
 
644
835
  /* Table might be in use by some outer statement. */
645
 
  if (table->query_id && table->query_id != getQueryId())
 
836
  if (table->query_id && table->query_id != query_id)
646
837
  {
647
838
    my_error(ER_CANT_REOPEN_TABLE, MYF(0), table->getAlias());
648
839
    return -1;
660
851
 
661
852
  @param  session     Thread context
662
853
  @param  find    Table to remove
663
 
 
664
 
  @note because we risk the chance of deleting the share, we can't assume that it will exist past, this should be modified once we can use a TableShare::shared_ptr here.
665
854
*/
666
855
 
667
856
void Session::unlink_open_table(Table *find)
668
857
{
669
 
  const identifier::Table::Key find_key(find->getShare()->getCacheKey());
670
 
  Table **prev;
671
 
  safe_mutex_assert_owner(table::Cache::singleton().mutex().native_handle());
 
858
  char key[MAX_DBKEY_LENGTH];
 
859
  uint32_t key_length= find->getShare()->getCacheKeySize();
 
860
  Table *list, **prev;
 
861
  safe_mutex_assert_owner(LOCK_open.native_handle());
672
862
 
 
863
  memcpy(key, &find->getMutableShare()->getCacheKey()[0], key_length);
673
864
  /*
674
 
    Note that we need to hold table::Cache::singleton().mutex() while changing the
 
865
    Note that we need to hold LOCK_open while changing the
675
866
    open_tables list. Another thread may work on it.
676
 
    (See: table::Cache::singleton().removeTable(), wait_completed_table())
 
867
    (See: remove_table_from_cache(), mysql_wait_completed_table())
677
868
    Closing a MERGE child before the parent would be fatal if the
678
869
    other thread tries to abort the MERGE lock in between.
679
870
  */
680
871
  for (prev= &open_tables; *prev; )
681
872
  {
682
 
    Table *list= *prev;
 
873
    list= *prev;
683
874
 
684
 
    if (list->getShare()->getCacheKey() == find_key)
 
875
    if (list->getShare()->getCacheKeySize() == key_length &&
 
876
        not memcmp(&list->getShare()->getCacheKey()[0], key, key_length))
685
877
    {
686
878
      /* Remove table from open_tables list. */
687
879
      *prev= list->getNext();
688
880
 
689
881
      /* Close table. */
690
 
      table::remove_table(static_cast<table::Concurrent *>(list));
 
882
      remove_table(list);
691
883
    }
692
884
    else
693
885
    {
697
889
  }
698
890
 
699
891
  // Notify any 'refresh' threads
700
 
  locking::broadcast_refresh();
 
892
  broadcast_refresh();
701
893
}
702
894
 
703
895
 
720
912
  table that was locked with LOCK TABLES.
721
913
*/
722
914
 
723
 
void Session::drop_open_table(Table *table, const identifier::Table &identifier)
 
915
void Session::drop_open_table(Table *table, TableIdentifier &identifier)
724
916
{
725
917
  if (table->getShare()->getType())
726
918
  {
728
920
  }
729
921
  else
730
922
  {
731
 
    boost_unique_lock_t scoped_lock(table::Cache::singleton().mutex()); /* Close and drop a table (AUX routine) */
 
923
    boost::mutex::scoped_lock scoped_lock(LOCK_open); /* Close and drop a table (AUX routine) */
732
924
    /*
733
925
      unlink_open_table() also tells threads waiting for refresh or close
734
926
      that something has happened.
735
927
    */
736
928
    unlink_open_table(table);
737
 
    (void)plugin::StorageEngine::dropTable(*this, identifier);
 
929
    quick_rm_table(*this, identifier);
738
930
  }
739
931
}
740
932
 
750
942
  cond  Condition to wait for
751
943
*/
752
944
 
753
 
void Session::wait_for_condition(boost::mutex &mutex, boost::condition_variable_any &cond)
 
945
void Session::wait_for_condition(boost::mutex &mutex, boost::condition_variable &cond)
754
946
{
755
947
  /* Wait until the current table is up to date */
756
948
  const char *saved_proc_info;
757
 
  mysys_var->current_mutex= &mutex;
758
 
  mysys_var->current_cond= &cond;
 
949
  mysys_var->current_mutex= mutex.native_handle();
 
950
  mysys_var->current_cond= cond.native_handle();
759
951
  saved_proc_info= get_proc_info();
760
952
  set_proc_info("Waiting for table");
761
 
  {
762
 
    /*
763
 
      We must unlock mutex first to avoid deadlock becasue conditions are
764
 
      sent to this thread by doing locks in the following order:
765
 
      lock(mysys_var->mutex)
766
 
      lock(mysys_var->current_mutex)
767
 
 
768
 
      One by effect of this that one can only use wait_for_condition with
769
 
      condition variables that are guranteed to not disapper (freed) even if this
770
 
      mutex is unlocked
771
 
    */
772
 
    boost_unique_lock_t scopedLock(mutex, boost::adopt_lock_t());
773
 
    if (not getKilled())
774
 
    {
775
 
      cond.wait(scopedLock);
776
 
    }
777
 
  }
778
 
  boost_unique_lock_t mysys_scopedLock(mysys_var->mutex);
 
953
  if (!killed)
 
954
    (void) pthread_cond_wait(cond.native_handle(), mutex.native_handle());
 
955
 
 
956
  /*
 
957
    We must unlock mutex first to avoid deadlock becasue conditions are
 
958
    sent to this thread by doing locks in the following order:
 
959
    lock(mysys_var->mutex)
 
960
    lock(mysys_var->current_mutex)
 
961
 
 
962
    One by effect of this that one can only use wait_for_condition with
 
963
    condition variables that are guranteed to not disapper (freed) even if this
 
964
    mutex is unlocked
 
965
  */
 
966
 
 
967
  pthread_mutex_unlock(mutex.native_handle());
 
968
  pthread_mutex_lock(&mysys_var->mutex);
779
969
  mysys_var->current_mutex= 0;
780
970
  mysys_var->current_cond= 0;
781
971
  set_proc_info(saved_proc_info);
 
972
  pthread_mutex_unlock(&mysys_var->mutex);
 
973
}
 
974
 
 
975
 
 
976
/*
 
977
  Open table which is already name-locked by this thread.
 
978
 
 
979
  SYNOPSIS
 
980
  reopen_name_locked_table()
 
981
  session         Thread handle
 
982
  table_list  TableList object for table to be open, TableList::table
 
983
  member should point to Table object which was used for
 
984
  name-locking.
 
985
  link_in     true  - if Table object for table to be opened should be
 
986
  linked into Session::open_tables list.
 
987
  false - placeholder used for name-locking is already in
 
988
  this list so we only need to preserve Table::next
 
989
  pointer.
 
990
 
 
991
  NOTE
 
992
  This function assumes that its caller already acquired LOCK_open mutex.
 
993
 
 
994
  RETURN VALUE
 
995
  false - Success
 
996
  true  - Error
 
997
*/
 
998
 
 
999
bool Session::reopen_name_locked_table(TableList* table_list, bool link_in)
 
1000
{
 
1001
  Table *table= table_list->table;
 
1002
  TableShare *share;
 
1003
  char *table_name= table_list->table_name;
 
1004
  Table orig_table;
 
1005
 
 
1006
  safe_mutex_assert_owner(LOCK_open.native_handle());
 
1007
 
 
1008
  if (killed || !table)
 
1009
    return true;
 
1010
 
 
1011
  orig_table= *table;
 
1012
 
 
1013
  TableIdentifier identifier(table_list->db, table_list->table_name);
 
1014
  if (open_unireg_entry(this, table, table_name, identifier))
 
1015
  {
 
1016
    table->intern_close_table();
 
1017
    /*
 
1018
      If there was an error during opening of table (for example if it
 
1019
      does not exist) '*table' object can be wiped out. To be able
 
1020
      properly release name-lock in this case we should restore this
 
1021
      object to its original state.
 
1022
    */
 
1023
    *table= orig_table;
 
1024
    return true;
 
1025
  }
 
1026
 
 
1027
  share= table->getMutableShare();
 
1028
  /*
 
1029
    We want to prevent other connections from opening this table until end
 
1030
    of statement as it is likely that modifications of table's metadata are
 
1031
    not yet finished (for example CREATE TRIGGER have to change .TRG cursor,
 
1032
    or we might want to drop table if CREATE TABLE ... SELECT fails).
 
1033
    This also allows us to assume that no other connection will sneak in
 
1034
    before we will get table-level lock on this table.
 
1035
  */
 
1036
  share->resetVersion();
 
1037
  table->in_use = this;
 
1038
 
 
1039
  if (link_in)
 
1040
  {
 
1041
    table->setNext(open_tables);
 
1042
    open_tables= table;
 
1043
  }
 
1044
  else
 
1045
  {
 
1046
    /*
 
1047
      Table object should be already in Session::open_tables list so we just
 
1048
      need to set Table::next correctly.
 
1049
    */
 
1050
    table->setNext(orig_table.getNext());
 
1051
  }
 
1052
 
 
1053
  table->tablenr= current_tablenr++;
 
1054
  table->used_fields= 0;
 
1055
  table->const_table= 0;
 
1056
  table->null_row= false;
 
1057
  table->maybe_null= false;
 
1058
  table->force_index= false;
 
1059
  table->status= STATUS_NO_RECORD;
 
1060
 
 
1061
  return false;
782
1062
}
783
1063
 
784
1064
 
795
1075
  case of failure.
796
1076
*/
797
1077
 
798
 
table::Placeholder *Session::table_cache_insert_placeholder(const drizzled::identifier::Table &arg)
 
1078
Table *Session::table_cache_insert_placeholder(const char *db_name, const char *table_name)
799
1079
{
800
 
  safe_mutex_assert_owner(table::Cache::singleton().mutex().native_handle());
 
1080
  safe_mutex_assert_owner(LOCK_open.native_handle());
801
1081
 
802
1082
  /*
803
1083
    Create a table entry with the right key and with an old refresh version
 
1084
    Note that we must use multi_malloc() here as this is freed by the
 
1085
    table cache
804
1086
  */
805
 
  identifier::Table identifier(arg.getSchemaName(), arg.getTableName(), message::Table::INTERNAL);
806
 
  table::Placeholder *table= new table::Placeholder(this, identifier);
 
1087
  TableIdentifier identifier(db_name, table_name, message::Table::INTERNAL);
 
1088
  TablePlaceholder *table= new TablePlaceholder(this, identifier);
807
1089
 
808
 
  if (not table::Cache::singleton().insert(table))
 
1090
  if (not add_table(table))
809
1091
  {
810
 
    safe_delete(table);
 
1092
    delete table;
811
1093
 
812
1094
    return NULL;
813
1095
  }
837
1119
  @retval  true   Error occured (OOM)
838
1120
  @retval  false  Success. 'table' parameter set according to above rules.
839
1121
*/
840
 
bool Session::lock_table_name_if_not_cached(const identifier::Table &identifier, Table **table)
 
1122
bool Session::lock_table_name_if_not_cached(TableIdentifier &identifier, Table **table)
841
1123
{
842
 
  const identifier::Table::Key &key(identifier.getKey());
843
 
 
844
 
  boost_unique_lock_t scope_lock(table::Cache::singleton().mutex()); /* Obtain a name lock even though table is not in cache (like for create table)  */
845
 
 
846
 
  table::CacheMap::iterator iter;
847
 
 
848
 
  iter= table::getCache().find(key);
849
 
 
850
 
  if (iter != table::getCache().end())
 
1124
  const TableIdentifier::Key &key(identifier.getKey());
 
1125
 
 
1126
  boost::mutex::scoped_lock scope_lock(LOCK_open); /* Obtain a name lock even though table is not in cache (like for create table)  */
 
1127
 
 
1128
  TableOpenCache::iterator iter;
 
1129
 
 
1130
  iter= get_open_cache().find(key);
 
1131
 
 
1132
  if (iter != get_open_cache().end())
851
1133
  {
852
1134
    *table= 0;
853
1135
    return false;
854
1136
  }
855
1137
 
856
 
  if (not (*table= table_cache_insert_placeholder(identifier)))
 
1138
  if (not (*table= table_cache_insert_placeholder(identifier.getSchemaName().c_str(), identifier.getTableName().c_str())))
857
1139
  {
858
1140
    return true;
859
1141
  }
913
1195
  if (check_stack_overrun(this, STACK_MIN_SIZE_FOR_OPEN, (unsigned char *)&alias))
914
1196
    return NULL;
915
1197
 
916
 
  if (getKilled())
 
1198
  if (killed)
917
1199
    return NULL;
918
1200
 
919
 
  identifier::Table identifier(table_list->getSchemaName(), table_list->getTableName());
920
 
  const identifier::Table::Key &key(identifier.getKey());
921
 
  table::CacheRange ppp;
 
1201
  TableIdentifier identifier(table_list->db, table_list->table_name);
 
1202
  const TableIdentifier::Key &key(identifier.getKey());
 
1203
  TableOpenCacheRange ppp;
922
1204
 
923
1205
  /*
924
1206
    Unless requested otherwise, try to resolve this table in the list
927
1209
    same name. This block implements the behaviour.
928
1210
    TODO -> move this block into a separate function.
929
1211
  */
930
 
  bool reset= false;
931
 
  for (table= getTemporaryTables(); table ; table=table->getNext())
 
1212
  for (table= temporary_tables; table ; table=table->getNext())
932
1213
  {
933
1214
    if (table->getShare()->getCacheKey() == key)
934
1215
    {
944
1225
        return NULL;
945
1226
      }
946
1227
      table->query_id= getQueryId();
947
 
      reset= true;
 
1228
      goto reset;
 
1229
    }
 
1230
  }
 
1231
 
 
1232
  if (flags & DRIZZLE_OPEN_TEMPORARY_ONLY)
 
1233
  {
 
1234
    my_error(ER_NO_SUCH_TABLE, MYF(0), table_list->db, table_list->table_name);
 
1235
    return NULL;
 
1236
  }
 
1237
 
 
1238
  /*
 
1239
    If it's the first table from a list of tables used in a query,
 
1240
    remember refresh_version (the version of open_cache state).
 
1241
    If the version changes while we're opening the remaining tables,
 
1242
    we will have to back off, close all the tables opened-so-far,
 
1243
    and try to reopen them.
 
1244
 
 
1245
    Note-> refresh_version is currently changed only during FLUSH TABLES.
 
1246
  */
 
1247
  if (!open_tables)
 
1248
  {
 
1249
    version= refresh_version;
 
1250
  }
 
1251
  else if ((version != refresh_version) &&
 
1252
           ! (flags & DRIZZLE_LOCK_IGNORE_FLUSH))
 
1253
  {
 
1254
    /* Someone did a refresh while thread was opening tables */
 
1255
    if (refresh)
 
1256
      *refresh= true;
 
1257
 
 
1258
    return NULL;
 
1259
  }
 
1260
 
 
1261
  /*
 
1262
    Before we test the global cache, we test our local session cache.
 
1263
  */
 
1264
  if (cached_table)
 
1265
  {
 
1266
    assert(false); /* Not implemented yet */
 
1267
  }
 
1268
 
 
1269
  /*
 
1270
    Non pre-locked/LOCK TABLES mode, and the table is not temporary:
 
1271
    this is the normal use case.
 
1272
    Now we should:
 
1273
    - try to find the table in the table cache.
 
1274
    - if one of the discovered Table instances is name-locked
 
1275
    (table->getShare()->version == 0) back off -- we have to wait
 
1276
    until no one holds a name lock on the table.
 
1277
    - if there is no such Table in the name cache, read the table definition
 
1278
    and insert it into the cache.
 
1279
    We perform all of the above under LOCK_open which currently protects
 
1280
    the open cache (also known as table cache) and table definitions stored
 
1281
    on disk.
 
1282
  */
 
1283
 
 
1284
  LOCK_open.lock(); /* Lock for FLUSH TABLES for open table */
 
1285
 
 
1286
  /*
 
1287
    Actually try to find the table in the open_cache.
 
1288
    The cache may contain several "Table" instances for the same
 
1289
    physical table. The instances that are currently "in use" by
 
1290
    some thread have their "in_use" member != NULL.
 
1291
    There is no good reason for having more than one entry in the
 
1292
    hash for the same physical table, except that we use this as
 
1293
    an implicit "pending locks queue" - see
 
1294
    wait_for_locked_table_names for details.
 
1295
  */
 
1296
  ppp= get_open_cache().equal_range(key);
 
1297
 
 
1298
  table= NULL;
 
1299
  for (TableOpenCache::const_iterator iter= ppp.first;
 
1300
       iter != ppp.second; ++iter, table= NULL)
 
1301
  {
 
1302
    table= (*iter).second;
 
1303
 
 
1304
    if (not table->in_use)
948
1305
      break;
949
 
    }
950
 
  }
951
 
 
952
 
  if (not reset)
953
 
  {
954
 
    if (flags & DRIZZLE_OPEN_TEMPORARY_ONLY)
955
 
    {
956
 
      my_error(ER_TABLE_UNKNOWN, identifier);
957
 
      return NULL;
958
 
    }
959
 
 
960
1306
    /*
961
 
      If it's the first table from a list of tables used in a query,
962
 
      remember refresh_version (the version of open_cache state).
963
 
      If the version changes while we're opening the remaining tables,
964
 
      we will have to back off, close all the tables opened-so-far,
965
 
      and try to reopen them.
966
 
 
967
 
      Note-> refresh_version is currently changed only during FLUSH TABLES.
 
1307
      Here we flush tables marked for flush.
 
1308
      Normally, table->getShare()->version contains the value of
 
1309
      refresh_version from the moment when this table was
 
1310
      (re-)opened and added to the cache.
 
1311
      If since then we did (or just started) FLUSH TABLES
 
1312
      statement, refresh_version has been increased.
 
1313
      For "name-locked" Table instances, table->getShare()->version is set
 
1314
      to 0 (see lock_table_name for details).
 
1315
      In case there is a pending FLUSH TABLES or a name lock, we
 
1316
      need to back off and re-start opening tables.
 
1317
      If we do not back off now, we may dead lock in case of lock
 
1318
      order mismatch with some other thread:
 
1319
      c1-> name lock t1; -- sort of exclusive lock
 
1320
      c2-> open t2;      -- sort of shared lock
 
1321
      c1-> name lock t2; -- blocks
 
1322
      c2-> open t1; -- blocks
968
1323
    */
969
 
    if (!open_tables)
970
 
    {
971
 
      version= refresh_version;
972
 
    }
973
 
    else if ((version != refresh_version) &&
974
 
             ! (flags & DRIZZLE_LOCK_IGNORE_FLUSH))
975
 
    {
976
 
      /* Someone did a refresh while thread was opening tables */
 
1324
    if (table->needs_reopen_or_name_lock())
 
1325
    {
 
1326
      if (flags & DRIZZLE_LOCK_IGNORE_FLUSH)
 
1327
      {
 
1328
        /* Force close at once after usage */
 
1329
        version= table->getShare()->getVersion();
 
1330
        continue;
 
1331
      }
 
1332
 
 
1333
      /* Avoid self-deadlocks by detecting self-dependencies. */
 
1334
      if (table->open_placeholder && table->in_use == this)
 
1335
      {
 
1336
        LOCK_open.unlock();
 
1337
        my_error(ER_UPDATE_TABLE_USED, MYF(0), table->getMutableShare()->getTableName());
 
1338
        return NULL;
 
1339
      }
 
1340
 
 
1341
      /*
 
1342
        Back off, part 1: mark the table as "unused" for the
 
1343
        purpose of name-locking by setting table->db_stat to 0. Do
 
1344
        that only for the tables in this thread that have an old
 
1345
        table->getShare()->version (this is an optimization (?)).
 
1346
        table->db_stat == 0 signals wait_for_locked_table_names
 
1347
        that the tables in question are not used any more. See
 
1348
        table_is_used call for details.
 
1349
      */
 
1350
      close_old_data_files(false, false);
 
1351
 
 
1352
      /*
 
1353
        Back-off part 2: try to avoid "busy waiting" on the table:
 
1354
        if the table is in use by some other thread, we suspend
 
1355
        and wait till the operation is complete: when any
 
1356
        operation that juggles with table->getShare()->version completes,
 
1357
        it broadcasts COND_refresh condition variable.
 
1358
        If 'old' table we met is in use by current thread we return
 
1359
        without waiting since in this situation it's this thread
 
1360
        which is responsible for broadcasting on COND_refresh
 
1361
        (and this was done already in Session::close_old_data_files()).
 
1362
        Good example of such situation is when we have statement
 
1363
        that needs two instances of table and FLUSH TABLES comes
 
1364
        after we open first instance but before we open second
 
1365
        instance.
 
1366
      */
 
1367
      if (table->in_use != this)
 
1368
      {
 
1369
        /* wait_for_conditionwill unlock LOCK_open for us */
 
1370
        wait_for_condition(LOCK_open, COND_refresh);
 
1371
      }
 
1372
      else
 
1373
      {
 
1374
        LOCK_open.unlock();
 
1375
      }
 
1376
      /*
 
1377
        There is a refresh in progress for this table.
 
1378
        Signal the caller that it has to try again.
 
1379
      */
977
1380
      if (refresh)
978
1381
        *refresh= true;
979
 
 
980
1382
      return NULL;
981
1383
    }
982
 
 
983
 
    /*
984
 
      Before we test the global cache, we test our local session cache.
985
 
    */
986
 
    if (cached_table)
987
 
    {
988
 
      assert(false); /* Not implemented yet */
989
 
    }
990
 
 
991
 
    /*
992
 
      Non pre-locked/LOCK TABLES mode, and the table is not temporary:
993
 
      this is the normal use case.
994
 
      Now we should:
995
 
      - try to find the table in the table cache.
996
 
      - if one of the discovered Table instances is name-locked
997
 
      (table->getShare()->version == 0) back off -- we have to wait
998
 
      until no one holds a name lock on the table.
999
 
      - if there is no such Table in the name cache, read the table definition
1000
 
      and insert it into the cache.
1001
 
      We perform all of the above under table::Cache::singleton().mutex() which currently protects
1002
 
      the open cache (also known as table cache) and table definitions stored
1003
 
      on disk.
1004
 
    */
1005
 
 
1006
 
    {
1007
 
      boost::mutex::scoped_lock scopedLock(table::Cache::singleton().mutex());
1008
 
 
1009
 
      /*
1010
 
        Actually try to find the table in the open_cache.
1011
 
        The cache may contain several "Table" instances for the same
1012
 
        physical table. The instances that are currently "in use" by
1013
 
        some thread have their "in_use" member != NULL.
1014
 
        There is no good reason for having more than one entry in the
1015
 
        hash for the same physical table, except that we use this as
1016
 
        an implicit "pending locks queue" - see
1017
 
        wait_for_locked_table_names for details.
1018
 
      */
1019
 
      ppp= table::getCache().equal_range(key);
1020
 
 
1021
 
      table= NULL;
1022
 
      for (table::CacheMap::const_iterator iter= ppp.first;
1023
 
           iter != ppp.second; ++iter, table= NULL)
 
1384
  }
 
1385
  if (table)
 
1386
  {
 
1387
    unused_tables.unlink(table);
 
1388
    table->in_use= this;
 
1389
  }
 
1390
  else
 
1391
  {
 
1392
    /* Insert a new Table instance into the open cache */
 
1393
    int error;
 
1394
    /* Free cache if too big */
 
1395
    unused_tables.cull();
 
1396
 
 
1397
    if (table_list->isCreate())
 
1398
    {
 
1399
      TableIdentifier  lock_table_identifier(table_list->db, table_list->table_name, message::Table::STANDARD);
 
1400
 
 
1401
      if (not plugin::StorageEngine::doesTableExist(*this, lock_table_identifier))
1024
1402
      {
1025
 
        table= (*iter).second;
1026
 
 
1027
 
        if (not table->in_use)
1028
 
          break;
1029
1403
        /*
1030
 
          Here we flush tables marked for flush.
1031
 
          Normally, table->getShare()->version contains the value of
1032
 
          refresh_version from the moment when this table was
1033
 
          (re-)opened and added to the cache.
1034
 
          If since then we did (or just started) FLUSH TABLES
1035
 
          statement, refresh_version has been increased.
1036
 
          For "name-locked" Table instances, table->getShare()->version is set
1037
 
          to 0 (see lock_table_name for details).
1038
 
          In case there is a pending FLUSH TABLES or a name lock, we
1039
 
          need to back off and re-start opening tables.
1040
 
          If we do not back off now, we may dead lock in case of lock
1041
 
          order mismatch with some other thread:
1042
 
          c1-> name lock t1; -- sort of exclusive lock
1043
 
          c2-> open t2;      -- sort of shared lock
1044
 
          c1-> name lock t2; -- blocks
1045
 
          c2-> open t1; -- blocks
 
1404
          Table to be created, so we need to create placeholder in table-cache.
1046
1405
        */
1047
 
        if (table->needs_reopen_or_name_lock())
 
1406
        if (!(table= table_cache_insert_placeholder(table_list->db, table_list->table_name)))
1048
1407
        {
1049
 
          if (flags & DRIZZLE_LOCK_IGNORE_FLUSH)
1050
 
          {
1051
 
            /* Force close at once after usage */
1052
 
            version= table->getShare()->getVersion();
1053
 
            continue;
1054
 
          }
1055
 
 
1056
 
          /* Avoid self-deadlocks by detecting self-dependencies. */
1057
 
          if (table->open_placeholder && table->in_use == this)
1058
 
          {
1059
 
            my_error(ER_UPDATE_TABLE_USED, MYF(0), table->getShare()->getTableName());
1060
 
            return NULL;
1061
 
          }
1062
 
 
1063
 
          /*
1064
 
            Back off, part 1: mark the table as "unused" for the
1065
 
            purpose of name-locking by setting table->db_stat to 0. Do
1066
 
            that only for the tables in this thread that have an old
1067
 
            table->getShare()->version (this is an optimization (?)).
1068
 
            table->db_stat == 0 signals wait_for_locked_table_names
1069
 
            that the tables in question are not used any more. See
1070
 
            table_is_used call for details.
1071
 
          */
1072
 
          close_old_data_files(false, false);
1073
 
 
1074
 
          /*
1075
 
            Back-off part 2: try to avoid "busy waiting" on the table:
1076
 
            if the table is in use by some other thread, we suspend
1077
 
            and wait till the operation is complete: when any
1078
 
            operation that juggles with table->getShare()->version completes,
1079
 
            it broadcasts COND_refresh condition variable.
1080
 
            If 'old' table we met is in use by current thread we return
1081
 
            without waiting since in this situation it's this thread
1082
 
            which is responsible for broadcasting on COND_refresh
1083
 
            (and this was done already in Session::close_old_data_files()).
1084
 
            Good example of such situation is when we have statement
1085
 
            that needs two instances of table and FLUSH TABLES comes
1086
 
            after we open first instance but before we open second
1087
 
            instance.
1088
 
          */
1089
 
          if (table->in_use != this)
1090
 
          {
1091
 
            /* wait_for_conditionwill unlock table::Cache::singleton().mutex() for us */
1092
 
            wait_for_condition(table::Cache::singleton().mutex(), COND_refresh);
1093
 
            scopedLock.release();
1094
 
          }
1095
 
          else
1096
 
          {
1097
 
            scopedLock.unlock();
1098
 
          }
1099
 
 
1100
 
          /*
1101
 
            There is a refresh in progress for this table.
1102
 
            Signal the caller that it has to try again.
1103
 
          */
1104
 
          if (refresh)
1105
 
            *refresh= true;
1106
 
 
 
1408
          LOCK_open.unlock();
1107
1409
          return NULL;
1108
1410
        }
1109
 
      }
1110
 
 
1111
 
      if (table)
1112
 
      {
1113
 
        table::getUnused().unlink(static_cast<table::Concurrent *>(table));
1114
 
        table->in_use= this;
1115
 
      }
1116
 
      else
1117
 
      {
1118
 
        /* Insert a new Table instance into the open cache */
1119
 
        int error;
1120
 
        /* Free cache if too big */
1121
 
        table::getUnused().cull();
1122
 
 
1123
 
        if (table_list->isCreate())
1124
 
        {
1125
 
          identifier::Table  lock_table_identifier(table_list->getSchemaName(), table_list->getTableName(), message::Table::STANDARD);
1126
 
 
1127
 
          if (not plugin::StorageEngine::doesTableExist(*this, lock_table_identifier))
1128
 
          {
1129
 
            /*
1130
 
              Table to be created, so we need to create placeholder in table-cache.
1131
 
            */
1132
 
            if (!(table= table_cache_insert_placeholder(lock_table_identifier)))
1133
 
            {
1134
 
              return NULL;
1135
 
            }
1136
 
            /*
1137
 
              Link placeholder to the open tables list so it will be automatically
1138
 
              removed once tables are closed. Also mark it so it won't be ignored
1139
 
              by other trying to take name-lock.
1140
 
            */
1141
 
            table->open_placeholder= true;
1142
 
            table->setNext(open_tables);
1143
 
            open_tables= table;
1144
 
 
1145
 
            return table ;
1146
 
          }
1147
 
          /* Table exists. Let us try to open it. */
1148
 
        }
1149
 
 
1150
 
        /* make a new table */
1151
 
        {
1152
 
          table::Concurrent *new_table= new table::Concurrent;
1153
 
          table= new_table;
1154
 
          if (new_table == NULL)
1155
 
          {
1156
 
            return NULL;
1157
 
          }
1158
 
 
1159
 
          error= new_table->open_unireg_entry(this, alias, identifier);
1160
 
          if (error != 0)
1161
 
          {
1162
 
            delete new_table;
1163
 
            return NULL;
1164
 
          }
1165
 
          (void)table::Cache::singleton().insert(new_table);
1166
 
        }
1167
 
      }
1168
 
    }
1169
 
 
1170
 
    if (refresh)
1171
 
    {
1172
 
      table->setNext(open_tables); /* Link into simple list */
1173
 
      open_tables= table;
1174
 
    }
1175
 
    table->reginfo.lock_type= TL_READ; /* Assume read */
1176
 
 
1177
 
  }
 
1411
        /*
 
1412
          Link placeholder to the open tables list so it will be automatically
 
1413
          removed once tables are closed. Also mark it so it won't be ignored
 
1414
          by other trying to take name-lock.
 
1415
        */
 
1416
        table->open_placeholder= true;
 
1417
        table->setNext(open_tables);
 
1418
        open_tables= table;
 
1419
        LOCK_open.unlock();
 
1420
 
 
1421
        return table ;
 
1422
      }
 
1423
      /* Table exists. Let us try to open it. */
 
1424
    }
 
1425
 
 
1426
    /* make a new table */
 
1427
    table= new Table;
 
1428
    if (table == NULL)
 
1429
    {
 
1430
      LOCK_open.unlock();
 
1431
      return NULL;
 
1432
    }
 
1433
 
 
1434
    error= open_unireg_entry(this, table, alias, identifier);
 
1435
    if (error != 0)
 
1436
    {
 
1437
      delete table;
 
1438
      LOCK_open.unlock();
 
1439
      return NULL;
 
1440
    }
 
1441
    (void)add_table(table);
 
1442
  }
 
1443
 
 
1444
  LOCK_open.unlock();
 
1445
  if (refresh)
 
1446
  {
 
1447
    table->setNext(open_tables); /* Link into simple list */
 
1448
    open_tables= table;
 
1449
  }
 
1450
  table->reginfo.lock_type= TL_READ; /* Assume read */
 
1451
 
 
1452
reset:
1178
1453
  assert(table->getShare()->getTableCount() > 0 || table->getShare()->getType() != message::Table::STANDARD);
1179
1454
 
 
1455
  if (lex->need_correct_ident())
 
1456
    table->alias_name_used= my_strcasecmp(table_alias_charset,
 
1457
                                          table->getMutableShare()->getTableName(), alias);
1180
1458
  /* Fix alias if table name changes */
1181
1459
  if (strcmp(table->getAlias(), alias))
1182
1460
  {
1183
 
    table->setAlias(alias);
 
1461
    uint32_t length=(uint32_t) strlen(alias)+1;
 
1462
    table->alias= (char*) realloc((char*) table->alias, length);
 
1463
    memcpy((void*) table->alias, alias, length);
1184
1464
  }
1185
1465
 
1186
1466
  /* These variables are also set in reopen_table() */
1207
1487
}
1208
1488
 
1209
1489
 
 
1490
#if 0
 
1491
/*
 
1492
  Reopen an table because the definition has changed.
 
1493
 
 
1494
  SYNOPSIS
 
1495
  reopen_table()
 
1496
  table Table object
 
1497
 
 
1498
  NOTES
 
1499
  The data cursor for the table is already closed and the share is released
 
1500
  The table has a 'dummy' share that mainly contains database and table name.
 
1501
 
 
1502
  RETURN
 
1503
  0  ok
 
1504
  1  error. The old table object is not changed.
 
1505
*/
 
1506
 
 
1507
bool reopen_table(Table *table)
 
1508
{
 
1509
  Table tmp;
 
1510
  bool error= 1;
 
1511
  Field **field;
 
1512
  uint32_t key,part;
 
1513
  TableList table_list;
 
1514
  Session *session= table->in_use;
 
1515
 
 
1516
  assert(table->getShare()->ref_count == 0);
 
1517
  assert(!table->sort.io_cache);
 
1518
 
 
1519
#ifdef EXTRA_DEBUG
 
1520
  if (table->db_stat)
 
1521
    errmsg_printf(ERRMSG_LVL_ERROR, _("Table %s had a open data Cursor in reopen_table"),
 
1522
                  table->alias);
 
1523
#endif
 
1524
  table_list.db=         const_cast<char *>(table->getShare()->getSchemaName());
 
1525
  table_list.table_name= table->getShare()->getTableName();
 
1526
  table_list.table=      table;
 
1527
 
 
1528
  if (wait_for_locked_table_names(session, &table_list))
 
1529
    return true;                             // Thread was killed
 
1530
 
 
1531
  if (open_unireg_entry(session, &tmp, &table_list,
 
1532
                        table->alias,
 
1533
                        table->getShare()->getCacheKey(),
 
1534
                        table->getShare()->getCacheKeySize()))
 
1535
    goto end;
 
1536
 
 
1537
  /* This list copies variables set by open_table */
 
1538
  tmp.tablenr=          table->tablenr;
 
1539
  tmp.used_fields=      table->used_fields;
 
1540
  tmp.const_table=      table->const_table;
 
1541
  tmp.null_row=         table->null_row;
 
1542
  tmp.maybe_null=       table->maybe_null;
 
1543
  tmp.status=           table->status;
 
1544
 
 
1545
  /* Get state */
 
1546
  tmp.in_use=           session;
 
1547
  tmp.reginfo.lock_type=table->reginfo.lock_type;
 
1548
 
 
1549
  /* Replace table in open list */
 
1550
  tmp.next=             table->next;
 
1551
  tmp.prev=             table->prev;
 
1552
 
 
1553
  if (table->cursor)
 
1554
    table->delete_table(true);          // close cursor, free everything
 
1555
 
 
1556
  *table= tmp;
 
1557
  table->default_column_bitmaps();
 
1558
  table->cursor->change_table_ptr(table, table->s);
 
1559
 
 
1560
  assert(table->alias != 0);
 
1561
  for (field=table->field ; *field ; field++)
 
1562
  {
 
1563
    (*field)->table= (*field)->orig_table= table;
 
1564
    (*field)->table_name= &table->alias;
 
1565
  }
 
1566
  for (key=0 ; key < table->getShare()->keys ; key++)
 
1567
  {
 
1568
    for (part=0 ; part < table->key_info[key].usable_key_parts ; part++)
 
1569
      table->key_info[key].key_part[part].field->table= table;
 
1570
  }
 
1571
 
 
1572
  broadcast_refresh();
 
1573
  error= false;
 
1574
 
 
1575
end:
 
1576
  return(error);
 
1577
}
 
1578
#endif
 
1579
 
 
1580
 
1210
1581
/**
1211
1582
  Close all instances of a table open by this thread and replace
1212
1583
  them with exclusive name-locks.
1224
1595
  the strings are used in a loop even after the share may be freed.
1225
1596
*/
1226
1597
 
1227
 
void Session::close_data_files_and_morph_locks(const identifier::Table &identifier)
 
1598
void Session::close_data_files_and_morph_locks(TableIdentifier &identifier)
1228
1599
{
1229
 
  safe_mutex_assert_owner(table::Cache::singleton().mutex().native_handle()); /* Adjust locks at the end of ALTER TABLEL */
 
1600
  safe_mutex_assert_owner(LOCK_open.native_handle()); /* Adjust locks at the end of ALTER TABLEL */
1230
1601
 
1231
1602
  if (lock)
1232
1603
  {
1234
1605
      If we are not under LOCK TABLES we should have only one table
1235
1606
      open and locked so it makes sense to remove the lock at once.
1236
1607
    */
1237
 
    unlockTables(lock);
 
1608
    mysql_unlock_tables(this, lock);
1238
1609
    lock= 0;
1239
1610
  }
1240
1611
 
1269
1640
  combination when one needs tables to be reopened (for
1270
1641
  example see openTablesLock()).
1271
1642
 
1272
 
  @note One should have lock on table::Cache::singleton().mutex() when calling this.
 
1643
  @note One should have lock on LOCK_open when calling this.
1273
1644
 
1274
1645
  @return false in case of success, true - otherwise.
1275
1646
*/
1276
1647
 
1277
 
bool Session::reopen_tables()
 
1648
bool Session::reopen_tables(bool get_locks, bool)
1278
1649
{
1279
1650
  Table *table,*next,**prev;
1280
 
  Table **tables= 0;                    // For locks
1281
 
  Table **tables_ptr= 0;                        // For locks
1282
 
  bool error= false;
 
1651
  Table **tables,**tables_ptr;                  // For locks
 
1652
  bool error=0, not_used;
1283
1653
  const uint32_t flags= DRIZZLE_LOCK_NOTIFY_IF_NEED_REOPEN |
1284
1654
    DRIZZLE_LOCK_IGNORE_GLOBAL_READ_LOCK |
1285
1655
    DRIZZLE_LOCK_IGNORE_FLUSH;
1287
1657
  if (open_tables == NULL)
1288
1658
    return false;
1289
1659
 
1290
 
  safe_mutex_assert_owner(table::Cache::singleton().mutex().native_handle());
 
1660
  safe_mutex_assert_owner(LOCK_open.native_handle());
 
1661
  if (get_locks)
1291
1662
  {
1292
1663
    /*
1293
1664
      The ptr is checked later
1301
1672
    }
1302
1673
    tables= new Table *[opens];
1303
1674
  }
1304
 
 
 
1675
  else
 
1676
  {
 
1677
    tables= &open_tables;
 
1678
  }
1305
1679
  tables_ptr =tables;
1306
1680
 
1307
1681
  prev= &open_tables;
1310
1684
    next= table->getNext();
1311
1685
 
1312
1686
    my_error(ER_CANT_REOPEN_TABLE, MYF(0), table->getAlias());
1313
 
    table::remove_table(static_cast<table::Concurrent *>(table));
 
1687
    remove_table(table);
1314
1688
    error= 1;
1315
1689
  }
1316
1690
  *prev=0;
1317
 
 
1318
1691
  if (tables != tables_ptr)                     // Should we get back old locks
1319
1692
  {
1320
1693
    DrizzleLock *local_lock;
1321
1694
    /*
1322
1695
      We should always get these locks. Anyway, we must not go into
1323
 
      wait_for_tables() as it tries to acquire table::Cache::singleton().mutex(), which is
 
1696
      wait_for_tables() as it tries to acquire LOCK_open, which is
1324
1697
      already locked.
1325
1698
    */
1326
1699
    some_tables_deleted= false;
1327
1700
 
1328
 
    if ((local_lock= lockTables(tables, (uint32_t) (tables_ptr - tables), flags)))
 
1701
    if ((local_lock= mysql_lock_tables(this, tables, (uint32_t) (tables_ptr - tables),
 
1702
                                 flags, &not_used)))
1329
1703
    {
1330
1704
      /* unused */
1331
1705
    }
1341
1715
    }
1342
1716
  }
1343
1717
 
1344
 
  delete [] tables;
1345
 
 
1346
 
  locking::broadcast_refresh();
1347
 
 
1348
 
  return error;
 
1718
  if (get_locks && tables)
 
1719
    delete [] tables;
 
1720
 
 
1721
  broadcast_refresh();
 
1722
 
 
1723
  return(error);
1349
1724
}
1350
1725
 
1351
1726
 
1376
1751
    */
1377
1752
    if (table->needs_reopen_or_name_lock())
1378
1753
    {
1379
 
      found= true;
 
1754
      found=1;
1380
1755
      if (table->db_stat)
1381
1756
      {
1382
1757
        if (morph_locks)
1390
1765
              lock on it. This will also give them a chance to close their
1391
1766
              instances of this table.
1392
1767
            */
1393
 
            abortLock(ulcktbl);
1394
 
            removeLock(ulcktbl);
 
1768
            mysql_lock_abort(this, ulcktbl);
 
1769
            mysql_lock_remove(this, ulcktbl);
1395
1770
            ulcktbl->lock_count= 0;
1396
1771
          }
1397
1772
          if ((ulcktbl != table) && ulcktbl->db_stat)
1431
1806
    }
1432
1807
  }
1433
1808
  if (found)
1434
 
    locking::broadcast_refresh();
 
1809
    broadcast_refresh();
 
1810
}
 
1811
 
 
1812
 
 
1813
/*
 
1814
  Wait until all threads has closed the tables in the list
 
1815
  We have also to wait if there is thread that has a lock on this table even
 
1816
  if the table is closed
 
1817
*/
 
1818
 
 
1819
bool table_is_used(Table *table, bool wait_for_name_lock)
 
1820
{
 
1821
  do
 
1822
  {
 
1823
    const TableIdentifier::Key &key(table->getShare()->getCacheKey());
 
1824
 
 
1825
    TableOpenCacheRange ppp;
 
1826
    ppp= get_open_cache().equal_range(key);
 
1827
 
 
1828
    for (TableOpenCache::const_iterator iter= ppp.first;
 
1829
         iter != ppp.second; ++iter)
 
1830
    {
 
1831
      Table *search= (*iter).second;
 
1832
      if (search->in_use == table->in_use)
 
1833
        continue;                               // Name locked by this thread
 
1834
      /*
 
1835
        We can't use the table under any of the following conditions:
 
1836
        - There is an name lock on it (Table is to be deleted or altered)
 
1837
        - If we are in flush table and we didn't execute the flush
 
1838
        - If the table engine is open and it's an old version
 
1839
        (We must wait until all engines are shut down to use the table)
 
1840
      */
 
1841
      if ( (search->locked_by_name && wait_for_name_lock) ||
 
1842
           (search->is_name_opened() && search->needs_reopen_or_name_lock()))
 
1843
        return 1;
 
1844
    }
 
1845
  } while ((table=table->getNext()));
 
1846
  return 0;
 
1847
}
 
1848
 
 
1849
 
 
1850
/* Wait until all used tables are refreshed */
 
1851
 
 
1852
bool wait_for_tables(Session *session)
 
1853
{
 
1854
  bool result;
 
1855
 
 
1856
  session->set_proc_info("Waiting for tables");
 
1857
  {
 
1858
    boost::mutex::scoped_lock lock(LOCK_open);
 
1859
    while (!session->killed)
 
1860
    {
 
1861
      session->some_tables_deleted= false;
 
1862
      session->close_old_data_files(false, dropping_tables != 0);
 
1863
      if (!table_is_used(session->open_tables, 1))
 
1864
        break;
 
1865
      COND_refresh.wait(lock);
 
1866
    }
 
1867
    if (session->killed)
 
1868
      result= true;                                     // aborted
 
1869
    else
 
1870
    {
 
1871
      /* Now we can open all tables without any interference */
 
1872
      session->set_proc_info("Reopen tables");
 
1873
      session->version= refresh_version;
 
1874
      result= session->reopen_tables(false, false);
 
1875
    }
 
1876
  }
 
1877
  session->set_proc_info(0);
 
1878
 
 
1879
  return result;
1435
1880
}
1436
1881
 
1437
1882
 
1459
1904
*/
1460
1905
 
1461
1906
 
1462
 
Table *drop_locked_tables(Session *session, const drizzled::identifier::Table &identifier)
 
1907
Table *drop_locked_tables(Session *session, const drizzled::TableIdentifier &identifier)
1463
1908
{
1464
1909
  Table *table,*next,**prev, *found= 0;
1465
1910
  prev= &session->open_tables;
1466
1911
 
1467
1912
  /*
1468
 
    Note that we need to hold table::Cache::singleton().mutex() while changing the
 
1913
    Note that we need to hold LOCK_open while changing the
1469
1914
    open_tables list. Another thread may work on it.
1470
 
    (See: table::Cache::singleton().removeTable(), wait_completed_table())
 
1915
    (See: remove_table_from_cache(), mysql_wait_completed_table())
1471
1916
    Closing a MERGE child before the parent would be fatal if the
1472
1917
    other thread tries to abort the MERGE lock in between.
1473
1918
  */
1476
1921
    next=table->getNext();
1477
1922
    if (table->getShare()->getCacheKey() == identifier.getKey())
1478
1923
    {
1479
 
      session->removeLock(table);
 
1924
      mysql_lock_remove(session, table);
1480
1925
 
1481
1926
      if (!found)
1482
1927
      {
1491
1936
      else
1492
1937
      {
1493
1938
        /* We already have a name lock, remove copy */
1494
 
        table::remove_table(static_cast<table::Concurrent *>(table));
 
1939
        remove_table(table);
1495
1940
      }
1496
1941
    }
1497
1942
    else
1501
1946
    }
1502
1947
  }
1503
1948
  *prev=0;
1504
 
 
1505
1949
  if (found)
1506
 
    locking::broadcast_refresh();
 
1950
    broadcast_refresh();
1507
1951
 
1508
 
  return found;
 
1952
  return(found);
1509
1953
}
1510
1954
 
1511
1955
 
1515
1959
  other threads trying to get the lock.
1516
1960
*/
1517
1961
 
1518
 
void abort_locked_tables(Session *session, const drizzled::identifier::Table &identifier)
 
1962
void abort_locked_tables(Session *session, const drizzled::TableIdentifier &identifier)
1519
1963
{
1520
1964
  Table *table;
1521
1965
  for (table= session->open_tables; table ; table= table->getNext())
1523
1967
    if (table->getShare()->getCacheKey() == identifier.getKey())
1524
1968
    {
1525
1969
      /* If MERGE child, forward lock handling to parent. */
1526
 
      session->abortLock(table);
1527
 
      assert(0);
 
1970
      mysql_lock_abort(session, table);
1528
1971
      break;
1529
1972
    }
1530
1973
  }
1531
1974
}
1532
1975
 
 
1976
/*
 
1977
  Load a table definition from cursor and open unireg table
 
1978
 
 
1979
  SYNOPSIS
 
1980
  open_unireg_entry()
 
1981
  session                       Thread handle
 
1982
  entry         Store open table definition here
 
1983
  table_list            TableList with db, table_name
 
1984
  alias         Alias name
 
1985
  cache_key             Key for share_cache
 
1986
  cache_key_length      length of cache_key
 
1987
 
 
1988
  NOTES
 
1989
  Extra argument for open is taken from session->open_options
 
1990
  One must have a lock on LOCK_open when calling this function
 
1991
 
 
1992
  RETURN
 
1993
  0     ok
 
1994
#       Error
 
1995
*/
 
1996
 
 
1997
static int open_unireg_entry(Session *session,
 
1998
                             Table *entry,
 
1999
                             const char *alias,
 
2000
                             TableIdentifier &identifier)
 
2001
{
 
2002
  int error;
 
2003
  TableShare *share;
 
2004
  uint32_t discover_retry_count= 0;
 
2005
 
 
2006
  safe_mutex_assert_owner(LOCK_open.native_handle());
 
2007
retry:
 
2008
  if (not (share= TableShare::getShareCreate(session,
 
2009
                                             identifier,
 
2010
                                             &error)))
 
2011
    return 1;
 
2012
 
 
2013
  while ((error= share->open_table_from_share(session,
 
2014
                                              identifier,
 
2015
                                              alias,
 
2016
                                              (uint32_t) (HA_OPEN_KEYFILE |
 
2017
                                                          HA_OPEN_RNDFILE |
 
2018
                                                          HA_GET_INDEX |
 
2019
                                                          HA_TRY_READ_ONLY),
 
2020
                                              session->open_options, *entry)))
 
2021
  {
 
2022
    if (error == 7)                             // Table def changed
 
2023
    {
 
2024
      share->resetVersion();                        // Mark share as old
 
2025
      if (discover_retry_count++)               // Retry once
 
2026
        goto err;
 
2027
 
 
2028
      /*
 
2029
        TODO->
 
2030
        Here we should wait until all threads has released the table.
 
2031
        For now we do one retry. This may cause a deadlock if there
 
2032
        is other threads waiting for other tables used by this thread.
 
2033
 
 
2034
        Proper fix would be to if the second retry failed:
 
2035
        - Mark that table def changed
 
2036
        - Return from open table
 
2037
        - Close all tables used by this thread
 
2038
        - Start waiting that the share is released
 
2039
        - Retry by opening all tables again
 
2040
      */
 
2041
 
 
2042
      /*
 
2043
        TO BE FIXED
 
2044
        To avoid deadlock, only wait for release if no one else is
 
2045
        using the share.
 
2046
      */
 
2047
      if (share->getTableCount() != 1)
 
2048
        goto err;
 
2049
      /* Free share and wait until it's released by all threads */
 
2050
      TableShare::release(share);
 
2051
 
 
2052
      if (!session->killed)
 
2053
      {
 
2054
        drizzle_reset_errors(session, 1);         // Clear warnings
 
2055
        session->clear_error();                 // Clear error message
 
2056
        goto retry;
 
2057
      }
 
2058
      return 1;
 
2059
    }
 
2060
 
 
2061
    goto err;
 
2062
  }
 
2063
 
 
2064
  return 0;
 
2065
 
 
2066
err:
 
2067
  TableShare::release(share);
 
2068
 
 
2069
  return 1;
 
2070
}
 
2071
 
1533
2072
 
1534
2073
/*
1535
2074
  Open all tables in list
1597
2136
     * to see if it exists so that an unauthorized user cannot phish for
1598
2137
     * table/schema information via error messages
1599
2138
     */
1600
 
    identifier::Table the_table(tables->getSchemaName(), tables->getTableName());
1601
 
    if (not plugin::Authorization::isAuthorized(*user(), the_table))
 
2139
    TableIdentifier the_table(tables->db, tables->table_name);
 
2140
    if (not plugin::Authorization::isAuthorized(getSecurityContext(),
 
2141
                                                the_table))
1602
2142
    {
1603
2143
      result= -1;                               // Fatal error
1604
2144
      break;
1695
2235
 
1696
2236
  set_proc_info("Opening table");
1697
2237
  current_tablenr= 0;
1698
 
  while (!(table= openTable(table_list, &refresh)) && refresh) ;
 
2238
  while (!(table= openTable(table_list, &refresh)) &&
 
2239
         refresh)
 
2240
    ;
1699
2241
 
1700
2242
  if (table)
1701
2243
  {
1704
2246
 
1705
2247
    assert(lock == 0);  // You must lock everything at once
1706
2248
    if ((table->reginfo.lock_type= lock_type) != TL_UNLOCK)
1707
 
    {
1708
 
      if (not (lock= lockTables(&table_list->table, 1, 0)))
1709
 
        table= NULL;
1710
 
    }
 
2249
      if (! (lock= mysql_lock_tables(this, &table_list->table, 1, 0, &refresh)))
 
2250
        table= 0;
1711
2251
  }
1712
2252
 
1713
2253
  set_proc_info(0);
1761
2301
  Table **start,**ptr;
1762
2302
  uint32_t lock_flag= DRIZZLE_LOCK_NOTIFY_IF_NEED_REOPEN;
1763
2303
 
1764
 
  if (!(ptr=start=(Table**) session->getMemRoot()->allocate(sizeof(Table*)*count)))
 
2304
  if (!(ptr=start=(Table**) session->alloc(sizeof(Table*)*count)))
1765
2305
    return -1;
1766
 
 
1767
2306
  for (table= tables; table; table= table->next_global)
1768
2307
  {
1769
2308
    if (!table->placeholder())
1770
2309
      *(ptr++)= table->table;
1771
2310
  }
1772
2311
 
1773
 
  if (not (session->lock= session->lockTables(start, (uint32_t) (ptr - start), lock_flag)))
 
2312
  if (!(session->lock= mysql_lock_tables(session, start, (uint32_t) (ptr - start),
 
2313
                                         lock_flag, need_reopen)))
1774
2314
  {
1775
2315
    return -1;
1776
2316
  }
1799
2339
#  Table object
1800
2340
*/
1801
2341
 
1802
 
Table *Open_tables_state::open_temporary_table(const identifier::Table &identifier,
1803
 
                                               bool link_in_list)
 
2342
Table *Session::open_temporary_table(TableIdentifier &identifier,
 
2343
                                     bool link_in_list)
1804
2344
{
 
2345
  TableShare *share;
 
2346
 
1805
2347
  assert(identifier.isTmp());
1806
 
 
1807
 
 
1808
 
  table::Temporary *new_tmp_table= new table::Temporary(identifier.getType(),
1809
 
                                                        identifier,
1810
 
                                                        const_cast<char *>(const_cast<identifier::Table&>(identifier).getPath().c_str()),
1811
 
                                                        static_cast<uint32_t>(identifier.getPath().length()));
 
2348
  share= new TableShare(identifier.getType(),
 
2349
                        identifier,
 
2350
                        const_cast<char *>(identifier.getPath().c_str()), static_cast<uint32_t>(identifier.getPath().length()));
 
2351
 
 
2352
 
 
2353
  Table *new_tmp_table= new Table;
1812
2354
  if (not new_tmp_table)
1813
2355
    return NULL;
1814
2356
 
1815
2357
  /*
1816
2358
    First open the share, and then open the table from the share we just opened.
1817
2359
  */
1818
 
  if (new_tmp_table->getMutableShare()->open_table_def(*static_cast<Session *>(this), identifier) ||
1819
 
      new_tmp_table->getMutableShare()->open_table_from_share(static_cast<Session *>(this), identifier, identifier.getTableName().c_str(),
1820
 
                                                              (uint32_t) (HA_OPEN_KEYFILE | HA_OPEN_RNDFILE |
1821
 
                                                                          HA_GET_INDEX),
1822
 
                                                              ha_open_options,
1823
 
                                                              *new_tmp_table))
 
2360
  if (share->open_table_def(*this, identifier) ||
 
2361
      share->open_table_from_share(this, identifier, identifier.getTableName().c_str(),
 
2362
                            (uint32_t) (HA_OPEN_KEYFILE | HA_OPEN_RNDFILE |
 
2363
                                        HA_GET_INDEX),
 
2364
                            ha_open_options,
 
2365
                            *new_tmp_table))
1824
2366
  {
1825
2367
    /* No need to lock share->mutex as this is not needed for tmp tables */
1826
 
    delete new_tmp_table->getMutableShare();
 
2368
    delete share;
1827
2369
    delete new_tmp_table;
1828
2370
 
1829
2371
    return 0;
1865
2407
{
1866
2408
  if (session->mark_used_columns != MARK_COLUMNS_NONE)
1867
2409
  {
1868
 
    boost::dynamic_bitset<> *current_bitmap= NULL;
 
2410
    MyBitmap *current_bitmap, *other_bitmap;
1869
2411
 
1870
2412
    /*
1871
2413
      We always want to register the used keys, as the column bitmap may have
1878
2420
    if (session->mark_used_columns == MARK_COLUMNS_READ)
1879
2421
    {
1880
2422
      current_bitmap= table->read_set;
 
2423
      other_bitmap=   table->write_set;
1881
2424
    }
1882
2425
    else
1883
2426
    {
1884
2427
      current_bitmap= table->write_set;
 
2428
      other_bitmap=   table->read_set;
1885
2429
    }
1886
2430
 
1887
 
    //if (current_bitmap->testAndSet(field->position()))
1888
 
    if (current_bitmap->test(field->position()))
 
2431
    if (current_bitmap->testAndSet(field->field_index))
1889
2432
    {
1890
2433
      if (session->mark_used_columns == MARK_COLUMNS_WRITE)
1891
2434
        session->dup_field= field;
1929
2472
                           const char *name, uint32_t , Item **,
1930
2473
                           bool, TableList **actual_table)
1931
2474
{
1932
 
  List<Natural_join_column>::iterator
1933
 
    field_it(table_ref->join_columns->begin());
 
2475
  List_iterator_fast<Natural_join_column>
 
2476
    field_it(*(table_ref->join_columns));
1934
2477
  Natural_join_column *nj_col, *curr_nj_col;
1935
2478
  Field *found_field;
1936
2479
 
1944
2487
    {
1945
2488
      if (nj_col)
1946
2489
      {
1947
 
        my_error(ER_NON_UNIQ_ERROR, MYF(0), name, session->where());
 
2490
        my_error(ER_NON_UNIQ_ERROR, MYF(0), name, session->where);
1948
2491
        return NULL;
1949
2492
      }
1950
2493
      nj_col= curr_nj_col;
2119
2662
      */
2120
2663
      table_name && table_name[0] &&
2121
2664
      (my_strcasecmp(table_alias_charset, table_list->alias, table_name) ||
2122
 
       (db_name && db_name[0] && table_list->getSchemaName() && table_list->getSchemaName()[0] &&
2123
 
        strcmp(db_name, table_list->getSchemaName()))))
 
2665
       (db_name && db_name[0] && table_list->db && table_list->db[0] &&
 
2666
        strcmp(db_name, table_list->db))))
2124
2667
    return 0;
2125
2668
 
2126
2669
  *actual_table= NULL;
2145
2688
    */
2146
2689
    if (table_name && table_name[0])
2147
2690
    {
2148
 
      List<TableList>::iterator it(table_list->getNestedJoin()->join_list.begin());
 
2691
      List_iterator<TableList> it(table_list->getNestedJoin()->join_list);
2149
2692
      TableList *table;
2150
2693
      while ((table= it++))
2151
2694
      {
2195
2738
      {
2196
2739
        Table *table= field_to_set->getTable();
2197
2740
        if (session->mark_used_columns == MARK_COLUMNS_READ)
2198
 
          table->setReadSet(field_to_set->position());
 
2741
          table->setReadSet(field_to_set->field_index);
2199
2742
        else
2200
 
          table->setWriteSet(field_to_set->position());
 
2743
          table->setWriteSet(field_to_set->field_index);
2201
2744
      }
2202
2745
    }
2203
2746
  }
2295
2838
        fields.
2296
2839
      */
2297
2840
      {
2298
 
        Select_Lex *current_sel= session->getLex()->current_select;
 
2841
        Select_Lex *current_sel= session->lex->current_select;
2299
2842
        Select_Lex *last_select= table_ref->select_lex;
2300
2843
        /*
2301
2844
          If the field was an outer referencee, mark all selects using this
2341
2884
      */
2342
2885
      item->cached_table= found ?  0 : actual_table;
2343
2886
 
2344
 
      assert(session->where());
 
2887
      assert(session->where);
2345
2888
      /*
2346
2889
        If we found a fully qualified field we return it directly as it can't
2347
2890
        have duplicates.
2354
2897
        if (report_error == REPORT_ALL_ERRORS ||
2355
2898
            report_error == IGNORE_EXCEPT_NON_UNIQUE)
2356
2899
          my_error(ER_NON_UNIQ_ERROR, MYF(0),
2357
 
                   table_name ? item->full_name() : name, session->where());
 
2900
                   table_name ? item->full_name() : name, session->where);
2358
2901
        return (Field*) 0;
2359
2902
      }
2360
2903
      found= cur_field;
2387
2930
      strcat(buff, table_name);
2388
2931
      table_name=buff;
2389
2932
    }
2390
 
    my_error(ER_UNKNOWN_TABLE, MYF(0), table_name, session->where());
 
2933
    my_error(ER_UNKNOWN_TABLE, MYF(0), table_name, session->where);
2391
2934
  }
2392
2935
  else
2393
2936
  {
2394
2937
    if (report_error == REPORT_ALL_ERRORS ||
2395
2938
        report_error == REPORT_EXCEPT_NON_UNIQUE)
2396
 
      my_error(ER_BAD_FIELD_ERROR, MYF(0), item->full_name(), session->where());
 
2939
      my_error(ER_BAD_FIELD_ERROR, MYF(0), item->full_name(), session->where);
2397
2940
    else
2398
2941
      found= not_found_field;
2399
2942
  }
2444
2987
                  find_item_error_report_type report_error,
2445
2988
                  enum_resolution_type *resolution)
2446
2989
{
2447
 
  List<Item>::iterator li(items.begin());
 
2990
  List_iterator<Item> li(items);
2448
2991
  Item **found=0, **found_unaliased= 0, *item;
2449
2992
  const char *db_name=0;
2450
2993
  const char *field_name=0;
2520
3063
            */
2521
3064
            if (report_error != IGNORE_ERRORS)
2522
3065
              my_error(ER_NON_UNIQ_ERROR, MYF(0),
2523
 
                       find->full_name(), session->where());
 
3066
                       find->full_name(), session->where);
2524
3067
            return (Item**) 0;
2525
3068
          }
2526
3069
          found_unaliased= li.ref();
2551
3094
              continue;                           // Same field twice
2552
3095
            if (report_error != IGNORE_ERRORS)
2553
3096
              my_error(ER_NON_UNIQ_ERROR, MYF(0),
2554
 
                       find->full_name(), session->where());
 
3097
                       find->full_name(), session->where);
2555
3098
            return (Item**) 0;
2556
3099
          }
2557
3100
          found= li.ref();
2603
3146
    {
2604
3147
      if (report_error != IGNORE_ERRORS)
2605
3148
        my_error(ER_NON_UNIQ_ERROR, MYF(0),
2606
 
                 find->full_name(), session->where());
 
3149
                 find->full_name(), session->where);
2607
3150
      return (Item **) 0;
2608
3151
    }
2609
3152
    if (found_unaliased)
2619
3162
  {
2620
3163
    if (report_error == REPORT_ALL_ERRORS)
2621
3164
      my_error(ER_BAD_FIELD_ERROR, MYF(0),
2622
 
               find->full_name(), session->where());
 
3165
               find->full_name(), session->where);
2623
3166
    return (Item **) 0;
2624
3167
  }
2625
3168
  else
2647
3190
static bool
2648
3191
test_if_string_in_list(const char *find, List<String> *str_list)
2649
3192
{
2650
 
  List<String>::iterator str_list_it(str_list->begin());
 
3193
  List_iterator<String> str_list_it(*str_list);
2651
3194
  String *curr_str;
2652
3195
  size_t find_length= strlen(find);
2653
3196
  while ((curr_str= str_list_it++))
2753
3296
    /* true if field_name_1 is a member of using_fields */
2754
3297
    bool is_using_column_1;
2755
3298
    if (!(nj_col_1= it_1.get_or_create_column_ref(leaf_1)))
2756
 
      return(result);
 
3299
      goto err;
2757
3300
    field_name_1= nj_col_1->name();
2758
3301
    is_using_column_1= using_fields &&
2759
3302
      test_if_string_in_list(field_name_1, using_fields);
2771
3314
      Natural_join_column *cur_nj_col_2;
2772
3315
      const char *cur_field_name_2;
2773
3316
      if (!(cur_nj_col_2= it_2.get_or_create_column_ref(leaf_2)))
2774
 
        return(result);
 
3317
        goto err;
2775
3318
      cur_field_name_2= cur_nj_col_2->name();
2776
3319
 
2777
3320
      /*
2790
3333
        if (cur_nj_col_2->is_common ||
2791
3334
            (found && (!using_fields || is_using_column_1)))
2792
3335
        {
2793
 
          my_error(ER_NON_UNIQ_ERROR, MYF(0), field_name_1, session->where());
2794
 
          return(result);
 
3336
          my_error(ER_NON_UNIQ_ERROR, MYF(0), field_name_1, session->where);
 
3337
          goto err;
2795
3338
        }
2796
3339
        nj_col_2= cur_nj_col_2;
2797
3340
        found= true;
2824
3367
      Item_func_eq *eq_cond;
2825
3368
 
2826
3369
      if (!item_1 || !item_2)
2827
 
        return(result); // out of memory
 
3370
        goto err;                               // out of memory
2828
3371
 
2829
3372
      /*
2830
3373
        In the case of no_wrap_view_item == 0, the created items must be
2849
3392
      */
2850
3393
      if (set_new_item_local_context(session, item_ident_1, nj_col_1->table_ref) ||
2851
3394
          set_new_item_local_context(session, item_ident_2, nj_col_2->table_ref))
2852
 
        return(result);
 
3395
        goto err;
2853
3396
 
2854
3397
      if (!(eq_cond= new Item_func_eq(item_ident_1, item_ident_2)))
2855
 
        return(result);                               /* Out of memory. */
 
3398
        goto err;                               /* Out of memory. */
2856
3399
 
2857
3400
      /*
2858
3401
        Add the new equi-join condition to the ON clause. Notice that
2869
3412
      {
2870
3413
        Table *table_1= nj_col_1->table_ref->table;
2871
3414
        /* Mark field_1 used for table cache. */
2872
 
        table_1->setReadSet(field_1->position());
 
3415
        table_1->setReadSet(field_1->field_index);
2873
3416
        table_1->covering_keys&= field_1->part_of_key;
2874
3417
        table_1->merge_keys|= field_1->part_of_key;
2875
3418
      }
2877
3420
      {
2878
3421
        Table *table_2= nj_col_2->table_ref->table;
2879
3422
        /* Mark field_2 used for table cache. */
2880
 
        table_2->setReadSet(field_2->position());
 
3423
        table_2->setReadSet(field_2->field_index);
2881
3424
        table_2->covering_keys&= field_2->part_of_key;
2882
3425
        table_2->merge_keys|= field_2->part_of_key;
2883
3426
      }
2898
3441
  */
2899
3442
  result= false;
2900
3443
 
 
3444
err:
2901
3445
  return(result);
2902
3446
}
2903
3447
 
2955
3499
 
2956
3500
  if (!(non_join_columns= new List<Natural_join_column>) ||
2957
3501
      !(natural_using_join->join_columns= new List<Natural_join_column>))
2958
 
  {
2959
 
    return(result);
2960
 
  }
 
3502
    goto err;
2961
3503
 
2962
3504
  /* Append the columns of the first join operand. */
2963
3505
  for (it_1.set(table_ref_1); !it_1.end_of_fields(); it_1.next())
2981
3523
  if (using_fields && found_using_fields < using_fields->elements)
2982
3524
  {
2983
3525
    String *using_field_name;
2984
 
    List<String>::iterator using_fields_it(using_fields->begin());
 
3526
    List_iterator_fast<String> using_fields_it(*using_fields);
2985
3527
    while ((using_field_name= using_fields_it++))
2986
3528
    {
2987
3529
      const char *using_field_name_ptr= using_field_name->c_ptr();
2988
 
      List<Natural_join_column>::iterator
2989
 
        it(natural_using_join->join_columns->begin());
 
3530
      List_iterator_fast<Natural_join_column>
 
3531
        it(*(natural_using_join->join_columns));
2990
3532
      Natural_join_column *common_field;
2991
3533
 
2992
3534
      for (;;)
2995
3537
        if (!(common_field= it++))
2996
3538
        {
2997
3539
          my_error(ER_BAD_FIELD_ERROR, MYF(0), using_field_name_ptr,
2998
 
                   session->where());
2999
 
          return(result);
 
3540
                   session->where);
 
3541
          goto err;
3000
3542
        }
3001
3543
        if (!my_strcasecmp(system_charset_info,
3002
3544
                           common_field->name(), using_field_name_ptr))
3024
3566
 
3025
3567
  result= false;
3026
3568
 
 
3569
err:
3027
3570
  return(result);
3028
3571
}
3029
3572
 
3068
3611
  /* Call the procedure recursively for each nested table reference. */
3069
3612
  if (table_ref->getNestedJoin())
3070
3613
  {
3071
 
    List<TableList>::iterator nested_it(table_ref->getNestedJoin()->join_list.begin());
 
3614
    List_iterator_fast<TableList> nested_it(table_ref->getNestedJoin()->join_list);
3072
3615
    TableList *same_level_left_neighbor= nested_it++;
3073
3616
    TableList *same_level_right_neighbor= NULL;
3074
3617
    /* Left/right-most neighbors, possibly at higher levels in the join tree. */
3109
3652
      if (cur_table_ref->getNestedJoin() &&
3110
3653
          store_top_level_join_columns(session, cur_table_ref,
3111
3654
                                       real_left_neighbor, real_right_neighbor))
3112
 
        return(result);
 
3655
        goto err;
3113
3656
      same_level_right_neighbor= cur_table_ref;
3114
3657
    }
3115
3658
  }
3122
3665
  {
3123
3666
    assert(table_ref->getNestedJoin() &&
3124
3667
           table_ref->getNestedJoin()->join_list.elements == 2);
3125
 
    List<TableList>::iterator operand_it(table_ref->getNestedJoin()->join_list.begin());
 
3668
    List_iterator_fast<TableList> operand_it(table_ref->getNestedJoin()->join_list);
3126
3669
    /*
3127
3670
      Notice that the order of join operands depends on whether table_ref
3128
3671
      represents a LEFT or a RIGHT join. In a RIGHT join, the operands are
3141
3684
      std::swap(table_ref_1, table_ref_2);
3142
3685
    if (mark_common_columns(session, table_ref_1, table_ref_2,
3143
3686
                            using_fields, &found_using_fields))
3144
 
      return(result);
 
3687
      goto err;
3145
3688
 
3146
3689
    /*
3147
3690
      Swap the join operands back, so that we pick the columns of the second
3153
3696
    if (store_natural_using_join_columns(session, table_ref, table_ref_1,
3154
3697
                                         table_ref_2, using_fields,
3155
3698
                                         found_using_fields))
3156
 
      return(result);
 
3699
      goto err;
3157
3700
 
3158
3701
    /*
3159
3702
      Change NATURAL JOIN to JOIN ... ON. We do this for both operands
3186
3729
  }
3187
3730
  result= false; /* All is OK. */
3188
3731
 
 
3732
err:
3189
3733
  return(result);
3190
3734
}
3191
3735
 
3218
3762
                                         List<TableList> *from_clause,
3219
3763
                                         Name_resolution_context *context)
3220
3764
{
3221
 
  session->setWhere("from clause");
 
3765
  session->where= "from clause";
3222
3766
  if (from_clause->elements == 0)
3223
3767
    return false; /* We come here in the case of UNIONs. */
3224
3768
 
3225
 
  List<TableList>::iterator table_ref_it(from_clause->begin());
 
3769
  List_iterator_fast<TableList> table_ref_it(*from_clause);
3226
3770
  TableList *table_ref; /* Current table reference. */
3227
3771
  /* Table reference to the left of the current. */
3228
3772
  TableList *left_neighbor;
3272
3816
    return 0;
3273
3817
 
3274
3818
  Item *item;
3275
 
  List<Item>::iterator it(fields.begin());
 
3819
  List_iterator<Item> it(fields);
3276
3820
 
3277
 
  session->getLex()->current_select->cur_pos_in_select_list= 0;
 
3821
  session->lex->current_select->cur_pos_in_select_list= 0;
3278
3822
  while (wild_num && (item= it++))
3279
3823
  {
3280
3824
    if (item->type() == Item::FIELD_ITEM &&
3284
3828
    {
3285
3829
      uint32_t elem= fields.elements;
3286
3830
      bool any_privileges= ((Item_field *) item)->any_privileges;
3287
 
      Item_subselect *subsel= session->getLex()->current_select->master_unit()->item;
 
3831
      Item_subselect *subsel= session->lex->current_select->master_unit()->item;
3288
3832
      if (subsel &&
3289
3833
          subsel->substype() == Item_subselect::EXISTS_SUBS)
3290
3834
      {
3315
3859
      wild_num--;
3316
3860
    }
3317
3861
    else
3318
 
      session->getLex()->current_select->cur_pos_in_select_list++;
 
3862
      session->lex->current_select->cur_pos_in_select_list++;
3319
3863
  }
3320
 
  session->getLex()->current_select->cur_pos_in_select_list= UNDEF_POS;
 
3864
  session->lex->current_select->cur_pos_in_select_list= UNDEF_POS;
3321
3865
 
3322
3866
  return 0;
3323
3867
}
3332
3876
{
3333
3877
  register Item *item;
3334
3878
  enum_mark_columns save_mark_used_columns= session->mark_used_columns;
3335
 
  nesting_map save_allow_sum_func= session->getLex()->allow_sum_func;
3336
 
  List<Item>::iterator it(fields.begin());
 
3879
  nesting_map save_allow_sum_func= session->lex->allow_sum_func;
 
3880
  List_iterator<Item> it(fields);
3337
3881
  bool save_is_item_list_lookup;
3338
3882
 
3339
3883
  session->mark_used_columns= mark_used_columns;
3340
3884
  if (allow_sum_func)
3341
 
    session->getLex()->allow_sum_func|= 1 << session->getLex()->current_select->nest_level;
3342
 
  session->setWhere(Session::DEFAULT_WHERE);
3343
 
  save_is_item_list_lookup= session->getLex()->current_select->is_item_list_lookup;
3344
 
  session->getLex()->current_select->is_item_list_lookup= 0;
 
3885
    session->lex->allow_sum_func|= 1 << session->lex->current_select->nest_level;
 
3886
  session->where= Session::DEFAULT_WHERE;
 
3887
  save_is_item_list_lookup= session->lex->current_select->is_item_list_lookup;
 
3888
  session->lex->current_select->is_item_list_lookup= 0;
3345
3889
 
3346
3890
  /*
3347
3891
    To prevent fail on forward lookup we fill it with zerows,
3351
3895
    There is other way to solve problem: fill array with pointers to list,
3352
3896
    but it will be slower.
3353
3897
 
3354
 
    TODO-> remove it when (if) we made one list for allfields and ref_pointer_array
 
3898
TODO: remove it when (if) we made one list for allfields and
 
3899
ref_pointer_array
3355
3900
  */
3356
3901
  if (ref_pointer_array)
3357
 
  {
3358
3902
    memset(ref_pointer_array, 0, sizeof(Item *) * fields.elements);
3359
 
  }
3360
3903
 
3361
3904
  Item **ref= ref_pointer_array;
3362
 
  session->getLex()->current_select->cur_pos_in_select_list= 0;
 
3905
  session->lex->current_select->cur_pos_in_select_list= 0;
3363
3906
  while ((item= it++))
3364
3907
  {
3365
3908
    if ((!item->fixed && item->fix_fields(session, it.ref())) || (item= *(it.ref()))->check_cols(1))
3366
3909
    {
3367
 
      session->getLex()->current_select->is_item_list_lookup= save_is_item_list_lookup;
3368
 
      session->getLex()->allow_sum_func= save_allow_sum_func;
 
3910
      session->lex->current_select->is_item_list_lookup= save_is_item_list_lookup;
 
3911
      session->lex->allow_sum_func= save_allow_sum_func;
3369
3912
      session->mark_used_columns= save_mark_used_columns;
3370
3913
      return true;
3371
3914
    }
3375
3918
        sum_func_list)
3376
3919
      item->split_sum_func(session, ref_pointer_array, *sum_func_list);
3377
3920
    session->used_tables|= item->used_tables();
3378
 
    session->getLex()->current_select->cur_pos_in_select_list++;
 
3921
    session->lex->current_select->cur_pos_in_select_list++;
3379
3922
  }
3380
 
  session->getLex()->current_select->is_item_list_lookup= save_is_item_list_lookup;
3381
 
  session->getLex()->current_select->cur_pos_in_select_list= UNDEF_POS;
 
3923
  session->lex->current_select->is_item_list_lookup= save_is_item_list_lookup;
 
3924
  session->lex->current_select->cur_pos_in_select_list= UNDEF_POS;
3382
3925
 
3383
 
  session->getLex()->allow_sum_func= save_allow_sum_func;
 
3926
  session->lex->allow_sum_func= save_allow_sum_func;
3384
3927
  session->mark_used_columns= save_mark_used_columns;
3385
3928
  return(test(session->is_error()));
3386
3929
}
3549
4092
 
3550
4093
bool
3551
4094
insert_fields(Session *session, Name_resolution_context *context, const char *db_name,
3552
 
              const char *table_name, List<Item>::iterator *it,
 
4095
              const char *table_name, List_iterator<Item> *it,
3553
4096
              bool )
3554
4097
{
3555
4098
  Field_iterator_table_ref field_iterator;
3588
4131
    assert(tables->is_leaf_for_name_resolution());
3589
4132
 
3590
4133
    if ((table_name && my_strcasecmp(table_alias_charset, table_name, tables->alias)) ||
3591
 
        (db_name && my_strcasecmp(system_charset_info, tables->getSchemaName(),db_name)))
 
4134
        (db_name && strcasecmp(tables->db,db_name)))
3592
4135
      continue;
3593
4136
 
3594
4137
    /*
3624
4167
      if ((field= field_iterator.field()))
3625
4168
      {
3626
4169
        /* Mark fields as used to allow storage engine to optimze access */
3627
 
        field->getTable()->setReadSet(field->position());
 
4170
        field->getTable()->setReadSet(field->field_index);
3628
4171
        if (table)
3629
4172
        {
3630
4173
          table->covering_keys&= field->part_of_key;
3652
4195
        }
3653
4196
      }
3654
4197
      else
3655
 
      {
3656
4198
        session->used_tables|= item->used_tables();
3657
 
      }
3658
 
 
3659
 
      session->getLex()->current_select->cur_pos_in_select_list++;
 
4199
      session->lex->current_select->cur_pos_in_select_list++;
3660
4200
    }
3661
4201
    /*
3662
4202
      In case of stored tables, all fields are considered as used,
3675
4215
    qualified '*', and all columns were coalesced, we have to give a more
3676
4216
    meaningful message than ER_BAD_TABLE_ERROR.
3677
4217
  */
3678
 
  if (not table_name)
3679
 
  {
 
4218
  if (!table_name)
3680
4219
    my_message(ER_NO_TABLES_USED, ER(ER_NO_TABLES_USED), MYF(0));
3681
 
  }
3682
4220
  else
3683
 
  {
3684
4221
    my_error(ER_BAD_TABLE_ERROR, MYF(0), table_name);
3685
 
  }
3686
4222
 
3687
4223
  return true;
3688
4224
}
3709
4245
int Session::setup_conds(TableList *leaves, COND **conds)
3710
4246
{
3711
4247
  Session *session= this;
3712
 
  Select_Lex *select_lex= session->getLex()->current_select;
 
4248
  Select_Lex *select_lex= session->lex->current_select;
3713
4249
  TableList *table= NULL;       // For HP compilers
3714
4250
  void *save_session_marker= session->session_marker;
3715
4251
  /*
3731
4267
  session->session_marker= (void*)1;
3732
4268
  if (*conds)
3733
4269
  {
3734
 
    session->setWhere("where clause");
 
4270
    session->where="where clause";
3735
4271
    if ((!(*conds)->fixed && (*conds)->fix_fields(session, conds)) ||
3736
4272
        (*conds)->check_cols(1))
3737
4273
      goto err_no_arena;
3753
4289
      {
3754
4290
        /* Make a join an a expression */
3755
4291
        session->session_marker= (void*)embedded;
3756
 
        session->setWhere("on clause");
 
4292
        session->where="on clause";
3757
4293
        if ((!embedded->on_expr->fixed && embedded->on_expr->fix_fields(session, &embedded->on_expr)) ||
3758
4294
            embedded->on_expr->check_cols(1))
3759
4295
          goto err_no_arena;
3767
4303
  }
3768
4304
  session->session_marker= save_session_marker;
3769
4305
 
3770
 
  session->getLex()->current_select->is_item_list_lookup= save_is_item_list_lookup;
 
4306
  session->lex->current_select->is_item_list_lookup= save_is_item_list_lookup;
3771
4307
  return(test(session->is_error()));
3772
4308
 
3773
4309
err_no_arena:
3805
4341
bool
3806
4342
fill_record(Session *session, List<Item> &fields, List<Item> &values, bool ignore_errors)
3807
4343
{
3808
 
  List<Item>::iterator f(fields.begin());
3809
 
  List<Item>::iterator v(values.begin());
 
4344
  List_iterator_fast<Item> f(fields),v(values);
3810
4345
  Item *value;
3811
4346
  Item_field *field;
3812
4347
  Table *table;
3824
4359
    field= static_cast<Item_field *>(f++);
3825
4360
    table= field->field->getTable();
3826
4361
    table->auto_increment_field_not_null= false;
3827
 
    f= fields.begin();
 
4362
    f.rewind();
3828
4363
  }
3829
4364
 
3830
4365
  while ((field= static_cast<Item_field *>(f++)))
3839
4374
    if ((value->save_in_field(rfield, 0) < 0) && !ignore_errors)
3840
4375
    {
3841
4376
      my_message(ER_UNKNOWN_ERROR, ER(ER_UNKNOWN_ERROR), MYF(0));
3842
 
      if (table)
3843
 
        table->auto_increment_field_not_null= false;
3844
 
 
3845
 
      return true;
 
4377
      goto err;
3846
4378
    }
3847
4379
  }
3848
4380
 
3849
4381
  return session->is_error();
 
4382
 
 
4383
err:
 
4384
  if (table)
 
4385
    table->auto_increment_field_not_null= false;
 
4386
 
 
4387
  return true;
3850
4388
}
3851
4389
 
3852
4390
 
3871
4409
 
3872
4410
bool fill_record(Session *session, Field **ptr, List<Item> &values, bool)
3873
4411
{
3874
 
  List<Item>::iterator v(values.begin());
 
4412
  List_iterator_fast<Item> v(values);
3875
4413
  Item *value;
3876
4414
  Table *table= 0;
3877
4415
  Field *field;
3889
4427
    table= (*ptr)->getTable();
3890
4428
    table->auto_increment_field_not_null= false;
3891
4429
  }
3892
 
 
3893
4430
  while ((field = *ptr++) && ! session->is_error())
3894
4431
  {
3895
4432
    value=v++;
3896
4433
    table= field->getTable();
3897
 
 
3898
4434
    if (field == table->next_number_field)
3899
4435
      table->auto_increment_field_not_null= true;
3900
 
 
3901
4436
    if (value->save_in_field(field, 0) < 0)
3902
 
    {
3903
 
      if (table)
3904
 
        table->auto_increment_field_not_null= false;
3905
 
 
3906
 
      return true;
3907
 
    }
 
4437
      goto err;
3908
4438
  }
3909
4439
 
3910
4440
  return(session->is_error());
 
4441
 
 
4442
err:
 
4443
  if (table)
 
4444
    table->auto_increment_field_not_null= false;
 
4445
 
 
4446
  return true;
3911
4447
}
3912
4448
 
3913
4449
 
3914
4450
bool drizzle_rm_tmp_tables()
3915
4451
{
 
4452
  Session *session;
3916
4453
 
3917
4454
  assert(drizzle_tmpdir.size());
3918
 
  Session::shared_ptr session= Session::make_shared(plugin::Listen::getNullClient(), catalog::local());
3919
4455
 
3920
 
  if (not session)
 
4456
  if (!(session= new Session(plugin::Listen::getNullClient())))
3921
4457
    return true;
3922
 
  session->thread_stack= (char*) session.get();
 
4458
  session->thread_stack= (char*) &session;
3923
4459
  session->storeGlobals();
3924
4460
 
3925
4461
  plugin::StorageEngine::removeLostTemporaryTables(*session, drizzle_tmpdir.c_str());
3926
4462
 
 
4463
  session->lockForDelete();
 
4464
  delete session;
 
4465
 
3927
4466
  return false;
3928
4467
}
3929
4468
 
3933
4472
  unireg support functions
3934
4473
 *****************************************************************************/
3935
4474
 
3936
 
 
 
4475
/*
 
4476
  Invalidate any cache entries that are for some DB
 
4477
 
 
4478
  SYNOPSIS
 
4479
  remove_db_from_cache()
 
4480
  db            Database name. This will be in lower case if
 
4481
  lower_case_table_name is set
 
4482
 
 
4483
NOTE:
 
4484
We can't use hash_delete when looping hash_elements. We mark them first
 
4485
and afterwards delete those marked unused.
 
4486
*/
 
4487
 
 
4488
void remove_db_from_cache(const SchemaIdentifier &schema_identifier)
 
4489
{
 
4490
  safe_mutex_assert_owner(LOCK_open.native_handle());
 
4491
 
 
4492
  for (TableOpenCache::const_iterator iter= get_open_cache().begin();
 
4493
       iter != get_open_cache().end();
 
4494
       iter++)
 
4495
  {
 
4496
    Table *table= (*iter).second;
 
4497
 
 
4498
    if (not schema_identifier.getPath().compare(table->getMutableShare()->getSchemaName()))
 
4499
    {
 
4500
      table->getMutableShare()->resetVersion();                 /* Free when thread is ready */
 
4501
      if (not table->in_use)
 
4502
        unused_tables.relink(table);
 
4503
    }
 
4504
  }
 
4505
 
 
4506
  unused_tables.cullByVersion();
 
4507
}
 
4508
 
 
4509
 
 
4510
/*
 
4511
  Mark all entries with the table as deleted to force an reopen of the table
 
4512
 
 
4513
  The table will be closed (not stored in cache) by the current thread when
 
4514
  close_thread_tables() is called.
 
4515
 
 
4516
  PREREQUISITES
 
4517
  Lock on LOCK_open()
 
4518
 
 
4519
  RETURN
 
4520
  0  This thread now have exclusive access to this table and no other thread
 
4521
  can access the table until close_thread_tables() is called.
 
4522
  1  Table is in use by another thread
 
4523
*/
 
4524
 
 
4525
bool remove_table_from_cache(Session *session, TableIdentifier &identifier, uint32_t flags)
 
4526
{
 
4527
  const TableIdentifier::Key &key(identifier.getKey());
 
4528
  bool result= false; 
 
4529
  bool signalled= false;
 
4530
 
 
4531
  for (;;)
 
4532
  {
 
4533
    result= signalled= false;
 
4534
 
 
4535
    TableOpenCacheRange ppp;
 
4536
    ppp= get_open_cache().equal_range(key);
 
4537
 
 
4538
    for (TableOpenCache::const_iterator iter= ppp.first;
 
4539
         iter != ppp.second; ++iter)
 
4540
    {
 
4541
      Table *table= (*iter).second;
 
4542
      Session *in_use;
 
4543
 
 
4544
      table->getMutableShare()->resetVersion();         /* Free when thread is ready */
 
4545
      if (!(in_use=table->in_use))
 
4546
      {
 
4547
        unused_tables.relink(table);
 
4548
      }
 
4549
      else if (in_use != session)
 
4550
      {
 
4551
        /*
 
4552
          Mark that table is going to be deleted from cache. This will
 
4553
          force threads that are in mysql_lock_tables() (but not yet
 
4554
          in thr_multi_lock()) to abort it's locks, close all tables and retry
 
4555
        */
 
4556
        in_use->some_tables_deleted= true;
 
4557
        if (table->is_name_opened())
 
4558
        {
 
4559
          result= true;
 
4560
        }
 
4561
        /*
 
4562
          Now we must abort all tables locks used by this thread
 
4563
          as the thread may be waiting to get a lock for another table.
 
4564
          Note that we need to hold LOCK_open while going through the
 
4565
          list. So that the other thread cannot change it. The other
 
4566
          thread must also hold LOCK_open whenever changing the
 
4567
          open_tables list. Aborting the MERGE lock after a child was
 
4568
          closed and before the parent is closed would be fatal.
 
4569
        */
 
4570
        for (Table *session_table= in_use->open_tables;
 
4571
             session_table ;
 
4572
             session_table= session_table->getNext())
 
4573
        {
 
4574
          /* Do not handle locks of MERGE children. */
 
4575
          if (session_table->db_stat)   // If table is open
 
4576
            signalled|= mysql_lock_abort_for_thread(session, session_table);
 
4577
        }
 
4578
      }
 
4579
      else
 
4580
        result= result || (flags & RTFC_OWNED_BY_Session_FLAG);
 
4581
    }
 
4582
 
 
4583
    unused_tables.cullByVersion();
 
4584
 
 
4585
    /* Remove table from table definition cache if it's not in use */
 
4586
    TableShare::release(identifier);
 
4587
 
 
4588
    if (result && (flags & RTFC_WAIT_OTHER_THREAD_FLAG))
 
4589
    {
 
4590
      /*
 
4591
        Signal any thread waiting for tables to be freed to
 
4592
        reopen their tables
 
4593
      */
 
4594
      broadcast_refresh();
 
4595
      if (!(flags & RTFC_CHECK_KILLED_FLAG) || !session->killed)
 
4596
      {
 
4597
        dropping_tables++;
 
4598
        if (likely(signalled))
 
4599
          (void) pthread_cond_wait(COND_refresh.native_handle(), LOCK_open.native_handle());
 
4600
        else
 
4601
        {
 
4602
          struct timespec abstime;
 
4603
          /*
 
4604
            It can happen that another thread has opened the
 
4605
            table but has not yet locked any table at all. Since
 
4606
            it can be locked waiting for a table that our thread
 
4607
            has done LOCK Table x WRITE on previously, we need to
 
4608
            ensure that the thread actually hears our signal
 
4609
            before we go to sleep. Thus we wait for a short time
 
4610
            and then we retry another loop in the
 
4611
            remove_table_from_cache routine.
 
4612
          */
 
4613
          set_timespec(abstime, 10);
 
4614
          pthread_cond_timedwait(COND_refresh.native_handle(), LOCK_open.native_handle(), &abstime);
 
4615
        }
 
4616
        dropping_tables--;
 
4617
        continue;
 
4618
      }
 
4619
    }
 
4620
    break;
 
4621
  }
 
4622
 
 
4623
  return result;
 
4624
}
3937
4625
 
3938
4626
 
3939
4627
/**