~drizzle-trunk/drizzle/development

« back to all changes in this revision

Viewing changes to drizzled/sql_base.cc

  • Committer: Brian Aker
  • Date: 2010-06-02 17:48:07 UTC
  • mto: (1578.6.10 explain-drizzle)
  • mto: This revision was merged to the branch mainline in revision 1589.
  • Revision ID: brian@gir-2.local-20100602174807-9unmrwp18ewkwol5
Modify merge-buffer to use std::vector in one location (just curious to see
if this shows up on benchmarks).

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"
35
34
 
36
35
#include <drizzled/sql_select.h>
37
36
#include <drizzled/error.h>
44
43
#include <drizzled/check_stack_overrun.h>
45
44
#include <drizzled/lock.h>
46
45
#include <drizzled/plugin/listen.h>
47
 
#include <drizzled/cached_directory.h>
48
 
#include <drizzled/field/epoch.h>
 
46
#include "drizzled/cached_directory.h"
 
47
#include <drizzled/field/timestamp.h>
49
48
#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>
 
49
#include "drizzled/memory/multi_malloc.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_placeholder.h"
63
57
 
64
58
using namespace std;
65
59
 
68
62
 
69
63
extern bool volatile shutdown_in_progress;
70
64
 
 
65
/**
 
66
  @defgroup Data_Dictionary Data Dictionary
 
67
  @{
 
68
*/
 
69
Table *unused_tables;                           /* Used by mysql_test */
 
70
HASH open_cache;                                /* Used by mysql_test */
 
71
static int open_unireg_entry(Session *session,
 
72
                             Table *entry,
 
73
                             const char *alias,
 
74
                             char *cache_key, uint32_t cache_key_length);
 
75
void free_cache_entry(void *entry);
 
76
unsigned char *table_cache_key(const unsigned char *record,
 
77
                               size_t *length,
 
78
                               bool );
 
79
 
 
80
#if 0
 
81
static bool reopen_table(Table *table);
 
82
#endif
 
83
 
 
84
unsigned char *table_cache_key(const unsigned char *record,
 
85
                               size_t *length,
 
86
                               bool )
 
87
{
 
88
  Table *entry=(Table*) record;
 
89
  *length= entry->getShare()->getCacheKeySize();
 
90
  return (unsigned char*) entry->getMutableShare()->getCacheKey();
 
91
}
 
92
 
 
93
HASH *get_open_cache()
 
94
{
 
95
  return &open_cache;
 
96
}
 
97
 
 
98
 
71
99
bool table_cache_init(void)
72
100
{
73
 
  return false;
74
 
}
75
 
 
76
 
uint32_t cached_open_tables(void)
77
 
{
78
 
  return table::getCache().size();
 
101
  return hash_init(&open_cache, &my_charset_bin,
 
102
                   (size_t) table_cache_size+16,
 
103
                   0, 0, table_cache_key,
 
104
                   free_cache_entry, 0);
79
105
}
80
106
 
81
107
void table_cache_free(void)
82
108
{
83
109
  refresh_version++;                            // Force close of open tables
84
110
 
85
 
  table::getUnused().clear();
86
 
  table::getCache().clear();
87
 
}
 
111
  while (unused_tables)
 
112
    hash_delete(&open_cache, (unsigned char*) unused_tables);
 
113
 
 
114
  if (not open_cache.records)                   // Safety first
 
115
    hash_free(&open_cache);
 
116
}
 
117
 
 
118
uint32_t cached_open_tables(void)
 
119
{
 
120
  return open_cache.records;
 
121
}
 
122
 
88
123
 
89
124
/*
90
125
  Close cursor handle, but leave the table in the table cache
97
132
  By leaving the table in the table cache, it disallows any other thread
98
133
  to open the table
99
134
 
100
 
  session->getKilled() will be set if we run out of memory
 
135
  session->killed will be set if we run out of memory
101
136
 
102
137
  If closing a MERGE child, the calling function has to take care for
103
138
  closing the parent too, if necessary.
106
141
 
107
142
void close_handle_and_leave_table_as_lock(Table *table)
108
143
{
 
144
  TableShare *share, *old_share= table->getMutableShare();
 
145
 
109
146
  assert(table->db_stat);
110
 
  assert(table->getShare()->getType() == message::Table::STANDARD);
111
147
 
112
148
  /*
113
149
    Make a local copy of the table share and free the current one.
114
150
    This has to be done to ensure that the table share is removed from
115
151
    the table defintion cache as soon as the last instance is removed
116
152
  */
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()));
 
153
  share= new TableShare(const_cast<char *>(old_share->getCacheKey()),  static_cast<uint32_t>(old_share->getCacheKeySize()));
 
154
  share->tmp_table= message::Table::INTERNAL;       // for intern_close_table()
122
155
 
123
156
  table->cursor->close();
124
157
  table->db_stat= 0;                            // Mark cursor closed
125
 
  table::instance::release(table->getMutableShare());
 
158
  TableShare::release(table->getMutableShare());
126
159
  table->setShare(share);
 
160
  table->cursor->change_table_ptr(table, table->getMutableShare());
127
161
}
128
162
 
129
163
 
141
175
  }
142
176
}
143
177
 
 
178
/*
 
179
  Remove table from the open table cache
 
180
 
 
181
  SYNOPSIS
 
182
  free_cache_entry()
 
183
  entry         Table to remove
 
184
 
 
185
  NOTE
 
186
  We need to have a lock on LOCK_open when calling this
 
187
*/
 
188
 
 
189
void free_cache_entry(void *entry)
 
190
{
 
191
  Table *table= static_cast<Table *>(entry);
 
192
 
 
193
  table->intern_close_table();
 
194
  if (not table->in_use)
 
195
  {
 
196
    table->next->prev=table->prev;              /* remove from used chain */
 
197
    table->prev->next=table->next;
 
198
    if (table == unused_tables)
 
199
    {
 
200
      unused_tables= unused_tables->next;
 
201
      if (table == unused_tables)
 
202
        unused_tables= NULL;
 
203
    }
 
204
  }
 
205
 
 
206
  if (table->isPlaceHolder())
 
207
  {
 
208
    delete table;
 
209
  }
 
210
  else
 
211
  {
 
212
    free(table);
 
213
  }
 
214
}
 
215
 
144
216
/* Free resources allocated by filesort() and read_record() */
145
217
 
146
218
void Table::free_io_cache()
147
219
{
148
220
  if (sort.io_cache)
149
221
  {
150
 
    sort.io_cache->close_cached_file();
151
 
    safe_delete(sort.io_cache);
 
222
    close_cached_file(sort.io_cache);
 
223
    delete sort.io_cache;
 
224
    sort.io_cache= 0;
152
225
  }
153
226
}
154
227
 
158
231
 
159
232
  @param session Thread context (may be NULL)
160
233
  @param tables List of tables to remove from the cache
161
 
  @param have_lock If table::Cache::singleton().mutex() is locked
 
234
  @param have_lock If LOCK_open is locked
162
235
  @param wait_for_refresh Wait for a impending flush
163
236
  @param wait_for_placeholders Wait for tables being reopened so that the GRL
164
237
  won't proceed while write-locked tables are being reopened by other
173
246
  bool result= false;
174
247
  Session *session= this;
175
248
 
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
 
      {
 
249
  pthread_mutex_lock(&LOCK_open); /* Optionally lock for remove tables from open_cahe if not in use */
 
250
 
 
251
  if (tables == NULL)
 
252
  {
 
253
    refresh_version++;                          // Force close of open tables
 
254
    while (unused_tables)
 
255
    {
 
256
      hash_delete(&open_cache,(unsigned char*) unused_tables);
 
257
    }
 
258
 
 
259
    if (wait_for_refresh)
 
260
    {
 
261
      /*
 
262
        Other threads could wait in a loop in open_and_lock_tables(),
 
263
        trying to lock one or more of our tables.
 
264
 
 
265
        If they wait for the locks in thr_multi_lock(), their lock
 
266
        request is aborted. They loop in open_and_lock_tables() and
 
267
        enter open_table(). Here they notice the table is refreshed and
 
268
        wait for COND_refresh. Then they loop again in
 
269
        openTablesLock() and this time open_table() succeeds. At
 
270
        this moment, if we (the FLUSH TABLES thread) are scheduled and
 
271
        on another FLUSH TABLES enter close_cached_tables(), they could
 
272
        awake while we sleep below, waiting for others threads (us) to
 
273
        close their open tables. If this happens, the other threads
 
274
        would find the tables unlocked. They would get the locks, one
 
275
        after the other, and could do their destructive work. This is an
 
276
        issue if we have LOCK TABLES in effect.
 
277
 
 
278
        The problem is that the other threads passed all checks in
 
279
        open_table() before we refresh the table.
 
280
 
 
281
        The fix for this problem is to set some_tables_deleted for all
 
282
        threads with open tables. These threads can still get their
 
283
        locks, but will immediately release them again after checking
 
284
        this variable. They will then loop in openTablesLock()
 
285
        again. There they will wait until we update all tables version
 
286
        below.
 
287
 
 
288
        Setting some_tables_deleted is done by remove_table_from_cache()
 
289
        in the other branch.
 
290
 
 
291
        In other words (reviewer suggestion): You need this setting of
 
292
        some_tables_deleted for the case when table was opened and all
 
293
        related checks were passed before incrementing refresh_version
 
294
        (which you already have) but attempt to lock the table happened
 
295
        after the call to Session::close_old_data_files() i.e. after removal of
 
296
        current thread locks.
 
297
      */
 
298
      for (uint32_t idx=0 ; idx < open_cache.records ; idx++)
 
299
      {
 
300
        Table *table=(Table*) hash_element(&open_cache,idx);
 
301
        if (table->in_use)
 
302
          table->in_use->some_tables_deleted= false;
 
303
      }
 
304
    }
 
305
  }
 
306
  else
 
307
  {
 
308
    bool found= false;
 
309
    for (TableList *table= tables; table; table= table->next_local)
 
310
    {
 
311
      if (remove_table_from_cache(session, table->db, table->table_name,
 
312
                                  RTFC_OWNED_BY_Session_FLAG))
 
313
        found= true;
 
314
    }
 
315
    if (!found)
 
316
      wait_for_refresh= false;                  // Nothing to wait for
 
317
  }
 
318
 
 
319
  if (wait_for_refresh)
 
320
  {
 
321
    /*
 
322
      If there is any table that has a lower refresh_version, wait until
 
323
      this is closed (or this thread is killed) before returning
 
324
    */
 
325
    session->mysys_var->current_mutex= &LOCK_open;
 
326
    session->mysys_var->current_cond= &COND_refresh;
 
327
    session->set_proc_info("Flushing tables");
 
328
 
 
329
    session->close_old_data_files();
 
330
 
 
331
    bool found= true;
 
332
    /* Wait until all threads has closed all the tables we had locked */
 
333
    while (found && ! session->killed)
 
334
    {
 
335
      found= false;
 
336
      for (uint32_t idx=0 ; idx < open_cache.records ; idx++)
 
337
      {
 
338
        Table *table=(Table*) hash_element(&open_cache,idx);
 
339
        /* Avoid a self-deadlock. */
 
340
        if (table->in_use == session)
 
341
          continue;
187
342
        /*
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.
 
343
          Note that we wait here only for tables which are actually open, and
 
344
          not for placeholders with Table::open_placeholder set. Waiting for
 
345
          latter will cause deadlock in the following scenario, for example:
 
346
 
 
347
conn1: lock table t1 write;
 
348
conn2: lock table t2 write;
 
349
conn1: flush tables;
 
350
conn2: flush tables;
 
351
 
 
352
It also does not make sense to wait for those of placeholders that
 
353
are employed by CREATE TABLE as in this case table simply does not
 
354
exist yet.
223
355
        */
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))
 
356
        if (table->needs_reopen_or_name_lock() && (table->db_stat ||
 
357
                                                   (table->open_placeholder && wait_for_placeholders)))
242
358
        {
243
359
          found= true;
 
360
          pthread_cond_wait(&COND_refresh,&LOCK_open);
 
361
          break;
244
362
        }
245
363
      }
246
 
      if (!found)
247
 
        wait_for_refresh= false;                        // Nothing to wait for
248
364
    }
 
365
    /*
 
366
      No other thread has the locked tables open; reopen them and get the
 
367
      old locks. This should always succeed (unless some external process
 
368
      has removed the tables)
 
369
    */
 
370
    result= session->reopen_tables(true, true);
249
371
 
250
 
    if (wait_for_refresh)
 
372
    /* Set version for table */
 
373
    for (Table *table= session->open_tables; table ; table= table->next)
251
374
    {
252
375
      /*
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
 
      }
 
376
        Preserve the version (0) of write locked tables so that a impending
 
377
        global read lock won't sneak in.
 
378
      */
 
379
      if (table->reginfo.lock_type < TL_WRITE_ALLOW_WRITE)
 
380
        table->getMutableShare()->version= refresh_version;
315
381
    }
316
382
  }
317
383
 
 
384
  pthread_mutex_unlock(&LOCK_open);
 
385
 
318
386
  if (wait_for_refresh)
319
387
  {
320
 
    boost_unique_lock_t scopedLock(session->mysys_var->mutex);
 
388
    pthread_mutex_lock(&session->mysys_var->mutex);
321
389
    session->mysys_var->current_mutex= 0;
322
390
    session->mysys_var->current_cond= 0;
323
391
    session->set_proc_info(0);
 
392
    pthread_mutex_unlock(&session->mysys_var->mutex);
324
393
  }
325
394
 
326
395
  return result;
331
400
  move one table to free list 
332
401
*/
333
402
 
334
 
bool Session::free_cached_table(boost::mutex::scoped_lock &scopedLock)
 
403
bool Session::free_cached_table()
335
404
{
336
405
  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());
 
406
  Table *table= open_tables;
 
407
 
 
408
  safe_mutex_assert_owner(&LOCK_open);
343
409
  assert(table->key_read == 0);
344
410
  assert(!table->cursor || table->cursor->inited == Cursor::NONE);
345
411
 
346
 
  open_tables= table->getNext();
 
412
  open_tables= table->next;
347
413
 
348
414
  if (table->needs_reopen_or_name_lock() ||
349
415
      version != refresh_version || !table->db_stat)
350
416
  {
351
 
    table::remove_table(table);
 
417
    hash_delete(&open_cache,(unsigned char*) table);
352
418
    found_old_table= true;
353
419
  }
354
420
  else
361
427
 
362
428
    /* Free memory and reset for next loop */
363
429
    table->cursor->ha_reset();
364
 
    table->in_use= NULL;
 
430
    table->in_use= false;
365
431
 
366
 
    table::getUnused().link(table);
 
432
    if (unused_tables)
 
433
    {
 
434
      table->next= unused_tables;               /* Link in last */
 
435
      table->prev= unused_tables->prev;
 
436
      unused_tables->prev= table;
 
437
      table->prev->next= table;
 
438
    }
 
439
    else
 
