~drizzle-trunk/drizzle/development

« back to all changes in this revision

Viewing changes to drizzled/sql_base.cc

Cleaned up a few global tests which aren't happy now.

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 <drizzled/server_includes.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 <mysys/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 <mysys/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
 
 
61
 
#include <drizzled/refresh_version.h>
 
49
#include "drizzled/memory/multi_malloc.h"
62
50
 
63
51
using namespace std;
64
 
 
65
 
namespace drizzled
66
 
{
67
 
 
68
 
extern bool volatile shutdown_in_progress;
 
52
using namespace drizzled;
 
53
 
 
54
bool drizzle_rm_tmp_tables();
 
55
 
 
56
/**
 
57
  @defgroup Data_Dictionary Data Dictionary
 
58
  @{
 
59
*/
 
60
Table *unused_tables;                           /* Used by mysql_test */
 
61
HASH open_cache;                                /* Used by mysql_test */
 
62
static int open_unireg_entry(Session *session, Table *entry, TableList *table_list,
 
63
                             const char *alias,
 
64
                             char *cache_key, uint32_t cache_key_length);
 
65
extern "C"
 
66
{
 
67
  void free_cache_entry(void *entry);
 
68
  unsigned char *table_cache_key(const unsigned char *record,
 
69
                                 size_t *length,
 
70
                                 bool );
 
71
}
 
72
 
 
73
 
 
74
 
 
75
unsigned char *table_cache_key(const unsigned char *record,
 
76
                               size_t *length,
 
77
                               bool )
 
78
{
 
79
  Table *entry=(Table*) record;
 
80
  *length= entry->s->table_cache_key.length;
 
81
  return (unsigned char*) entry->s->table_cache_key.str;
 
82
}
 
83
 
69
84
 
70
85
bool table_cache_init(void)
71
86
{
72
 
  return false;
73
 
}
74
 
 
75
 
uint32_t cached_open_tables(void)
76
 
{
77
 
  return table::getCache().size();
 
87
  return hash_init(&open_cache, &my_charset_bin,
 
88
                   (size_t) table_cache_size+16,
 
89
                   0, 0, table_cache_key,
 
90
                   free_cache_entry, 0);
78
91
}
79
92
 
80
93
void table_cache_free(void)
81
94
{
82
95
  refresh_version++;                            // Force close of open tables
83
96
 
84
 
  table::getUnused().clear();
85
 
  table::getCache().clear();
86
 
}
 
97
  while (unused_tables)
 
98
    hash_delete(&open_cache,(unsigned char*) unused_tables);
 
99
 
 
100
  if (!open_cache.records)                      // Safety first
 
101
    hash_free(&open_cache);
 
102
}
 
103
 
 
104
uint32_t cached_open_tables(void)
 
105
{
 
106
  return open_cache.records;
 
107
}
 
108
 
87
109
 
88
110
/*
89
 
  Close cursor handle, but leave the table in the table cache
 
111
  Close file handle, but leave the table in the table cache
90
112
 
91
113
  SYNOPSIS
92
114
  close_handle_and_leave_table_as_lock()
96
118
  By leaving the table in the table cache, it disallows any other thread
97
119
  to open the table
98
120
 
99
 
  session->getKilled() will be set if we run out of memory
 
121
  session->killed will be set if we run out of memory
100
122
 
101
123
  If closing a MERGE child, the calling function has to take care for
102
124
  closing the parent too, if necessary.
105
127
 
106
128
void close_handle_and_leave_table_as_lock(Table *table)
107
129
{
 
130
  TableShare *share, *old_share= table->s;
 
131
  char *key_buff;
 
132
  MEM_ROOT *mem_root= &table->mem_root;
 
133
 
108
134
  assert(table->db_stat);
109
 
  assert(table->getShare()->getType() == message::Table::STANDARD);
110
135
 
111
136
  /*
112
137
    Make a local copy of the table share and free the current one.
113
138
    This has to be done to ensure that the table share is removed from
114
139
    the table defintion cache as soon as the last instance is removed
115
140
  */
116
 
  identifier::Table identifier(table->getShare()->getSchemaName(), table->getShare()->getTableName(), message::Table::INTERNAL);
117
 
  const identifier::Table::Key &key(identifier.getKey());
118
 
  TableShare *share= new TableShare(identifier.getType(),
119
 
                                    identifier,
120
 
                                    const_cast<char *>(key.vector()),  static_cast<uint32_t>(table->getShare()->getCacheKeySize()));
121
 
 
122
 
  table->cursor->close();
123
 
  table->db_stat= 0;                            // Mark cursor closed
124
 
  table::instance::release(table->getMutableShare());
125
 
  table->setShare(share);
126
 
}
127
 
 
 
141
  if (multi_alloc_root(mem_root,
 
142
                       &share, sizeof(*share),
 
143
                       &key_buff, old_share->table_cache_key.length,
 
144
                       NULL))
 
145
  {
 
146
    memset(share, 0, sizeof(*share));
 
147
    share->set_table_cache_key(key_buff, old_share->table_cache_key.str,
 
148
                               old_share->table_cache_key.length);
 
149
    share->tmp_table= INTERNAL_TMP_TABLE;       // for intern_close_table()
 
150
  }
 
151
 
 
152
  table->file->close();
 
153
  table->db_stat= 0;                            // Mark file closed
 
154
  TableShare::release(table->s);
 
155
  table->s= share;
 
156
  table->file->change_table_ptr(table, table->s);
 
157
}
 
158
 
 
159
 
 
160
 
 
161
/*
 
162
  Create a list for all open tables matching SQL expression
 
163
 
 
164
  SYNOPSIS
 
165
  list_open_tables()
 
166
  wild          SQL like expression
 
167
 
 
168
  NOTES
 
169
  One gets only a list of tables for which one has any kind of privilege.
 
170
  db and table names are allocated in result struct, so one doesn't need
 
171
  a lock on LOCK_open when traversing the return list.
 
172
 
 
173
  RETURN VALUES
 
174
  true  Error 
 
175
*/
 
176
 
 
177
bool list_open_tables(const char *db, const char *wild, bool(*func)(Table *table, open_table_list_st& open_list), Table *display)
 
178
{
 
179
  vector<open_table_list_st> open_list;
 
180
  vector<open_table_list_st>::iterator it;
 
181
  open_table_list_st table;
 
182
 
 
183
  /* What we really need is an optimization for knowing unique tables */
 
184
  if (db && wild)
 
185
    open_list.reserve(sizeof(open_table_list_st) * (open_cache.records % 2));
 
186
  else
 
187
    open_list.reserve(sizeof(open_table_list_st) * open_cache.records);
 
188
 
 
189
  pthread_mutex_lock(&LOCK_open); /* List all open tables */
 
190
 
 
191
  for (uint32_t idx= 0; idx < open_cache.records; idx++)
 
192
  {
 
193
    bool found= false;
 
194
    Table *entry=(Table*) hash_element(&open_cache,idx);
 
195
 
 
196
    if (db && my_strcasecmp(system_charset_info, db, entry->s->db.str))
 
197
      continue;
 
198
    if (wild && wild_compare(entry->s->table_name.str, wild, 0))
 
199
      continue;
 
200
 
 
201
    for (it= open_list.begin(); it < open_list.end(); it++)
 
202
    {
 
203
      if (!(*it).table.compare(entry->s->table_name.str) &&
 
204
          !(*it).db.compare(entry->s->db.str))
 
205
      {
 
206
        if (entry->in_use)
 
207
          (*it).in_use++;
 
208
        if (entry->locked_by_name)
 
209
          (*it).locked++;
 
210
 
 
211
        found= true;
 
212
 
 
213
        break;
 
214
      }
 
215
    }
 
216
 
 
217
    if (found)
 
218
      continue;
 
219
 
 
220
    table.db= entry->s->db.str;
 
221
    table.table= entry->s->table_name.str;
 
222
    open_list.push_back(table);
 
223
  }
 
224
  pthread_mutex_unlock(&LOCK_open);
 
225
 
 
226
  for (it= open_list.begin(); it < open_list.end(); it++)
 
227
  {
 
228
    if (func(display, *it))
 
229
      return true;
 
230
  }
 
231
 
 
232
  return false;
 
233
}
128
234
 
129
235
/*****************************************************************************
130
236
 *       Functions to free open table cache
134
240
void Table::intern_close_table()
135
241
{                                               // Free all structures
136
242
  free_io_cache();
137
 
  if (cursor)                              // Not true if name lock
 
243
  if (file)                              // Not true if name lock
 
244
    closefrm(true);                     // close file
 
245
}
 
246
 
 
247
/*
 
248
  Remove table from the open table cache
 
249
 
 
250
  SYNOPSIS
 
251
  free_cache_entry()
 
252
  entry         Table to remove
 
253
 
 
254
  NOTE
 
255
  We need to have a lock on LOCK_open when calling this
 
256
*/
 
257
 
 
258
void free_cache_entry(void *entry)
 
259
{
 
260
  Table *table= static_cast<Table *>(entry);
 
261
  table->intern_close_table();
 
262
  if (!table->in_use)
138
263
  {
139
 
    delete_table(true);                 // close cursor
 
264
    table->next->prev=table->prev;              /* remove from used chain */
 
265
    table->prev->next=table->next;
 
266
    if (table == unused_tables)
 
267
    {
 
268
      unused_tables=unused_tables->next;
 
269
      if (table == unused_tables)
 
270
        unused_tables= NULL;
 
271
    }
140
272
  }
 
273
  free(table);
141
274
}
142
275
 
143
276
/* Free resources allocated by filesort() and read_record() */
146
279
{
147
280
  if (sort.io_cache)
148
281
  {
149
 
    sort.io_cache->close_cached_file();
 
282
    close_cached_file(sort.io_cache);
150
283
    delete sort.io_cache;
151
284
    sort.io_cache= 0;
152
285
  }
158
291
 
159
292
  @param session Thread context (may be NULL)
160
293
  @param tables List of tables to remove from the cache
161
 
  @param have_lock If table::Cache::singleton().mutex() is locked
 
294
  @param have_lock If LOCK_open is locked
162
295
  @param wait_for_refresh Wait for a impending flush
163
296
  @param wait_for_placeholders Wait for tables being reopened so that the GRL
164
297
  won't proceed while write-locked tables are being reopened by other
173
306
  bool result= false;
174
307
  Session *session= this;
175
308
 
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
 
      {
 
309
  pthread_mutex_lock(&LOCK_open); /* Optionally lock for remove tables from open_cahe if not in use */
 
310
 
 
311
  if (tables == NULL)
 
312
  {
 
313
    refresh_version++;                          // Force close of open tables
 
314
    while (unused_tables)
 
315
      hash_delete(&open_cache,(unsigned char*) unused_tables);
 
316
 
 
317
    if (wait_for_refresh)
 
318
    {
 
319
      /*
 
320
        Other threads could wait in a loop in open_and_lock_tables(),
 
321
        trying to lock one or more of our tables.
 
322
 
 
323
        If they wait for the locks in thr_multi_lock(), their lock
 
324
        request is aborted. They loop in open_and_lock_tables() and
 
325
        enter open_table(). Here they notice the table is refreshed and
 
326
        wait for COND_refresh. Then they loop again in
 
327
        openTablesLock() and this time open_table() succeeds. At
 
328
        this moment, if we (the FLUSH TABLES thread) are scheduled and
 
329
        on another FLUSH TABLES enter close_cached_tables(), they could
 
330
        awake while we sleep below, waiting for others threads (us) to
 
331
        close their open tables. If this happens, the other threads
 
332
        would find the tables unlocked. They would get the locks, one
 
333
        after the other, and could do their destructive work. This is an
 
334
        issue if we have LOCK TABLES in effect.
 
335
 
 
336
        The problem is that the other threads passed all checks in
 
337
        open_table() before we refresh the table.
 
338
 
 
339
        The fix for this problem is to set some_tables_deleted for all
 
340
        threads with open tables. These threads can still get their
 
341
        locks, but will immediately release them again after checking
 
342
        this variable. They will then loop in openTablesLock()
 
343
        again. There they will wait until we update all tables version
 
344
        below.
 
345
 
 
346
        Setting some_tables_deleted is done by remove_table_from_cache()
 
347
        in the other branch.
 
348
 
 
349
        In other words (reviewer suggestion): You need this setting of
 
350
        some_tables_deleted for the case when table was opened and all
 
351
        related checks were passed before incrementing refresh_version
 
352
        (which you already have) but attempt to lock the table happened
 
353
        after the call to Session::close_old_data_files() i.e. after removal of
 
354
        current thread locks.
 
355
      */
 
356
      for (uint32_t idx=0 ; idx < open_cache.records ; idx++)
 
357
      {
 
358
        Table *table=(Table*) hash_element(&open_cache,idx);
 
359
        if (table->in_use)
 
360
          table->in_use->some_tables_deleted= false;
 
361
      }
 
362
    }
 
363
  }
 
364
  else
 
365
  {
 
366
    bool found= false;
 
367
    for (TableList *table= tables; table; table= table->next_local)
 
368
    {
 
369
      if (remove_table_from_cache(session, table->db, table->table_name,
 
370
                                  RTFC_OWNED_BY_Session_FLAG))
 
371
        found= true;
 
372
    }
 
373
    if (!found)
 
374
      wait_for_refresh= false;                  // Nothing to wait for
 
375
  }
 
376
 
 
377
  if (wait_for_refresh)
 
378
  {
 
379
    /*
 
380
      If there is any table that has a lower refresh_version, wait until
 
381
      this is closed (or this thread is killed) before returning
 
382
    */
 
383
    session->mysys_var->current_mutex= &LOCK_open;
 
384
    session->mysys_var->current_cond= &COND_refresh;
 
385
    session->set_proc_info("Flushing tables");
 
386
 
 
387
    session->close_old_data_files();
 
388
 
 
389
    bool found= true;
 
390
    /* Wait until all threads has closed all the tables we had locked */
 
391
    while (found && ! session->killed)
 
392
    {
 
393
      found= false;
 
394
      for (uint32_t idx=0 ; idx < open_cache.records ; idx++)
 
395
      {
 
396
        Table *table=(Table*) hash_element(&open_cache,idx);
 
397
        /* Avoid a self-deadlock. */
 
398
        if (table->in_use == session)
 
399
          continue;
187
400
        /*
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.
 
401
          Note that we wait here only for tables which are actually open, and
 
402
          not for placeholders with Table::open_placeholder set. Waiting for
 
403
          latter will cause deadlock in the following scenario, for example:
 
404
 
 
405
conn1: lock table t1 write;
 
406
conn2: lock table t2 write;
 
407
conn1: flush tables;
 
408
conn2: flush tables;
 
409
 
 
410
It also does not make sense to wait for those of placeholders that
 
411
are employed by CREATE TABLE as in this case table simply does not
 
412
exist yet.
223
413
        */
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))
 
414
        if (table->needs_reopen_or_name_lock() && (table->db_stat ||
 
415
                                                   (table->open_placeholder && wait_for_placeholders)))
242
416
        {
243
417
          found= true;
 
418
          pthread_cond_wait(&COND_refresh,&LOCK_open);
 
419
          break;
244
420
        }
245
421
      }
246
 
      if (!found)
247
 
        wait_for_refresh= false;                        // Nothing to wait for
248
422
    }
 
423
    /*
 
424
      No other thread has the locked tables open; reopen them and get the
 
425
      old locks. This should always succeed (unless some external process
 
426
      has removed the tables)
 
427
    */
 
428
    result= session->reopen_tables(true, true);
249
429
 
250
 
    if (wait_for_refresh)
 
430
    /* Set version for table */
 
431
    for (Table *table= session->open_tables; table ; table= table->next)
251
432
    {
252
433
      /*
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
 
      }
 
434
        Preserve the version (0) of write locked tables so that a impending
 
435
        global read lock won't sneak in.
 
436
      */
 
437
      if (table->reginfo.lock_type < TL_WRITE_ALLOW_WRITE)
 
438
        table->s->version= refresh_version;
315
439
    }
316
440
  }