440
    {
 
441
      unused_tables= table->next= table->prev=table;
 
442
    }
367
443
  }
368
444
 
369
445
  return found_old_table;
382
458
{
383
459
  bool found_old_table= false;
384
460
 
385
 
  safe_mutex_assert_not_owner(table::Cache::singleton().mutex().native_handle());
 
461
  safe_mutex_assert_not_owner(&LOCK_open);
386
462
 
387
 
  boost_unique_lock_t scoped_lock(table::Cache::singleton().mutex()); /* Close all open tables on Session */
 
463
  pthread_mutex_lock(&LOCK_open); /* Close all open tables on Session */
388
464
 
389
465
  while (open_tables)
390
466
  {
391
 
    found_old_table|= free_cached_table(scoped_lock);
 
467
    found_old_table|= free_cached_table();
392
468
  }
393
469
  some_tables_deleted= false;
394
470
 
395
471
  if (found_old_table)
396
472
  {
397
473
    /* Tell threads waiting for refresh that something has happened */
398
 
    locking::broadcast_refresh();
 
474
    broadcast_refresh();
399
475
  }
 
476
 
 
477
  pthread_mutex_unlock(&LOCK_open);
400
478
}
401
479
 
402
480
/*
424
502
{
425
503
  for (; table; table= table->*link )
426
504
  {
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
 
    {
 
505
    if ((table->table == 0 || table->table->getShare()->tmp_table == message::Table::STANDARD) &&
 
506
        strcasecmp(table->db, db_name) == 0 &&
 
507
        strcasecmp(table->table_name, table_name) == 0)
431
508
      break;
432
 
    }
433
509
  }
434
510
  return table;
435
511
}
490
566
  if (table->table)
491
567
  {
492
568
    /* temporary table is always unique */
493
 
    if (table->table && table->table->getShare()->getType() != message::Table::STANDARD)
 
569
    if (table->table && table->table->getShare()->tmp_table != message::Table::STANDARD)
494
570
      return 0;
495
571
    table= table->find_underlying_table(table->table);
496
572
    /*
499
575
    */
500
576
    assert(table);
501
577
  }
502
 
  d_name= table->getSchemaName();
503
 
  t_name= table->getTableName();
 
578
  d_name= table->db;
 
579
  t_name= table->table_name;
504
580
  t_alias= table->alias;
505
581
 
506
582
  for (;;)
521
597
}
522
598
 
523
599
 
524
 
void Open_tables_state::doGetTableNames(const identifier::Schema &schema_identifier,
525
 
                                        std::set<std::string>& set_of_names)
 
600
void Session::doGetTableNames(SchemaIdentifier &schema_identifier,
 
601
                              std::set<std::string>& set_of_names)
526
602
{
527
 
  for (Table *table= getTemporaryTables() ; table ; table= table->getNext())
 
603
  for (Table *table= temporary_tables ; table ; table= table->next)
528
604
  {
529
605
    if (schema_identifier.compare(table->getShare()->getSchemaName()))
530
606
    {
533
609
  }
534
610
}
535
611
 
536
 
void Open_tables_state::doGetTableNames(CachedDirectory &,
537
 
                                        const identifier::Schema &schema_identifier,
538
 
                                        std::set<std::string> &set_of_names)
 
612
void Session::doGetTableNames(CachedDirectory &,
 
613
                              SchemaIdentifier &schema_identifier,
 
614
                              std::set<std::string> &set_of_names)
539
615
{
540
616
  doGetTableNames(schema_identifier, set_of_names);
541
617
}
542
618
 
543
 
void Open_tables_state::doGetTableIdentifiers(const identifier::Schema &schema_identifier,
544
 
                                              identifier::Table::vector &set_of_identifiers)
 
619
void Session::doGetTableIdentifiers(SchemaIdentifier &schema_identifier,
 
620
                                    TableIdentifiers &set_of_identifiers)
545
621
{
546
 
  for (Table *table= getTemporaryTables() ; table ; table= table->getNext())
 
622
  for (Table *table= temporary_tables ; table ; table= table->next)
547
623
  {
548
624
    if (schema_identifier.compare(table->getShare()->getSchemaName()))
549
625
    {
550
 
      set_of_identifiers.push_back(identifier::Table(table->getShare()->getSchemaName(),
 
626
      set_of_identifiers.push_back(TableIdentifier(table->getShare()->getSchemaName(),
551
627
                                                   table->getShare()->getTableName(),
552
628
                                                   table->getShare()->getPath()));
553
629
    }
554
630
  }
555
631
}
556
632
 
557
 
void Open_tables_state::doGetTableIdentifiers(CachedDirectory &,
558
 
                                              const identifier::Schema &schema_identifier,
559
 
                                              identifier::Table::vector &set_of_identifiers)
 
633
void Session::doGetTableIdentifiers(CachedDirectory &,
 
634
                                    SchemaIdentifier &schema_identifier,
 
635
                                    TableIdentifiers &set_of_identifiers)
560
636
{
561
637
  doGetTableIdentifiers(schema_identifier, set_of_identifiers);
562
638
}
563
639
 
564
 
bool Open_tables_state::doDoesTableExist(const identifier::Table &identifier)
 
640
bool Session::doDoesTableExist(TableIdentifier &identifier)
565
641
{
566
 
  for (Table *table= getTemporaryTables() ; table ; table= table->getNext())
 
642
  for (Table *table= temporary_tables ; table ; table= table->next)
567
643
  {
568
 
    if (table->getShare()->getType() == message::Table::TEMPORARY)
 
644
    if (table->getShare()->tmp_table == message::Table::TEMPORARY)
569
645
    {
570
 
      if (identifier.getKey() == table->getShare()->getCacheKey())
 
646
      if (identifier.compare(table->getShare()->getSchemaName(), table->getShare()->getTableName()))
571
647
      {
572
648
        return true;
573
649
      }
577
653
  return false;
578
654
}
579
655
 
580
 
int Open_tables_state::doGetTableDefinition(const identifier::Table &identifier,
581
 
                                            message::Table &table_proto)
 
656
int Session::doGetTableDefinition(TableIdentifier &identifier,
 
657
                                  message::Table &table_proto)
582
658
{
583
 
  for (Table *table= getTemporaryTables() ; table ; table= table->getNext())
 
659
  for (Table *table= temporary_tables ; table ; table= table->next)
584
660
  {
585
 
    if (table->getShare()->getType() == message::Table::TEMPORARY)
 
661
    if (table->getShare()->tmp_table == message::Table::TEMPORARY)
586
662
    {
587
 
      if (identifier.getKey() == table->getShare()->getCacheKey())
 
663
      if (identifier.compare(table->getShare()->getSchemaName(), table->getShare()->getTableName()))
588
664
      {
589
 
        table_proto.CopyFrom(*(table->getShare()->getTableMessage()));
 
665
        table_proto.CopyFrom(*(table->getShare()->getTableProto()));
590
666
 
591
667
        return EEXIST;
592
668
      }
596
672
  return ENOENT;
597
673
}
598
674
 
599
 
Table *Open_tables_state::find_temporary_table(const identifier::Table &identifier)
600
 
{
601
 
  for (Table *table= temporary_tables ; table ; table= table->getNext())
602
 
  {
603
 
    if (identifier.getKey() == table->getShare()->getCacheKey())
 
675
Table *Session::find_temporary_table(const char *new_db, const char *table_name)
 
676
{
 
677
  char  key[MAX_DBKEY_LENGTH];
 
678
  uint  key_length;
 
679
 
 
680
  key_length= TableShare::createKey(key, new_db, table_name);
 
681
 
 
682
  for (Table *table= temporary_tables ; table ; table= table->next)
 
683
  {
 
684
    if (table->getShare()->getCacheKeySize() == key_length &&
 
685
        not memcmp(table->getMutableShare()->getCacheKey(), key, key_length))
 
686
    {
 
687
      return table;
 
688
    }
 
689
  }
 
690
  return NULL;                               // Not a temporary table
 
691
}
 
692
 
 
693
Table *Session::find_temporary_table(TableList *table_list)
 
694
{
 
695
  return find_temporary_table(table_list->db, table_list->table_name);
 
696
}
 
697
 
 
698
Table *Session::find_temporary_table(TableIdentifier &identifier)
 
699
{
 
700
  char  key[MAX_DBKEY_LENGTH];
 
701
  uint  key_length;
 
702
 
 
703
  key_length= TableShare::createKey(key, identifier);
 
704
 
 
705
  for (Table *table= temporary_tables ; table ; table= table->next)
 
706
  {
 
707
    if (table->getShare()->getCacheKeySize() == key_length &&
 
708
        not memcmp(table->getMutableShare()->getCacheKey(), key, key_length))
 
709
 
604
710
      return table;
605
711
  }
606
712
 
634
740
  @retval -1  the table is in use by a outer query
635
741
*/
636
742
 
637
 
int Open_tables_state::drop_temporary_table(const drizzled::identifier::Table &identifier)
 
743
int Session::drop_temporary_table(TableList *table_list)
638
744
{
639
745
  Table *table;
640
746
 
641
 
  if (not (table= find_temporary_table(identifier)))
 
747
  if (not (table= find_temporary_table(table_list)))
642
748
    return 1;
643
749
 
644
750
  /* Table might be in use by some outer statement. */
645
 
  if (table->query_id && table->query_id != getQueryId())
 
751
  if (table->query_id && table->query_id != query_id)
646
752
  {
647
 
    my_error(ER_CANT_REOPEN_TABLE, MYF(0), table->getAlias());
 
753
    my_error(ER_CANT_REOPEN_TABLE, MYF(0), table->alias);
648
754
    return -1;
649
755
  }
650
756
 
654
760
}
655
761
 
656
762
 
 
763
/* move table first in unused links */
 
764
 
 
765
static void relink_unused(Table *table)
 
766
{
 
767
  if (table != unused_tables)
 
768
  {
 
769
    table->prev->next=table->next;              /* Remove from unused list */
 
770
    table->next->prev=table->prev;
 
771
    table->next=unused_tables;                  /* Link in unused tables */
 
772
    table->prev=unused_tables->prev;
 
773
    unused_tables->prev->next=table;
 
774
    unused_tables->prev=table;
 
775
    unused_tables=table;
 
776
  }
 
777
}
 
778
 
 
779
 
657
780
/**
658
781
  Remove all instances of table from thread's open list and
659
782
  table cache.
660
783
 
661
784
  @param  session     Thread context
662
785
  @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
786
*/
666
787
 
667
788
void Session::unlink_open_table(Table *find)
668
789
{
669
 
  const identifier::Table::Key find_key(find->getShare()->getCacheKey());
670
 
  Table **prev;
671
 
  safe_mutex_assert_owner(table::Cache::singleton().mutex().native_handle());
672
 
 
 
790
  char key[MAX_DBKEY_LENGTH];
 
791
  uint32_t key_length= find->getShare()->getCacheKeySize();
 
792
  Table *list, **prev;
 
793
 
 
794
  safe_mutex_assert_owner(&LOCK_open);
 
795
 
 
796
  memcpy(key, find->getMutableShare()->getCacheKey(), key_length);
673
797
  /*
674
 
    Note that we need to hold table::Cache::singleton().mutex() while changing the
 
798
    Note that we need to hold LOCK_open while changing the
675
799
    open_tables list. Another thread may work on it.
676
 
    (See: table::Cache::singleton().removeTable(), wait_completed_table())
 
800
    (See: remove_table_from_cache(), mysql_wait_completed_table())
677
801
    Closing a MERGE child before the parent would be fatal if the
678
802
    other thread tries to abort the MERGE lock in between.
679
803
  */
680
804
  for (prev= &open_tables; *prev; )
681
805
  {
682
 
    Table *list= *prev;
 
806
    list= *prev;
683
807
 
684
 
    if (list->getShare()->getCacheKey() == find_key)
 
808
    if (list->getShare()->getCacheKeySize() == key_length &&
 
809
        not memcmp(list->getMutableShare()->getCacheKey(), key, key_length))
685
810
    {
686
811
      /* Remove table from open_tables list. */
687
 
      *prev= list->getNext();
 
812
      *prev= list->next;
688
813
 
689
814
      /* Close table. */
690
 
      table::remove_table(static_cast<table::Concurrent *>(list));
 
815
      hash_delete(&open_cache,(unsigned char*) list); // Close table
691
816
    }
692
817
    else
693
818
    {
694
819
      /* Step to next entry in open_tables list. */
695
 
      prev= list->getNextPtr();
 
820
      prev= &list->next;
696
821
    }
697
822
  }
698
823
 
699
824
  // Notify any 'refresh' threads
700
 
  locking::broadcast_refresh();
 
825
  broadcast_refresh();
701
826
}
702
827
 
703
828
 
720
845
  table that was locked with LOCK TABLES.
721
846
*/
722
847
 
723
 
void Session::drop_open_table(Table *table, const identifier::Table &identifier)
 
848
void Session::drop_open_table(Table *table, TableIdentifier &identifier)
724
849
{
725
 
  if (table->getShare()->getType())
 
850
  if (table->getShare()->tmp_table)
726
851
  {
727
852
    close_temporary_table(table);
728
853
  }
729
854
  else
730
855
  {
731
 
    boost_unique_lock_t scoped_lock(table::Cache::singleton().mutex()); /* Close and drop a table (AUX routine) */
 
856
    pthread_mutex_lock(&LOCK_open); /* Close and drop a table (AUX routine) */
732
857
    /*
733
858
      unlink_open_table() also tells threads waiting for refresh or close
734
859
      that something has happened.
735
860
    */
736
861
    unlink_open_table(table);
737
 
    (void)plugin::StorageEngine::dropTable(*this, identifier);
 
862
    quick_rm_table(*this, identifier);
 
863
    pthread_mutex_unlock(&LOCK_open);
738
864
  }
739
865
}
740
866
 
750
876
  cond  Condition to wait for
751
877
*/
752
878
 
753
 
void Session::wait_for_condition(boost::mutex &mutex, boost::condition_variable_any &cond)
 
879
void Session::wait_for_condition(pthread_mutex_t *mutex, pthread_cond_t *cond)
754
880
{
755
881
  /* Wait until the current table is up to date */
756
882
  const char *saved_proc_info;
757
 
  mysys_var->current_mutex= &mutex;
758
 
  mysys_var->current_cond= &cond;
 
883
  mysys_var->current_mutex= mutex;
 
884
  mysys_var->current_cond= cond;
759
885
  saved_proc_info= get_proc_info();
760
886
  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);
 
887
  if (!killed)
 
888
    (void) pthread_cond_wait(cond, mutex);
 
889
 
 
890
  /*
 
891
    We must unlock mutex first to avoid deadlock becasue conditions are
 
892
    sent to this thread by doing locks in the following order:
 
893
    lock(mysys_var->mutex)
 
894
    lock(mysys_var->current_mutex)
 
895
 
 
896
    One by effect of this that one can only use wait_for_condition with
 
897
    condition variables that are guranteed to not disapper (freed) even if this
 
898
    mutex is unlocked
 
899
  */
 
900
 
 
901
  pthread_mutex_unlock(mutex);
 
902
  pthread_mutex_lock(&mysys_var->mutex);
779
903
  mysys_var->current_mutex= 0;
780
904
  mysys_var->current_cond= 0;
781
905
  set_proc_info(saved_proc_info);
 
906
  pthread_mutex_unlock(&mysys_var->mutex);
 
907
}
 
908
 
 
909
 
 
910
/*
 
911
  Open table which is already name-locked by this thread.
 
912
 
 
913
  SYNOPSIS
 
914
  reopen_name_locked_table()
 
915
  session         Thread handle
 
916
  table_list  TableList object for table to be open, TableList::table
 
917
  member should point to Table object which was used for
 
918
  name-locking.
 
919
  link_in     true  - if Table object for table to be opened should be
 
920
  linked into Session::open_tables list.
 
921
  false - placeholder used for name-locking is already in
 
922
  this list so we only need to preserve Table::next
 
923
  pointer.
 
924
 
 
925
  NOTE
 
926
  This function assumes that its caller already acquired LOCK_open mutex.
 
927
 
 
928
  RETURN VALUE
 
929
  false - Success
 
930
  true  - Error
 
931
*/
 
932
 
 
933
bool Session::reopen_name_locked_table(TableList* table_list, bool link_in)
 
934
{
 
935
  Table *table= table_list->table;
 
936
  TableShare *share;
 
937
  char *table_name= table_list->table_name;
 
938
  Table orig_table;
 
939
 
 
940
  safe_mutex_assert_owner(&LOCK_open);
 
941
 
 
942
  if (killed || !table)
 
943
    return true;
 
944
 
 
945
  orig_table= *table;
 
946
 
 
947
  if (open_unireg_entry(this, table, table_name,
 
948
                        const_cast<char *>(table->getMutableShare()->getCacheKey()),
 
949
                        table->getShare()->getCacheKeySize()))
 
950
  {
 
951
    table->intern_close_table();
 
952
    /*
 
953
      If there was an error during opening of table (for example if it
 
954
      does not exist) '*table' object can be wiped out. To be able
 
955
      properly release name-lock in this case we should restore this
 
956
      object to its original state.
 
957
    */
 
958
    *table= orig_table;
 
959
    return true;
 
960
  }
 
961
 
 
962
  share= table->getMutableShare();
 
963
  /*
 
964
    We want to prevent other connections from opening this table until end
 
965
    of statement as it is likely that modifications of table's metadata are
 
966
    not yet finished (for example CREATE TRIGGER have to change .TRG cursor,
 
967
    or we might want to drop table if CREATE TABLE ... SELECT fails).
 
968
    This also allows us to assume that no other connection will sneak in
 
969
    before we will get table-level lock on this table.
 
970
  */
 
971
  share->version=0;
 
972
  table->in_use = this;
 
973
 
 
974
  if (link_in)
 
975
  {
 
976
    table->next= open_tables;
 
977
    open_tables= table;
 
978
  }
 
979
  else
 
980
  {
 
981
    /*
 
982
      Table object should be already in Session::open_tables list so we just
 
983
      need to set Table::next correctly.
 
984
    */
 
985
    table->next= orig_table.next;
 
986
  }
 
987
 
 
988
  table->tablenr= current_tablenr++;
 
989
  table->used_fields= 0;
 
990
  table->const_table= 0;
 
991
  table->null_row= false;
 
992
  table->maybe_null= false;
 
993
  table->force_index= false;
 
994
  table->status= STATUS_NO_RECORD;
 
995
 
 
996
  return false;
782
997
}
783
998
 
784
999
 
795
1010
  case of failure.
796
1011
*/
797
1012
 
798
 
table::Placeholder *Session::table_cache_insert_placeholder(const drizzled::identifier::Table &arg)
 
1013
Table *Session::table_cache_insert_placeholder(const char *key, uint32_t key_length)
799
1014
{
800
 
  safe_mutex_assert_owner(table::Cache::singleton().mutex().native_handle());
 
1015
  safe_mutex_assert_owner(&LOCK_open);
801
1016
 
802
1017
  /*
803
1018
    Create a table entry with the right key and with an old refresh version
 
1019
    Note that we must use multi_malloc() here as this is freed by the
 
1020
    table cache
804
1021
  */
805
 
  identifier::Table identifier(arg.getSchemaName(), arg.getTableName(), message::Table::INTERNAL);
806
 
  table::Placeholder *table= new table::Placeholder(this, identifier);
 
1022
  TablePlaceholder *table= new TablePlaceholder(key, key_length);
 
1023
  table->in_use= this;
807
1024
 
808
 
  if (not table::Cache::singleton().insert(table))
 
1025
  if (my_hash_insert(&open_cache, (unsigned char*)table))
809
1026
  {
810
 
    safe_delete(table);
 
1027
    delete table;
811
1028
 
812
1029
    return NULL;
813
1030
  }
837
1054
  @retval  true   Error occured (OOM)
838
1055
  @retval  false  Success. 'table' parameter set according to above rules.
839
1056
*/
840
 
bool Session::lock_table_name_if_not_cached(const identifier::Table &identifier, Table **table)
841
 
{
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())
 
1057
bool Session::lock_table_name_if_not_cached(TableIdentifier &identifier, Table **table)
 
1058
{
 
1059
  return lock_table_name_if_not_cached(identifier.getSchemaName().c_str(), identifier.getTableName().c_str(), table);
 
1060
}
 
1061
 
 
1062
bool Session::lock_table_name_if_not_cached(const char *new_db,
 
1063
                                            const char *table_name, Table **table)
 
1064
{
 
1065
  char key[MAX_DBKEY_LENGTH];
 
1066
  char *key_pos= key;
 
1067
  uint32_t key_length;
 
1068
 
 
1069
  key_pos= strcpy(key_pos, new_db) + strlen(new_db);
 
1070
  key_pos= strcpy(key_pos+1, table_name) + strlen(table_name);
 
1071
  key_length= (uint32_t) (key_pos-key)+1;
 
1072
 
 
1073
  pthread_mutex_lock(&LOCK_open); /* Obtain a name lock even though table is not in cache (like for create table)  */
 
1074
 
 
1075
  if (hash_search(&open_cache, (unsigned char *)key, key_length))
851
1076
  {
 
1077
    pthread_mutex_unlock(&LOCK_open);
852
1078
    *table= 0;
853
1079
    return false;
854
1080
  }
855
1081
 
856
 
  if (not (*table= table_cache_insert_placeholder(identifier)))
 
1082
  if (not (*table= table_cache_insert_placeholder(key, key_length)))
857
1083
  {
 
1084
    pthread_mutex_unlock(&LOCK_open);
858
1085
    return true;
859
1086
  }
860
1087
  (*table)->open_placeholder= true;
861
 
  (*table)->setNext(open_tables);
 
1088
  (*table)->next= open_tables;
862
1089
  open_tables= *table;
 
1090
  pthread_mutex_unlock(&LOCK_open);
863
1091
 
864
1092
  return false;
865
1093
}
900
1128
Table *Session::openTable(TableList *table_list, bool *refresh, uint32_t flags)
901
1129
{
902
1130
  Table *table;
 
1131
  char key[MAX_DBKEY_LENGTH];
 
1132
  unsigned int key_length;
903
1133
  const char *alias= table_list->alias;
 
1134
  HASH_SEARCH_STATE state;
904
1135
 
905
1136
  /* Parsing of partitioning information from .frm needs session->lex set up. */
906
1137
  assert(lex->is_lex_started);
913
1144
  if (check_stack_overrun(this, STACK_MIN_SIZE_FOR_OPEN, (unsigned char *)&alias))
914
1145
    return NULL;
915
1146
 
916
 
  if (getKilled())
 
1147
  if (killed)
917
1148
    return NULL;
918
1149
 
919
 
  identifier::Table identifier(table_list->getSchemaName(), table_list->getTableName());
920
 
  const identifier::Table::Key &key(identifier.getKey());
921
 
  table::CacheRange ppp;
 
1150
  key_length= table_list->create_table_def_key(key);
922
1151
 
923
1152
  /*
924
1153
    Unless requested otherwise, try to resolve this table in the list
927
1156
    same name. This block implements the behaviour.
928
1157
    TODO -> move this block into a separate function.
929
1158
  */
930
 
  bool reset= false;
931
 
  for (table= getTemporaryTables(); table ; table=table->getNext())
 
1159
  for (table= temporary_tables; table ; table=table->next)
932
1160
  {
933
 
    if (table->getShare()->getCacheKey() == key)
 
1161
    if (table->getShare()->getCacheKeySize() == key_length && !memcmp(table->getMutableShare()->getCacheKey(), key, key_length))
934
1162
    {
935
1163
      /*
936
1164
        We're trying to use the same temporary table twice in a query.
940
1168
      */
941
1169
      if (table->query_id)
942
1170
      {
943
 
        my_error(ER_CANT_REOPEN_TABLE, MYF(0), table->getAlias());
 
1171
        my_error(ER_CANT_REOPEN_TABLE, MYF(0), table->alias);
944
1172
        return NULL;
945
1173
      }
946
1174
      table->query_id= getQueryId();
947
 
      reset= true;
948
 
      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
 
 
 
1175
      goto reset;
 
1176
    }
 
1177
  }
 
1178
 
 
1179
  if (flags & DRIZZLE_OPEN_TEMPORARY_ONLY)
 
1180
  {
 
1181
    my_error(ER_NO_SUCH_TABLE, MYF(0), table_list->db, table_list->table_name);
 
1182
    return NULL;
 
1183
  }
 
1184
 
 
1185
  /*
 
1186
    If it's the first table from a list of tables used in a query,
 
1187
    remember refresh_version (the version of open_cache state).
 
1188
    If the version changes while we're opening the remaining tables,
 
1189
    we will have to back off, close all the tables opened-so-far,
 
1190
    and try to reopen them.
 
1191
 
 
1192
    Note-> refresh_version is currently changed only during FLUSH TABLES.
 
1193
  */
 
1194
  if (!open_tables)
 
1195
  {
 
1196
    version= refresh_version;
 
1197
  }
 
1198
  else if ((version != refresh_version) &&
 
1199
           ! (flags & DRIZZLE_LOCK_IGNORE_FLUSH))
 
1200
  {
 
1201
    /* Someone did a refresh while thread was opening tables */
 
1202
    if (refresh)
 
1203
      *refresh= true;
 
1204
 
 
1205
    return NULL;
 
1206
  }
 
1207
 
 
1208
  /*
 
1209
    Before we test the global cache, we test our local session cache.
 
1210
  */
 
1211
  if (cached_table)
 
1212
  {
 
1213
    assert(false); /* Not implemented yet */
 
1214
  }
 
1215
 
 
1216
  /*
 
1217
    Non pre-locked/LOCK TABLES mode, and the table is not temporary:
 
1218
    this is the normal use case.
 
1219
    Now we should:
 
1220
    - try to find the table in the table cache.
 
1221
    - if one of the discovered Table instances is name-locked
 
1222
    (table->getShare()->version == 0) back off -- we have to wait
 
1223
    until no one holds a name lock on the table.
 
1224
    - if there is no such Table in the name cache, read the table definition
 
1225
    and insert it into the cache.
 
1226
    We perform all of the above under LOCK_open which currently protects
 
1227
    the open cache (also known as table cache) and table definitions stored
 
1228
    on disk.
 
1229
  */
 
1230
 
 
1231
  pthread_mutex_lock(&LOCK_open); /* Lock for FLUSH TABLES for open table */
 
1232
 
 
1233
  /*
 
1234
    Actually try to find the table in the open_cache.
 
1235
    The cache may contain several "Table" instances for the same
 
1236
    physical table. The instances that are currently "in use" by
 
1237
    some thread have their "in_use" member != NULL.
 
1238
    There is no good reason for having more than one entry in the
 
1239
    hash for the same physical table, except that we use this as
 
1240
    an implicit "pending locks queue" - see
 
1241
    wait_for_locked_table_names for details.
 
1242
  */
 
1243
  for (table= (Table*) hash_first(&open_cache, (unsigned char*) key, key_length,
 
1244
                                  &state);
 
1245
       table && table->in_use ;
 
1246
       table= (Table*) hash_next(&open_cache, (unsigned char*) key, key_length,
 
1247
                                 &state))
 
1248
  {
960
1249
    /*
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.
 
1250
      Here we flush tables marked for flush.
 
1251
      Normally, table->getShare()->version contains the value of
 
1252
      refresh_version from the moment when this table was
 
1253
      (re-)opened and added to the cache.
 
1254
      If since then we did (or just started) FLUSH TABLES
 
1255
      statement, refresh_version has been increased.
 
1256
      For "name-locked" Table instances, table->getShare()->version is set
 
1257
      to 0 (see lock_table_name for details).
 
1258
      In case there is a pending FLUSH TABLES or a name lock, we
 
1259
      need to back off and re-start opening tables.
 
1260
      If we do not back off now, we may dead lock in case of lock
 
1261
      order mismatch with some other thread:
 
1262
c1: name lock t1; -- sort of exclusive lock
 
1263
c2: open t2;      -- sort of shared lock
 
1264
c1: name lock t2; -- blocks
 
1265
c2: open t1; -- blocks
968
1266
    */
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 */
 
1267
    if (table->needs_reopen_or_name_lock())
 
1268
    {
 
1269
      if (flags & DRIZZLE_LOCK_IGNORE_FLUSH)
 
1270
      {
 
1271
        /* Force close at once after usage */
 
1272
        version= table->getShare()->version;
 
1273
        continue;
 
1274
      }
 
1275
 
 
1276
      /* Avoid self-deadlocks by detecting self-dependencies. */
 
1277
      if (table->open_placeholder && table->in_use == this)
 
1278
      {
 
1279
        pthread_mutex_unlock(&LOCK_open);
 
1280
        my_error(ER_UPDATE_TABLE_USED, MYF(0), table->getMutableShare()->getTableName());
 
1281
        return NULL;
 
1282
      }
 
1283
 
 
1284
      /*
 
1285
        Back off, part 1: mark the table as "unused" for the
 
1286
        purpose of name-locking by setting table->db_stat to 0. Do
 
1287
        that only for the tables in this thread that have an old
 
1288
        table->getShare()->version (this is an optimization (?)).
 
1289
        table->db_stat == 0 signals wait_for_locked_table_names
 
1290
        that the tables in question are not used any more. See
 
1291
        table_is_used call for details.
 
1292
      */
 
1293
      close_old_data_files(false, false);
 
1294
 
 
1295
      /*
 
1296
        Back-off part 2: try to avoid "busy waiting" on the table:
 
1297
        if the table is in use by some other thread, we suspend
 
1298
        and wait till the operation is complete: when any
 
1299
        operation that juggles with table->getShare()->version completes,
 
1300
        it broadcasts COND_refresh condition variable.
 
1301
        If 'old' table we met is in use by current thread we return
 
1302
        without waiting since in this situation it's this thread
 
1303
        which is responsible for broadcasting on COND_refresh
 
1304
        (and this was done already in Session::close_old_data_files()).
 
1305
        Good example of such situation is when we have statement
 
1306
        that needs two instances of table and FLUSH TABLES comes
 
1307
        after we open first instance but before we open second
 
1308
        instance.
 
1309
      */
 
1310
      if (table->in_use != this)
 
1311
      {
 
1312
        /* wait_for_conditionwill unlock LOCK_open for us */
 
1313
        wait_for_condition(&LOCK_open, &COND_refresh);
 
1314
      }
 
1315
      else
 
1316
      {
 
1317
        pthread_mutex_unlock(&LOCK_open);
 
1318
      }
 
1319
      /*
 
1320
        There is a refresh in progress for this table.
 
1321
        Signal the caller that it has to try again.
 
1322
      */
977
1323
      if (refresh)
978
1324
        *refresh= true;
979
 
 
980
1325
      return NULL;
981
1326
    }
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 */
 
1327
  }
 
1328
  if (table)
 
1329
  {
 
1330
    /* Unlink the table from "unused_tables" list. */
 
1331
    if (table == unused_tables)
 
1332
    {  // First unused
 
1333
      unused_tables=unused_tables->next; // Remove from link
 
1334
      if (table == unused_tables)
 
1335
        unused_tables= NULL;
989
1336
    }
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
 
 
 
1337
    table->prev->next=table->next; /* Remove from unused list */
 
1338
    table->next->prev=table->prev;
 
1339
    table->in_use= this;
 
1340
  }
 
1341
  else
 
1342
  {
 
1343
    /* Insert a new Table instance into the open cache */
 
1344
    int error;
 
1345
    /* Free cache if too big */
 
1346
    while (open_cache.records > table_cache_size && unused_tables)
 
1347
      hash_delete(&open_cache,(unsigned char*) unused_tables);
 
1348
 
 
1349
    if (table_list->create)
1006
1350
    {
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)
 
1351
      TableIdentifier  lock_table_identifier(table_list->db, table_list->table_name, message::Table::STANDARD);
 
1352
 
 
1353
      if (not plugin::StorageEngine::doesTableExist(*this, lock_table_identifier))
1024
1354
      {
1025
 
        table= (*iter).second;
1026
 
 
1027
 
        if (not table->in_use)
1028
 
          break;
1029
1355
        /*
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
 
1356
          Table to be created, so we need to create placeholder in table-cache.
1046
1357
        */
1047
 
        if (table->needs_reopen_or_name_lock())
 
1358
        if (!(table= table_cache_insert_placeholder(key, key_length)))
1048
1359
        {
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
 
 
 
1360
          pthread_mutex_unlock(&LOCK_open);
1107
1361
          return NULL;
1108
1362
        }
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
 
  }
1178
 
  assert(table->getShare()->getTableCount() > 0 || table->getShare()->getType() != message::Table::STANDARD);
1179
 
 
 
1363
        /*
 
1364
          Link placeholder to the open tables list so it will be automatically
 
1365
          removed once tables are closed. Also mark it so it won't be ignored
 
1366
          by other trying to take name-lock.
 
1367
        */
 
1368
        table->open_placeholder= true;
 
1369
        table->next= open_tables;
 
1370
        open_tables= table;
 
1371
        pthread_mutex_unlock(&LOCK_open);
 
1372
 
 
1373
        return table ;
 
1374
      }
 
1375
      /* Table exists. Let us try to open it. */
 
1376
    }
 
1377
 
 
1378
    /* make a new table */
 
1379
    table= (Table *)malloc(sizeof(Table));
 
1380
    memset(table, 0, sizeof(Table));
 
1381
    if (table == NULL)
 
1382
    {
 
1383
      pthread_mutex_unlock(&LOCK_open);
 
1384
      return NULL;
 
1385
    }
 
1386
 
 
1387
    error= open_unireg_entry(this, table, alias, key, key_length);
 
1388
    if (error != 0)
 
1389
    {
 
1390
      free(table);
 
1391
      pthread_mutex_unlock(&LOCK_open);
 
1392
      return NULL;
 
1393
    }
 
1394
    my_hash_insert(&open_cache, (unsigned char*) table);
 
1395
  }
 
1396
 
 
1397
  pthread_mutex_unlock(&LOCK_open);
 
1398
  if (refresh)
 
1399
  {
 
1400
    table->next= open_tables; /* Link into simple list */
 
1401
    open_tables= table;
 
1402
  }
 
1403
  table->reginfo.lock_type= TL_READ; /* Assume read */
 
1404
 
 
1405
reset:
 
1406
  assert(table->getShare()->ref_count > 0 || table->getShare()->tmp_table != message::Table::STANDARD);
 
1407
 
 
1408
  if (lex->need_correct_ident())
 
1409
    table->alias_name_used= my_strcasecmp(table_alias_charset,
 
1410
                                          table->getMutableShare()->getTableName(), alias);
1180
1411
  /* Fix alias if table name changes */
1181
 
  if (strcmp(table->getAlias(), alias))
 
1412
  if (strcmp(table->alias, alias))
1182
1413
  {
1183
 
    table->setAlias(alias);
 
1414
    uint32_t length=(uint32_t) strlen(alias)+1;
 
1415
    table->alias= (char*) realloc((char*) table->alias, length);
 
1416
    memcpy((void*) table->alias, alias, length);
1184
1417
  }
1185
1418
 
1186
1419
  /* These variables are also set in reopen_table() */
1191
1424
  table->maybe_null= false;
1192
1425
  table->force_index= false;
1193
1426
  table->status=STATUS_NO_RECORD;
1194
 
  table->insert_values.clear();
 
1427
  table->insert_values= 0;
1195
1428
  /* Catch wrong handling of the auto_increment_field_not_null. */
1196
1429
  assert(!table->auto_increment_field_not_null);
1197
1430
  table->auto_increment_field_not_null= false;
1198
1431
  if (table->timestamp_field)
1199
 
  {
1200
1432
    table->timestamp_field_type= table->timestamp_field->get_auto_set_type();
1201
 
  }
1202
1433
  table->pos_in_table_list= table_list;
1203
1434
  table->clear_column_bitmaps();
1204
1435
  assert(table->key_read == 0);
1207
1438
}
1208
1439
 
1209
1440
 
 
1441
#if 0
 
1442
/*
 
1443
  Reopen an table because the definition has changed.
 
1444
 
 
1445
  SYNOPSIS
 
1446
  reopen_table()
 
1447
  table Table object
 
1448
 
 
1449
  NOTES
 
1450
  The data cursor for the table is already closed and the share is released
 
1451
  The table has a 'dummy' share that mainly contains database and table name.
 
1452
 
 
1453
  RETURN
 
1454
  0  ok
 
1455
  1  error. The old table object is not changed.
 
1456
*/
 
1457
 
 
1458
bool reopen_table(Table *table)
 
1459
{
 
1460
  Table tmp;
 
1461
  bool error= 1;
 
1462
  Field **field;
 
1463
  uint32_t key,part;
 
1464
  TableList table_list;
 
1465
  Session *session= table->in_use;
 
1466
 
 
1467
  assert(table->getShare()->ref_count == 0);
 
1468
  assert(!table->sort.io_cache);
 
1469
 
 
1470
#ifdef EXTRA_DEBUG
 
1471
  if (table->db_stat)
 
1472
    errmsg_printf(ERRMSG_LVL_ERROR, _("Table %s had a open data Cursor in reopen_table"),
 
1473
                  table->alias);
 
1474
#endif
 
1475
  table_list.db=         const_cast<char *>(table->getShare()->getSchemaName());
 
1476
  table_list.table_name= table->getShare()->getTableName();
 
1477
  table_list.table=      table;
 
1478
 
 
1479
  if (wait_for_locked_table_names(session, &table_list))
 
1480
    return true;                             // Thread was killed
 
1481
 
 
1482
  if (open_unireg_entry(session, &tmp, &table_list,
 
1483
                        table->alias,
 
1484
                        table->getShare()->getCacheKey(),
 
1485
                        table->getShare()->getCacheKeySize()))
 
1486
    goto end;
 
1487
 
 
1488
  /* This list copies variables set by open_table */
 
1489
  tmp.tablenr=          table->tablenr;
 
1490
  tmp.used_fields=      table->used_fields;
 
1491
  tmp.const_table=      table->const_table;
 
1492
  tmp.null_row=         table->null_row;
 
1493
  tmp.maybe_null=       table->maybe_null;
 
1494
  tmp.status=           table->status;
 
1495
 
 
1496
  /* Get state */
 
1497
  tmp.in_use=           session;
 
1498
  tmp.reginfo.lock_type=table->reginfo.lock_type;
 
1499
 
 
1500
  /* Replace table in open list */
 
1501
  tmp.next=             table->next;
 
1502
  tmp.prev=             table->prev;
 
1503
 
 
1504
  if (table->cursor)
 
1505
    table->delete_table(true);          // close cursor, free everything
 
1506
 
 
1507
  *table= tmp;
 
1508
  table->default_column_bitmaps();
 
1509
  table->cursor->change_table_ptr(table, table->s);
 
1510
 
 
1511
  assert(table->alias != 0);
 
1512
  for (field=table->field ; *field ; field++)
 
1513
  {
 
1514
    (*field)->table= (*field)->orig_table= table;
 
1515
    (*field)->table_name= &table->alias;
 
1516
  }
 
1517
  for (key=0 ; key < table->getShare()->keys ; key++)
 
1518
  {
 
1519
    for (part=0 ; part < table->key_info[key].usable_key_parts ; part++)
 
1520
      table->key_info[key].key_part[part].field->table= table;
 
1521
  }
 
1522
 
 
1523
  broadcast_refresh();
 
1524
  error= false;
 
1525
 
 
1526
end:
 
1527
  return(error);
 
1528
}
 
1529
#endif
 
1530
 
 
1531
 
1210
1532
/**
1211
1533
  Close all instances of a table open by this thread and replace
1212
1534
  them with exclusive name-locks.
1224
1546
  the strings are used in a loop even after the share may be freed.
1225
1547
*/
1226
1548
 
1227
 
void Session::close_data_files_and_morph_locks(const identifier::Table &identifier)
 
1549
void Session::close_data_files_and_morph_locks(TableIdentifier &identifier)
1228
1550
{
1229
 
  safe_mutex_assert_owner(table::Cache::singleton().mutex().native_handle()); /* Adjust locks at the end of ALTER TABLEL */
 
1551
  Table *table;
 
1552
 
 
1553
  safe_mutex_assert_owner(&LOCK_open); /* Adjust locks at the end of ALTER TABLEL */
1230
1554
 
1231
1555
  if (lock)
1232
1556
  {
1234
1558
      If we are not under LOCK TABLES we should have only one table
1235
1559
      open and locked so it makes sense to remove the lock at once.
1236
1560
    */
1237
 
    unlockTables(lock);
 
1561
    mysql_unlock_tables(this, lock);
1238
1562
    lock= 0;
1239
1563
  }
1240
1564
 
1243
1567
    for target table name if we process ALTER Table ... RENAME.
1244
1568
    So loop below makes sense even if we are not under LOCK TABLES.
1245
1569
  */
1246
 
  for (Table *table= open_tables; table ; table=table->getNext())
 
1570
  for (table= open_tables; table ; table=table->next)
1247
1571
  {
1248
 
    if (table->getShare()->getCacheKey() == identifier.getKey())
 
1572
    if (!strcmp(table->getMutableShare()->getTableName(), identifier.getTableName().c_str()) &&
 
1573
        !strcasecmp(table->getMutableShare()->getSchemaName(), identifier.getSchemaName().c_str()))
1249
1574
    {
1250
1575
      table->open_placeholder= true;
1251
1576
      close_handle_and_leave_table_as_lock(table);
1269
1594
  combination when one needs tables to be reopened (for
1270
1595
  example see openTablesLock()).
1271
1596
 
1272
 
  @note One should have lock on table::Cache::singleton().mutex() when calling this.
 
1597
  @note One should have lock on LOCK_open when calling this.
1273
1598
 
1274
1599
  @return false in case of success, true - otherwise.
1275
1600
*/
1276
1601
 
1277
 
bool Session::reopen_tables()
 
1602
bool Session::reopen_tables(bool get_locks, bool)
1278
1603
{
1279
1604
  Table *table,*next,**prev;
1280
 
  Table **tables= 0;                    // For locks
1281
 
  Table **tables_ptr= 0;                        // For locks
1282
 
  bool error= false;
 
1605
  Table **tables,**tables_ptr;                  // For locks
 
1606
  bool error=0, not_used;
1283
1607
  const uint32_t flags= DRIZZLE_LOCK_NOTIFY_IF_NEED_REOPEN |
1284
1608
    DRIZZLE_LOCK_IGNORE_GLOBAL_READ_LOCK |
1285
1609
    DRIZZLE_LOCK_IGNORE_FLUSH;
1287
1611
  if (open_tables == NULL)
1288
1612
    return false;
1289
1613
 
1290
 
  safe_mutex_assert_owner(table::Cache::singleton().mutex().native_handle());
 
1614
  safe_mutex_assert_owner(&LOCK_open);
 
1615
  if (get_locks)
1291
1616
  {
1292
1617
    /*
1293
1618
      The ptr is checked later
1295
1620
    */
1296
1621
    uint32_t opens= 0;
1297
1622
 
1298
 
    for (table= open_tables; table ; table=table->getNext())
 
1623
    for (table= open_tables; table ; table=table->next)
1299
1624
    {
1300
1625
      opens++;
1301
1626
    }
1302
1627
    tables= new Table *[opens];
1303
1628
  }
1304
 
 
 
1629
  else
 
1630
  {
 
1631
    tables= &open_tables;
 
1632
  }
1305
1633
  tables_ptr =tables;
1306
1634
 
1307
1635
  prev= &open_tables;
1308
1636
  for (table= open_tables; table ; table=next)
1309
1637
  {
1310
 
    next= table->getNext();
 
1638
    next= table->next;
1311
1639
 
1312
 
    my_error(ER_CANT_REOPEN_TABLE, MYF(0), table->getAlias());
1313
 
    table::remove_table(static_cast<table::Concurrent *>(table));
 
1640
    my_error(ER_CANT_REOPEN_TABLE, MYF(0), table->alias);
 
1641
    hash_delete(&open_cache,(unsigned char*) table);
1314
1642
    error= 1;
1315
1643
  }
1316
1644
  *prev=0;
1317
 
 
1318
1645
  if (tables != tables_ptr)                     // Should we get back old locks
1319
1646
  {
1320
 
    DrizzleLock *local_lock;
 
1647
    DRIZZLE_LOCK *local_lock;
1321
1648
    /*
1322
1649
      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
 
1650
      wait_for_tables() as it tries to acquire LOCK_open, which is
1324
1651
      already locked.
1325
1652
    */
1326
1653
    some_tables_deleted= false;
1327
1654
 
1328
 
    if ((local_lock= lockTables(tables, (uint32_t) (tables_ptr - tables), flags)))
 
1655
    if ((local_lock= mysql_lock_tables(this, tables, (uint32_t) (tables_ptr - tables),
 
1656
                                 flags, &not_used)))
1329
1657
    {
1330
1658
      /* unused */
1331
1659
    }
1341
1669
    }
1342
1670
  }
1343
1671
 
1344
 
  delete [] tables;
1345
 
 
1346
 
  locking::broadcast_refresh();
1347
 
 
1348
 
  return error;
 
1672
  if (get_locks && tables)
 
1673
    delete [] tables;
 
1674
 
 
1675
  broadcast_refresh();
 
1676
 
 
1677
  return(error);
1349
1678
}
1350
1679
 
1351
1680
 
1369
1698
 
1370
1699
  Table *table= open_tables;
1371
1700
 
1372
 
  for (; table ; table=table->getNext())
 
1701
  for (; table ; table=table->next)
1373
1702
  {
1374
1703
    /*
1375
1704
      Reopen marked for flush.
1376
1705
    */
1377
1706
    if (table->needs_reopen_or_name_lock())
1378
1707
    {
1379
 
      found= true;
 
1708
      found=1;
1380
1709
      if (table->db_stat)
1381
1710
      {
1382
1711
        if (morph_locks)
1390
1719
              lock on it. This will also give them a chance to close their
1391
1720
              instances of this table.
1392
1721
            */
1393
 
            abortLock(ulcktbl);
1394
 
            removeLock(ulcktbl);
 
1722
            mysql_lock_abort(this, ulcktbl);
 
1723
            mysql_lock_remove(this, ulcktbl);
1395
1724
            ulcktbl->lock_count= 0;
1396
1725
          }
1397
1726
          if ((ulcktbl != table) && ulcktbl->db_stat)
1431
1760
    }
1432
1761
  }
1433
1762
  if (found)
1434
 
    locking::broadcast_refresh();
 
1763
    broadcast_refresh();
 
1764
}
 
1765
 
 
1766
 
 
1767
/*
 
1768
  Wait until all threads has closed the tables in the list
 
1769
  We have also to wait if there is thread that has a lock on this table even
 
1770
  if the table is closed
 
1771
*/
 
1772
 
 
1773
bool table_is_used(Table *table, bool wait_for_name_lock)
 
1774
{
 
1775
  do
 
1776
  {
 
1777
    char *key= const_cast<char *>(table->getMutableShare()->getCacheKey());
 
1778
    uint32_t key_length= table->getShare()->getCacheKeySize();
 
1779
 
 
1780
    HASH_SEARCH_STATE state;
 
1781
    for (Table *search= (Table*) hash_first(&open_cache, (unsigned char*) key,
 
1782
                                            key_length, &state);
 
1783
         search ;
 
1784
         search= (Table*) hash_next(&open_cache, (unsigned char*) key,
 
1785
                                    key_length, &state))
 
1786
    {
 
1787
      if (search->in_use == table->in_use)
 
1788
        continue;                               // Name locked by this thread
 
1789
      /*
 
1790
        We can't use the table under any of the following conditions:
 
1791
        - There is an name lock on it (Table is to be deleted or altered)
 
1792
        - If we are in flush table and we didn't execute the flush
 
1793
        - If the table engine is open and it's an old version
 
1794
        (We must wait until all engines are shut down to use the table)
 
1795
      */
 
1796
      if ( (search->locked_by_name && wait_for_name_lock) ||
 
1797
           (search->is_name_opened() && search->needs_reopen_or_name_lock()))
 
1798
        return 1;
 
1799
    }
 
1800
  } while ((table=table->next));
 
1801
  return 0;
 
1802
}
 
1803
 
 
1804
 
 
1805
/* Wait until all used tables are refreshed */
 
1806
 
 
1807
bool wait_for_tables(Session *session)
 
1808
{
 
1809
  bool result;
 
1810
 
 
1811
  session->set_proc_info("Waiting for tables");
 
1812
  pthread_mutex_lock(&LOCK_open); /* Lock for all tables to be refreshed */
 
1813
  while (!session->killed)
 
1814
  {
 
1815
    session->some_tables_deleted= false;
 
1816
    session->close_old_data_files(false, dropping_tables != 0);
 
1817
    if (!table_is_used(session->open_tables, 1))
 
1818
      break;
 
1819
    (void) pthread_cond_wait(&COND_refresh,&LOCK_open);
 
1820
  }
 
1821
  if (session->killed)
 
1822
    result= true;                                       // aborted
 
1823
  else
 
1824
  {
 
1825
    /* Now we can open all tables without any interference */
 
1826
    session->set_proc_info("Reopen tables");
 
1827
    session->version= refresh_version;
 
1828
    result= session->reopen_tables(false, false);
 
1829
  }
 
1830
  pthread_mutex_unlock(&LOCK_open);
 
1831
  session->set_proc_info(0);
 
1832
 
 
1833
  return result;
1435
1834
}
1436
1835
 
1437
1836
 
1459
1858
*/
1460
1859
 
1461
1860
 
1462
 
Table *drop_locked_tables(Session *session, const drizzled::identifier::Table &identifier)
 
1861
Table *drop_locked_tables(Session *session,const char *db, const char *table_name)
1463
1862
{
1464
1863
  Table *table,*next,**prev, *found= 0;
1465
1864
  prev= &session->open_tables;
1466
1865
 
1467
1866
  /*
1468
 
    Note that we need to hold table::Cache::singleton().mutex() while changing the
 
1867
    Note that we need to hold LOCK_open while changing the
1469
1868
    open_tables list. Another thread may work on it.
1470
 
    (See: table::Cache::singleton().removeTable(), wait_completed_table())
 
1869
    (See: remove_table_from_cache(), mysql_wait_completed_table())
1471
1870
    Closing a MERGE child before the parent would be fatal if the
1472
1871
    other thread tries to abort the MERGE lock in between.
1473
1872
  */
1474
1873
  for (table= session->open_tables; table ; table=next)
1475
1874
  {
1476
 
    next=table->getNext();
1477
 
    if (table->getShare()->getCacheKey() == identifier.getKey())
 
1875
    next=table->next;
 
1876
    if (!strcmp(table->getMutableShare()->getTableName(), table_name) &&
 
1877
        !strcasecmp(table->getMutableShare()->getSchemaName(), db))
1478
1878
    {
1479
 
      session->removeLock(table);
 
1879
      mysql_lock_remove(session, table);
1480
1880
 
1481
1881
      if (!found)
1482
1882
      {
1491
1891
      else
1492
1892
      {
1493
1893
        /* We already have a name lock, remove copy */
1494
 
        table::remove_table(static_cast<table::Concurrent *>(table));
 
1894
        hash_delete(&open_cache,(unsigned char*) table);
1495
1895
      }
1496
1896
    }
1497
1897
    else
1498
1898
    {
1499
1899
      *prev=table;
1500
 
      prev= table->getNextPtr();
 
1900
      prev= &table->next;
1501
1901
    }
1502
1902
  }
1503
1903
  *prev=0;
1504
 
 
1505
1904
  if (found)
1506
 
    locking::broadcast_refresh();
 
1905
    broadcast_refresh();
1507
1906
 
1508
 
  return found;
 
1907
  return(found);
1509
1908
}
1510
1909
 
1511
1910
 
1515
1914
  other threads trying to get the lock.
1516
1915
*/
1517
1916
 
1518
 
void abort_locked_tables(Session *session, const drizzled::identifier::Table &identifier)
 
1917
void abort_locked_tables(Session *session,const char *db, const char *table_name)
1519
1918
{
1520
1919
  Table *table;
1521
 
  for (table= session->open_tables; table ; table= table->getNext())
 
1920
  for (table= session->open_tables; table ; table= table->next)
1522
1921
  {
1523
 
    if (table->getShare()->getCacheKey() == identifier.getKey())
 
1922
    if (!strcmp(table->getMutableShare()->getTableName(), table_name) &&
 
1923
        !strcmp(table->getMutableShare()->getSchemaName(), db))
1524
1924
    {
1525
1925
      /* If MERGE child, forward lock handling to parent. */
1526
 
      session->abortLock(table);
1527
 
      assert(0);
 
1926
      mysql_lock_abort(session, table);
1528
1927
      break;
1529
1928
    }
1530
1929
  }
1531
1930
}
1532
1931
 
 
1932
/*
 
1933
  Load a table definition from cursor and open unireg table
 
1934
 
 
1935
  SYNOPSIS
 
1936
  open_unireg_entry()
 
1937
  session                       Thread handle
 
1938
  entry         Store open table definition here
 
1939
  table_list            TableList with db, table_name
 
1940
  alias         Alias name
 
1941
  cache_key             Key for share_cache
 
1942
  cache_key_length      length of cache_key
 
1943
 
 
1944
  NOTES
 
1945
  Extra argument for open is taken from session->open_options
 
1946
  One must have a lock on LOCK_open when calling this function
 
1947
 
 
1948
  RETURN
 
1949
  0     ok
 
1950
#       Error
 
1951
*/
 
1952
 
 
1953
static int open_unireg_entry(Session *session,
 
1954
                             Table *entry,
 
1955
                             const char *alias,
 
1956
                             char *cache_key, uint32_t cache_key_length)
 
1957
{
 
1958
  int error;
 
1959
  TableShare *share;
 
1960
  uint32_t discover_retry_count= 0;
 
1961
 
 
1962
  safe_mutex_assert_owner(&LOCK_open);
 
1963
retry:
 
1964
  if (not (share= TableShare::getShare(session, cache_key,
 
1965
                                       cache_key_length,
 
1966
                                       &error)))
 
1967
    return 1;
 
1968
 
 
1969
  while ((error= share->open_table_from_share(session, alias,
 
1970
                                              (uint32_t) (HA_OPEN_KEYFILE |
 
1971
                                                          HA_OPEN_RNDFILE |
 
1972
                                                          HA_GET_INDEX |
 
1973
                                                          HA_TRY_READ_ONLY),
 
1974
                                              session->open_options, *entry)))
 
1975
  {
 
1976
    if (error == 7)                             // Table def changed
 
1977
    {
 
1978
      share->version= 0;                        // Mark share as old
 
1979
      if (discover_retry_count++)               // Retry once
 
1980
        goto err;
 
1981
 
 
1982
      /*
 
1983
        TODO->
 
1984
        Here we should wait until all threads has released the table.
 
1985
        For now we do one retry. This may cause a deadlock if there
 
1986
        is other threads waiting for other tables used by this thread.
 
1987
 
 
1988
        Proper fix would be to if the second retry failed:
 
1989
        - Mark that table def changed
 
1990
        - Return from open table
 
1991
        - Close all tables used by this thread
 
1992
        - Start waiting that the share is released
 
1993
        - Retry by opening all tables again
 
1994
      */
 
1995
 
 
1996
      /*
 
1997
        TO BE FIXED
 
1998
        To avoid deadlock, only wait for release if no one else is
 
1999
        using the share.
 
2000
      */
 
2001
      if (share->ref_count != 1)
 
2002
        goto err;
 
2003
      /* Free share and wait until it's released by all threads */
 
2004
      TableShare::release(share);
 
2005
 
 
2006
      if (!session->killed)
 
2007
      {
 
2008
        drizzle_reset_errors(session, 1);         // Clear warnings
 
2009
        session->clear_error();                 // Clear error message
 
2010
        goto retry;
 
2011
      }
 
2012
      return 1;
 
2013
    }
 
2014
 
 
2015
    goto err;
 
2016
  }
 
2017
 
 
2018
  return 0;
 
2019
 
 
2020
err:
 
2021
  TableShare::release(share);
 
2022
 
 
2023
  return 1;
 
2024
}
 
2025
 
1533
2026
 
1534
2027
/*
1535
2028
  Open all tables in list
1597
2090
     * to see if it exists so that an unauthorized user cannot phish for
1598
2091
     * table/schema information via error messages
1599
2092
     */
1600
 
    identifier::Table the_table(tables->getSchemaName(), tables->getTableName());
1601
 
    if (not plugin::Authorization::isAuthorized(*user(), the_table))
 
2093
    TableIdentifier the_table(tables->db, tables->table_name);
 
2094
    if (not plugin::Authorization::isAuthorized(getSecurityContext(),
 
2095
                                                the_table))
1602
2096
    {
1603
2097
      result= -1;                               // Fatal error
1604
2098
      break;
1644
2138
    {
1645
2139
      if (tables->lock_type == TL_WRITE_DEFAULT)
1646
2140
        tables->table->reginfo.lock_type= update_lock_default;
1647
 
      else if (tables->table->getShare()->getType() == message::Table::STANDARD)
 
2141
      else if (tables->table->getShare()->tmp_table == message::Table::STANDARD)
1648
2142
        tables->table->reginfo.lock_type= tables->lock_type;
1649
2143
    }
1650
2144
  }
1695
2189
 
1696
2190
  set_proc_info("Opening table");
1697
2191
  current_tablenr= 0;
1698
 
  while (!(table= openTable(table_list, &refresh)) && refresh) ;
 
2192
  while (!(table= openTable(table_list, &refresh)) &&
 
2193
         refresh)
 
2194
    ;
1699
2195
 
1700
2196
  if (table)
1701
2197
  {
1704
2200
 
1705
2201
    assert(lock == 0);  // You must lock everything at once
1706
2202
    if ((table->reginfo.lock_type= lock_type) != TL_UNLOCK)
1707
 
    {
1708
 
      if (not (lock= lockTables(&table_list->table, 1, 0)))
1709
 
        table= NULL;
1710
 
    }
 
2203
      if (! (lock= mysql_lock_tables(this, &table_list->table, 1, 0, &refresh)))
 
2204
        table= 0;
1711
2205
  }
1712
2206
 
1713
2207
  set_proc_info(0);
1761
2255
  Table **start,**ptr;
1762
2256
  uint32_t lock_flag= DRIZZLE_LOCK_NOTIFY_IF_NEED_REOPEN;
1763
2257
 
1764
 
  if (!(ptr=start=(Table**) session->getMemRoot()->allocate(sizeof(Table*)*count)))
 
2258
  if (!(ptr=start=(Table**) session->alloc(sizeof(Table*)*count)))
1765
2259
    return -1;
1766
 
 
1767
2260
  for (table= tables; table; table= table->next_global)
1768
2261
  {
1769
2262
    if (!table->placeholder())
1770
2263
      *(ptr++)= table->table;
1771
2264
  }
1772
2265
 
1773
 
  if (not (session->lock= session->lockTables(start, (uint32_t) (ptr - start), lock_flag)))
 
2266
  if (!(session->lock= mysql_lock_tables(session, start, (uint32_t) (ptr - start),
 
2267
                                         lock_flag, need_reopen)))
1774
2268
  {
1775
2269
    return -1;
1776
2270
  }
1799
2293
#  Table object
1800
2294
*/
1801
2295
 
1802
 
Table *Open_tables_state::open_temporary_table(const identifier::Table &identifier,
1803
 
                                               bool link_in_list)
 
2296
Table *Session::open_temporary_table(TableIdentifier &identifier,
 
2297
                                     bool link_in_list)
1804
2298
{
1805
 
  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()));
1812
 
  if (not new_tmp_table)
 
2299
  Table *new_tmp_table;
 
2300
  TableShare *share;
 
2301
  char cache_key[MAX_DBKEY_LENGTH];
 
2302
  uint32_t key_length;
 
2303
 
 
2304
  /* Create the cache_key for temporary tables */
 
2305
  key_length= TableShare::createKey(cache_key, const_cast<char*>(identifier.getSchemaName().c_str()),
 
2306
                                    const_cast<char*>(identifier.getTableName().c_str()));
 
2307
 
 
2308
  share= new TableShare(cache_key, key_length,
 
2309
                        const_cast<char *>(identifier.getPath().c_str()), static_cast<uint32_t>(identifier.getPath().length()));
 
2310
 
 
2311
  if (!(new_tmp_table= (Table*) malloc(sizeof(*new_tmp_table))))
1813
2312
    return NULL;
1814
2313
 
 
2314
  memset(new_tmp_table, 0, sizeof(*new_tmp_table));
 
2315
 
 
2316
 
1815
2317
  /*
1816
2318
    First open the share, and then open the table from the share we just opened.
1817
2319
  */
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))
 
2320
  if (share->open_table_def(*this, identifier) ||
 
2321
      share->open_table_from_share(this, identifier.getTableName().c_str(),
 
2322
                            (uint32_t) (HA_OPEN_KEYFILE | HA_OPEN_RNDFILE |
 
2323
                                        HA_GET_INDEX),
 
2324
                            ha_open_options,
 
2325
                            *new_tmp_table))
1824
2326
  {
1825
2327
    /* No need to lock share->mutex as this is not needed for tmp tables */
1826
 
    delete new_tmp_table->getMutableShare();
1827
 
    delete new_tmp_table;
 
2328
    delete share;
 
2329
    free((char*) new_tmp_table);
1828
2330
 
1829
2331
    return 0;
1830
2332
  }
1831
2333
 
1832
2334
  new_tmp_table->reginfo.lock_type= TL_WRITE;    // Simulate locked
 
2335
  share->tmp_table= message::Table::TEMPORARY;
1833
2336
 
1834
2337
  if (link_in_list)
1835
2338
  {
1836
2339
    /* growing temp list at the head */
1837
 
    new_tmp_table->setNext(this->temporary_tables);
1838
 
    if (new_tmp_table->getNext())
1839
 
    {
1840
 
      new_tmp_table->getNext()->setPrev(new_tmp_table);
1841
 
    }
 
2340
    new_tmp_table->next= this->temporary_tables;
 
2341
    if (new_tmp_table->next)
 
2342
      new_tmp_table->next->prev= new_tmp_table;
1842
2343
    this->temporary_tables= new_tmp_table;
1843
 
    this->temporary_tables->setPrev(0);
 
2344
    this->temporary_tables->prev= 0;
1844
2345
  }
1845
2346
  new_tmp_table->pos_in_table_list= 0;
1846
2347
 
1865
2366
{
1866
2367
  if (session->mark_used_columns != MARK_COLUMNS_NONE)
1867
2368
  {
1868
 
    boost::dynamic_bitset<> *current_bitmap= NULL;
 
2369
    MyBitmap *current_bitmap, *other_bitmap;
1869
2370
 
1870
2371
    /*
1871
2372
      We always want to register the used keys, as the column bitmap may have
1878
2379
    if (session->mark_used_columns == MARK_COLUMNS_READ)
1879
2380
    {
1880
2381
      current_bitmap= table->read_set;
 
2382
      other_bitmap=   table->write_set;
1881
2383
    }
1882
2384
    else
1883
2385
    {
1884
2386
      current_bitmap= table->write_set;
 
2387
      other_bitmap=   table->read_set;
1885
2388
    }
1886
2389
 
1887
 
    //if (current_bitmap->testAndSet(field->position()))
1888
 
    if (current_bitmap->test(field->position()))
 
2390
    if (current_bitmap->testAndSet(field->field_index))
1889
2391
    {
1890
2392
      if (session->mark_used_columns == MARK_COLUMNS_WRITE)
1891
2393
        session->dup_field= field;
1929
2431
                           const char *name, uint32_t , Item **,
1930
2432
                           bool, TableList **actual_table)
1931
2433
{
1932
 
  List<Natural_join_column>::iterator
1933
 
    field_it(table_ref->join_columns->begin());
 
2434
  List_iterator_fast<Natural_join_column>
 
2435
    field_it(*(table_ref->join_columns));
1934
2436
  Natural_join_column *nj_col, *curr_nj_col;
1935
2437
  Field *found_field;
1936
2438
 
1944
2446
    {
1945
2447
      if (nj_col)
1946
2448
      {
1947
 
        my_error(ER_NON_UNIQ_ERROR, MYF(0), name, session->where());
 
2449
        my_error(ER_NON_UNIQ_ERROR, MYF(0), name, session->where);
1948
2450
        return NULL;
1949
2451
      }
1950
2452
      nj_col= curr_nj_col;
1954
2456
    return NULL;
1955
2457
  {
1956
2458
    /* This is a base table. */
1957
 
    assert(nj_col->table_ref->table == nj_col->table_field->getTable());
 
2459
    assert(nj_col->table_ref->table == nj_col->table_field->table);
1958
2460
    found_field= nj_col->table_field;
1959
2461
    update_field_dependencies(session, found_field, nj_col->table_ref->table);
1960
2462
  }
1991
2493
  uint32_t cached_field_index= *cached_field_index_ptr;
1992
2494
 
1993
2495
  /* We assume here that table->field < NO_CACHED_FIELD_INDEX = UINT_MAX */
1994
 
  if (cached_field_index < table->getShare()->sizeFields() &&
 
2496
  if (cached_field_index < table->getShare()->fields &&
1995
2497
      !my_strcasecmp(system_charset_info,
1996
 
                     table->getField(cached_field_index)->field_name, name))
1997
 
  {
1998
 
    field_ptr= table->getFields() + cached_field_index;
1999
 
  }
2000
 
  else if (table->getShare()->getNamedFieldSize())
2001
 
  {
2002
 
    field_ptr= table->getMutableShare()->getNamedField(std::string(name, length));
 
2498
                     table->field[cached_field_index]->field_name, name))
 
2499
    field_ptr= table->field + cached_field_index;
 
2500
  else if (table->getShare()->name_hash.records)
 
2501
  {
 
2502
    field_ptr= (Field**) hash_search(&table->getShare()->name_hash, (unsigned char*) name,
 
2503
                                     length);
2003
2504
    if (field_ptr)
2004
2505
    {
2005
2506
      /*
2006
2507
        field_ptr points to field in TableShare. Convert it to the matching
2007
2508
        field in table
2008
2509
      */
2009
 
      field_ptr= (table->getFields() + table->getShare()->positionFields(field_ptr));
 
2510
      field_ptr= (table->field + (field_ptr - table->getMutableShare()->getFields()));
2010
2511
    }
2011
2512
  }
2012
2513
  else
2013
2514
  {
2014
 
    if (!(field_ptr= table->getFields()))
 
2515
    if (!(field_ptr= table->field))
2015
2516
      return((Field *)0);
2016
2517
    for (; *field_ptr; ++field_ptr)
2017
2518
      if (!my_strcasecmp(system_charset_info, (*field_ptr)->field_name, name))
2020
2521
 
2021
2522
  if (field_ptr && *field_ptr)
2022
2523
  {
2023
 
    *cached_field_index_ptr= field_ptr - table->getFields();
 
2524
    *cached_field_index_ptr= field_ptr - table->field;
2024
2525
    field= *field_ptr;
2025
2526
  }
2026
2527
  else
2029
2530
        my_strcasecmp(system_charset_info, name, "_rowid") ||
2030
2531
        table->getShare()->rowid_field_offset == 0)
2031
2532
      return((Field*) 0);
2032
 
    field= table->getField(table->getShare()->rowid_field_offset-1);
 
2533
    field= table->field[table->getShare()->rowid_field_offset-1];
2033
2534
  }
2034
2535
 
2035
2536
  update_field_dependencies(session, field, table);
2111
2612
    TODO-> Ensure that table_name, db_name and tables->db always points to something !
2112
2613
  */
2113
2614
  if (/* Exclude nested joins. */
2114
 
      (!table_list->getNestedJoin()) &&
 
2615
      (!table_list->nested_join) &&
2115
2616
      /* Include merge views and information schema tables. */
2116
2617
      /*
2117
2618
        Test if the field qualifiers match the table reference we plan
2119
2620
      */
2120
2621
      table_name && table_name[0] &&
2121
2622
      (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()))))
 
2623
       (db_name && db_name[0] && table_list->db && table_list->db[0] &&
 
2624
        strcmp(db_name, table_list->db))))
2124
2625
    return 0;
2125
2626
 
2126
2627
  *actual_table= NULL;
2127
2628
 
2128
 
  if (!table_list->getNestedJoin())
 
2629
  if (!table_list->nested_join)
2129
2630
  {
2130
2631
    /* 'table_list' is a stored table. */
2131
2632
    assert(table_list->table);
2145
2646
    */
2146
2647
    if (table_name && table_name[0])
2147
2648
    {
2148
 
      List<TableList>::iterator it(table_list->getNestedJoin()->join_list.begin());
 
2649
      List_iterator<TableList> it(table_list->nested_join->join_list);
2149
2650
      TableList *table;
2150
2651
      while ((table= it++))
2151
2652
      {
2193
2694
        field_to_set= fld;
2194
2695
      if (field_to_set)
2195
2696
      {
2196
 
        Table *table= field_to_set->getTable();
 
2697
        Table *table= field_to_set->table;
2197
2698
        if (session->mark_used_columns == MARK_COLUMNS_READ)
2198
 
          table->setReadSet(field_to_set->position());
 
2699
          table->setReadSet(field_to_set->field_index);
2199
2700
        else
2200
 
          table->setWriteSet(field_to_set->position());
 
2701
          table->setWriteSet(field_to_set->field_index);
2201
2702
      }
2202
2703
    }
2203
2704
  }
2295
2796
        fields.
2296
2797
      */
2297
2798
      {
2298
 
        Select_Lex *current_sel= session->getLex()->current_select;
 
2799
        Select_Lex *current_sel= session->lex->current_select;
2299
2800
        Select_Lex *last_select= table_ref->select_lex;
2300
2801
        /*
2301
2802
          If the field was an outer referencee, mark all selects using this
2341
2842
      */
2342
2843
      item->cached_table= found ?  0 : actual_table;
2343
2844
 
2344
 
      assert(session->where());
 
2845
      assert(session->where);
2345
2846
      /*
2346
2847
        If we found a fully qualified field we return it directly as it can't
2347
2848
        have duplicates.
2354
2855
        if (report_error == REPORT_ALL_ERRORS ||
2355
2856
            report_error == IGNORE_EXCEPT_NON_UNIQUE)
2356
2857
          my_error(ER_NON_UNIQ_ERROR, MYF(0),
2357
 
                   table_name ? item->full_name() : name, session->where());
 
2858
                   table_name ? item->full_name() : name, session->where);
2358
2859
        return (Field*) 0;
2359
2860
      }
2360
2861
      found= cur_field;
2387
2888
      strcat(buff, table_name);
2388
2889
      table_name=buff;
2389
2890
    }
2390
 
    my_error(ER_UNKNOWN_TABLE, MYF(0), table_name, session->where());
 
2891
    my_error(ER_UNKNOWN_TABLE, MYF(0), table_name, session->where);
2391
2892
  }
2392
2893
  else
2393
2894
  {
2394
2895
    if (report_error == REPORT_ALL_ERRORS ||
2395
2896
        report_error == REPORT_EXCEPT_NON_UNIQUE)
2396
 
      my_error(ER_BAD_FIELD_ERROR, MYF(0), item->full_name(), session->where());
 
2897
      my_error(ER_BAD_FIELD_ERROR, MYF(0), item->full_name(), session->where);
2397
2898
    else
2398
2899
      found= not_found_field;
2399
2900
  }
2439
2940
 
2440
2941
 
2441
2942
Item **
2442
 
find_item_in_list(Session *session,
2443
 
                  Item *find, List<Item> &items, uint32_t *counter,
 
2943
find_item_in_list(Item *find, List<Item> &items, uint32_t *counter,
2444
2944
                  find_item_error_report_type report_error,
2445
2945
                  enum_resolution_type *resolution)
2446
2946
{
2447
 
  List<Item>::iterator li(items.begin());
 
2947
  List_iterator<Item> li(items);
2448
2948
  Item **found=0, **found_unaliased= 0, *item;
2449
2949
  const char *db_name=0;
2450
2950
  const char *field_name=0;
2520
3020
            */
2521
3021
            if (report_error != IGNORE_ERRORS)
2522
3022
              my_error(ER_NON_UNIQ_ERROR, MYF(0),
2523
 
                       find->full_name(), session->where());
 
3023
                       find->full_name(), current_session->where);
2524
3024
            return (Item**) 0;
2525
3025
          }
2526
3026
          found_unaliased= li.ref();
2551
3051
              continue;                           // Same field twice
2552
3052
            if (report_error != IGNORE_ERRORS)
2553
3053
              my_error(ER_NON_UNIQ_ERROR, MYF(0),
2554
 
                       find->full_name(), session->where());
 
3054
                       find->full_name(), current_session->where);
2555
3055
            return (Item**) 0;
2556
3056
          }
2557
3057
          found= li.ref();
2603
3103
    {
2604
3104
      if (report_error != IGNORE_ERRORS)
2605
3105
        my_error(ER_NON_UNIQ_ERROR, MYF(0),
2606
 
                 find->full_name(), session->where());
 
3106
                 find->full_name(), current_session->where);
2607
3107
      return (Item **) 0;
2608
3108
    }