317
441
 
 
442
  pthread_mutex_unlock(&LOCK_open);
 
443
 
318
444
  if (wait_for_refresh)
319
445
  {
320
 
    boost_unique_lock_t scopedLock(session->mysys_var->mutex);
 
446
    pthread_mutex_lock(&session->mysys_var->mutex);
321
447
    session->mysys_var->current_mutex= 0;
322
448
    session->mysys_var->current_cond= 0;
323
449
    session->set_proc_info(0);
 
450
    pthread_mutex_unlock(&session->mysys_var->mutex);
324
451
  }
325
452
 
326
453
  return result;
331
458
  move one table to free list 
332
459
*/
333
460
 
334
 
bool Session::free_cached_table(boost::mutex::scoped_lock &scopedLock)
 
461
bool Session::free_cached_table()
335
462
{
336
463
  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());
 
464
  Table *table= open_tables;
 
465
 
 
466
  safe_mutex_assert_owner(&LOCK_open);
343
467
  assert(table->key_read == 0);
344
 
  assert(!table->cursor || table->cursor->inited == Cursor::NONE);
 
468
  assert(!table->file || table->file->inited == Cursor::NONE);
345
469
 
346
 
  open_tables= table->getNext();
 
470
  open_tables= table->next;
347
471
 
348
472
  if (table->needs_reopen_or_name_lock() ||
349
473
      version != refresh_version || !table->db_stat)
350
474
  {
351
 
    table::remove_table(table);
 
475
    hash_delete(&open_cache,(unsigned char*) table);
352
476
    found_old_table= true;
353
477
  }
354
478
  else
357
481
      Open placeholders have Table::db_stat set to 0, so they should be
358
482
      handled by the first alternative.
359
483
    */
360
 
    assert(not table->open_placeholder);
 
484
    assert(!table->open_placeholder);
361
485
 
362
486
    /* Free memory and reset for next loop */
363
 
    table->cursor->ha_reset();
364
 
    table->in_use= NULL;
 
487
    table->file->ha_reset();
 
488
    table->in_use= false;
365
489
 
366
 
    table::getUnused().link(table);
 
490
    if (unused_tables)
 
491
    {
 
492
      table->next= unused_tables;               /* Link in last */
 
493
      table->prev= unused_tables->prev;
 
494
      unused_tables->prev= table;
 
495
      table->prev->next= table;
 
496
    }
 
497
    else
 
498
      unused_tables= table->next=table->prev=table;
367
499
  }
368
500
 
369
501
  return found_old_table;
382
514
{
383
515
  bool found_old_table= false;
384
516
 
385
 
  safe_mutex_assert_not_owner(table::Cache::singleton().mutex().native_handle());
 
517
  safe_mutex_assert_not_owner(&LOCK_open);
386
518
 
387
 
  boost_unique_lock_t scoped_lock(table::Cache::singleton().mutex()); /* Close all open tables on Session */
 
519
  pthread_mutex_lock(&LOCK_open); /* Close all open tables on Session */
388
520
 
389
521
  while (open_tables)
390
 
  {
391
 
    found_old_table|= free_cached_table(scoped_lock);
392
 
  }
 
522
    found_old_table|= free_cached_table();
393
523
  some_tables_deleted= false;
394
524
 
395
525
  if (found_old_table)
396
526
  {
397
527
    /* Tell threads waiting for refresh that something has happened */
398
 
    locking::broadcast_refresh();
 
528
    broadcast_refresh();
399
529
  }
 
530
 
 
531
  pthread_mutex_unlock(&LOCK_open);
400
532
}
401
533
 
402
534
/*
424
556
{
425
557
  for (; table; table= table->*link )
426
558
  {
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
 
    {
 
559
    if ((table->table == 0 || table->table->s->tmp_table == NO_TMP_TABLE) &&
 
560
        strcmp(table->db, db_name) == 0 &&
 
561
        strcmp(table->table_name, table_name) == 0)
431
562
      break;
432
 
    }
433
563
  }
434
564
  return table;
435
565
}
471
601
0 if table is unique
472
602
*/
473
603
 
474
 