2609
3109
    if (found_unaliased)
2619
3119
  {
2620
3120
    if (report_error == REPORT_ALL_ERRORS)
2621
3121
      my_error(ER_BAD_FIELD_ERROR, MYF(0),
2622
 
               find->full_name(), session->where());
 
3122
               find->full_name(), current_session->where);
2623
3123
    return (Item **) 0;
2624
3124
  }
2625
3125
  else
2647
3147
static bool
2648
3148
test_if_string_in_list(const char *find, List<String> *str_list)
2649
3149
{
2650
 
  List<String>::iterator str_list_it(str_list->begin());
 
3150
  List_iterator<String> str_list_it(*str_list);
2651
3151
  String *curr_str;
2652
3152
  size_t find_length= strlen(find);
2653
3153
  while ((curr_str= str_list_it++))
2737
3237
    Leaf table references to which new natural join columns are added
2738
3238
    if the leaves are != NULL.
2739
3239
  */
2740
 
  TableList *leaf_1= (table_ref_1->getNestedJoin() &&
2741
 
                      ! table_ref_1->is_natural_join) ?
 
3240
  TableList *leaf_1= (table_ref_1->nested_join &&
 
3241
                      !table_ref_1->is_natural_join) ?
2742
3242
    NULL : table_ref_1;
2743
 
  TableList *leaf_2= (table_ref_2->getNestedJoin() &&
2744
 
                      ! table_ref_2->is_natural_join) ?
 
3243
  TableList *leaf_2= (table_ref_2->nested_join &&
 
3244
                      !table_ref_2->is_natural_join) ?
2745
3245
    NULL : table_ref_2;
2746
3246
 
2747
3247
  *found_using_fields= 0;
2753
3253
    /* true if field_name_1 is a member of using_fields */
2754
3254
    bool is_using_column_1;
2755
3255
    if (!(nj_col_1= it_1.get_or_create_column_ref(leaf_1)))
2756
 
      return(result);
 
3256
      goto err;
2757
3257
    field_name_1= nj_col_1->name();
2758
3258
    is_using_column_1= using_fields &&
2759
3259
      test_if_string_in_list(field_name_1, using_fields);
2771
3271
      Natural_join_column *cur_nj_col_2;
2772
3272
      const char *cur_field_name_2;
2773
3273
      if (!(cur_nj_col_2= it_2.get_or_create_column_ref(leaf_2)))
2774
 
        return(result);
 
3274
        goto err;
2775
3275
      cur_field_name_2= cur_nj_col_2->name();
2776
3276
 
2777
3277
      /*
2790
3290
        if (cur_nj_col_2->is_common ||
2791
3291
            (found && (!using_fields || is_using_column_1)))
2792
3292
        {
2793
 
          my_error(ER_NON_UNIQ_ERROR, MYF(0), field_name_1, session->where());
2794
 
          return(result);
 
3293
          my_error(ER_NON_UNIQ_ERROR, MYF(0), field_name_1, session->where);
 
3294
          goto err;
2795
3295
        }
2796
3296
        nj_col_2= cur_nj_col_2;
2797
3297
        found= true;
2824
3324
      Item_func_eq *eq_cond;
2825
3325
 
2826
3326
      if (!item_1 || !item_2)
2827
 
        return(result); // out of memory
 
3327
        goto err;                               // out of memory
2828
3328
 
2829
3329
      /*
2830
3330
        In the case of no_wrap_view_item == 0, the created items must be
2849
3349
      */
2850
3350
      if (set_new_item_local_context(session, item_ident_1, nj_col_1->table_ref) ||
2851
3351
          set_new_item_local_context(session, item_ident_2, nj_col_2->table_ref))
2852
 
        return(result);
 
3352
        goto err;
2853
3353
 
2854
3354
      if (!(eq_cond= new Item_func_eq(item_ident_1, item_ident_2)))
2855
 
        return(result);                               /* Out of memory. */
 
3355
        goto err;                               /* Out of memory. */
2856
3356
 
2857
3357
      /*
2858
3358
        Add the new equi-join condition to the ON clause. Notice that
2869
3369
      {
2870
3370
        Table *table_1= nj_col_1->table_ref->table;
2871
3371
        /* Mark field_1 used for table cache. */
2872
 
        table_1->setReadSet(field_1->position());
 
3372
        table_1->setReadSet(field_1->field_index);
2873
3373
        table_1->covering_keys&= field_1->part_of_key;
2874
3374
        table_1->merge_keys|= field_1->part_of_key;
2875
3375
      }