TableList* unique_table(TableList *table, TableList *table_list,
 
604
TableList* unique_table(Session *session, TableList *table, TableList *table_list,
475
605
                        bool check_alias)
476
606
{
477
607
  TableList *res;
490
620
  if (table->table)
491
621
  {
492
622
    /* temporary table is always unique */
493
 
    if (table->table && table->table->getShare()->getType() != message::Table::STANDARD)
 
623
    if (table->table && table->table->s->tmp_table != NO_TMP_TABLE)
494
624
      return 0;
495
625
    table= table->find_underlying_table(table->table);
496
626
    /*
499
629
    */
500
630
    assert(table);
501
631
  }
502
 
  d_name= table->getSchemaName();
503
 
  t_name= table->getTableName();
 
632
  d_name= table->db;
 
633
  t_name= table->table_name;
504
634
  t_alias= table->alias;
505
635
 
506
636
  for (;;)
507
637
  {
508
 
    if ((! (res= find_table_in_global_list(table_list, d_name, t_name))) ||
 
638
    if (((! (res= find_table_in_global_list(table_list, d_name, t_name))) &&
 
639
         (! (res= mysql_lock_have_duplicate(session, table, table_list)))) ||
509
640
        ((!res->table || res->table != table->table) &&
510
641
         (!check_alias || !(my_strcasecmp(files_charset_info, t_alias, res->alias))) &&
511
642
         res->select_lex && !res->select_lex->exclude_from_table_unique_test))
521
652
}
522
653
 
523
654
 
524
 
void Open_tables_state::doGetTableNames(const identifier::Schema &schema_identifier,
525
 
                                        std::set<std::string>& set_of_names)
526
 
{
527
 
  for (Table *table= getTemporaryTables() ; table ; table= table->getNext())
528
 
  {
529
 
    if (schema_identifier.compare(table->getShare()->getSchemaName()))
530
 
    {
531
 
      set_of_names.insert(table->getShare()->getTableName());
532
 
    }
533
 
  }
534
 
}
535
 
 
536
 
void Open_tables_state::doGetTableNames(CachedDirectory &,
537
 
                                        const identifier::Schema &schema_identifier,
538
 
                                        std::set<std::string> &set_of_names)
539
 
{
540
 
  doGetTableNames(schema_identifier, set_of_names);
541
 
}
542
 
 
543
 
void Open_tables_state::doGetTableIdentifiers(const identifier::Schema &schema_identifier,
544
 
                                              identifier::Table::vector &set_of_identifiers)
545
 
{
546
 
  for (Table *table= getTemporaryTables() ; table ; table= table->getNext())
547
 
  {
548
 
    if (schema_identifier.compare(table->getShare()->getSchemaName()))
549
 
    {
550
 
      set_of_identifiers.push_back(identifier::Table(table->getShare()->getSchemaName(),
551
 
                                                   table->getShare()->getTableName(),
552
 
                                                   table->getShare()->getPath()));
553
 
    }
554
 
  }
555
 
}
556
 
 
557
 
void Open_tables_state::doGetTableIdentifiers(CachedDirectory &,
558
 
                                              const identifier::Schema &schema_identifier,
559
 
                                              identifier::Table::vector &set_of_identifiers)
560
 
{
561
 
  doGetTableIdentifiers(schema_identifier, set_of_identifiers);
562
 
}
563
 
 
564
 
bool Open_tables_state::doDoesTableExist(const identifier::Table &identifier)
565
 
{
566
 
  for (Table *table= getTemporaryTables() ; table ; table= table->getNext())
567
 
  {
568
 
    if (table->getShare()->getType() == message::Table::TEMPORARY)
569
 
    {
570
 
      if (identifier.getKey() == table->getShare()->getCacheKey())
571
 
      {
572
 
        return true;
573
 
      }
574
 
    }
575
 
  }
576
 
 
577
 
  return false;
578
 
}
579
 
 
580
 
int Open_tables_state::doGetTableDefinition(const identifier::Table &identifier,
581
 
                                            message::Table &table_proto)
582
 
{
583
 
  for (Table *table= getTemporaryTables() ; table ; table= table->getNext())
584
 
  {
585
 
    if (table->getShare()->getType() == message::Table::TEMPORARY)
586
 
    {
587
 
      if (identifier.getKey() == table->getShare()->getCacheKey())
588
 
      {
589
 
        table_proto.CopyFrom(*(table->getShare()->getTableMessage()));
590
 
 
591
 
        return EEXIST;
592
 
      }
593
 
    }
594
 
  }
595
 
 
596
 
  return ENOENT;
597
 
}
598
 
 
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())
 
655
Table *Session::find_temporary_table(const char *new_db, const char *table_name)
 
656
{
 
657
  char  key[MAX_DBKEY_LENGTH];
 
658
  uint  key_length;
 
659
  Table *table;
 
660
 
 
661
  key_length= TableShare::createKey(key, new_db, table_name);
 
662
 
 
663
  for (table= temporary_tables ; table ; table= table->next)
 
664
  {
 
665
    if (table->s->table_cache_key.length == key_length &&
 
666
        !memcmp(table->s->table_cache_key.str, key, key_length))
604
667
      return table;
605
668
  }
606
 
 
607
669
  return NULL;                               // Not a temporary table
608
670
}
609
671
 
 
672
Table *Session::find_temporary_table(TableList *table_list)
 
673
{
 
674
  return find_temporary_table(table_list->db, table_list->table_name);
 
675
}
 
676
 
610
677
 
611
678
/**
612
679
  Drop a temporary table.
634
701
  @retval -1  the table is in use by a outer query
635
702
*/
636
703
 
637
 
int Open_tables_state::drop_temporary_table(const drizzled::identifier::Table &identifier)
 
704
int Session::drop_temporary_table(TableList *table_list)
638
705
{
639
706
  Table *table;
640
707
 
641
 
  if (not (table= find_temporary_table(identifier)))
 
708
  if (!(table= find_temporary_table(table_list)))
642
709
    return 1;
643
710
 
644
711
  /* Table might be in use by some outer statement. */
645
 
  if (table->query_id && table->query_id != getQueryId())
 
712
  if (table->query_id && table->query_id != query_id)
646
713
  {
647
 
    my_error(ER_CANT_REOPEN_TABLE, MYF(0), table->getAlias());
 
714
    my_error(ER_CANT_REOPEN_TABLE, MYF(0), table->alias);
648
715
    return -1;
649
716
  }
650
717
 
651
 
  close_temporary_table(table);
 
718
  close_temporary_table(table, true, true);
652
719
 
653
720
  return 0;
654
721
}
655
722
 
656
723
 
 
724
/* move table first in unused links */
 
725
 
 
726
static void relink_unused(Table *table)
 
727
{
 
728
  if (table != unused_tables)
 
729
  {
 
730
    table->prev->next=table->next;              /* Remove from unused list */
 
731
    table->next->prev=table->prev;
 
732
    table->next=unused_tables;                  /* Link in unused tables */
 
733
    table->prev=unused_tables->prev;
 
734
    unused_tables->prev->next=table;
 
735
    unused_tables->prev=table;
 
736
    unused_tables=table;
 
737
  }
 
738
}
 
739
 
 
740
 
657
741
/**
658
742
  Remove all instances of table from thread's open list and
659
743
  table cache.
660
744
 
661
745
  @param  session     Thread context
662
746
  @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
747
*/
666
748
 
667
749
void Session::unlink_open_table(Table *find)
668
750
{
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
 
 
 
751
  char key[MAX_DBKEY_LENGTH];
 
752
  uint32_t key_length= find->s->table_cache_key.length;
 
753
  Table *list, **prev;
 
754
 
 
755
  safe_mutex_assert_owner(&LOCK_open);
 
756
 
 
757
  memcpy(key, find->s->table_cache_key.str, key_length);
673
758
  /*
674
 
    Note that we need to hold table::Cache::singleton().mutex() while changing the
 
759
    Note that we need to hold LOCK_open while changing the
675
760
    open_tables list. Another thread may work on it.
676
 
    (See: table::Cache::singleton().removeTable(), wait_completed_table())
 
761
    (See: remove_table_from_cache(), mysql_wait_completed_table())
677
762
    Closing a MERGE child before the parent would be fatal if the
678
763
    other thread tries to abort the MERGE lock in between.
679
764
  */
680
765
  for (prev= &open_tables; *prev; )
681
766
  {
682
 
    Table *list= *prev;
 
767
    list= *prev;
683
768
 
684
 
    if (list->getShare()->getCacheKey() == find_key)
 
769
    if (list->s->table_cache_key.length == key_length &&
 
770
        !memcmp(list->s->table_cache_key.str, key, key_length))
685
771
    {
686
772
      /* Remove table from open_tables list. */
687
 
      *prev= list->getNext();
688
 
 
 
773
      *prev= list->next;
689
774
      /* Close table. */
690
 
      table::remove_table(static_cast<table::Concurrent *>(list));
 
775
      hash_delete(&open_cache,(unsigned char*) list); // Close table
691
776
    }
692
777
    else
693
778
    {
694
779
      /* Step to next entry in open_tables list. */
695
 
      prev= list->getNextPtr();
 
780
      prev= &list->next;
696
781
    }
697
782
  }
698
783
 
699
784
  // Notify any 'refresh' threads
700
 
  locking::broadcast_refresh();
 
785
  broadcast_refresh();
701
786
}
702
787
 
703
788
 
720
805
  table that was locked with LOCK TABLES.
721
806
*/
722
807
 
723
 
void Session::drop_open_table(Table *table, const identifier::Table &identifier)
 
808
void Session::drop_open_table(Table *table, const char *db_name,
 
809
                              const char *table_name)
724
810
{
725
 
  if (table->getShare()->getType())
726
 
  {
727
 
    close_temporary_table(table);
728
 
  }
 
811
  if (table->s->tmp_table)
 
812
    close_temporary_table(table, true, true);
729
813
  else
730
814
  {
731
 
    boost_unique_lock_t scoped_lock(table::Cache::singleton().mutex()); /* Close and drop a table (AUX routine) */
 
815
    pthread_mutex_lock(&LOCK_open); /* Close and drop a table (AUX routine) */
732
816
    /*
733
817
      unlink_open_table() also tells threads waiting for refresh or close
734
818
      that something has happened.
735
819
    */
736
820
    unlink_open_table(table);
737
 
    (void)plugin::StorageEngine::dropTable(*this, identifier);
 
821
    quick_rm_table(*this, db_name, table_name, false);
 
822
    pthread_mutex_unlock(&LOCK_open);
738
823
  }
739
824
}
740
825
 
750
835
  cond  Condition to wait for
751
836
*/
752
837
 
753
 
void Session::wait_for_condition(boost::mutex &mutex, boost::condition_variable_any &cond)
 
838
void Session::wait_for_condition(pthread_mutex_t *mutex, pthread_cond_t *cond)
754
839
{
755
840
  /* Wait until the current table is up to date */
756
841
  const char *saved_proc_info;
757
 
  mysys_var->current_mutex= &mutex;
758
 
  mysys_var->current_cond= &cond;
 
842
  mysys_var->current_mutex= mutex;
 
843
  mysys_var->current_cond= cond;
759
844
  saved_proc_info= get_proc_info();
760
845
  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);
 
846
  if (!killed)
 
847
    (void) pthread_cond_wait(cond, mutex);
 
848
 
 
849
  /*
 
850
    We must unlock mutex first to avoid deadlock becasue conditions are
 
851
    sent to this thread by doing locks in the following order:
 
852
    lock(mysys_var->mutex)
 
853
    lock(mysys_var->current_mutex)
 
854
 
 
855
    One by effect of this that one can only use wait_for_condition with
 
856
    condition variables that are guranteed to not disapper (freed) even if this
 
857
    mutex is unlocked
 
858
  */
 
859
 
 
860
  pthread_mutex_unlock(mutex);
 
861
  pthread_mutex_lock(&mysys_var->mutex);
779
862
  mysys_var->current_mutex= 0;
780
863
  mysys_var->current_cond= 0;
781
864
  set_proc_info(saved_proc_info);
 
865
  pthread_mutex_unlock(&mysys_var->mutex);
 
866
}
 
867
 
 
868
 
 
869
/*
 
870
  Open table which is already name-locked by this thread.
 
871
 
 
872
  SYNOPSIS
 
873
  reopen_name_locked_table()
 
874
  session         Thread handle
 
875
  table_list  TableList object for table to be open, TableList::table
 
876
  member should point to Table object which was used for
 
877
  name-locking.
 
878
  link_in     true  - if Table object for table to be opened should be
 
879
  linked into Session::open_tables list.
 
880
  false - placeholder used for name-locking is already in
 
881
  this list so we only need to preserve Table::next
 
882
  pointer.
 
883
 
 
884
  NOTE
 
885
  This function assumes that its caller already acquired LOCK_open mutex.
 
886
 
 
887
  RETURN VALUE
 
888
  false - Success
 
889
  true  - Error
 
890
*/
 
891
 
 
892
bool Session::reopen_name_locked_table(TableList* table_list, bool link_in)
 
893
{
 
894
  Table *table= table_list->table;
 
895
  TableShare *share;
 
896
  char *table_name= table_list->table_name;
 
897
  Table orig_table;
 
898
 
 
899
  safe_mutex_assert_owner(&LOCK_open);
 
900
 
 
901
  if (killed || !table)
 
902
    return true;
 
903
 
 
904
  orig_table= *table;
 
905
 
 
906
  if (open_unireg_entry(this, table, table_list, table_name,
 
907
                        table->s->table_cache_key.str,
 
908
                        table->s->table_cache_key.length))
 
909
  {
 
910
    table->intern_close_table();
 
911
    /*
 
912
      If there was an error during opening of table (for example if it
 
913
      does not exist) '*table' object can be wiped out. To be able
 
914
      properly release name-lock in this case we should restore this
 
915
      object to its original state.
 
916
    */
 
917
    *table= orig_table;
 
918
    return true;
 
919
  }
 
920
 
 
921
  share= table->s;
 
922
  /*
 
923
    We want to prevent other connections from opening this table until end
 
924
    of statement as it is likely that modifications of table's metadata are
 
925
    not yet finished (for example CREATE TRIGGER have to change .TRG file,
 
926
    or we might want to drop table if CREATE TABLE ... SELECT fails).
 
927
    This also allows us to assume that no other connection will sneak in
 
928
    before we will get table-level lock on this table.
 
929
  */
 
930
  share->version=0;
 
931
  table->in_use = this;
 
932
 
 
933
  if (link_in)
 
934
  {
 
935
    table->next= open_tables;
 
936
    open_tables= table;
 
937
  }
 
938
  else
 
939
  {
 
940
    /*
 
941
      Table object should be already in Session::open_tables list so we just
 
942
      need to set Table::next correctly.
 
943
    */
 
944
    table->next= orig_table.next;
 
945
  }
 
946
 
 
947
  table->tablenr= current_tablenr++;
 
948
  table->used_fields= 0;
 
949
  table->const_table= 0;
 
950
  table->null_row= false;
 
951
  table->maybe_null= false;
 
952
  table->force_index= false;
 
953
  table->status= STATUS_NO_RECORD;
 
954
 
 
955
  return false;
782
956
}
783
957
 
784
958
 
795
969
  case of failure.
796
970
*/
797
971
 
798
 
table::Placeholder *Session::table_cache_insert_placeholder(const drizzled::identifier::Table &arg)
 
972
Table *Session::table_cache_insert_placeholder(const char *key, uint32_t key_length)
799
973
{
800
 
  safe_mutex_assert_owner(table::Cache::singleton().mutex().native_handle());
 
974
  Table *table;
 
975
  TableShare *share;
 
976
  char *key_buff;
 
977
 
 
978
  safe_mutex_assert_owner(&LOCK_open);
801
979
 
802
980
  /*
803
981
    Create a table entry with the right key and with an old refresh version
 
982
    Note that we must use multi_malloc() here as this is freed by the
 
983
    table cache
804
984
  */
805
 
  identifier::Table identifier(arg.getSchemaName(), arg.getTableName(), message::Table::INTERNAL);
806
 
  table::Placeholder *table= new table::Placeholder(this, identifier);
807
 
 
808
 
  if (not table::Cache::singleton().insert(table))
 
985
  if (! memory::multi_malloc(true,
 
986
                             &table, sizeof(*table),
 
987
                             &share, sizeof(*share),
 
988
                             &key_buff, key_length,
 
989
                             NULL))
 
990
    return NULL;
 
991
 
 
992
  table->s= share;
 
993
  share->set_table_cache_key(key_buff, key, key_length);
 
994
  share->tmp_table= INTERNAL_TMP_TABLE;  // for intern_close_table
 
995
  table->in_use= this;
 
996
  table->locked_by_name=1;
 
997
 
 
998
  if (my_hash_insert(&open_cache, (unsigned char*)table))
809
999
  {
810
 
    delete table;
811
 
 
 
1000
    free((unsigned char*) table);
812
1001
    return NULL;
813
1002
  }
814
1003
 
837
1026
  @retval  true   Error occured (OOM)
838
1027
  @retval  false  Success. 'table' parameter set according to above rules.
839
1028
*/
840
 
bool Session::lock_table_name_if_not_cached(const identifier::Table &identifier, Table **table)
 
1029
 
 
1030
bool Session::lock_table_name_if_not_cached(const char *new_db,
 
1031
                                            const char *table_name, Table **table)
841
1032
{
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())
 
1033
  char key[MAX_DBKEY_LENGTH];
 
1034
  char *key_pos= key;
 
1035
  uint32_t key_length;
 
1036
 
 
1037
  key_pos= strcpy(key_pos, new_db) + strlen(new_db);
 
1038
  key_pos= strcpy(key_pos+1, table_name) + strlen(table_name);
 
1039
  key_length= (uint32_t) (key_pos-key)+1;
 
1040
 
 
1041
  pthread_mutex_lock(&LOCK_open); /* Obtain a name lock even though table is not in cache (like for create table)  */
 
1042
 
 
1043
  if (hash_search(&open_cache, (unsigned char *)key, key_length))
851
1044
  {
 
1045
    pthread_mutex_unlock(&LOCK_open);
852
1046
    *table= 0;
853
1047
    return false;
854
1048
  }
855
 
 
856
 
  if (not (*table= table_cache_insert_placeholder(identifier)))
 
1049
  if (!(*table= table_cache_insert_placeholder(key, key_length)))
857
1050
  {
 
1051
    pthread_mutex_unlock(&LOCK_open);
858
1052
    return true;
859
1053
  }
860
1054
  (*table)->open_placeholder= true;
861
 
  (*table)->setNext(open_tables);
 
1055
  (*table)->next= open_tables;
862
1056
  open_tables= *table;
 
1057
  pthread_mutex_unlock(&LOCK_open);
863
1058
 
864
1059
  return false;
865
1060
}
899
1094
 
900
1095
Table *Session::openTable(TableList *table_list, bool *refresh, uint32_t flags)
901
1096
{
902
 
  Table *table;
 
1097
  register Table *table;
 
1098
  char key[MAX_DBKEY_LENGTH];
 
1099
  unsigned int key_length;
903
1100
  const char *alias= table_list->alias;
 
1101
  HASH_SEARCH_STATE state;
904
1102
 
905
1103
  /* Parsing of partitioning information from .frm needs session->lex set up. */
906
1104
  assert(lex->is_lex_started);
913
1111
  if (check_stack_overrun(this, STACK_MIN_SIZE_FOR_OPEN, (unsigned char *)&alias))
914
1112
    return NULL;
915
1113
 
916
 
  if (getKilled())
 
1114
  if (killed)
917
1115
    return NULL;
918
1116
 
919
 
  identifier::Table identifier(table_list->getSchemaName(), table_list->getTableName());
920
 
  const identifier::Table::Key &key(identifier.getKey());
921
 
  table::CacheRange ppp;
 
1117
  key_length= table_list->create_table_def_key(key);
922
1118
 
923
1119
  /*
924
1120
    Unless requested otherwise, try to resolve this table in the list
927
1123
    same name. This block implements the behaviour.
928
1124
    TODO -> move this block into a separate function.
929
1125
  */
930
 
  bool reset= false;
931
 
  for (table= getTemporaryTables(); table ; table=table->getNext())
 
1126
  for (table= temporary_tables; table ; table=table->next)
932
1127
  {
933
 
    if (table->getShare()->getCacheKey() == key)
 
1128
    if (table->s->table_cache_key.length == key_length && !memcmp(table->s->table_cache_key.str, key, key_length))
934
1129
    {
935
1130
      /*
936
1131
        We're trying to use the same temporary table twice in a query.
940
1135
      */
941
1136
      if (table->query_id)
942
1137
      {
943
 
        my_error(ER_CANT_REOPEN_TABLE, MYF(0), table->getAlias());
 
1138
        my_error(ER_CANT_REOPEN_TABLE, MYF(0), table->alias);
944
1139
        return NULL;
945
1140
      }
946
 
      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
 
 
 
1141
      table->query_id= query_id;
 
1142
      goto reset;
 
1143
    }
 
1144
  }
 
1145
 
 
1146
  if (flags & DRIZZLE_OPEN_TEMPORARY_ONLY)
 
1147
  {
 
1148
    my_error(ER_NO_SUCH_TABLE, MYF(0), table_list->db, table_list->table_name);
 
1149
    return NULL;
 
1150
  }
 
1151
 
 
1152
  /*
 
1153
    If it's the first table from a list of tables used in a query,
 
1154
    remember refresh_version (the version of open_cache state).
 
1155
    If the version changes while we're opening the remaining tables,
 
1156
    we will have to back off, close all the tables opened-so-far,
 
1157
    and try to reopen them.
 
1158
 
 
1159
    Note-> refresh_version is currently changed only during FLUSH TABLES.
 
1160
  */
 
1161
  if (!open_tables)
 
1162
    version= refresh_version;
 
1163
  else if ((version != refresh_version) &&
 
1164
           ! (flags & DRIZZLE_LOCK_IGNORE_FLUSH))
 
1165
  {
 
1166
    /* Someone did a refresh while thread was opening tables */
 
1167
    if (refresh)
 
1168
      *refresh= true;
 
1169
 
 
1170
    return NULL;
 
1171
  }
 
1172
 
 
1173
  /*
 
1174
    Before we test the global cache, we test our local session cache.
 
1175
  */
 
1176
  if (cached_table)
 
1177
  {
 
1178
    assert(false); /* Not implemented yet */
 
1179
  }
 
1180
 
 
1181
  /*
 
1182
    Non pre-locked/LOCK TABLES mode, and the table is not temporary:
 
1183
    this is the normal use case.
 
1184
    Now we should:
 
1185
    - try to find the table in the table cache.
 
1186
    - if one of the discovered Table instances is name-locked
 
1187
    (table->s->version == 0) back off -- we have to wait
 
1188
    until no one holds a name lock on the table.
 
1189
    - if there is no such Table in the name cache, read the table definition
 
1190
    and insert it into the cache.
 
1191
    We perform all of the above under LOCK_open which currently protects
 
1192
    the open cache (also known as table cache) and table definitions stored
 
1193
    on disk.
 
1194
  */
 
1195
 
 
1196
  pthread_mutex_lock(&LOCK_open); /* Lock for FLUSH TABLES for open table */
 
1197
 
 
1198
  /*
 
1199
    Actually try to find the table in the open_cache.
 
1200
    The cache may contain several "Table" instances for the same
 
1201
    physical table. The instances that are currently "in use" by
 
1202
    some thread have their "in_use" member != NULL.
 
1203
    There is no good reason for having more than one entry in the
 
1204
    hash for the same physical table, except that we use this as
 
1205
    an implicit "pending locks queue" - see
 
1206
    wait_for_locked_table_names for details.
 
1207
  */
 
1208
  for (table= (Table*) hash_first(&open_cache, (unsigned char*) key, key_length,
 
1209
                                  &state);
 
1210
       table && table->in_use ;
 
1211
       table= (Table*) hash_next(&open_cache, (unsigned char*) key, key_length,
 
1212
                                 &state))
 
1213
  {
960
1214
    /*
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.
 
1215
      Here we flush tables marked for flush.
 
1216
      Normally, table->s->version contains the value of
 
1217
      refresh_version from the moment when this table was
 
1218
      (re-)opened and added to the cache.
 
1219
      If since then we did (or just started) FLUSH TABLES
 
1220
      statement, refresh_version has been increased.
 
1221
      For "name-locked" Table instances, table->s->version is set
 
1222
      to 0 (see lock_table_name for details).
 
1223
      In case there is a pending FLUSH TABLES or a name lock, we
 
1224
      need to back off and re-start opening tables.
 
1225
      If we do not back off now, we may dead lock in case of lock
 
1226
      order mismatch with some other thread:
 
1227
c1: name lock t1; -- sort of exclusive lock
 
1228
c2: open t2;      -- sort of shared lock
 
1229
c1: name lock t2; -- blocks
 
1230
c2: open t1; -- blocks
968
1231
    */
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 */
 
1232
    if (table->needs_reopen_or_name_lock())
 
1233
    {
 
1234
      if (flags & DRIZZLE_LOCK_IGNORE_FLUSH)
 
1235
      {
 
1236
        /* Force close at once after usage */
 
1237
        version= table->s->version;
 
1238
        continue;
 
1239
      }
 
1240
 
 
1241
      /* Avoid self-deadlocks by detecting self-dependencies. */
 
1242
      if (table->open_placeholder && table->in_use == this)
 
1243
      {
 
1244
        pthread_mutex_unlock(&LOCK_open);
 
1245
        my_error(ER_UPDATE_TABLE_USED, MYF(0), table->s->table_name.str);
 
1246
        return NULL;
 
1247
      }
 
1248
 
 
1249
      /*
 
1250
        Back off, part 1: mark the table as "unused" for the
 
1251
        purpose of name-locking by setting table->db_stat to 0. Do
 
1252
        that only for the tables in this thread that have an old
 
1253
        table->s->version (this is an optimization (?)).
 
1254
        table->db_stat == 0 signals wait_for_locked_table_names
 
1255
        that the tables in question are not used any more. See
 
1256
        table_is_used call for details.
 
1257
      */
 
1258
      close_old_data_files(false, false);
 
1259
 
 
1260
      /*
 
1261
        Back-off part 2: try to avoid "busy waiting" on the table:
 
1262
        if the table is in use by some other thread, we suspend
 
1263
        and wait till the operation is complete: when any
 
1264
        operation that juggles with table->s->version completes,
 
1265
        it broadcasts COND_refresh condition variable.
 
1266
        If 'old' table we met is in use by current thread we return
 
1267
        without waiting since in this situation it's this thread
 
1268
        which is responsible for broadcasting on COND_refresh
 
1269
        (and this was done already in Session::close_old_data_files()).
 
1270
        Good example of such situation is when we have statement
 
1271
        that needs two instances of table and FLUSH TABLES comes
 
1272
        after we open first instance but before we open second
 
1273
        instance.
 
1274
      */
 
1275
      if (table->in_use != this)
 
1276
      {
 
1277
        /* wait_for_conditionwill unlock LOCK_open for us */
 
1278
        wait_for_condition(&LOCK_open, &COND_refresh);
 
1279
      }
 
1280
      else
 
1281
      {
 
1282
        pthread_mutex_unlock(&LOCK_open);
 
1283
      }
 
1284
      /*
 
1285
        There is a refresh in progress for this table.
 
1286
        Signal the caller that it has to try again.
 
1287
      */
977
1288
      if (refresh)
978
1289
        *refresh= true;
979
 
 
980
1290
      return NULL;
981
1291
    }
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 */
 
1292
  }
 
1293
  if (table)
 
1294
  {
 
1295
    /* Unlink the table from "unused_tables" list. */
 
1296
    if (table == unused_tables)
 
1297
    {  // First unused
 
1298
      unused_tables=unused_tables->next; // Remove from link
 
1299
      if (table == unused_tables)
 
1300
        unused_tables= NULL;
989
1301
    }
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
 
 
 
1302
    table->prev->next=table->next; /* Remove from unused list */
 
1303
    table->next->prev=table->prev;
 
1304
    table->in_use= this;
 
1305
  }
 
1306
  else
 
1307
  {
 
1308
    /* Insert a new Table instance into the open cache */
 
1309
    int error;
 
1310
    /* Free cache if too big */
 
1311
    while (open_cache.records > table_cache_size && unused_tables)
 
1312
      hash_delete(&open_cache,(unsigned char*) unused_tables);
 
1313
 
 
1314
    if (table_list->create)
1006
1315
    {
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)
 
1316
      char path[FN_REFLEN];
 
1317
      size_t length;
 
1318
 
 
1319
      length= build_table_filename(path, sizeof(path),
 
1320
                                   table_list->db, table_list->table_name,
 
1321
                                   false);
 
1322
 
 
1323
      if (plugin::StorageEngine::getTableDefinition(*this, path, table_list->db, table_list->table_name, false) != EEXIST)
1024
1324
      {
1025
 
        table= (*iter).second;
1026
 
 
1027
 
        if (not table->in_use)
1028
 
          break;
1029
1325
        /*
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
 
1326
          Table to be created, so we need to create placeholder in table-cache.
1046
1327
        */
1047
 
        if (table->needs_reopen_or_name_lock())
 
1328
        if (!(table= table_cache_insert_placeholder(key, key_length)))
1048
1329
        {
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
 
 
 
1330
          pthread_mutex_unlock(&LOCK_open);
1107
1331
          return NULL;
1108
1332
        }
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
 
 
 
1333
        /*
 
1334
          Link placeholder to the open tables list so it will be automatically
 
1335
          removed once tables are closed. Also mark it so it won't be ignored
 
1336
          by other trying to take name-lock.
 
1337
        */
 
1338
        table->open_placeholder= true;
 
1339
        table->next= open_tables;
 
1340
        open_tables= table;
 
1341
        pthread_mutex_unlock(&LOCK_open);
 
1342
 
 
1343
        return table ;
 
1344
      }
 
1345
      /* Table exists. Let us try to open it. */
 
1346
    }
 
1347
 
 
1348
    /* make a new table */
 
1349
    table= (Table *)malloc(sizeof(Table));
 
1350
    if (table == NULL)
 
1351
    {
 
1352
      pthread_mutex_unlock(&LOCK_open);
 
1353
      return NULL;
 
1354
    }
 
1355
 
 
1356
    error= open_unireg_entry(this, table, table_list, alias, key, key_length);
 
1357
    if (error != 0)
 
1358
    {
 
1359
      free(table);
 
1360
      pthread_mutex_unlock(&LOCK_open);
 
1361
      return NULL;
 
1362
    }
 
1363
    my_hash_insert(&open_cache, (unsigned char*) table);
 
1364
  }
 
1365
 
 
1366
  pthread_mutex_unlock(&LOCK_open);
 
1367
  if (refresh)
 
1368
  {
 
1369
    table->next= open_tables; /* Link into simple list */
 
1370
    open_tables=table;
 
1371
  }
 
1372
  table->reginfo.lock_type= TL_READ; /* Assume read */
 
1373
 
 
1374
reset:
 
1375
  assert(table->s->ref_count > 0 || table->s->tmp_table != NO_TMP_TABLE);
 
1376
 
 
1377
  if (lex->need_correct_ident())
 
1378
    table->alias_name_used= my_strcasecmp(table_alias_charset,
 
1379
                                          table->s->table_name.str, alias);
1180
1380
  /* Fix alias if table name changes */
1181
 
  if (strcmp(table->getAlias(), alias))
 
1381
  if (strcmp(table->alias, alias))
1182
1382
  {
1183
 
    table->setAlias(alias);
 
1383
    uint32_t length=(uint32_t) strlen(alias)+1;
 
1384
    table->alias= (char*) realloc((char*) table->alias, length);
 
1385
    memcpy((void*) table->alias, alias, length);
1184
1386
  }
1185
1387
 
1186
1388
  /* These variables are also set in reopen_table() */
1191
1393
  table->maybe_null= false;
1192
1394
  table->force_index= false;
1193
1395
  table->status=STATUS_NO_RECORD;
1194
 
  table->insert_values.clear();
 
1396
  table->insert_values= 0;
1195
1397
  /* Catch wrong handling of the auto_increment_field_not_null. */
1196
1398
  assert(!table->auto_increment_field_not_null);
1197
1399
  table->auto_increment_field_not_null= false;
1198
1400
  if (table->timestamp_field)
1199
 
  {
1200
1401
    table->timestamp_field_type= table->timestamp_field->get_auto_set_type();
1201
 
  }
1202
1402
  table->pos_in_table_list= table_list;
1203
1403
  table->clear_column_bitmaps();
1204
1404
  assert(table->key_read == 0);
1207
1407
}
1208
1408
 