2877
3377
      {
2878
3378
        Table *table_2= nj_col_2->table_ref->table;
2879
3379
        /* Mark field_2 used for table cache. */
2880
 
        table_2->setReadSet(field_2->position());
 
3380
        table_2->setReadSet(field_2->field_index);
2881
3381
        table_2->covering_keys&= field_2->part_of_key;
2882
3382
        table_2->merge_keys|= field_2->part_of_key;
2883
3383
      }
2898
3398
  */
2899
3399
  result= false;
2900
3400
 
 
3401
err:
2901
3402
  return(result);
2902
3403
}
2903
3404
 
2939
3440
*/
2940
3441
 
2941
3442
static bool
2942
 
store_natural_using_join_columns(Session *session,
 
3443
store_natural_using_join_columns(Session *,
2943
3444
                                 TableList *natural_using_join,
2944
3445
                                 TableList *table_ref_1,
2945
3446
                                 TableList *table_ref_2,
2955
3456
 
2956
3457
  if (!(non_join_columns= new List<Natural_join_column>) ||
2957
3458
      !(natural_using_join->join_columns= new List<Natural_join_column>))
2958
 
  {
2959
 
    return(result);
2960
 
  }
 
3459
    goto err;
2961
3460
 
2962
3461
  /* Append the columns of the first join operand. */
2963
3462
  for (it_1.set(table_ref_1); !it_1.end_of_fields(); it_1.next())
2981
3480
  if (using_fields && found_using_fields < using_fields->elements)
2982
3481
  {
2983
3482
    String *using_field_name;
2984
 
    List<String>::iterator using_fields_it(using_fields->begin());
 
3483
    List_iterator_fast<String> using_fields_it(*using_fields);
2985
3484
    while ((using_field_name= using_fields_it++))
2986
3485
    {
2987
3486
      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());
 
3487
      List_iterator_fast<Natural_join_column>
 
3488
        it(*(natural_using_join->join_columns));
2990
3489
      Natural_join_column *common_field;
2991
3490
 
2992
3491
      for (;;)
2995
3494
        if (!(common_field= it++))
2996
3495
        {
2997
3496
          my_error(ER_BAD_FIELD_ERROR, MYF(0), using_field_name_ptr,
2998
 
                   session->where());
2999
 
          return(result);
 
3497
                   current_session->where);
 
3498
          goto err;
3000
3499
        }
3001
3500
        if (!my_strcasecmp(system_charset_info,
3002
3501
                           common_field->name(), using_field_name_ptr))
3024
3523
 
3025
3524
  result= false;
3026
3525
 
 
3526
err:
3027
3527
  return(result);
3028
3528
}
3029
3529
 
3066
3566
  bool result= true;
3067
3567
 
3068
3568
  /* Call the procedure recursively for each nested table reference. */
3069
 
  if (table_ref->getNestedJoin())
 
3569
  if (table_ref->nested_join)
3070
3570
  {
3071
 
    List<TableList>::iterator nested_it(table_ref->getNestedJoin()->join_list.begin());
 
3571
    List_iterator_fast<TableList> nested_it(table_ref->nested_join->join_list);
3072
3572
    TableList *same_level_left_neighbor= nested_it++;
3073
3573
    TableList *same_level_right_neighbor= NULL;
3074
3574
    /* Left/right-most neighbors, possibly at higher levels in the join tree. */
3093
3593
          cur_table_ref->outer_join & JOIN_TYPE_RIGHT)
3094
3594
      {
3095
3595
        /* This can happen only for JOIN ... ON. */
3096
 
        assert(table_ref->getNestedJoin()->join_list.elements == 2);
 
3596
        assert(table_ref->nested_join->join_list.elements == 2);
3097
3597
        std::swap(same_level_left_neighbor, cur_table_ref);
3098
3598
      }
3099
3599
 
3106
3606
      real_right_neighbor= (same_level_right_neighbor) ?
3107
3607
        same_level_right_neighbor : right_neighbor;
3108
3608
 
3109
 
      if (cur_table_ref->getNestedJoin() &&
 
3609
      if (cur_table_ref->nested_join &&
3110
3610
          store_top_level_join_columns(session, cur_table_ref,
3111
3611
                                       real_left_neighbor, real_right_neighbor))
3112
 
        return(result);
 
3612
        goto err;
3113
3613
      same_level_right_neighbor= cur_table_ref;
3114
3614
    }
3115
3615
  }
3120
3620
  */
3121
3621
  if (table_ref->is_natural_join)
3122
3622
  {
3123
 
    assert(table_ref->getNestedJoin() &&
3124
 
           table_ref->getNestedJoin()->join_list.elements == 2);
3125
 
    List<TableList>::iterator operand_it(table_ref->getNestedJoin()->join_list.begin());
 
3623
    assert(table_ref->nested_join &&
 
3624
           table_ref->nested_join->join_list.elements == 2);
 
3625
    List_iterator_fast<TableList> operand_it(table_ref->nested_join->join_list);
3126
3626
    /*
3127
3627
      Notice that the order of join operands depends on whether table_ref
3128
3628
      represents a LEFT or a RIGHT join. In a RIGHT join, the operands are
3141
3641
      std::swap(table_ref_1, table_ref_2);
3142
3642
    if (mark_common_columns(session, table_ref_1, table_ref_2,
3143
3643
                            using_fields, &found_using_fields))
3144
 
      return(result);
 
3644
      goto err;
3145
3645
 
3146
3646
    /*
3147
3647
      Swap the join operands back, so that we pick the columns of the second
3153
3653
    if (store_natural_using_join_columns(session, table_ref, table_ref_1,
3154
3654
                                         table_ref_2, using_fields,
3155
3655
                                         found_using_fields))
3156
 
      return(result);
 
3656
      goto err;
3157
3657
 
3158
3658
    /*
3159
3659
      Change NATURAL JOIN to JOIN ... ON. We do this for both operands
3186
3686
  }
3187
3687
  result= false; /* All is OK. */
3188
3688
 
 
3689
err:
3189
3690
  return(result);
3190
3691
}
3191
3692
 