1209
1409
 
 
1410
/*
 
1411
  Reopen an table because the definition has changed.
 
1412
 
 
1413
  SYNOPSIS
 
1414
  reopen_table()
 
1415
  table Table object
 
1416
 
 
1417
  NOTES
 
1418
  The data file for the table is already closed and the share is released
 
1419
  The table has a 'dummy' share that mainly contains database and table name.
 
1420
 
 
1421
  RETURN
 
1422
  0  ok
 
1423
  1  error. The old table object is not changed.
 
1424
*/
 
1425
 
 
1426
bool reopen_table(Table *table)
 
1427
{
 
1428
  Table tmp;
 
1429
  bool error= 1;
 
1430
  Field **field;
 
1431
  uint32_t key,part;
 
1432
  TableList table_list;
 
1433
  Session *session= table->in_use;
 
1434
 
 
1435
  assert(table->s->ref_count == 0);
 
1436
  assert(!table->sort.io_cache);
 
1437
 
 
1438
#ifdef EXTRA_DEBUG
 
1439
  if (table->db_stat)
 
1440
    errmsg_printf(ERRMSG_LVL_ERROR, _("Table %s had a open data Cursor in reopen_table"),
 
1441
                  table->alias);
 
1442
#endif
 
1443
  table_list.db=         table->s->db.str;
 
1444
  table_list.table_name= table->s->table_name.str;
 
1445
  table_list.table=      table;
 
1446
 
 
1447
  if (wait_for_locked_table_names(session, &table_list))
 
1448
    return true;                             // Thread was killed
 
1449
 
 
1450
  if (open_unireg_entry(session, &tmp, &table_list,
 
1451
                        table->alias,
 
1452
                        table->s->table_cache_key.str,
 
1453
                        table->s->table_cache_key.length))
 
1454
    goto end;
 
1455
 
 
1456
  /* This list copies variables set by open_table */
 
1457
  tmp.tablenr=          table->tablenr;
 
1458
  tmp.used_fields=      table->used_fields;
 
1459
  tmp.const_table=      table->const_table;
 
1460
  tmp.null_row=         table->null_row;
 
1461
  tmp.maybe_null=       table->maybe_null;
 
1462
  tmp.status=           table->status;
 
1463
 
 
1464
  /* Get state */
 
1465
  tmp.in_use=           session;
 
1466
  tmp.reginfo.lock_type=table->reginfo.lock_type;
 
1467
 
 
1468
  /* Replace table in open list */
 
1469
  tmp.next=             table->next;
 
1470
  tmp.prev=             table->prev;
 
1471
 
 
1472
  if (table->file)
 
1473
    table->closefrm(true);              // close file, free everything
 
1474
 
 
1475
  *table= tmp;
 
1476
  table->default_column_bitmaps();
 
1477
  table->file->change_table_ptr(table, table->s);
 
1478
 
 
1479
  assert(table->alias != 0);
 
1480
  for (field=table->field ; *field ; field++)
 
1481
  {
 
1482
    (*field)->table= (*field)->orig_table= table;
 
1483
    (*field)->table_name= &table->alias;
 
1484
  }
 
1485
  for (key=0 ; key < table->s->keys ; key++)
 
1486
  {
 
1487
    for (part=0 ; part < table->key_info[key].usable_key_parts ; part++)
 
1488
      table->key_info[key].key_part[part].field->table= table;
 
1489
  }
 
1490
 
 
1491
  broadcast_refresh();
 
1492
  error= false;
 
1493
 
 
1494
end:
 
1495
  return(error);
 
1496
}
 
1497
 
 
1498
 
1210
1499
/**
1211
1500
  Close all instances of a table open by this thread and replace
1212
1501
  them with exclusive name-locks.
1224
1513
  the strings are used in a loop even after the share may be freed.
1225
1514
*/
1226
1515
 
1227
 
void Session::close_data_files_and_morph_locks(const identifier::Table &identifier)
 