3218
3719
                                         List<TableList> *from_clause,
3219
3720
                                         Name_resolution_context *context)
3220
3721
{
3221
 
  session->setWhere("from clause");
 
3722
  session->where= "from clause";
3222
3723
  if (from_clause->elements == 0)
3223
3724
    return false; /* We come here in the case of UNIONs. */
3224
3725
 
3225
 
  List<TableList>::iterator table_ref_it(from_clause->begin());
 
3726
  List_iterator_fast<TableList> table_ref_it(*from_clause);
3226
3727
  TableList *table_ref; /* Current table reference. */
3227
3728
  /* Table reference to the left of the current. */
3228
3729
  TableList *left_neighbor;
3272
3773
    return 0;
3273
3774
 
3274
3775
  Item *item;
3275
 
  List<Item>::iterator it(fields.begin());
 
3776
  List_iterator<Item> it(fields);
3276
3777
 
3277
 
  session->getLex()->current_select->cur_pos_in_select_list= 0;
 
3778
  session->lex->current_select->cur_pos_in_select_list= 0;
3278
3779
  while (wild_num && (item= it++))
3279
3780
  {
3280
3781
    if (item->type() == Item::FIELD_ITEM &&
3284
3785
    {
3285
3786
      uint32_t elem= fields.elements;
3286
3787
      bool any_privileges= ((Item_field *) item)->any_privileges;
3287
 
      Item_subselect *subsel= session->getLex()->current_select->master_unit()->item;
 
3788
      Item_subselect *subsel= session->lex->current_select->master_unit()->item;
3288
3789
      if (subsel &&
3289
3790
          subsel->substype() == Item_subselect::EXISTS_SUBS)
3290
3791
      {
3315
3816
      wild_num--;
3316
3817
    }
3317
3818
    else
3318
 
      session->getLex()->current_select->cur_pos_in_select_list++;
 
3819
      session->lex->current_select->cur_pos_in_select_list++;
3319
3820
  }
3320
 
  session->getLex()->current_select->cur_pos_in_select_list= UNDEF_POS;
 
3821
  session->lex->current_select->cur_pos_in_select_list= UNDEF_POS;
3321
3822
 
3322
3823
  return 0;
3323
3824
}
3332
3833
{
3333
3834
  register Item *item;
3334
3835
  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());
 
3836
  nesting_map save_allow_sum_func= session->lex->allow_sum_func;
 
3837
  List_iterator<Item> it(fields);
3337
3838
  bool save_is_item_list_lookup;
3338
3839
 
3339
3840
  session->mark_used_columns= mark_used_columns;
3340
3841
  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;
 
3842
    session->lex->allow_sum_func|= 1 << session->lex->current_select->nest_level;
 
3843
  session->where= Session::DEFAULT_WHERE;
 
3844
  save_is_item_list_lookup= session->lex->current_select->is_item_list_lookup;
 
3845
  session->lex->current_select->is_item_list_lookup= 0;
3345
3846
 
3346
3847
  /*
3347
3848
    To prevent fail on forward lookup we fill it with zerows,
3351
3852
    There is other way to solve problem: fill array with pointers to list,
3352
3853
    but it will be slower.
3353
3854
 
3354
 
    TODO-> remove it when (if) we made one list for allfields and ref_pointer_array
 
3855
TODO: remove it when (if) we made one list for allfields and
 
3856
ref_pointer_array
3355
3857
  */
3356
3858
  if (ref_pointer_array)
3357
 
  {
3358
3859
    memset(ref_pointer_array, 0, sizeof(Item *) * fields.elements);
3359
 
  }
3360
3860
 
3361
3861
  Item **ref= ref_pointer_array;
3362
 
  session->getLex()->current_select->cur_pos_in_select_list= 0;
 
3862
  session->lex->current_select->cur_pos_in_select_list= 0;
3363
3863
  while ((item= it++))
3364
3864
  {
3365
3865
    if ((!item->fixed && item->fix_fields(session, it.ref())) || (item= *(it.ref()))->check_cols(1))
3366
3866
    {
3367
 
      session->getLex()->current_select->is_item_list_lookup= save_is_item_list_lookup;
3368
 
      session->getLex()->allow_sum_func= save_allow_sum_func;
 
3867
      session->lex->current_select->is_item_list_lookup= save_is_item_list_lookup;
 
3868
      session->lex->allow_sum_func= save_allow_sum_func;
3369
3869
      session->mark_used_columns= save_mark_used_columns;
3370
3870
      return true;
3371
3871
    }
3375
3875
        sum_func_list)
3376
3876
      item->split_sum_func(session, ref_pointer_array, *sum_func_list);
3377
3877
    session->used_tables|= item->used_tables();
3378
 
    session->getLex()->current_select->cur_pos_in_select_list++;
 
3878
    session->lex->current_select->cur_pos_in_select_list++;
3379
3879
  }
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;
 
3880
  session->lex->current_select->is_item_list_lookup= save_is_item_list_lookup;
 
3881
  session->lex->current_select->cur_pos_in_select_list= UNDEF_POS;
3382
3882
 
3383
 
  session->getLex()->allow_sum_func= save_allow_sum_func;
 
3883
  session->lex->allow_sum_func= save_allow_sum_func;
3384
3884
  session->mark_used_columns= save_mark_used_columns;
3385
3885
  return(test(session->is_error()));
3386
3886
}
3549
4049
 
3550
4050
bool
3551
4051
insert_fields(Session *session, Name_resolution_context *context, const char *db_name,
3552
 
              const char *table_name, List<Item>::iterator *it,
 
4052
              const char *table_name, List_iterator<Item> *it,
3553
4053
              bool )