1516
void Session::close_data_files_and_morph_locks(const char *new_db, const char *new_table_name)
1228
1517
{
1229
 
  safe_mutex_assert_owner(table::Cache::singleton().mutex().native_handle()); /* Adjust locks at the end of ALTER TABLEL */
 
1518
  Table *table;
 
1519
 
 
1520
  safe_mutex_assert_owner(&LOCK_open); /* Adjust locks at the end of ALTER TABLEL */
1230
1521
 
1231
1522
  if (lock)
1232
1523
  {
1234
1525
      If we are not under LOCK TABLES we should have only one table
1235
1526
      open and locked so it makes sense to remove the lock at once.
1236
1527
    */
1237
 
    unlockTables(lock);
 
1528
    mysql_unlock_tables(this, lock);
1238
1529
    lock= 0;
1239
1530
  }
1240
1531
 
1243
1534
    for target table name if we process ALTER Table ... RENAME.
1244
1535
    So loop below makes sense even if we are not under LOCK TABLES.
1245
1536
  */
1246
 
  for (Table *table= open_tables; table ; table=table->getNext())
 
1537
  for (table= open_tables; table ; table=table->next)
1247
1538
  {
1248
 
    if (table->getShare()->getCacheKey() == identifier.getKey())
 
1539
    if (!strcmp(table->s->table_name.str, new_table_name) &&
 
1540
        !strcmp(table->s->db.str, new_db))
1249
1541
    {
1250
1542
      table->open_placeholder= true;
1251
1543
      close_handle_and_leave_table_as_lock(table);
1269
1561
  combination when one needs tables to be reopened (for
1270
1562
  example see openTablesLock()).
1271
1563
 
1272
 
  @note One should have lock on table::Cache::singleton().mutex() when calling this.
 
1564
  @note One should have lock on LOCK_open when calling this.
1273
1565
 
1274
1566
  @return false in case of success, true - otherwise.
1275
1567
*/
1276
1568
 
1277
 
bool Session::reopen_tables()
 
1569
bool Session::reopen_tables(bool get_locks, bool mark_share_as_old)
1278
1570
{
1279
1571
  Table *table,*next,**prev;
1280
 
  Table **tables= 0;                    // For locks
1281
 
  Table **tables_ptr= 0;                        // For locks
1282
 
  bool error= false;
 
1572
  Table **tables,**tables_ptr;                  // For locks
 
1573
  bool error=0, not_used;
1283
1574
  const uint32_t flags= DRIZZLE_LOCK_NOTIFY_IF_NEED_REOPEN |
1284
1575
    DRIZZLE_LOCK_IGNORE_GLOBAL_READ_LOCK |
1285
1576
    DRIZZLE_LOCK_IGNORE_FLUSH;
1287
1578
  if (open_tables == NULL)
1288
1579
    return false;
1289
1580
 
1290
 
  safe_mutex_assert_owner(table::Cache::singleton().mutex().native_handle());
 
1581
  safe_mutex_assert_owner(&LOCK_open);
 
1582
  if (get_locks)
1291
1583
  {
1292
1584
    /*
1293
1585
      The ptr is checked later
1295
1587
    */
1296
1588
    uint32_t opens= 0;
1297
1589
 
1298
 
    for (table= open_tables; table ; table=table->getNext())
1299
 
    {
 
1590
    for (table= open_tables; table ; table=table->next)
1300
1591
      opens++;
1301
 
    }
1302
1592
    tables= new Table *[opens];
1303
1593
  }
1304
 
 
 
1594
  else
 
1595
    tables= &open_tables;
1305
1596
  tables_ptr =tables;
1306
1597
 
1307
1598
  prev= &open_tables;
1308
1599
  for (table= open_tables; table ; table=next)
1309
1600
  {
1310
 
    next= table->getNext();
1311
 
 
1312
 
    my_error(ER_CANT_REOPEN_TABLE, MYF(0), table->getAlias());
1313
 
    table::remove_table(static_cast<table::Concurrent *>(table));
1314
 
    error= 1;
 
1601
    uint32_t db_stat= table->db_stat;
 
1602
    next= table->next;
 
1603
    if (!tables || (!db_stat && reopen_table(table)))
 
1604
    {
 
1605
      my_error(ER_CANT_REOPEN_TABLE, MYF(0), table->alias);
 
1606
      hash_delete(&open_cache,(unsigned char*) table);
 
1607
      error= 1;
 
1608
    }
 
1609
    else
 
1610
    {
 
1611
      *prev= table;
 
1612
      prev= &table->next;
 
1613
      /* Do not handle locks of MERGE children. */
 
1614
      if (get_locks && !db_stat)
 
1615
        *tables_ptr++= table;                   // need new lock on this
 
1616
      if (mark_share_as_old)
 
1617
      {
 
1618
        table->s->version= 0;
 
1619
        table->open_placeholder= false;
 
1620
      }
 
1621
    }
1315
1622
  }
1316
1623
  *prev=0;
1317
 
 
1318
1624
  if (tables != tables_ptr)                     // Should we get back old locks
1319
1625
  {
1320
 
    DrizzleLock *local_lock;
 
1626
    DRIZZLE_LOCK *local_lock;
1321
1627
    /*
1322
1628
      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
 
1629
      wait_for_tables() as it tries to acquire LOCK_open, which is
1324
1630
      already locked.
1325
1631
    */
1326
1632
    some_tables_deleted= false;
1327
1633
 
1328
 
    if ((local_lock= lockTables(tables, (uint32_t) (tables_ptr - tables), flags)))
 
1634
    if ((local_lock= mysql_lock_tables(this, tables, (uint32_t) (tables_ptr - tables),
 
1635
                                 flags, &not_used)))
1329
1636
    {
1330
1637
      /* unused */
1331
1638
    }
1341
1648
    }
1342
1649
  }
1343
1650
 
1344
 
  delete [] tables;
1345
 
 
1346
 
  locking::broadcast_refresh();
1347
 
 
1348
 
  return error;
 
1651
  if (get_locks && tables)
 
1652
    delete [] tables;
 
1653
 
 
1654
  broadcast_refresh();
 
1655
 
 
1656
  return(error);
1349
1657
}
1350
1658
 
1351
1659
 
1369
1677
 
1370
1678
  Table *table= open_tables;
1371
1679
 
1372
 
  for (; table ; table=table->getNext())
 
1680
  for (; table ; table=table->next)
1373
1681
  {
1374
1682
    /*
1375
1683
      Reopen marked for flush.
1376
1684
    */
1377
1685
    if (table->needs_reopen_or_name_lock())
1378
1686
    {
1379
 
      found= true;
 
1687
      found=1;
1380
1688
      if (table->db_stat)
1381
1689
      {
1382
1690
        if (morph_locks)
1390
1698
              lock on it. This will also give them a chance to close their
1391
1699
              instances of this table.
1392
1700
            */
1393
 
            abortLock(ulcktbl);
1394
 
            removeLock(ulcktbl);
 
1701
            mysql_lock_abort(this, ulcktbl);
 
1702
            mysql_lock_remove(this, ulcktbl);
1395
1703
            ulcktbl->lock_count= 0;
1396
1704
          }
1397
1705
          if ((ulcktbl != table) && ulcktbl->db_stat)
1431
1739
    }
1432
1740
  }
1433
1741
  if (found)
1434
 
    locking::broadcast_refresh();
 
1742
    broadcast_refresh();
 
1743
}
 
1744
 
 
1745
 
 
1746
/*
 
1747
  Wait until all threads has closed the tables in the list
 
1748
  We have also to wait if there is thread that has a lock on this table even
 
1749
  if the table is closed
 
1750
*/
 
1751
 
 
1752
bool table_is_used(Table *table, bool wait_for_name_lock)
 
1753
{
 
1754
  do
 
1755
  {
 
1756
    char *key= table->s->table_cache_key.str;
 
1757
    uint32_t key_length= table->s->table_cache_key.length;
 
1758
 
 
1759
    HASH_SEARCH_STATE state;
 
1760
    for (Table *search= (Table*) hash_first(&open_cache, (unsigned char*) key,
 
1761
                                            key_length, &state);
 
1762
         search ;
 
1763
         search= (Table*) hash_next(&open_cache, (unsigned char*) key,
 
1764
                                    key_length, &state))
 
1765
    {
 
1766
      if (search->in_use == table->in_use)
 
1767
        continue;                               // Name locked by this thread
 
1768
      /*
 
1769
        We can't use the table under any of the following conditions:
 
1770
        - There is an name lock on it (Table is to be deleted or altered)
 
1771
        - If we are in flush table and we didn't execute the flush
 
1772
        - If the table engine is open and it's an old version
 
1773
        (We must wait until all engines are shut down to use the table)
 
1774
      */
 
1775
      if ( (search->locked_by_name && wait_for_name_lock) ||
 
1776
           (search->is_name_opened() && search->needs_reopen_or_name_lock()))
 
1777
        return 1;
 
1778
    }
 
1779
  } while ((table=table->next));
 
1780
  return 0;
 
1781
}
 
1782
 
 
1783
 
 
1784
/* Wait until all used tables are refreshed */
 
1785
 
 
1786
bool wait_for_tables(Session *session)
 
1787
{
 
1788
  bool result;
 
1789
 
 
1790
  session->set_proc_info("Waiting for tables");
 
1791
  pthread_mutex_lock(&LOCK_open); /* Lock for all tables to be refreshed */
 
1792
  while (!session->killed)
 
1793
  {
 
1794
    session->some_tables_deleted= false;
 
1795
    session->close_old_data_files(false, dropping_tables != 0);
 
1796
    if (!table_is_used(session->open_tables, 1))
 
1797
      break;
 
1798
    (void) pthread_cond_wait(&COND_refresh,&LOCK_open);
 
1799
  }
 
1800
  if (session->killed)
 
1801
    result= true;                                       // aborted
 
1802
  else
 
1803
  {
 
1804
    /* Now we can open all tables without any interference */
 
1805
    session->set_proc_info("Reopen tables");
 
1806
    session->version= refresh_version;
 
1807
    result= session->reopen_tables(false, false);
 
1808
  }
 
1809
  pthread_mutex_unlock(&LOCK_open);
 
1810
  session->set_proc_info(0);
 
1811
 
 
1812
  return result;
1435
1813
}
1436
1814
 
1437
1815
 
1459
1837
*/
1460
1838
 
1461
1839
 
1462
 
Table *drop_locked_tables(Session *session, const drizzled::identifier::Table &identifier)
 
1840
Table *drop_locked_tables(Session *session,const char *db, const char *table_name)
1463
1841
{
1464
1842
  Table *table,*next,**prev, *found= 0;
1465
1843
  prev= &session->open_tables;
1466
1844
 
1467
1845
  /*
1468
 
    Note that we need to hold table::Cache::singleton().mutex() while changing the
 
1846
    Note that we need to hold LOCK_open while changing the
1469
1847
    open_tables list. Another thread may work on it.
1470
 
    (See: table::Cache::singleton().removeTable(), wait_completed_table())
 
1848
    (See: remove_table_from_cache(), mysql_wait_completed_table())
1471
1849
    Closing a MERGE child before the parent would be fatal if the
1472
1850
    other thread tries to abort the MERGE lock in between.
1473
1851
  */
1474
1852
  for (table= session->open_tables; table ; table=next)
1475
1853
  {
1476
 
    next=table->getNext();
1477
 
    if (table->getShare()->getCacheKey() == identifier.getKey())
 
1854
    next=table->next;
 
1855
    if (!strcmp(table->s->table_name.str, table_name) &&
 
1856
        !strcmp(table->s->db.str, db))
1478
1857
    {
1479
 
      session->removeLock(table);
 
1858
      mysql_lock_remove(session, table);
1480
1859
 
1481
1860
      if (!found)
1482
1861
      {
1485
1864
        if (table->db_stat)
1486
1865
        {
1487
1866
          table->db_stat= 0;
1488
 
          table->cursor->close();
 
1867
          table->file->close();
1489
1868
        }
1490
1869
      }
1491
1870
      else
1492
1871
      {
1493
1872
        /* We already have a name lock, remove copy */
1494
 
        table::remove_table(static_cast<table::Concurrent *>(table));
 
1873
        hash_delete(&open_cache,(unsigned char*) table);
1495
1874
      }
1496
1875
    }
1497
1876
    else
1498
1877
    {
1499
1878
      *prev=table;
1500
 
      prev= table->getNextPtr();
 
1879
      prev= &table->next;
1501
1880
    }
1502
1881
  }
1503
1882
  *prev=0;
1504
 
 
1505
1883
  if (found)
1506
 
    locking::broadcast_refresh();
 
1884
    broadcast_refresh();
1507
1885
 
1508
 
  return found;
 
1886
  return(found);
1509
1887
}
1510
1888
 
1511
1889
 
1515
1893
  other threads trying to get the lock.
1516
1894
*/
1517
1895
 
1518
 
void abort_locked_tables(Session *session, const drizzled::identifier::Table &identifier)
 
1896
void abort_locked_tables(Session *session,const char *db, const char *table_name)
1519
1897
{
1520
1898
  Table *table;
1521
 
  for (table= session->open_tables; table ; table= table->getNext())
 
1899
  for (table= session->open_tables; table ; table= table->next)
1522
1900
  {
1523
 
    if (table->getShare()->getCacheKey() == identifier.getKey())
 
1901
    if (!strcmp(table->s->table_name.str, table_name) &&
 
1902
        !strcmp(table->s->db.str, db))
1524
1903
    {
1525
1904
      /* If MERGE child, forward lock handling to parent. */
1526
 
      session->abortLock(table);
1527
 
      assert(0);
 
1905
      mysql_lock_abort(session, table);
1528
1906
      break;
1529
1907
    }
1530
1908
  }
1531
1909
}
1532
1910
 
 
1911
/*
 
1912
  Load a table definition from file and open unireg table
 
1913
 
 
1914
  SYNOPSIS
 
1915
  open_unireg_entry()
 
1916
  session                       Thread handle
 
1917
  entry         Store open table definition here
 
1918
  table_list            TableList with db, table_name
 
1919
  alias         Alias name
 
1920
  cache_key             Key for share_cache
 
1921
  cache_key_length      length of cache_key
 
1922
 
 
1923
  NOTES
 
1924
  Extra argument for open is taken from session->open_options
 
1925
  One must have a lock on LOCK_open when calling this function
 
1926
 
 
1927
  RETURN
 
1928
  0     ok
 
1929
#       Error
 
1930
*/
 
1931
 
 
1932
static int open_unireg_entry(Session *session, Table *entry, TableList *table_list,
 
1933
                             const char *alias,
 
1934
                             char *cache_key, uint32_t cache_key_length)
 
1935
{
 
1936
  int error;
 
1937
  TableShare *share;
 
1938
  uint32_t discover_retry_count= 0;
 
1939
 
 
1940
  safe_mutex_assert_owner(&LOCK_open);
 
1941
retry:
 
1942
  if (!(share= TableShare::getShare(session, table_list, cache_key,
 
1943
                                    cache_key_length,
 
1944
                                    table_list->i_s_requested_object,
 
1945
                                    &error)))
 
1946
    return 1;
 
1947
 
 
1948
  while ((error= open_table_from_share(session, share, alias,
 
1949
                                       (uint32_t) (HA_OPEN_KEYFILE |
 
1950
                                                   HA_OPEN_RNDFILE |
 
1951
                                                   HA_GET_INDEX |
 
1952
                                                   HA_TRY_READ_ONLY),
 
1953
                                       (EXTRA_RECORD),
 
1954
                                       session->open_options, entry, OTM_OPEN)))
 
1955
  {
 
1956
    if (error == 7)                             // Table def changed
 
1957
    {
 
1958
      share->version= 0;                        // Mark share as old
 
1959
      if (discover_retry_count++)               // Retry once
 
1960
        goto err;
 
1961
 
 
1962
      /*
 
1963
        TODO->
 
1964
        Here we should wait until all threads has released the table.
 
1965
        For now we do one retry. This may cause a deadlock if there
 
1966
        is other threads waiting for other tables used by this thread.
 
1967
 
 
1968
        Proper fix would be to if the second retry failed:
 
1969
        - Mark that table def changed
 
1970
        - Return from open table
 
1971
        - Close all tables used by this thread
 
1972
        - Start waiting that the share is released
 
1973
        - Retry by opening all tables again
 
1974
      */
 
1975
 
 
1976
      /*
 
1977
        TO BE FIXED
 
1978
        To avoid deadlock, only wait for release if no one else is
 
1979
        using the share.
 
1980
      */
 
1981
      if (share->ref_count != 1)
 
1982
        goto err;
 
1983
      /* Free share and wait until it's released by all threads */
 
1984
      TableShare::release(share);
 
1985
 
 
1986
      if (!session->killed)
 
1987
      {
 
1988
        drizzle_reset_errors(session, 1);         // Clear warnings
 
1989
        session->clear_error();                 // Clear error message
 
1990
        goto retry;
 
1991
      }
 
1992
      return 1;
 
1993
    }
 
1994
    if (!entry->s || !entry->s->crashed)
 
1995
      goto err;
 
1996
    // Code below is for repairing a crashed file
 
1997
    if ((error= lock_table_name(session, table_list, true)))
 
1998
    {
 
1999
      if (error < 0)
 
2000
        goto err;
 
2001
      if (wait_for_locked_table_names(session, table_list))
 
2002
      {
 
2003
        unlock_table_name(table_list);
 
2004
        goto err;
 
2005
      }
 
2006
    }
 
2007
    pthread_mutex_unlock(&LOCK_open);
 
2008
    session->clear_error();                             // Clear error message
 
2009
    error= 0;
 
2010
    if (open_table_from_share(session, share, alias,
 
2011
                              (uint32_t) (HA_OPEN_KEYFILE | HA_OPEN_RNDFILE |
 
2012
                                          HA_GET_INDEX |
 
2013
                                          HA_TRY_READ_ONLY),
 
2014
                              EXTRA_RECORD,
 
2015
                              ha_open_options | HA_OPEN_FOR_REPAIR,
 
2016
                              entry, OTM_OPEN) || ! entry->file)
 
2017
    {
 
2018
      /* Give right error message */
 
2019
      session->clear_error();
 
2020
      my_error(ER_NOT_KEYFILE, MYF(0), share->table_name.str, my_errno);
 
2021
      errmsg_printf(ERRMSG_LVL_ERROR, _("Couldn't repair table: %s.%s"), share->db.str,
 
2022
                    share->table_name.str);
 
2023
      if (entry->file)
 
2024
        entry->closefrm(false);
 
2025
      error=1;
 
2026
    }
 
2027
    else
 
2028
      session->clear_error();                   // Clear error message
 
2029
    pthread_mutex_lock(&LOCK_open);
 
2030
    unlock_table_name(table_list);
 
2031
 
 
2032
    if (error)
 
2033
      goto err;
 
2034
    break;
 
2035
  }
 
2036
 
 
2037
  /*
 
2038
    If we are here, there was no fatal error (but error may be still
 
2039
    unitialized).
 
2040
  */
 
2041
  if (unlikely(entry->file->implicit_emptied))
 
2042
  {
 
2043
    ReplicationServices &replication_services= ReplicationServices::singleton();
 
2044
    entry->file->implicit_emptied= 0;
 
2045
    {
 
2046
      char *query, *end;
 
2047
      uint32_t query_buf_size= 20 + share->db.length + share->table_name.length +1;
 
2048
      if ((query= (char*) malloc(query_buf_size)))
 
2049
      {
 
2050
        /* 
 
2051
          "this DELETE FROM is needed even with row-based binlogging"
 
2052
 
 
2053
          We inherited this from MySQL. TODO: fix it to issue a propper truncate
 
2054
          of the table (though that may not be completely right sematics).
 
2055
        */
 
2056
        end= query;
 
2057
        end+= sprintf(query, "DELETE FROM `%s`.`%s`", share->db.str,
 
2058
                      share->table_name.str);
 
2059
        replication_services.rawStatement(session, query, (size_t)(end - query)); 
 
2060
        free(query);
 
2061
      }
 
2062
      else
 
2063
      {
 
2064
        errmsg_printf(ERRMSG_LVL_ERROR, _("When opening HEAP table, could not allocate memory "
 
2065
                                          "to write 'DELETE FROM `%s`.`%s`' to replication"),
 
2066
                      table_list->db, table_list->table_name);
 
2067
        my_error(ER_OUTOFMEMORY, MYF(0), query_buf_size);
 
2068
        entry->closefrm(false);
 
2069
        goto err;
 
2070
      }
 
2071
    }
 
2072
  }
 
2073
  return 0;
 
2074
 
 
2075
err:
 
2076
  TableShare::release(share);
 
2077
 
 
2078
  return 1;
 
2079
}
 
2080
 
1533
2081
 
1534
2082
/*
1535
2083
  Open all tables in list
1590
2138
    {
1591
2139
      continue;
1592
2140
    }
 
2141
    /*
 
2142
      If this TableList object is a placeholder for an information_schema
 
2143
      table, create a temporary table to represent the information_schema
 
2144
      table in the query. Do not fill it yet - will be filled during
 
2145
      execution.
 
2146
    */
 
2147
    if (tables->schema_table)
 
2148
    {
 
2149
      if (mysql_schema_table(this, lex, tables) == false)
 
2150
        continue;
 
2151
      return -1;
 
2152
    }
1593
2153
    (*counter)++;
1594
2154
 
1595
2155
    /*
1596
 
     * Is the user authorized to see this table? Do this before we check
1597
 
     * to see if it exists so that an unauthorized user cannot phish for
1598
 
     * table/schema information via error messages
1599
 
     */
1600
 
    identifier::Table the_table(tables->getSchemaName(), tables->getTableName());
1601
 
    if (not plugin::Authorization::isAuthorized(user(), the_table))
1602
 
    {
1603
 
      result= -1;                               // Fatal error
1604
 
      break;
1605
 
    }
1606
 
 
1607
 
 
1608
 
    /*
1609
2156
      Not a placeholder: must be a base table or a view, and the table is
1610
2157
      not opened yet. Try to open the table.
1611
2158
    */
1644
2191
    {
1645
2192
      if (tables->lock_type == TL_WRITE_DEFAULT)
1646
2193
        tables->table->reginfo.lock_type= update_lock_default;
1647
 
      else if (tables->table->getShare()->getType() == message::Table::STANDARD)
 
2194
      else if (tables->table->s->tmp_table == NO_TMP_TABLE)
1648
2195
        tables->table->reginfo.lock_type= tables->lock_type;
1649
2196
    }
1650
2197
  }
1695
2242
 
1696
2243
  set_proc_info("Opening table");
1697
2244
  current_tablenr= 0;
1698
 
  while (!(table= openTable(table_list, &refresh)) && refresh) ;
 
2245
  while (!(table= openTable(table_list, &refresh)) &&
 
2246
         refresh)
 
2247
    ;
1699
2248
 
1700
2249
  if (table)
1701
2250
  {
1704
2253
 
1705
2254
    assert(lock == 0);  // You must lock everything at once
1706
2255
    if ((table->reginfo.lock_type= lock_type) != TL_UNLOCK)
1707
 
    {
1708
 
      if (not (lock= lockTables(&table_list->table, 1, 0)))
1709
 
        table= NULL;
1710
 
    }
 
2256
      if (! (lock= mysql_lock_tables(this, &table_list->table, 1, 0, &refresh)))
 
2257
        table= 0;
1711
2258
  }
1712
2259
 
1713
2260
  set_proc_info(0);
1761
2308
  Table **start,**ptr;
1762
2309
  uint32_t lock_flag= DRIZZLE_LOCK_NOTIFY_IF_NEED_REOPEN;
1763
2310
 
1764
 
  if (!(ptr=start=(Table**) session->getMemRoot()->allocate(sizeof(Table*)*count)))
 
2311
  if (!(ptr=start=(Table**) session->alloc(sizeof(Table*)*count)))
1765
2312
    return -1;
1766
 
 
1767
2313
  for (table= tables; table; table= table->next_global)
1768
2314
  {
1769
2315
    if (!table->placeholder())
1770
2316
      *(ptr++)= table->table;
1771
2317
  }
1772
2318
 
1773
 
  if (not (session->lock= session->lockTables(start, (uint32_t) (ptr - start), lock_flag)))
 
2319
  if (!(session->lock= mysql_lock_tables(session, start, (uint32_t) (ptr - start),
 
2320
                                         lock_flag, need_reopen)))
1774
2321
  {
1775
2322
    return -1;
1776
2323
  }
1799
2346
#  Table object
1800
2347
*/
1801
2348
 
1802
 
Table *Open_tables_state::open_temporary_table(const identifier::Table &identifier,
1803
 
                                               bool link_in_list)
 
2349
Table *Session::open_temporary_table(const char *path, const char *db_arg,
 
2350
                                     const char *table_name_arg, bool link_in_list,
 
2351
                                     open_table_mode open_mode)
1804
2352
{
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)
 
2353
  Table *new_tmp_table;
 
2354
  TableShare *share;
 
2355
  char cache_key[MAX_DBKEY_LENGTH], *saved_cache_key, *tmp_path;
 
2356
  uint32_t key_length, path_length;
 
2357
  TableList table_list;
 
2358
 
 
2359
  table_list.db=         (char*) db_arg;
 
2360
  table_list.table_name= (char*) table_name_arg;
 
2361
  /* Create the cache_key for temporary tables */
 
2362
  key_length= table_list.create_table_def_key(cache_key);
 
2363
  path_length= strlen(path);
 
2364
 
 
2365
  if (!(new_tmp_table= (Table*) malloc(sizeof(*new_tmp_table) + sizeof(*share) +
 
2366
                                   path_length + 1 + key_length)))
1813
2367
    return NULL;
1814
2368
 
 
2369
  share= (TableShare*) (new_tmp_table+1);
 
2370
  tmp_path= (char*) (share+1);
 
2371
  saved_cache_key= strcpy(tmp_path, path)+path_length+1;
 
2372
  memcpy(saved_cache_key, cache_key, key_length);
 
2373
 
 
2374
  share->init(saved_cache_key, key_length, strchr(saved_cache_key, '\0')+1, tmp_path);
 
2375
 
1815
2376
  /*
1816
2377
    First open the share, and then open the table from the share we just opened.
1817
2378
  */
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))
 
2379
  if (open_table_def(*this, share) ||
 
2380
      open_table_from_share(this, share, table_name_arg,
 
2381
                            (open_mode == OTM_ALTER) ? 0 :
 
2382
                            (uint32_t) (HA_OPEN_KEYFILE | HA_OPEN_RNDFILE |
 
2383
                                        HA_GET_INDEX),
 
2384
                            (open_mode == OTM_ALTER) ?
 
2385
                            (EXTRA_RECORD | OPEN_FRM_FILE_ONLY)
 
2386
                            : (EXTRA_RECORD),
 
2387
                            ha_open_options,
 
2388
                            new_tmp_table, open_mode))
1824
2389
  {
1825
2390
    /* 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;
1828
 
 
 
2391
    share->free_table_share();
 
2392
    free((char*) new_tmp_table);
1829
2393
    return 0;
1830
2394
  }
1831
2395
 
1832
2396
  new_tmp_table->reginfo.lock_type= TL_WRITE;    // Simulate locked
 
2397
  if (open_mode == OTM_ALTER)
 
2398
  {
 
2399
    /*
 
2400
      Temporary table has been created with frm_only
 
2401
      and has not been created in any storage engine
 
2402
    */
 
2403
    share->tmp_table= TMP_TABLE_FRM_FILE_ONLY;
 
2404
  }
 
2405
  else
 
2406
    share->tmp_table= (new_tmp_table->file->has_transactions() ?
 
2407
                       TRANSACTIONAL_TMP_TABLE : NON_TRANSACTIONAL_TMP_TABLE);
1833
2408
 
1834
2409
  if (link_in_list)
1835
2410
  {
1836
2411
    /* 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
 
    }
 
2412
    new_tmp_table->next= this->temporary_tables;
 
2413
    if (new_tmp_table->next)
 
2414
      new_tmp_table->next->prev= new_tmp_table;
1842
2415
    this->temporary_tables= new_tmp_table;
1843
 
    this->temporary_tables->setPrev(0);
 
2416
    this->temporary_tables->prev= 0;
1844
2417
  }
1845
2418
  new_tmp_table->pos_in_table_list= 0;
1846
2419
 
1865
2438
{
1866
2439
  if (session->mark_used_columns != MARK_COLUMNS_NONE)
1867
2440
  {
1868
 
    boost::dynamic_bitset<> *current_bitmap= NULL;
 
2441
    MyBitmap *current_bitmap, *other_bitmap;
1869
2442
 
1870
2443
    /*
1871
2444
      We always want to register the used keys, as the column bitmap may have
1878
2451
    if (session->mark_used_columns == MARK_COLUMNS_READ)
1879
2452
    {
1880
2453
      current_bitmap= table->read_set;
 
2454
      other_bitmap=   table->write_set;
1881
2455
    }
1882
2456
    else
1883
2457
    {
1884
2458
      current_bitmap= table->write_set;
 
2459
      other_bitmap=   table->read_set;
1885
2460
    }
1886
2461
 
1887
 
    //if (current_bitmap->testAndSet(field->position()))
1888
 
    if (current_bitmap->test(field->position()))
 
2462
    if (current_bitmap->testAndSet(field->field_index))
1889
2463
    {
1890
2464
      if (session->mark_used_columns == MARK_COLUMNS_WRITE)
1891
2465
        session->dup_field= field;
1944
2518
    {
1945
2519
      if (nj_col)
1946
2520
      {
1947
 
        my_error(ER_NON_UNIQ_ERROR, MYF(0), name, session->where());
 
2521
        my_error(ER_NON_UNIQ_ERROR, MYF(0), name, session->where);
1948
2522
        return NULL;
1949
2523
      }
1950
2524
      nj_col= curr_nj_col;
1954
2528
    return NULL;
1955
2529
  {
1956
2530
    /* This is a base table. */
1957
 
    assert(nj_col->table_ref->table == nj_col->table_field->getTable());
 
2531
    assert(nj_col->table_ref->table == nj_col->table_field->table);
1958
2532
    found_field= nj_col->table_field;
1959
2533
    update_field_dependencies(session, found_field, nj_col->table_ref->table);
1960
2534
  }
1991
2565
  uint32_t cached_field_index= *cached_field_index_ptr;
1992
2566
 
1993
2567
  /* We assume here that table->field < NO_CACHED_FIELD_INDEX = UINT_MAX */
1994
 
  if (cached_field_index < table->getShare()->sizeFields() &&
 
2568
  if (cached_field_index < table->s->fields &&
1995
2569
      !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));
 
2570
                     table->field[cached_field_index]->field_name, name))
 
2571
    field_ptr= table->field + cached_field_index;
 
2572
  else if (table->s->name_hash.records)
 
2573
  {
 
2574
    field_ptr= (Field**) hash_search(&table->s->name_hash, (unsigned char*) name,
 
2575
                                     length);
2003
2576
    if (field_ptr)
2004
2577
    {
2005
2578
      /*
2006
2579
        field_ptr points to field in TableShare. Convert it to the matching
2007
2580
        field in table
2008
2581
      */
2009
 
      field_ptr= (table->getFields() + table->getShare()->positionFields(field_ptr));
 
2582
      field_ptr= (table->field + (field_ptr - table->s->field));
2010
2583
    }
2011
2584
  }
2012
2585
  else
2013
2586
  {
2014
 
    if (!(field_ptr= table->getFields()))
 
2587
    if (!(field_ptr= table->field))
2015
2588
      return((Field *)0);
2016
2589
    for (; *field_ptr; ++field_ptr)
2017
2590
      if (!my_strcasecmp(system_charset_info, (*field_ptr)->field_name, name))
2020
2593
 
2021
2594
  if (field_ptr && *field_ptr)
2022
2595
  {
2023
 
    *cached_field_index_ptr= field_ptr - table->getFields();
 
2596
    *cached_field_index_ptr= field_ptr - table->field;
2024
2597
    field= *field_ptr;
2025
2598
  }
2026
2599
  else
2027
2600
  {
2028
2601
    if (!allow_rowid ||
2029
2602
        my_strcasecmp(system_charset_info, name, "_rowid") ||
2030
 
        table->getShare()->rowid_field_offset == 0)
 
2603
        table->s->rowid_field_offset == 0)
2031
2604
      return((Field*) 0);
2032
 
    field= table->getField(table->getShare()->rowid_field_offset-1);
 
2605
    field= table->field[table->s->rowid_field_offset-1];
2033
2606
  }
2034
2607
 
2035
2608
  update_field_dependencies(session, field, table);
2108
2681
    inside the view, but we want to search directly in the view columns
2109
2682
    which are represented as a 'field_translation'.
2110
2683
 
2111
 
    TODO-> Ensure that table_name, db_name and tables->db always points to something !
 
2684
TODO: Ensure that table_name, db_name and tables->db always points to
 
2685
something !
2112
2686
  */
2113
2687
  if (/* Exclude nested joins. */
2114
 
      (!table_list->getNestedJoin()) &&
 
2688
      (!table_list->nested_join) &&
2115
2689
      /* Include merge views and information schema tables. */
2116
2690
      /*
2117
2691
        Test if the field qualifiers match the table reference we plan
2119
2693
      */
2120
2694
      table_name && table_name[0] &&
2121
2695
      (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()))))
 
2696
       (db_name && db_name[0] && table_list->db && table_list->db[0] &&
 
2697
        strcmp(db_name, table_list->db))))
2124
2698
    return 0;
2125
2699
 
2126
2700
  *actual_table= NULL;
2127
2701
 
2128
 
  if (!table_list->getNestedJoin())
 
2702
  if (!table_list->nested_join)
2129
2703
  {
2130
2704
    /* 'table_list' is a stored table. */
2131
2705
    assert(table_list->table);
2145
2719
    */
2146
2720
    if (table_name && table_name[0])
2147
2721
    {
2148
 
      List_iterator<TableList> it(table_list->getNestedJoin()->join_list);
 
2722
      List_iterator<TableList> it(table_list->nested_join->join_list);
2149
2723
      TableList *table;
2150
2724
      while ((table= it++))
2151
2725
      {
2193
2767
        field_to_set= fld;
2194
2768
      if (field_to_set)
2195
2769
      {
2196
 
        Table *table= field_to_set->getTable();
 
2770
        Table *table= field_to_set->table;
2197
2771
        if (session->mark_used_columns == MARK_COLUMNS_READ)
2198
 
          table->setReadSet(field_to_set->position());
 
2772
          table->setReadSet(field_to_set->field_index);
2199
2773
        else
2200
 
          table->setWriteSet(field_to_set->position());
 
2774
          table->setWriteSet(field_to_set->field_index);
2201
2775
      }
2202
2776
    }
2203
2777
  }
2341
2915
      */
2342
2916
      item->cached_table= found ?  0 : actual_table;
2343
2917
 
2344
 
      assert(session->where());
 
2918
      assert(session->where);
2345
2919
      /*
2346
2920
        If we found a fully qualified field we return it directly as it can't
2347
2921
        have duplicates.
2354
2928
        if (report_error == REPORT_ALL_ERRORS ||
2355
2929
            report_error == IGNORE_EXCEPT_NON_UNIQUE)
2356
2930
          my_error(ER_NON_UNIQ_ERROR, MYF(0),
2357
 
                   table_name ? item->full_name() : name, session->where());
 
2931
                   table_name ? item->full_name() : name, session->where);
2358
2932
        return (Field*) 0;
2359
2933
      }
2360
2934
      found= cur_field;
2387
2961
      strcat(buff, table_name);
2388
2962
      table_name=buff;
2389
2963
    }
2390
 
    my_error(ER_UNKNOWN_TABLE, MYF(0), table_name, session->where());
 
2964
    my_error(ER_UNKNOWN_TABLE, MYF(0), table_name, session->where);
2391
2965
  }
2392
2966
  else
2393
2967
  {
2394
2968
    if (report_error == REPORT_ALL_ERRORS ||
2395
2969
        report_error == REPORT_EXCEPT_NON_UNIQUE)
2396
 
      my_error(ER_BAD_FIELD_ERROR, MYF(0), item->full_name(), session->where());
 
2970
      my_error(ER_BAD_FIELD_ERROR, MYF(0), item->full_name(), session->where);
2397
2971
    else
2398
2972
      found= not_found_field;
2399
2973
  }
2439
3013
 
2440
3014
 
2441
3015
Item **
2442
 
find_item_in_list(Session *session,
2443
 
                  Item *find, List<Item> &items, uint32_t *counter,
 
3016
find_item_in_list(Item *find, List<Item> &items, uint32_t *counter,
2444
3017
                  find_item_error_report_type report_error,
2445
3018
                  enum_resolution_type *resolution)
2446
3019
{
2520
3093
            */
2521
3094
            if (report_error != IGNORE_ERRORS)
2522
3095
              my_error(ER_NON_UNIQ_ERROR, MYF(0),
2523
 
                       find->full_name(), session->where());
 
3096
                       find->full_name(), current_session->where);
2524
3097
            return (Item**) 0;
2525
3098
          }
2526
3099
          found_unaliased= li.ref();
2551
3124
              continue;                           // Same field twice
2552
3125
            if (report_error != IGNORE_ERRORS)
2553
3126
              my_error(ER_NON_UNIQ_ERROR, MYF(0),
2554
 
                       find->full_name(), session->where());
 
3127
                       find->full_name(), current_session->where);
2555
3128
            return (Item**) 0;
2556
3129
          }
2557
3130
          found= li.ref();
2603
3176
    {
2604
3177
      if (report_error != IGNORE_ERRORS)
2605
3178
        my_error(ER_NON_UNIQ_ERROR, MYF(0),
2606
 
                 find->full_name(), session->where());
 
3179
                 find->full_name(), current_session->where);
2607
3180
      return (Item **) 0;
2608
3181
    }
2609
3182
    if (found_unaliased)