3554
4054
{
3555
4055
  Field_iterator_table_ref field_iterator;
3588
4088
    assert(tables->is_leaf_for_name_resolution());
3589
4089
 
3590
4090
    if ((table_name && my_strcasecmp(table_alias_charset, table_name, tables->alias)) ||
3591
 
        (db_name && my_strcasecmp(system_charset_info, tables->getSchemaName(),db_name)))
 
4091
        (db_name && strcasecmp(tables->db,db_name)))
3592
4092
      continue;
3593
4093
 
3594
4094
    /*
3624
4124
      if ((field= field_iterator.field()))
3625
4125
      {
3626
4126
        /* Mark fields as used to allow storage engine to optimze access */
3627
 
        field->getTable()->setReadSet(field->position());
 
4127
        field->table->setReadSet(field->field_index);
3628
4128
        if (table)
3629
4129
        {
3630
4130
          table->covering_keys&= field->part_of_key;
3652
4152
        }
3653
4153
      }
3654
4154
      else
3655
 
      {
3656
4155
        session->used_tables|= item->used_tables();
3657
 
      }
3658
 
 
3659
 
      session->getLex()->current_select->cur_pos_in_select_list++;
 
4156
      session->lex->current_select->cur_pos_in_select_list++;
3660
4157
    }
3661
4158
    /*
3662
4159
      In case of stored tables, all fields are considered as used,
3665
4162
      For NATURAL joins, used_tables is updated in the IF above.
3666
4163
    */
3667
4164
    if (table)
3668
 
      table->used_fields= table->getShare()->sizeFields();
 
4165
      table->used_fields= table->getShare()->fields;
3669
4166
  }
3670
4167
  if (found)
3671
4168
    return false;
3675
4172
    qualified '*', and all columns were coalesced, we have to give a more
3676
4173
    meaningful message than ER_BAD_TABLE_ERROR.
3677
4174
  */
3678
 
  if (not table_name)
3679
 
  {
 
4175
  if (!table_name)
3680
4176
    my_message(ER_NO_TABLES_USED, ER(ER_NO_TABLES_USED), MYF(0));
3681
 
  }
3682
4177
  else
3683
 
  {
3684
4178
    my_error(ER_BAD_TABLE_ERROR, MYF(0), table_name);
3685
 
  }
3686
4179
 
3687
4180
  return true;
3688
4181
}
3709
4202
int Session::setup_conds(TableList *leaves, COND **conds)
3710
4203
{
3711
4204
  Session *session= this;
3712
 
  Select_Lex *select_lex= session->getLex()->current_select;
 
4205
  Select_Lex *select_lex= session->lex->current_select;
3713
4206
  TableList *table= NULL;       // For HP compilers
3714
4207
  void *save_session_marker= session->session_marker;
3715
4208
  /*
3731
4224
  session->session_marker= (void*)1;
3732
4225
  if (*conds)
3733
4226
  {
3734
 
    session->setWhere("where clause");
 
4227
    session->where="where clause";
3735
4228
    if ((!(*conds)->fixed && (*conds)->fix_fields(session, conds)) ||
3736
4229
        (*conds)->check_cols(1))
3737
4230
      goto err_no_arena;
3753
4246
      {
3754
4247
        /* Make a join an a expression */
3755
4248
        session->session_marker= (void*)embedded;
3756
 
        session->setWhere("on clause");
 
4249
        session->where="on clause";
3757
4250
        if ((!embedded->on_expr->fixed && embedded->on_expr->fix_fields(session, &embedded->on_expr)) ||
3758
4251
            embedded->on_expr->check_cols(1))
3759
4252
          goto err_no_arena;
3760
4253
        select_lex->cond_count++;
3761
4254
      }
3762
 
      embedding= embedded->getEmbedding();
 
4255
      embedding= embedded->embedding;
3763
4256
    }
3764
4257
    while (embedding &&
3765
 
           embedding->getNestedJoin()->join_list.head() == embedded);
 
4258
           embedding->nested_join->join_list.head() == embedded);
3766
4259
 
3767
4260
  }
3768
4261
  session->session_marker= save_session_marker;
3769
4262
 
3770
 
  session->getLex()->current_select->is_item_list_lookup= save_is_item_list_lookup;
 
4263
  session->lex->current_select->is_item_list_lookup= save_is_item_list_lookup;
3771
4264
  return(test(session->is_error()));
3772
4265
 
3773
4266
err_no_arena:
3805
4298
bool
3806
4299
fill_record(Session *session, List<Item> &fields, List<Item> &values, bool ignore_errors)
3807
4300
{
3808
 
  List<Item>::iterator f(fields.begin());
3809
 
  List<Item>::iterator v(values.begin());
 
4301
  List_iterator_fast<Item> f(fields),v(values);
3810
4302
  Item *value;
3811
4303
  Item_field *field;
3812
4304
  Table *table;
3822
4314
      thus we safely can take table from the first field.
3823
4315
    */
3824
4316
    field= static_cast<Item_field *>(f++);
3825
 
    table= field->field->getTable();
 
4317
    table= field->field->table;
3826
4318
    table->auto_increment_field_not_null= false;
3827
 
    f= fields.begin();
 
4319
    f.rewind();
3828
4320
  }
3829
4321
 
3830
4322
  while ((field= static_cast<Item_field *>(f++)))
3832
4324
    value= v++;
3833
4325
 
3834
4326
    Field *rfield= field->field;
3835
 
    table= rfield->getTable();
 
4327
    table= rfield->table;
3836
4328
 
3837
4329
    if (rfield == table->next_number_field)
3838
4330
      table->auto_increment_field_not_null= true;
3839
4331
    if ((value->save_in_field(rfield, 0) < 0) && !ignore_errors)
3840
4332
    {
3841
4333
      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;
 
4334
      goto err;
3846
4335
    }
3847
4336
  }
3848
4337
 
3849
4338
  return session->is_error();
 
4339
 
 
4340
err:
 
4341
  if (table)
 
4342
    table->auto_increment_field_not_null= false;
 
4343
 
 
4344
  return true;
3850
4345
}
3851
4346
 
3852
4347
 
3871
4366
 
3872
4367
bool fill_record(Session *session, Field **ptr, List<Item> &values, bool)
3873
4368
{
3874
 
  List<Item>::iterator v(values.begin());
 
4369
  List_iterator_fast<Item> v(values);
3875
4370
  Item *value;
3876
4371
  Table *table= 0;
3877
4372
  Field *field;
3886
4381
      On INSERT or UPDATE fields are checked to be from the same table,
3887
4382
      thus we safely can take table from the first field.
3888
4383
    */
3889
 
    table= (*ptr)->getTable();
 
4384
    table= (*ptr)->table;
3890
4385
    table->auto_increment_field_not_null= false;
3891
4386
  }
3892
 
 
3893
4387
  while ((field = *ptr++) && ! session->is_error())
3894
4388
  {
3895
4389
    value=v++;
3896
 
    table= field->getTable();
3897
 
 
 
4390
    table= field->table;
3898
4391
    if (field == table->next_number_field)
3899
4392
      table->auto_increment_field_not_null= true;
3900
 
 
3901
4393
    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
 
    }
 
4394
      goto err;
3908
4395
  }
3909
4396
 
3910
4397
  return(session->is_error());
 
4398
 
 
4399
err:
 
4400
  if (table)
 
4401
    table->auto_increment_field_not_null= false;
 
4402
 
 
4403
  return true;
3911
4404
}
3912
4405
 
3913
4406
 
3914
4407
bool drizzle_rm_tmp_tables()
3915
4408
{
 
4409
  Session *session;
3916
4410
 
3917
4411
  assert(drizzle_tmpdir.size());
3918
 
  Session::shared_ptr session= Session::make_shared(plugin::Listen::getNullClient(), catalog::local());
3919
4412
 
3920
 
  if (not session)
 
4413
  if (!(session= new Session(plugin::Listen::getNullClient())))
3921
4414
    return true;
3922
 
  session->thread_stack= (char*) session.get();
 
4415
  session->thread_stack= (char*) &session;
3923
4416
  session->storeGlobals();
3924
4417
 
3925
4418
  plugin::StorageEngine::removeLostTemporaryTables(*session, drizzle_tmpdir.c_str());
3926
4419
 
 
4420
  delete session;
 
4421
 
3927
4422
  return false;
3928
4423
}
3929
4424
 
3933
4428
  unireg support functions
3934
4429
 *****************************************************************************/
3935
4430
 
3936
 
 
 
4431
/*
 
4432
  Invalidate any cache entries that are for some DB
 
4433
 
 
4434
  SYNOPSIS
 
4435
  remove_db_from_cache()
 
4436
  db            Database name. This will be in lower case if
 
4437
  lower_case_table_name is set
 
4438
 
 
4439
NOTE:
 
4440
We can't use hash_delete when looping hash_elements. We mark them first
 
4441
and afterwards delete those marked unused.
 
4442
*/
 
4443
 
 
4444
void remove_db_from_cache(SchemaIdentifier &schema_identifier)
 
4445
{
 
4446
  safe_mutex_assert_owner(&LOCK_open);
 
4447
 
 
4448
  for (uint32_t idx=0 ; idx < open_cache.records ; idx++)
 
4449
  {
 
4450
    Table *table=(Table*) hash_element(&open_cache,idx);
 
4451
    if (not schema_identifier.getPath().compare(table->getMutableShare()->getSchemaName()))
 
4452
    {
 
4453
      table->getMutableShare()->version= 0L;                    /* Free when thread is ready */
 
4454
      if (not table->in_use)
 
4455
        relink_unused(table);
 
4456
    }
 
4457
  }
 
4458
  while (unused_tables && !unused_tables->getShare()->version)
 
4459
    hash_delete(&open_cache,(unsigned char*) unused_tables);
 
4460
}
 
4461
 
 
4462
 
 
4463
/*
 
4464
  Mark all entries with the table as deleted to force an reopen of the table
 
4465
 
 
4466
  The table will be closed (not stored in cache) by the current thread when
 
4467
  close_thread_tables() is called.
 
4468
 
 
4469
  PREREQUISITES
 
4470
  Lock on LOCK_open()
 
4471
 
 
4472
  RETURN
 
4473
  0  This thread now have exclusive access to this table and no other thread
 
4474
  can access the table until close_thread_tables() is called.
 
4475
  1  Table is in use by another thread
 
4476
*/
 
4477
 
 
4478
bool remove_table_from_cache(Session *session, const char *db, const char *table_name,
 
4479
                             uint32_t flags)
 
4480
{
 
4481
  char key[MAX_DBKEY_LENGTH];
 
4482
  char *key_pos= key;
 
4483
  uint32_t key_length;
 
4484
  Table *table;
 
4485
  bool result= false; 
 
4486
  bool signalled= false;
 
4487
 
 
4488
  key_pos= strcpy(key_pos, db) + strlen(db);
 
4489
  key_pos= strcpy(key_pos+1, table_name) + strlen(table_name);
 
4490
  key_length= (uint32_t) (key_pos-key)+1;
 
4491
 
 
4492
  for (;;)
 
4493
  {
 
4494
    HASH_SEARCH_STATE state;
 
4495
    result= signalled= false;
 
4496
 
 
4497
    for (table= (Table*) hash_first(&open_cache, (unsigned char*) key, key_length,
 
4498
                                    &state);
 
4499
         table;
 
4500
         table= (Table*) hash_next(&open_cache, (unsigned char*) key, key_length,
 
4501
                                   &state))
 
4502
    {
 
4503
      Session *in_use;
 
4504
 
 
4505
      table->getMutableShare()->version=0L;             /* Free when thread is ready */
 
4506
      if (!(in_use=table->in_use))
 
4507
      {
 
4508
        relink_unused(table);
 
4509
      }
 
4510
      else if (in_use != session)
 
4511
      {
 
4512
        /*
 
4513
          Mark that table is going to be deleted from cache. This will
 
4514
          force threads that are in mysql_lock_tables() (but not yet
 
4515
          in thr_multi_lock()) to abort it's locks, close all tables and retry
 
4516
        */
 
4517
        in_use->some_tables_deleted= true;
 
4518
        if (table->is_name_opened())
 
4519
        {
 
4520
          result= true;
 
4521
        }
 
4522
        /*
 
4523
          Now we must abort all tables locks used by this thread
 
4524
          as the thread may be waiting to get a lock for another table.
 
4525
          Note that we need to hold LOCK_open while going through the
 
4526
          list. So that the other thread cannot change it. The other
 
4527
          thread must also hold LOCK_open whenever changing the
 
4528
          open_tables list. Aborting the MERGE lock after a child was
 
4529
          closed and before the parent is closed would be fatal.
 
4530
        */
 
4531
        for (Table *session_table= in_use->open_tables;
 
4532
             session_table ;
 
4533
             session_table= session_table->next)
 
4534
        {
 
4535
          /* Do not handle locks of MERGE children. */
 
4536
          if (session_table->db_stat)   // If table is open
 
4537
            signalled|= mysql_lock_abort_for_thread(session, session_table);
 
4538
        }
 
4539
      }
 
4540
      else
 
4541
        result= result || (flags & RTFC_OWNED_BY_Session_FLAG);
 
4542
    }
 
4543
    while (unused_tables && !unused_tables->getShare()->version)
 
4544
      hash_delete(&open_cache,(unsigned char*) unused_tables);
 
4545
 
 
4546
    /* Remove table from table definition cache if it's not in use */
 
4547
    TableShare::release(key, key_length);
 
4548
 
 
4549
    if (result && (flags & RTFC_WAIT_OTHER_THREAD_FLAG))
 
4550
    {
 
4551
      /*
 
4552
        Signal any thread waiting for tables to be freed to
 
4553
        reopen their tables
 
4554
      */
 
4555
      broadcast_refresh();
 
4556
      if (!(flags & RTFC_CHECK_KILLED_FLAG) || !session->killed)
 
4557
      {
 
4558
        dropping_tables++;
 
4559
        if (likely(signalled))
 
4560
          (void) pthread_cond_wait(&COND_refresh, &LOCK_open);
 
4561
        else
 
4562
        {
 
4563
          struct timespec abstime;
 
4564
          /*
 
4565
            It can happen that another thread has opened the
 
4566
            table but has not yet locked any table at all. Since
 
4567
            it can be locked waiting for a table that our thread
 
4568
            has done LOCK Table x WRITE on previously, we need to
 
4569
            ensure that the thread actually hears our signal
 
4570
            before we go to sleep. Thus we wait for a short time
 
4571
            and then we retry another loop in the
 
4572
            remove_table_from_cache routine.
 
4573
          */
 
4574
          set_timespec(abstime, 10);
 
4575
          pthread_cond_timedwait(&COND_refresh, &LOCK_open, &abstime);
 
4576
        }
 
4577
        dropping_tables--;
 
4578
        continue;
 
4579
      }
 
4580
    }
 
4581
    break;
 
4582
  }
 
4583
  return result;
 
4584
}
3937
4585
 
3938
4586
 
3939
4587
/**