2619
3192
  {
2620
3193
    if (report_error == REPORT_ALL_ERRORS)
2621
3194
      my_error(ER_BAD_FIELD_ERROR, MYF(0),
2622
 
               find->full_name(), session->where());
 
3195
               find->full_name(), current_session->where);
2623
3196
    return (Item **) 0;
2624
3197
  }
2625
3198
  else
2737
3310
    Leaf table references to which new natural join columns are added
2738
3311
    if the leaves are != NULL.
2739
3312
  */
2740
 
  TableList *leaf_1= (table_ref_1->getNestedJoin() &&
2741
 
                      ! table_ref_1->is_natural_join) ?
 
3313
  TableList *leaf_1= (table_ref_1->nested_join &&
 
3314
                      !table_ref_1->is_natural_join) ?
2742
3315
    NULL : table_ref_1;
2743
 
  TableList *leaf_2= (table_ref_2->getNestedJoin() &&
2744
 
                      ! table_ref_2->is_natural_join) ?
 
3316
  TableList *leaf_2= (table_ref_2->nested_join &&
 
3317
                      !table_ref_2->is_natural_join) ?
2745
3318
    NULL : table_ref_2;
2746
3319
 
2747
3320
  *found_using_fields= 0;
2753
3326
    /* true if field_name_1 is a member of using_fields */
2754
3327
    bool is_using_column_1;
2755
3328
    if (!(nj_col_1= it_1.get_or_create_column_ref(leaf_1)))
2756
 
      return(result);
 
3329
      goto err;
2757
3330
    field_name_1= nj_col_1->name();
2758
3331
    is_using_column_1= using_fields &&
2759
3332
      test_if_string_in_list(field_name_1, using_fields);
2771
3344
      Natural_join_column *cur_nj_col_2;
2772
3345
      const char *cur_field_name_2;
2773
3346
      if (!(cur_nj_col_2= it_2.get_or_create_column_ref(leaf_2)))
2774
 
        return(result);
 
3347
        goto err;
2775
3348
      cur_field_name_2= cur_nj_col_2->name();
2776
3349
 
2777
3350
      /*
2790
3363
        if (cur_nj_col_2->is_common ||
2791
3364
            (found && (!using_fields || is_using_column_1)))
2792
3365
        {
2793
 
          my_error(ER_NON_UNIQ_ERROR, MYF(0), field_name_1, session->where());
2794
 
          return(result);
 
3366
          my_error(ER_NON_UNIQ_ERROR, MYF(0), field_name_1, session->where);
 
3367
          goto err;
2795
3368
        }
2796
3369
        nj_col_2= cur_nj_col_2;
2797
3370
        found= true;
2824
3397
      Item_func_eq *eq_cond;
2825
3398
 
2826
3399
      if (!item_1 || !item_2)
2827
 
        return(result); // out of memory
 
3400
        goto err;                               // out of memory
2828
3401
 
2829
3402
      /*
2830
3403
        In the case of no_wrap_view_item == 0, the created items must be
2849
3422
      */
2850
3423
      if (set_new_item_local_context(session, item_ident_1, nj_col_1->table_ref) ||
2851
3424
          set_new_item_local_context(session, item_ident_2, nj_col_2->table_ref))
2852
 
        return(result);
 
3425
        goto err;
2853
3426
 
2854
3427
      if (!(eq_cond= new Item_func_eq(item_ident_1, item_ident_2)))
2855
 
        return(result);                               /* Out of memory. */
 
3428
        goto err;                               /* Out of memory. */
2856
3429
 
2857
3430
      /*
2858
3431
        Add the new equi-join condition to the ON clause. Notice that
2869
3442
      {
2870
3443
        Table *table_1= nj_col_1->table_ref->table;
2871
3444
        /* Mark field_1 used for table cache. */
2872
 
        table_1->setReadSet(field_1->position());
 
3445
        table_1->setReadSet(field_1->field_index);
2873
3446
        table_1->covering_keys&= field_1->part_of_key;
2874
3447
        table_1->merge_keys|= field_1->part_of_key;
2875
3448
      }
2877
3450
      {
2878
3451
        Table *table_2= nj_col_2->table_ref->table;
2879
3452
        /* Mark field_2 used for table cache. */
2880
 
        table_2->setReadSet(field_2->position());
 
3453
        table_2->setReadSet(field_2->field_index);
2881
3454
        table_2->covering_keys&= field_2->part_of_key;
2882
3455
        table_2->merge_keys|= field_2->part_of_key;
2883
3456
      }
2898
3471
  */
2899
3472
  result= false;
2900
3473
 
 
3474
err:
2901
3475
  return(result);
2902
3476
}
2903
3477
 
2939
3513
*/
2940
3514
 
2941
3515
static bool
2942
 
store_natural_using_join_columns(Session *session,
 
3516
store_natural_using_join_columns(Session *,
2943
3517
                                 TableList *natural_using_join,
2944
3518
                                 TableList *table_ref_1,
2945
3519
                                 TableList *table_ref_2,
2955
3529
 
2956
3530
  if (!(non_join_columns= new List<Natural_join_column>) ||
2957
3531
      !(natural_using_join->join_columns= new List<Natural_join_column>))
2958
 
  {
2959
 
    return(result);
2960
 
  }
 
3532
    goto err;
2961
3533
 
2962
3534
  /* Append the columns of the first join operand. */
2963
3535
  for (it_1.set(table_ref_1); !it_1.end_of_fields(); it_1.next())
2995
3567
        if (!(common_field= it++))
2996
3568
        {
2997
3569
          my_error(ER_BAD_FIELD_ERROR, MYF(0), using_field_name_ptr,
2998
 
                   session->where());
2999
 
          return(result);
 
3570
                   current_session->where);
 
3571
          goto err;
3000
3572
        }
3001
3573
        if (!my_strcasecmp(system_charset_info,
3002
3574
                           common_field->name(), using_field_name_ptr))
3024
3596
 
3025
3597
  result= false;
3026
3598
 
 
3599
err:
3027
3600
  return(result);
3028
3601
}
3029
3602
 
3066
3639
  bool result= true;
3067
3640
 
3068
3641
  /* Call the procedure recursively for each nested table reference. */
3069
 
  if (table_ref->getNestedJoin())
 
3642
  if (table_ref->nested_join)
3070
3643
  {
3071
 
    List_iterator_fast<TableList> nested_it(table_ref->getNestedJoin()->join_list);
 
3644
    List_iterator_fast<TableList> nested_it(table_ref->nested_join->join_list);
3072
3645
    TableList *same_level_left_neighbor= nested_it++;
3073
3646
    TableList *same_level_right_neighbor= NULL;
3074
3647
    /* Left/right-most neighbors, possibly at higher levels in the join tree. */
3093
3666
          cur_table_ref->outer_join & JOIN_TYPE_RIGHT)
3094
3667
      {
3095
3668
        /* This can happen only for JOIN ... ON. */
3096
 
        assert(table_ref->getNestedJoin()->join_list.elements == 2);
 
3669
        assert(table_ref->nested_join->join_list.elements == 2);
3097
3670
        std::swap(same_level_left_neighbor, cur_table_ref);
3098
3671
      }
3099
3672
 
3106
3679
      real_right_neighbor= (same_level_right_neighbor) ?
3107
3680
        same_level_right_neighbor : right_neighbor;
3108
3681
 
3109
 
      if (cur_table_ref->getNestedJoin() &&
 
3682
      if (cur_table_ref->nested_join &&
3110
3683
          store_top_level_join_columns(session, cur_table_ref,
3111
3684
                                       real_left_neighbor, real_right_neighbor))
3112
 
        return(result);
 
3685
        goto err;
3113
3686
      same_level_right_neighbor= cur_table_ref;
3114
3687
    }
3115
3688
  }
3120
3693
  */
3121
3694
  if (table_ref->is_natural_join)
3122
3695
  {
3123
 
    assert(table_ref->getNestedJoin() &&
3124
 
           table_ref->getNestedJoin()->join_list.elements == 2);
3125
 
    List_iterator_fast<TableList> operand_it(table_ref->getNestedJoin()->join_list);
 
3696
    assert(table_ref->nested_join &&
 
3697
           table_ref->nested_join->join_list.elements == 2);
 
3698
    List_iterator_fast<TableList> operand_it(table_ref->nested_join->join_list);
3126
3699
    /*
3127
3700
      Notice that the order of join operands depends on whether table_ref
3128
3701
      represents a LEFT or a RIGHT join. In a RIGHT join, the operands are
3141
3714
      std::swap(table_ref_1, table_ref_2);
3142
3715
    if (mark_common_columns(session, table_ref_1, table_ref_2,
3143
3716
                            using_fields, &found_using_fields))
3144
 
      return(result);
 
3717
      goto err;
3145
3718
 
3146
3719
    /*
3147
3720
      Swap the join operands back, so that we pick the columns of the second
3153
3726
    if (store_natural_using_join_columns(session, table_ref, table_ref_1,
3154
3727
                                         table_ref_2, using_fields,
3155
3728
                                         found_using_fields))
3156
 
      return(result);
 
3729
      goto err;
3157
3730
 
3158
3731
    /*
3159
3732
      Change NATURAL JOIN to JOIN ... ON. We do this for both operands
3186
3759
  }
3187
3760
  result= false; /* All is OK. */
3188
3761
 
 
3762
err:
3189
3763
  return(result);
3190
3764
}
3191
3765
 
3218
3792
                                         List<TableList> *from_clause,
3219
3793
                                         Name_resolution_context *context)
3220
3794
{
3221
 
  session->setWhere("from clause");
 
3795
  session->where= "from clause";
3222
3796
  if (from_clause->elements == 0)
3223
3797
    return false; /* We come here in the case of UNIONs. */
3224
3798
 
3339
3913
  session->mark_used_columns= mark_used_columns;
3340
3914
  if (allow_sum_func)
3341
3915
    session->lex->allow_sum_func|= 1 << session->lex->current_select->nest_level;
3342
 
  session->setWhere(Session::DEFAULT_WHERE);
 
3916
  session->where= Session::DEFAULT_WHERE;
3343
3917
  save_is_item_list_lookup= session->lex->current_select->is_item_list_lookup;
3344
3918
  session->lex->current_select->is_item_list_lookup= 0;
3345
3919
 
3351
3925
    There is other way to solve problem: fill array with pointers to list,
3352
3926
    but it will be slower.
3353
3927
 
3354
 
    TODO-> remove it when (if) we made one list for allfields and ref_pointer_array
 
3928
TODO: remove it when (if) we made one list for allfields and
 
3929
ref_pointer_array
3355
3930
  */
3356
3931
  if (ref_pointer_array)
3357
 
  {
3358
3932
    memset(ref_pointer_array, 0, sizeof(Item *) * fields.elements);
3359
 
  }
3360
3933
 
3361
3934
  Item **ref= ref_pointer_array;
3362
3935
  session->lex->current_select->cur_pos_in_select_list= 0;
3588
4161
    assert(tables->is_leaf_for_name_resolution());
3589
4162
 
3590
4163
    if ((table_name && my_strcasecmp(table_alias_charset, table_name, tables->alias)) ||
3591
 
        (db_name && my_strcasecmp(system_charset_info, tables->getSchemaName(),db_name)))
 
4164
        (db_name && strcmp(tables->db,db_name)))
3592
4165
      continue;
3593
4166
 
3594
4167
    /*
3624
4197
      if ((field= field_iterator.field()))
3625
4198
      {
3626
4199
        /* Mark fields as used to allow storage engine to optimze access */
3627
 
        field->getTable()->setReadSet(field->position());
 
4200
        field->table->setReadSet(field->field_index);
3628
4201
        if (table)
3629
4202
        {
3630
4203
          table->covering_keys&= field->part_of_key;
3652
4225
        }
3653
4226
      }
3654
4227
      else
3655
 
      {
3656
4228
        session->used_tables|= item->used_tables();
3657
 
      }
3658
 
 
3659
4229
      session->lex->current_select->cur_pos_in_select_list++;
3660
4230
    }
3661
4231
    /*
3665
4235
      For NATURAL joins, used_tables is updated in the IF above.
3666
4236
    */
3667
4237
    if (table)
3668
 
      table->used_fields= table->getShare()->sizeFields();
 
4238
      table->used_fields= table->s->fields;
3669
4239
  }
3670
4240
  if (found)
3671
4241
    return false;
3672
4242
 
3673
4243
  /*
3674
 
    @TODO in the case when we skipped all columns because there was a
3675
 
    qualified '*', and all columns were coalesced, we have to give a more
3676
 
    meaningful message than ER_BAD_TABLE_ERROR.
 
4244
TODO: in the case when we skipped all columns because there was a
 
4245
qualified '*', and all columns were coalesced, we have to give a more
 
4246
meaningful message than ER_BAD_TABLE_ERROR.
3677
4247
  */
3678
 
  if (not table_name)
3679
 
  {
 
4248
  if (!table_name)
3680
4249
    my_message(ER_NO_TABLES_USED, ER(ER_NO_TABLES_USED), MYF(0));
3681
 
  }
3682
4250
  else
3683
 
  {
3684
4251
    my_error(ER_BAD_TABLE_ERROR, MYF(0), table_name);
3685
 
  }
3686
4252
 
3687
4253
  return true;
3688
4254
}
3731
4297
  session->session_marker= (void*)1;
3732
4298
  if (*conds)
3733
4299
  {
3734
 
    session->setWhere("where clause");
 
4300
    session->where="where clause";
3735
4301
    if ((!(*conds)->fixed && (*conds)->fix_fields(session, conds)) ||
3736
4302
        (*conds)->check_cols(1))
3737
4303
      goto err_no_arena;
3753
4319
      {
3754
4320
        /* Make a join an a expression */
3755
4321
        session->session_marker= (void*)embedded;
3756
 
        session->setWhere("on clause");
 
4322
        session->where="on clause";
3757
4323
        if ((!embedded->on_expr->fixed && embedded->on_expr->fix_fields(session, &embedded->on_expr)) ||
3758
4324
            embedded->on_expr->check_cols(1))
3759
4325
          goto err_no_arena;
3760
4326
        select_lex->cond_count++;
3761
4327
      }
3762
 
      embedding= embedded->getEmbedding();
 
4328
      embedding= embedded->embedding;
3763
4329
    }
3764
4330
    while (embedding &&
3765
 
           embedding->getNestedJoin()->join_list.head() == embedded);
 
4331
           embedding->nested_join->join_list.head() == embedded);
3766
4332
 
3767
4333
  }
3768
4334
  session->session_marker= save_session_marker;
3788
4354
 
3789
4355
  SYNOPSIS
3790
4356
  fill_record()
 
4357
  session           thread Cursor
3791
4358
  fields        Item_fields list to be filled
3792
4359
  values        values to fill with
3793
4360
  ignore_errors true if we should ignore errors
3803
4370
*/
3804
4371
 
3805
4372
bool
3806
 
fill_record(Session *session, List<Item> &fields, List<Item> &values, bool ignore_errors)
 
4373
fill_record(Session * session, List<Item> &fields, List<Item> &values, bool ignore_errors)
3807
4374
{
3808
4375
  List_iterator_fast<Item> f(fields),v(values);
3809
 
  Item *value;
 
4376
  Item *value, *fld;
3810
4377
  Item_field *field;
3811
 
  Table *table;
 
4378
  Table *table= 0;
 
4379
  List<Table> tbl_list;
 
4380
  bool abort_on_warning_saved= session->abort_on_warning;
 
4381
  tbl_list.empty();
3812
4382
 
3813
4383
  /*
3814
4384
    Reset the table->auto_increment_field_not_null as it is valid for
3820
4390
      On INSERT or UPDATE fields are checked to be from the same table,
3821
4391
      thus we safely can take table from the first field.
3822
4392
    */
3823
 
    field= static_cast<Item_field *>(f++);
3824
 
    table= field->field->getTable();
 
4393
    fld= (Item_field*)f++;
 
4394
    if (!(field= fld->filed_for_view_update()))
 
4395
    {
 
4396
      my_error(ER_NONUPDATEABLE_COLUMN, MYF(0), fld->name);
 
4397
      goto err;
 
4398
    }
 
4399
    table= field->field->table;
3825
4400
    table->auto_increment_field_not_null= false;
3826
4401
    f.rewind();
3827
4402
  }
3828
 
 
3829
 
  while ((field= static_cast<Item_field *>(f++)))
 
4403
  while ((fld= f++))
3830
4404
  {
3831
 
    value= v++;
3832
 
 
 
4405
    if (!(field= fld->filed_for_view_update()))
 
4406
    {
 
4407
      my_error(ER_NONUPDATEABLE_COLUMN, MYF(0), fld->name);
 
4408
      goto err;
 
4409
    }
 
4410
    value=v++;
3833
4411
    Field *rfield= field->field;
3834
 
    table= rfield->getTable();
3835
 
 
 
4412
    table= rfield->table;
3836
4413
    if (rfield == table->next_number_field)
3837
4414
      table->auto_increment_field_not_null= true;
3838
4415
    if ((value->save_in_field(rfield, 0) < 0) && !ignore_errors)
3839
4416
    {
3840
4417
      my_message(ER_UNKNOWN_ERROR, ER(ER_UNKNOWN_ERROR), MYF(0));
3841
 
      if (table)
3842
 
        table->auto_increment_field_not_null= false;
3843
 
 
3844
 
      return true;
3845
 
    }
3846
 
  }
3847
 
 
3848
 
  return session->is_error();
 
4418
      goto err;
 
4419
    }
 
4420
    tbl_list.push_back(table);
 
4421
  }
 
4422
  /* Update virtual fields*/
 
4423
  session->abort_on_warning= false;
 
4424
  if (tbl_list.head())
 
4425
  {
 
4426
    List_iterator_fast<Table> t(tbl_list);
 
4427
    Table *prev_table= 0;
 
4428
    while ((table= t++))
 
4429
    {
 
4430
      /*
 
4431
        Do simple optimization to prevent unnecessary re-generating
 
4432
        values for virtual fields
 
4433
      */
 
4434
      if (table != prev_table)
 
4435
        prev_table= table;
 
4436
    }
 
4437
  }
 
4438
  session->abort_on_warning= abort_on_warning_saved;
 
4439
  return(session->is_error());
 
4440
err:
 
4441
  session->abort_on_warning= abort_on_warning_saved;
 
4442
  if (table)
 
4443
    table->auto_increment_field_not_null= false;
 
4444
  return true;
3849
4445
}
3850
4446
 
3851
4447
 
3854
4450
 
3855
4451
  SYNOPSIS
3856
4452
  fill_record()
 
4453
  session           thread Cursor
3857
4454
  ptr           pointer on pointer to record
3858
4455
  values        list of fields
3859
4456
  ignore_errors true if we should ignore errors
3868
4465
  true    error occured
3869
4466
*/
3870
4467
 
3871
 
bool fill_record(Session *session, Field **ptr, List<Item> &values, bool)
 
4468
bool
 
4469
fill_record(Session *session, Field **ptr, List<Item> &values,
 
4470
            bool )
3872
4471
{
3873
4472
  List_iterator_fast<Item> v(values);
3874
4473
  Item *value;
3875
4474
  Table *table= 0;
3876
4475
  Field *field;
 
4476
  List<Table> tbl_list;
 
4477
  bool abort_on_warning_saved= session->abort_on_warning;
3877
4478
 
 
4479
  tbl_list.empty();
3878
4480
  /*
3879
4481
    Reset the table->auto_increment_field_not_null as it is valid for
3880
4482
    only one row.
3885
4487
      On INSERT or UPDATE fields are checked to be from the same table,
3886
4488
      thus we safely can take table from the first field.
3887
4489
    */
3888
 
    table= (*ptr)->getTable();
 
4490
    table= (*ptr)->table;
3889
4491
    table->auto_increment_field_not_null= false;
3890
4492
  }
3891
 
 
3892
4493
  while ((field = *ptr++) && ! session->is_error())
3893
4494
  {
3894
4495
    value=v++;
3895
 
    table= field->getTable();
3896
 
 
 
4496
    table= field->table;
3897
4497
    if (field == table->next_number_field)
3898
4498
      table->auto_increment_field_not_null= true;
3899
 
 
3900
4499
    if (value->save_in_field(field, 0) < 0)
 
4500
      goto err;
 
4501
    tbl_list.push_back(table);
 
4502
  }
 
4503
  /* Update virtual fields*/
 
4504
  session->abort_on_warning= false;
 
4505
  if (tbl_list.head())
 
4506
  {
 
4507
    List_iterator_fast<Table> t(tbl_list);
 
4508
    Table *prev_table= 0;
 
4509
    while ((table= t++))
3901
4510
    {
3902
 
      if (table)
3903
 
        table->auto_increment_field_not_null= false;
3904
 
 
3905
 
      return true;
 
4511
      /*
 
4512
        Do simple optimization to prevent unnecessary re-generating
 
4513
        values for virtual fields
 
4514
      */
 
4515
      if (table != prev_table)
 
4516
      {
 
4517
        prev_table= table;
 
4518
      }
3906
4519
    }
3907
4520
  }
3908
 
 
 
4521
  session->abort_on_warning= abort_on_warning_saved;
3909
4522
  return(session->is_error());
 
4523
 
 
4524
err:
 
4525
  session->abort_on_warning= abort_on_warning_saved;
 
4526
  if (table)
 
4527
    table->auto_increment_field_not_null= false;
 
4528
  return true;
3910
4529
}
3911
4530
 
3912
4531
 
3913
4532
bool drizzle_rm_tmp_tables()
3914
4533
{
3915
 
 
3916
 
  assert(drizzle_tmpdir.size());
3917
 
  Session::shared_ptr session= Session::make_shared(plugin::Listen::getNullClient(), catalog::local());
3918
 
 
3919
 
  if (not session)
 
4534
  char  filePath[FN_REFLEN], filePathCopy[FN_REFLEN];
 
4535
  Session *session;
 
4536
 
 
4537
  assert(drizzle_tmpdir);
 
4538
 
 
4539
  if (!(session= new Session(plugin::Listen::getNullClient())))
3920
4540
    return true;
3921
 
  session->thread_stack= (char*) session.get();
 
4541
  session->thread_stack= (char*) &session;
3922
4542
  session->storeGlobals();
3923
4543
 
3924
 
  plugin::StorageEngine::removeLostTemporaryTables(*session, drizzle_tmpdir.c_str());
 
4544
  CachedDirectory dir(drizzle_tmpdir);
 
4545
 
 
4546
  if (dir.fail())
 
4547
  {
 
4548
    my_errno= dir.getError();
 
4549
    my_error(ER_CANT_READ_DIR, MYF(0), drizzle_tmpdir, my_errno);
 
4550
    return true;
 
4551
  }
 
4552
 
 
4553
  CachedDirectory::Entries files= dir.getEntries();
 
4554
  CachedDirectory::Entries::iterator fileIter= files.begin();
 
4555
 
 
4556
  /* Remove all temp tables in the tmpdir */
 
4557
  while (fileIter != files.end())
 
4558
  {
 
4559
    CachedDirectory::Entry *entry= *fileIter;
 
4560
    string prefix= entry->filename.substr(0, TMP_FILE_PREFIX_LENGTH);
 
4561
 
 
4562
    if (prefix == TMP_FILE_PREFIX)
 
4563
    {
 
4564
      char *ext= fn_ext(entry->filename.c_str());
 
4565
      uint32_t ext_len= strlen(ext);
 
4566
      uint32_t filePath_len= snprintf(filePath, sizeof(filePath),
 
4567
                                      "%s%c%s", drizzle_tmpdir, FN_LIBCHAR,
 
4568
                                      entry->filename.c_str());
 
4569
 
 
4570
      if (ext_len && !memcmp(drizzled::plugin::DEFAULT_DEFINITION_FILE_EXT.c_str(), ext, ext_len))
 
4571
      {
 
4572
        TableShare share;
 
4573
        /* We should cut file extention before deleting of table */
 
4574
        memcpy(filePathCopy, filePath, filePath_len - ext_len);
 
4575
        filePathCopy[filePath_len - ext_len]= 0;
 
4576
        share.init(NULL, filePathCopy);
 
4577
        if (!open_table_def(*session, &share))
 
4578
        {
 
4579
          share.db_type()->doDropTable(*session, filePathCopy);
 
4580
        }
 
4581
        share.free_table_share();
 
4582
      }
 
4583
      /*
 
4584
        File can be already deleted by tmp_table.file->delete_table().
 
4585
        So we hide error messages which happnes during deleting of these
 
4586
        files(MYF(0)).
 
4587
      */
 
4588
      my_delete(filePath, MYF(0));
 
4589
    }
 
4590
 
 
4591
    ++fileIter;
 
4592
  }
 
4593
 
 
4594
  delete session;
3925
4595
 
3926
4596
  return false;
3927
4597
}
3932
4602
  unireg support functions
3933
4603
 *****************************************************************************/
3934
4604
 
3935
 
 
 
4605
/*
 
4606
  Invalidate any cache entries that are for some DB
 
4607
 
 
4608
  SYNOPSIS
 
4609
  remove_db_from_cache()
 
4610
  db            Database name. This will be in lower case if
 
4611
  lower_case_table_name is set
 
4612
 
 
4613
NOTE:
 
4614
We can't use hash_delete when looping hash_elements. We mark them first
 
4615
and afterwards delete those marked unused.
 
4616
*/
 
4617
 
 
4618
void remove_db_from_cache(const char *db)
 
4619
{
 
4620
  safe_mutex_assert_owner(&LOCK_open);
 
4621
 
 
4622
  for (uint32_t idx=0 ; idx < open_cache.records ; idx++)
 
4623
  {
 
4624
    Table *table=(Table*) hash_element(&open_cache,idx);
 
4625
    if (!strcmp(table->s->db.str, db))
 
4626
    {
 
4627
      table->s->version= 0L;                    /* Free when thread is ready */
 
4628
      if (!table->in_use)
 
4629
        relink_unused(table);
 
4630
    }
 
4631
  }
 
4632
  while (unused_tables && !unused_tables->s->version)
 
4633
    hash_delete(&open_cache,(unsigned char*) unused_tables);
 
4634
}
 
4635
 
 
4636
 
 
4637
/*
 
4638
  Mark all entries with the table as deleted to force an reopen of the table
 
4639
 
 
4640
  The table will be closed (not stored in cache) by the current thread when
 
4641
  close_thread_tables() is called.
 
4642
 
 
4643
  PREREQUISITES
 
4644
  Lock on LOCK_open()
 
4645
 
 
4646
  RETURN
 
4647
  0  This thread now have exclusive access to this table and no other thread
 
4648
  can access the table until close_thread_tables() is called.
 
4649
  1  Table is in use by another thread
 
4650
*/
 
4651
 
 
4652
bool remove_table_from_cache(Session *session, const char *db, const char *table_name,
 
4653
                             uint32_t flags)
 
4654
{
 
4655
  char key[MAX_DBKEY_LENGTH];
 
4656
  char *key_pos= key;
 
4657
  uint32_t key_length;
 
4658
  Table *table;
 
4659
  bool result= false; 
 
4660
  bool signalled= false;
 
4661
 
 
4662
  key_pos= strcpy(key_pos, db) + strlen(db);
 
4663
  key_pos= strcpy(key_pos+1, table_name) + strlen(table_name);
 
4664
  key_length= (uint32_t) (key_pos-key)+1;
 
4665
 
 
4666
  for (;;)
 
4667
  {
 
4668
    HASH_SEARCH_STATE state;
 
4669
    result= signalled= false;
 
4670
 
 
4671
    for (table= (Table*) hash_first(&open_cache, (unsigned char*) key, key_length,
 
4672
                                    &state);
 
4673
         table;
 
4674
         table= (Table*) hash_next(&open_cache, (unsigned char*) key, key_length,
 
4675
                                   &state))
 
4676
    {
 
4677
      Session *in_use;
 
4678
 
 
4679
      table->s->version=0L;             /* Free when thread is ready */
 
4680
      if (!(in_use=table->in_use))
 
4681
      {
 
4682
        relink_unused(table);
 
4683
      }
 
4684
      else if (in_use != session)
 
4685
      {
 
4686
        /*
 
4687
          Mark that table is going to be deleted from cache. This will
 
4688
          force threads that are in mysql_lock_tables() (but not yet
 
4689
          in thr_multi_lock()) to abort it's locks, close all tables and retry
 
4690
        */
 
4691
        in_use->some_tables_deleted= true;
 
4692
        if (table->is_name_opened())
 
4693
        {
 
4694
          result= true;
 
4695
        }
 
4696
        /*
 
4697
          Now we must abort all tables locks used by this thread
 
4698
          as the thread may be waiting to get a lock for another table.
 
4699
          Note that we need to hold LOCK_open while going through the
 
4700
          list. So that the other thread cannot change it. The other
 
4701
          thread must also hold LOCK_open whenever changing the
 
4702
          open_tables list. Aborting the MERGE lock after a child was
 
4703
          closed and before the parent is closed would be fatal.
 
4704
        */
 
4705
        for (Table *session_table= in_use->open_tables;
 
4706
             session_table ;
 
4707
             session_table= session_table->next)
 
4708
        {
 
4709
          /* Do not handle locks of MERGE children. */
 
4710
          if (session_table->db_stat)   // If table is open
 
4711
            signalled|= mysql_lock_abort_for_thread(session, session_table);
 
4712
        }
 
4713
      }
 
4714
      else
 
4715
        result= result || (flags & RTFC_OWNED_BY_Session_FLAG);
 
4716
    }
 
4717
    while (unused_tables && !unused_tables->s->version)
 
4718
      hash_delete(&open_cache,(unsigned char*) unused_tables);
 
4719
 
 
4720
    /* Remove table from table definition cache if it's not in use */
 
4721
    TableShare::release(key, key_length);
 
4722
 
 
4723
    if (result && (flags & RTFC_WAIT_OTHER_THREAD_FLAG))
 
4724
    {
 
4725
      /*
 
4726
        Signal any thread waiting for tables to be freed to
 
4727
        reopen their tables
 
4728
      */
 
4729
      broadcast_refresh();
 
4730
      if (!(flags & RTFC_CHECK_KILLED_FLAG) || !session->killed)
 
4731
      {
 
4732
        dropping_tables++;
 
4733
        if (likely(signalled))
 
4734
          (void) pthread_cond_wait(&COND_refresh, &LOCK_open);
 
4735
        else
 
4736
        {
 
4737
          struct timespec abstime;
 
4738
          /*
 
4739
            It can happen that another thread has opened the
 
4740
            table but has not yet locked any table at all. Since
 
4741
            it can be locked waiting for a table that our thread
 
4742
            has done LOCK Table x WRITE on previously, we need to
 
4743
            ensure that the thread actually hears our signal
 
4744
            before we go to sleep. Thus we wait for a short time
 
4745
            and then we retry another loop in the
 
4746
            remove_table_from_cache routine.
 
4747
          */
 
4748
          set_timespec(abstime, 10);
 
4749
          pthread_cond_timedwait(&COND_refresh, &LOCK_open, &abstime);
 
4750
        }
 
4751
        dropping_tables--;
 
4752
        continue;
 
4753
      }
 
4754
    }
 
4755
    break;
 
4756
  }
 
4757
  return result;
 
4758
}
3936
4759
 
3937
4760
 
3938
4761
/**
3944
4767
  pthread_kill(signal_thread, SIGTERM);
3945
4768
  shutdown_in_progress= 1;                      // Safety if kill didn't work
3946
4769
}
3947
 
 
3948
 
} /* namespace drizzled */