~drizzle-trunk/drizzle/development

« back to all changes in this revision

Viewing changes to drizzled/sql_base.cc

  • Committer: Brian Aker
  • Date: 2009-11-18 06:24:48 UTC
  • mfrom: (1220.1.15 staging)
  • Revision ID: brian@gaz-20091118062448-o36lo3yv81sc6u9z
Merge Brian + Stewart

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
111
  Close cursor handle, but leave the table in the table cache
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()));
 
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
  }
121
151
 
122
152
  table->cursor->close();
123
153
  table->db_stat= 0;                            // Mark cursor closed
124
 
  table::instance::release(table->getMutableShare());
125
 
  table->setShare(share);
126
 
}
127
 
 
 
154
  TableShare::release(table->s);
 
155
  table->s= share;
 
156
  table->cursor->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
135
241
{                                               // Free all structures
136
242
  free_io_cache();
137
243
  if (cursor)                              // Not true if name lock
 
244
    closefrm(true);                     // close cursor
 
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
468
  assert(!table->cursor || table->cursor->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
487
    table->cursor->ha_reset();
364
 
    table->in_use= NULL;
 
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
}
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 (;;)
521
651
}
522
652
 
523
653
 
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())
 
654
Table *Session::find_temporary_table(const char *new_db, const char *table_name)
 
655
{
 
656
  char  key[MAX_DBKEY_LENGTH];
 
657
  uint  key_length;
 
658
  Table *table;
 
659
 
 
660
  key_length= TableShare::createKey(key, new_db, table_name);
 
661
 
 
662
  for (table= temporary_tables ; table ; table= table->next)
 
663
  {
 
664
    if (table->s->table_cache_key.length == key_length &&
 
665
        !memcmp(table->s->table_cache_key.str, key, key_length))
604
666
      return table;
605
667
  }
606
 
 
607
668
  return NULL;                               // Not a temporary table
608
669
}
609
670
 
 
671
Table *Session::find_temporary_table(TableList *table_list)
 
672
{
 
673
  return find_temporary_table(table_list->db, table_list->table_name);
 
674
}
 
675
 
610
676
 
611
677
/**
612
678
  Drop a temporary table.
634
700
  @retval -1  the table is in use by a outer query
635
701
*/
636
702
 
637
 
int Open_tables_state::drop_temporary_table(const drizzled::identifier::Table &identifier)
 
703
int Session::drop_temporary_table(TableList *table_list)
638
704
{
639
705
  Table *table;
640
706
 
641
 
  if (not (table= find_temporary_table(identifier)))
 
707
  if (!(table= find_temporary_table(table_list)))
642
708
    return 1;
643
709
 
644
710
  /* Table might be in use by some outer statement. */
645
 
  if (table->query_id && table->query_id != getQueryId())
 
711
  if (table->query_id && table->query_id != query_id)
646
712
  {
647
 
    my_error(ER_CANT_REOPEN_TABLE, MYF(0), table->getAlias());
 
713
    my_error(ER_CANT_REOPEN_TABLE, MYF(0), table->alias);
648
714
    return -1;
649
715
  }
650
716
 
654
720
}
655
721
 
656
722
 
 
723
/* move table first in unused links */
 
724
 
 
725
static void relink_unused(Table *table)
 
726
{
 
727
  if (table != unused_tables)
 
728
  {
 
729
    table->prev->next=table->next;              /* Remove from unused list */
 
730
    table->next->prev=table->prev;
 
731
    table->next=unused_tables;                  /* Link in unused tables */
 
732
    table->prev=unused_tables->prev;
 
733
    unused_tables->prev->next=table;
 
734
    unused_tables->prev=table;
 
735
    unused_tables=table;
 
736
  }
 
737
}
 
738
 
 
739
 
657
740
/**
658
741
  Remove all instances of table from thread's open list and
659
742
  table cache.
660
743
 
661
744
  @param  session     Thread context
662
745
  @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
746
*/
666
747
 
667
748
void Session::unlink_open_table(Table *find)
668
749
{
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
 
 
 
750
  char key[MAX_DBKEY_LENGTH];
 
751
  uint32_t key_length= find->s->table_cache_key.length;
 
752
  Table *list, **prev;
 
753
 
 
754
  safe_mutex_assert_owner(&LOCK_open);
 
755
 
 
756
  memcpy(key, find->s->table_cache_key.str, key_length);
673
757
  /*
674
 
    Note that we need to hold table::Cache::singleton().mutex() while changing the
 
758
    Note that we need to hold LOCK_open while changing the
675
759
    open_tables list. Another thread may work on it.
676
 
    (See: table::Cache::singleton().removeTable(), wait_completed_table())
 
760
    (See: remove_table_from_cache(), mysql_wait_completed_table())
677
761
    Closing a MERGE child before the parent would be fatal if the
678
762
    other thread tries to abort the MERGE lock in between.
679
763
  */
680
764
  for (prev= &open_tables; *prev; )
681
765
  {
682
 
    Table *list= *prev;
 
766
    list= *prev;
683
767
 
684
 
    if (list->getShare()->getCacheKey() == find_key)
 
768
    if (list->s->table_cache_key.length == key_length &&
 
769
        !memcmp(list->s->table_cache_key.str, key, key_length))
685
770
    {
686
771
      /* Remove table from open_tables list. */
687
 
      *prev= list->getNext();
688
 
 
 
772
      *prev= list->next;
689
773
      /* Close table. */
690
 
      table::remove_table(static_cast<table::Concurrent *>(list));
 
774
      hash_delete(&open_cache,(unsigned char*) list); // Close table
691
775
    }
692
776
    else
693
777
    {
694
778
      /* Step to next entry in open_tables list. */
695
 
      prev= list->getNextPtr();
 
779
      prev= &list->next;
696
780
    }
697
781
  }
698
782
 
699
783
  // Notify any 'refresh' threads
700
 
  locking::broadcast_refresh();
 
784
  broadcast_refresh();
701
785
}
702
786
 
703
787
 
720
804
  table that was locked with LOCK TABLES.
721
805
*/
722
806
 
723
 
void Session::drop_open_table(Table *table, const identifier::Table &identifier)
 
807
void Session::drop_open_table(Table *table, const char *db_name,
 
808
                              const char *table_name)
724
809
{
725
 
  if (table->getShare()->getType())
726
 
  {
 
810
  if (table->s->tmp_table)
727
811
    close_temporary_table(table);
728
 
  }
729
812
  else
730
813
  {
731
 
    boost_unique_lock_t scoped_lock(table::Cache::singleton().mutex()); /* Close and drop a table (AUX routine) */
 
814
    pthread_mutex_lock(&LOCK_open); /* Close and drop a table (AUX routine) */
732
815
    /*
733
816
      unlink_open_table() also tells threads waiting for refresh or close
734
817
      that something has happened.
735
818
    */
736
819
    unlink_open_table(table);
737
 
    (void)plugin::StorageEngine::dropTable(*this, identifier);
 
820
    quick_rm_table(*this, db_name, table_name, false);
 
821
    pthread_mutex_unlock(&LOCK_open);
738
822
  }
739
823
}
740
824
 
750
834
  cond  Condition to wait for
751
835
*/
752
836
 
753
 
void Session::wait_for_condition(boost::mutex &mutex, boost::condition_variable_any &cond)
 
837
void Session::wait_for_condition(pthread_mutex_t *mutex, pthread_cond_t *cond)
754
838
{
755
839
  /* Wait until the current table is up to date */
756
840
  const char *saved_proc_info;
757
 
  mysys_var->current_mutex= &mutex;
758
 
  mysys_var->current_cond= &cond;
 
841
  mysys_var->current_mutex= mutex;
 
842
  mysys_var->current_cond= cond;
759
843
  saved_proc_info= get_proc_info();
760
844
  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);
 
845
  if (!killed)
 
846
    (void) pthread_cond_wait(cond, mutex);
 
847
 
 
848
  /*
 
849
    We must unlock mutex first to avoid deadlock becasue conditions are
 
850
    sent to this thread by doing locks in the following order:
 
851
    lock(mysys_var->mutex)
 
852
    lock(mysys_var->current_mutex)
 
853
 
 
854
    One by effect of this that one can only use wait_for_condition with
 
855
    condition variables that are guranteed to not disapper (freed) even if this
 
856
    mutex is unlocked
 
857
  */
 
858
 
 
859
  pthread_mutex_unlock(mutex);
 
860
  pthread_mutex_lock(&mysys_var->mutex);
779
861
  mysys_var->current_mutex= 0;
780
862
  mysys_var->current_cond= 0;
781
863
  set_proc_info(saved_proc_info);
 
864
  pthread_mutex_unlock(&mysys_var->mutex);
 
865
}
 
866
 
 
867
 
 
868
/*
 
869
  Open table which is already name-locked by this thread.
 
870
 
 
871
  SYNOPSIS
 
872
  reopen_name_locked_table()
 
873
  session         Thread handle
 
874
  table_list  TableList object for table to be open, TableList::table
 
875
  member should point to Table object which was used for
 
876
  name-locking.
 
877
  link_in     true  - if Table object for table to be opened should be
 
878
  linked into Session::open_tables list.
 
879
  false - placeholder used for name-locking is already in
 
880
  this list so we only need to preserve Table::next
 
881
  pointer.
 
882
 
 
883
  NOTE
 
884
  This function assumes that its caller already acquired LOCK_open mutex.
 
885
 
 
886
  RETURN VALUE
 
887
  false - Success
 
888
  true  - Error
 
889
*/
 
890
 
 
891
bool Session::reopen_name_locked_table(TableList* table_list, bool link_in)
 
892
{
 
893
  Table *table= table_list->table;
 
894
  TableShare *share;
 
895
  char *table_name= table_list->table_name;
 
896
  Table orig_table;
 
897
 
 
898
  safe_mutex_assert_owner(&LOCK_open);
 
899
 
 
900
  if (killed || !table)
 
901
    return true;
 
902
 
 
903
  orig_table= *table;
 
904
 
 
905
  if (open_unireg_entry(this, table, table_list, table_name,
 
906
                        table->s->table_cache_key.str,
 
907
                        table->s->table_cache_key.length))
 
908
  {
 
909
    table->intern_close_table();
 
910
    /*
 
911
      If there was an error during opening of table (for example if it
 
912
      does not exist) '*table' object can be wiped out. To be able
 
913
      properly release name-lock in this case we should restore this
 
914
      object to its original state.
 
915
    */
 
916
    *table= orig_table;
 
917
    return true;
 
918
  }
 
919
 
 
920
  share= table->s;
 
921
  /*
 
922
    We want to prevent other connections from opening this table until end
 
923
    of statement as it is likely that modifications of table's metadata are
 
924
    not yet finished (for example CREATE TRIGGER have to change .TRG cursor,
 
925
    or we might want to drop table if CREATE TABLE ... SELECT fails).
 
926
    This also allows us to assume that no other connection will sneak in
 
927
    before we will get table-level lock on this table.
 
928
  */
 
929
  share->version=0;
 
930
  table->in_use = this;
 
931
 
 
932
  if (link_in)
 
933
  {
 
934
    table->next= open_tables;
 
935
    open_tables= table;
 
936
  }
 
937
  else
 
938
  {
 
939
    /*
 
940
      Table object should be already in Session::open_tables list so we just
 
941
      need to set Table::next correctly.
 
942
    */
 
943
    table->next= orig_table.next;
 
944
  }
 
945
 
 
946
  table->tablenr= current_tablenr++;
 
947
  table->used_fields= 0;
 
948
  table->const_table= 0;
 
949
  table->null_row= false;
 
950
  table->maybe_null= false;
 
951
  table->force_index= false;
 
952
  table->status= STATUS_NO_RECORD;
 
953
 
 
954
  return false;
782
955
}
783
956
 
784
957
 
795
968
  case of failure.
796
969
*/
797
970
 
798
 
table::Placeholder *Session::table_cache_insert_placeholder(const drizzled::identifier::Table &arg)
 
971
Table *Session::table_cache_insert_placeholder(const char *key, uint32_t key_length)
799
972
{
800
 
  safe_mutex_assert_owner(table::Cache::singleton().mutex().native_handle());
 
973
  Table *table;
 
974
  TableShare *share;
 
975
  char *key_buff;
 
976
 
 
977
  safe_mutex_assert_owner(&LOCK_open);
801
978
 
802
979
  /*
803
980
    Create a table entry with the right key and with an old refresh version
 
981
    Note that we must use multi_malloc() here as this is freed by the
 
982
    table cache
804
983
  */
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))
 
984
  if (! memory::multi_malloc(true,
 
985
                             &table, sizeof(*table),
 
986
                             &share, sizeof(*share),
 
987
                             &key_buff, key_length,
 
988
                             NULL))
 
989
    return NULL;
 
990
 
 
991
  table->s= share;
 
992
  share->set_table_cache_key(key_buff, key, key_length);
 
993
  share->tmp_table= INTERNAL_TMP_TABLE;  // for intern_close_table
 
994
  table->in_use= this;
 
995
  table->locked_by_name=1;
 
996
 
 
997
  if (my_hash_insert(&open_cache, (unsigned char*)table))
809
998
  {
810
 
    delete table;
811
 
 
 
999
    free((unsigned char*) table);
812
1000
    return NULL;
813
1001
  }
814
1002
 
837
1025
  @retval  true   Error occured (OOM)
838
1026
  @retval  false  Success. 'table' parameter set according to above rules.
839
1027
*/
840
 
bool Session::lock_table_name_if_not_cached(const identifier::Table &identifier, Table **table)
 
1028
 
 
1029
bool Session::lock_table_name_if_not_cached(const char *new_db,
 
1030
                                            const char *table_name, Table **table)
841
1031
{
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())
 
1032
  char key[MAX_DBKEY_LENGTH];
 
1033
  char *key_pos= key;
 
1034
  uint32_t key_length;
 
1035
 
 
1036
  key_pos= strcpy(key_pos, new_db) + strlen(new_db);
 
1037
  key_pos= strcpy(key_pos+1, table_name) + strlen(table_name);
 
1038
  key_length= (uint32_t) (key_pos-key)+1;
 
1039
 
 
1040
  pthread_mutex_lock(&LOCK_open); /* Obtain a name lock even though table is not in cache (like for create table)  */
 
1041
 
 
1042
  if (hash_search(&open_cache, (unsigned char *)key, key_length))
851
1043
  {
 
1044
    pthread_mutex_unlock(&LOCK_open);
852
1045
    *table= 0;
853
1046
    return false;
854
1047
  }
855
 
 
856
 
  if (not (*table= table_cache_insert_placeholder(identifier)))
 
1048
  if (!(*table= table_cache_insert_placeholder(key, key_length)))
857
1049
  {
 
1050
    pthread_mutex_unlock(&LOCK_open);
858
1051
    return true;
859
1052
  }
860
1053
  (*table)->open_placeholder= true;
861
 
  (*table)->setNext(open_tables);
 
1054
  (*table)->next= open_tables;
862
1055
  open_tables= *table;
 
1056
  pthread_mutex_unlock(&LOCK_open);
863
1057
 
864
1058
  return false;
865
1059
}
900
1094
Table *Session::openTable(TableList *table_list, bool *refresh, uint32_t flags)
901
1095
{
902
1096
  Table *table;
 
1097
  char key[MAX_DBKEY_LENGTH];
 
1098
  unsigned int key_length;
903
1099
  const char *alias= table_list->alias;
 
1100
  HASH_SEARCH_STATE state;
904
1101
 
905
1102
  /* Parsing of partitioning information from .frm needs session->lex set up. */
906
1103
  assert(lex->is_lex_started);
913
1110
  if (check_stack_overrun(this, STACK_MIN_SIZE_FOR_OPEN, (unsigned char *)&alias))
914
1111
    return NULL;
915
1112
 
916
 
  if (getKilled())
 
1113
  if (killed)
917
1114
    return NULL;
918
1115
 
919
 
  identifier::Table identifier(table_list->getSchemaName(), table_list->getTableName());
920
 
  const identifier::Table::Key &key(identifier.getKey());
921
 
  table::CacheRange ppp;
 
1116
  key_length= table_list->create_table_def_key(key);
922
1117
 
923
1118
  /*
924
1119
    Unless requested otherwise, try to resolve this table in the list
927
1122
    same name. This block implements the behaviour.
928
1123
    TODO -> move this block into a separate function.
929
1124
  */
930
 
  bool reset= false;
931
 
  for (table= getTemporaryTables(); table ; table=table->getNext())
 
1125
  for (table= temporary_tables; table ; table=table->next)
932
1126
  {
933
 
    if (table->getShare()->getCacheKey() == key)
 
1127
    if (table->s->table_cache_key.length == key_length && !memcmp(table->s->table_cache_key.str, key, key_length))
934
1128
    {
935
1129
      /*
936
1130
        We're trying to use the same temporary table twice in a query.
940
1134
      */
941
1135
      if (table->query_id)
942
1136
      {
943
 
        my_error(ER_CANT_REOPEN_TABLE, MYF(0), table->getAlias());
 
1137
        my_error(ER_CANT_REOPEN_TABLE, MYF(0), table->alias);
944
1138
        return NULL;
945
1139
      }
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
 
 
 
1140
      table->query_id= query_id;
 
1141
      goto reset;
 
1142
    }
 
1143
  }
 
1144
 
 
1145
  if (flags & DRIZZLE_OPEN_TEMPORARY_ONLY)
 
1146
  {
 
1147
    my_error(ER_NO_SUCH_TABLE, MYF(0), table_list->db, table_list->table_name);
 
1148
    return NULL;
 
1149
  }
 
1150
 
 
1151
  /*
 
1152
    If it's the first table from a list of tables used in a query,
 
1153
    remember refresh_version (the version of open_cache state).
 
1154
    If the version changes while we're opening the remaining tables,
 
1155
    we will have to back off, close all the tables opened-so-far,
 
1156
    and try to reopen them.
 
1157
 
 
1158
    Note-> refresh_version is currently changed only during FLUSH TABLES.
 
1159
  */
 
1160
  if (!open_tables)
 
1161
    version= refresh_version;
 
1162
  else if ((version != refresh_version) &&
 
1163
           ! (flags & DRIZZLE_LOCK_IGNORE_FLUSH))
 
1164
  {
 
1165
    /* Someone did a refresh while thread was opening tables */
 
1166
    if (refresh)
 
1167
      *refresh= true;
 
1168
 
 
1169
    return NULL;
 
1170
  }
 
1171
 
 
1172
  /*
 
1173
    Before we test the global cache, we test our local session cache.
 
1174
  */
 
1175
  if (cached_table)
 
1176
  {
 
1177
    assert(false); /* Not implemented yet */
 
1178
  }
 
1179
 
 
1180
  /*
 
1181
    Non pre-locked/LOCK TABLES mode, and the table is not temporary:
 
1182
    this is the normal use case.
 
1183
    Now we should:
 
1184
    - try to find the table in the table cache.
 
1185
    - if one of the discovered Table instances is name-locked
 
1186
    (table->s->version == 0) back off -- we have to wait
 
1187
    until no one holds a name lock on the table.
 
1188
    - if there is no such Table in the name cache, read the table definition
 
1189
    and insert it into the cache.
 
1190
    We perform all of the above under LOCK_open which currently protects
 
1191
    the open cache (also known as table cache) and table definitions stored
 
1192
    on disk.
 
1193
  */
 
1194
 
 
1195
  pthread_mutex_lock(&LOCK_open); /* Lock for FLUSH TABLES for open table */
 
1196
 
 
1197
  /*
 
1198
    Actually try to find the table in the open_cache.
 
1199
    The cache may contain several "Table" instances for the same
 
1200
    physical table. The instances that are currently "in use" by
 
1201
    some thread have their "in_use" member != NULL.
 
1202
    There is no good reason for having more than one entry in the
 
1203
    hash for the same physical table, except that we use this as
 
1204
    an implicit "pending locks queue" - see
 
1205
    wait_for_locked_table_names for details.
 
1206
  */
 
1207
  for (table= (Table*) hash_first(&open_cache, (unsigned char*) key, key_length,
 
1208
                                  &state);
 
1209
       table && table->in_use ;
 
1210
       table= (Table*) hash_next(&open_cache, (unsigned char*) key, key_length,
 
1211
                                 &state))
 
1212
  {
960
1213
    /*
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.
 
1214
      Here we flush tables marked for flush.
 
1215
      Normally, table->s->version contains the value of
 
1216
      refresh_version from the moment when this table was
 
1217
      (re-)opened and added to the cache.
 
1218
      If since then we did (or just started) FLUSH TABLES
 
1219
      statement, refresh_version has been increased.
 
1220
      For "name-locked" Table instances, table->s->version is set
 
1221
      to 0 (see lock_table_name for details).
 
1222
      In case there is a pending FLUSH TABLES or a name lock, we
 
1223
      need to back off and re-start opening tables.
 
1224
      If we do not back off now, we may dead lock in case of lock
 
1225
      order mismatch with some other thread:
 
1226
c1: name lock t1; -- sort of exclusive lock
 
1227
c2: open t2;      -- sort of shared lock
 
1228
c1: name lock t2; -- blocks
 
1229
c2: open t1; -- blocks
968
1230
    */
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 */
 
1231
    if (table->needs_reopen_or_name_lock())
 
1232
    {
 
1233
      if (flags & DRIZZLE_LOCK_IGNORE_FLUSH)
 
1234
      {
 
1235
        /* Force close at once after usage */
 
1236
        version= table->s->version;
 
1237
        continue;
 
1238
      }
 
1239
 
 
1240
      /* Avoid self-deadlocks by detecting self-dependencies. */
 
1241
      if (table->open_placeholder && table->in_use == this)
 
1242
      {
 
1243
        pthread_mutex_unlock(&LOCK_open);
 
1244
        my_error(ER_UPDATE_TABLE_USED, MYF(0), table->s->table_name.str);
 
1245
        return NULL;
 
1246
      }
 
1247
 
 
1248
      /*
 
1249
        Back off, part 1: mark the table as "unused" for the
 
1250
        purpose of name-locking by setting table->db_stat to 0. Do
 
1251
        that only for the tables in this thread that have an old
 
1252
        table->s->version (this is an optimization (?)).
 
1253
        table->db_stat == 0 signals wait_for_locked_table_names
 
1254
        that the tables in question are not used any more. See
 
1255
        table_is_used call for details.
 
1256
      */
 
1257
      close_old_data_files(false, false);
 
1258
 
 
1259
      /*
 
1260
        Back-off part 2: try to avoid "busy waiting" on the table:
 
1261
        if the table is in use by some other thread, we suspend
 
1262
        and wait till the operation is complete: when any
 
1263
        operation that juggles with table->s->version completes,
 
1264
        it broadcasts COND_refresh condition variable.
 
1265
        If 'old' table we met is in use by current thread we return
 
1266
        without waiting since in this situation it's this thread
 
1267
        which is responsible for broadcasting on COND_refresh
 
1268
        (and this was done already in Session::close_old_data_files()).
 
1269
        Good example of such situation is when we have statement
 
1270
        that needs two instances of table and FLUSH TABLES comes
 
1271
        after we open first instance but before we open second
 
1272
        instance.
 
1273
      */
 
1274
      if (table->in_use != this)
 
1275
      {
 
1276
        /* wait_for_conditionwill unlock LOCK_open for us */
 
1277
        wait_for_condition(&LOCK_open, &COND_refresh);
 
1278
      }
 
1279
      else
 
1280
      {
 
1281
        pthread_mutex_unlock(&LOCK_open);
 
1282
      }
 
1283
      /*
 
1284
        There is a refresh in progress for this table.
 
1285
        Signal the caller that it has to try again.
 
1286
      */
977
1287
      if (refresh)
978
1288
        *refresh= true;
979
 
 
980
1289
      return NULL;
981
1290
    }
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 */
 
1291
  }
 
1292
  if (table)
 
1293
  {
 
1294
    /* Unlink the table from "unused_tables" list. */
 
1295
    if (table == unused_tables)
 
1296
    {  // First unused
 
1297
      unused_tables=unused_tables->next; // Remove from link
 
1298
      if (table == unused_tables)
 
1299
        unused_tables= NULL;
989
1300
    }
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
 
 
 
1301
    table->prev->next=table->next; /* Remove from unused list */
 
1302
    table->next->prev=table->prev;
 
1303
    table->in_use= this;
 
1304
  }
 
1305
  else
 
1306
  {
 
1307
    /* Insert a new Table instance into the open cache */
 
1308
    int error;
 
1309
    /* Free cache if too big */
 
1310
    while (open_cache.records > table_cache_size && unused_tables)
 
1311
      hash_delete(&open_cache,(unsigned char*) unused_tables);
 
1312
 
 
1313
    if (table_list->create)
1006
1314
    {
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)
 
1315
      char path[FN_REFLEN];
 
1316
      size_t length;
 
1317
 
 
1318
      length= build_table_filename(path, sizeof(path),
 
1319
                                   table_list->db, table_list->table_name,
 
1320
                                   false);
 
1321
 
 
1322
      if (plugin::StorageEngine::getTableDefinition(*this, path, table_list->db, table_list->table_name, false) != EEXIST)
1024
1323
      {
1025
 
        table= (*iter).second;
1026
 
 
1027
 
        if (not table->in_use)
1028
 
          break;
1029
1324
        /*
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
 
1325
          Table to be created, so we need to create placeholder in table-cache.
1046
1326
        */
1047
 
        if (table->needs_reopen_or_name_lock())
 
1327
        if (!(table= table_cache_insert_placeholder(key, key_length)))
1048
1328
        {
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
 
 
 
1329
          pthread_mutex_unlock(&LOCK_open);
1107
1330
          return NULL;
1108
1331
        }
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
 
 
 
1332
        /*
 
1333
          Link placeholder to the open tables list so it will be automatically
 
1334
          removed once tables are closed. Also mark it so it won't be ignored
 
1335
          by other trying to take name-lock.
 
1336
        */
 
1337
        table->open_placeholder= true;
 
1338
        table->next= open_tables;
 
1339
        open_tables= table;
 
1340
        pthread_mutex_unlock(&LOCK_open);
 
1341
 
 
1342
        return table ;
 
1343
      }
 
1344
      /* Table exists. Let us try to open it. */
 
1345
    }
 
1346
 
 
1347
    /* make a new table */
 
1348
    table= (Table *)malloc(sizeof(Table));
 
1349
    if (table == NULL)
 
1350
    {
 
1351
      pthread_mutex_unlock(&LOCK_open);
 
1352
      return NULL;
 
1353
    }
 
1354
 
 
1355
    error= open_unireg_entry(this, table, table_list, alias, key, key_length);
 
1356
    if (error != 0)
 
1357
    {
 
1358
      free(table);
 
1359
      pthread_mutex_unlock(&LOCK_open);
 
1360
      return NULL;
 
1361
    }
 
1362
    my_hash_insert(&open_cache, (unsigned char*) table);
 
1363
  }
 
1364
 
 
1365
  pthread_mutex_unlock(&LOCK_open);
 
1366
  if (refresh)
 
1367
  {
 
1368
    table->next= open_tables; /* Link into simple list */
 
1369
    open_tables=table;
 
1370
  }
 
1371
  table->reginfo.lock_type= TL_READ; /* Assume read */
 
1372
 
 
1373
reset:
 
1374
  assert(table->s->ref_count > 0 || table->s->tmp_table != NO_TMP_TABLE);
 
1375
 
 
1376
  if (lex->need_correct_ident())
 
1377
    table->alias_name_used= my_strcasecmp(table_alias_charset,
 
1378
                                          table->s->table_name.str, alias);
1180
1379
  /* Fix alias if table name changes */
1181
 
  if (strcmp(table->getAlias(), alias))
 
1380
  if (strcmp(table->alias, alias))
1182
1381
  {
1183
 
    table->setAlias(alias);
 
1382
    uint32_t length=(uint32_t) strlen(alias)+1;
 
1383
    table->alias= (char*) realloc((char*) table->alias, length);
 
1384
    memcpy((void*) table->alias, alias, length);
1184
1385
  }
1185
1386
 
1186
1387
  /* These variables are also set in reopen_table() */
1191
1392
  table->maybe_null= false;
1192
1393
  table->force_index= false;
1193
1394
  table->status=STATUS_NO_RECORD;
1194
 
  table->insert_values.clear();
 
1395
  table->insert_values= 0;
1195
1396
  /* Catch wrong handling of the auto_increment_field_not_null. */
1196
1397
  assert(!table->auto_increment_field_not_null);
1197
1398
  table->auto_increment_field_not_null= false;
1198
1399
  if (table->timestamp_field)
1199
 
  {
1200
1400
    table->timestamp_field_type= table->timestamp_field->get_auto_set_type();
1201
 
  }
1202
1401
  table->pos_in_table_list= table_list;
1203
1402
  table->clear_column_bitmaps();
1204
1403
  assert(table->key_read == 0);
1207
1406
}
1208
1407
 
1209
1408
 
 
1409
/*
 
1410
  Reopen an table because the definition has changed.
 
1411
 
 
1412
  SYNOPSIS
 
1413
  reopen_table()
 
1414
  table Table object
 
1415
 
 
1416
  NOTES
 
1417
  The data cursor for the table is already closed and the share is released
 
1418
  The table has a 'dummy' share that mainly contains database and table name.
 
1419
 
 
1420
  RETURN
 
1421
  0  ok
 
1422
  1  error. The old table object is not changed.
 
1423
*/
 
1424
 
 
1425
bool reopen_table(Table *table)
 
1426
{
 
1427
  Table tmp;
 
1428
  bool error= 1;
 
1429
  Field **field;
 
1430
  uint32_t key,part;
 
1431
  TableList table_list;
 
1432
  Session *session= table->in_use;
 
1433
 
 
1434
  assert(table->s->ref_count == 0);
 
1435
  assert(!table->sort.io_cache);
 
1436
 
 
1437
#ifdef EXTRA_DEBUG
 
1438
  if (table->db_stat)
 
1439
    errmsg_printf(ERRMSG_LVL_ERROR, _("Table %s had a open data Cursor in reopen_table"),
 
1440
                  table->alias);
 
1441
#endif
 
1442
  table_list.db=         table->s->db.str;
 
1443
  table_list.table_name= table->s->table_name.str;
 
1444
  table_list.table=      table;
 
1445
 
 
1446
  if (wait_for_locked_table_names(session, &table_list))
 
1447
    return true;                             // Thread was killed
 
1448
 
 
1449
  if (open_unireg_entry(session, &tmp, &table_list,
 
1450
                        table->alias,
 
1451
                        table->s->table_cache_key.str,
 
1452
                        table->s->table_cache_key.length))
 
1453
    goto end;
 
1454
 
 
1455
  /* This list copies variables set by open_table */
 
1456
  tmp.tablenr=          table->tablenr;
 
1457
  tmp.used_fields=      table->used_fields;
 
1458
  tmp.const_table=      table->const_table;
 
1459
  tmp.null_row=         table->null_row;
 
1460
  tmp.maybe_null=       table->maybe_null;
 
1461
  tmp.status=           table->status;
 
1462
 
 
1463
  /* Get state */
 
1464
  tmp.in_use=           session;
 
1465
  tmp.reginfo.lock_type=table->reginfo.lock_type;
 
1466
 
 
1467
  /* Replace table in open list */
 
1468
  tmp.next=             table->next;
 
1469
  tmp.prev=             table->prev;
 
1470
 
 
1471
  if (table->cursor)
 
1472
    table->closefrm(true);              // close cursor, free everything
 
1473
 
 
1474
  *table= tmp;
 
1475
  table->default_column_bitmaps();
 
1476
  table->cursor->change_table_ptr(table, table->s);
 
1477
 
 
1478
  assert(table->alias != 0);
 
1479
  for (field=table->field ; *field ; field++)
 
1480
  {
 
1481
    (*field)->table= (*field)->orig_table= table;
 
1482
    (*field)->table_name= &table->alias;
 
1483
  }
 
1484
  for (key=0 ; key < table->s->keys ; key++)
 
1485
  {
 
1486
    for (part=0 ; part < table->key_info[key].usable_key_parts ; part++)
 
1487
      table->key_info[key].key_part[part].field->table= table;
 
1488
  }
 
1489
 
 
1490
  broadcast_refresh();
 
1491
  error= false;
 
1492
 
 
1493
end:
 
1494
  return(error);
 
1495
}
 
1496
 
 
1497
 
1210
1498
/**
1211
1499
  Close all instances of a table open by this thread and replace
1212
1500
  them with exclusive name-locks.
1224
1512
  the strings are used in a loop even after the share may be freed.
1225
1513
*/
1226
1514
 
1227
 
void Session::close_data_files_and_morph_locks(const identifier::Table &identifier)
 
1515
void Session::close_data_files_and_morph_locks(const char *new_db, const char *new_table_name)
1228
1516
{
1229
 
  safe_mutex_assert_owner(table::Cache::singleton().mutex().native_handle()); /* Adjust locks at the end of ALTER TABLEL */
 
1517
  Table *table;
 
1518
 
 
1519
  safe_mutex_assert_owner(&LOCK_open); /* Adjust locks at the end of ALTER TABLEL */
1230
1520
 
1231
1521
  if (lock)
1232
1522
  {
1234
1524
      If we are not under LOCK TABLES we should have only one table
1235
1525
      open and locked so it makes sense to remove the lock at once.
1236
1526
    */
1237
 
    unlockTables(lock);
 
1527
    mysql_unlock_tables(this, lock);
1238
1528
    lock= 0;
1239
1529
  }
1240
1530
 
1243
1533
    for target table name if we process ALTER Table ... RENAME.
1244
1534
    So loop below makes sense even if we are not under LOCK TABLES.
1245
1535
  */
1246
 
  for (Table *table= open_tables; table ; table=table->getNext())
 
1536
  for (table= open_tables; table ; table=table->next)
1247
1537
  {
1248
 
    if (table->getShare()->getCacheKey() == identifier.getKey())
 
1538
    if (!strcmp(table->s->table_name.str, new_table_name) &&
 
1539
        !strcmp(table->s->db.str, new_db))
1249
1540
    {
1250
1541
      table->open_placeholder= true;
1251
1542
      close_handle_and_leave_table_as_lock(table);
1269
1560
  combination when one needs tables to be reopened (for
1270
1561
  example see openTablesLock()).
1271
1562
 
1272
 
  @note One should have lock on table::Cache::singleton().mutex() when calling this.
 
1563
  @note One should have lock on LOCK_open when calling this.
1273
1564
 
1274
1565
  @return false in case of success, true - otherwise.
1275
1566
*/
1276
1567
 
1277
 
bool Session::reopen_tables()
 
1568
bool Session::reopen_tables(bool get_locks, bool mark_share_as_old)
1278
1569
{
1279
1570
  Table *table,*next,**prev;
1280
 
  Table **tables= 0;                    // For locks
1281
 
  Table **tables_ptr= 0;                        // For locks
1282
 
  bool error= false;
 
1571
  Table **tables,**tables_ptr;                  // For locks
 
1572
  bool error=0, not_used;
1283
1573
  const uint32_t flags= DRIZZLE_LOCK_NOTIFY_IF_NEED_REOPEN |
1284
1574
    DRIZZLE_LOCK_IGNORE_GLOBAL_READ_LOCK |
1285
1575
    DRIZZLE_LOCK_IGNORE_FLUSH;
1287
1577
  if (open_tables == NULL)
1288
1578
    return false;
1289
1579
 
1290
 
  safe_mutex_assert_owner(table::Cache::singleton().mutex().native_handle());
 
1580
  safe_mutex_assert_owner(&LOCK_open);
 
1581
  if (get_locks)
1291
1582
  {
1292
1583
    /*
1293
1584
      The ptr is checked later
1295
1586
    */
1296
1587
    uint32_t opens= 0;
1297
1588
 
1298
 
    for (table= open_tables; table ; table=table->getNext())
1299
 
    {
 
1589
    for (table= open_tables; table ; table=table->next)
1300
1590
      opens++;
1301
 
    }
1302
1591
    tables= new Table *[opens];
1303
1592
  }
1304
 
 
 
1593
  else
 
1594
    tables= &open_tables;
1305
1595
  tables_ptr =tables;
1306
1596
 
1307
1597
  prev= &open_tables;
1308
1598
  for (table= open_tables; table ; table=next)
1309
1599
  {
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;
 
1600
    uint32_t db_stat= table->db_stat;
 
1601
    next= table->next;
 
1602
    if (!tables || (!db_stat && reopen_table(table)))
 
1603
    {
 
1604
      my_error(ER_CANT_REOPEN_TABLE, MYF(0), table->alias);
 
1605
      hash_delete(&open_cache,(unsigned char*) table);
 
1606
      error= 1;
 
1607
    }
 
1608
    else
 
1609
    {
 
1610
      *prev= table;
 
1611
      prev= &table->next;
 
1612
      /* Do not handle locks of MERGE children. */
 
1613
      if (get_locks && !db_stat)
 
1614
        *tables_ptr++= table;                   // need new lock on this
 
1615
      if (mark_share_as_old)
 
1616
      {
 
1617
        table->s->version= 0;
 
1618
        table->open_placeholder= false;
 
1619
      }
 
1620
    }
1315
1621
  }
1316
1622
  *prev=0;
1317
 
 
1318
1623
  if (tables != tables_ptr)                     // Should we get back old locks
1319
1624
  {
1320
 
    DrizzleLock *local_lock;
 
1625
    DRIZZLE_LOCK *local_lock;
1321
1626
    /*
1322
1627
      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
 
1628
      wait_for_tables() as it tries to acquire LOCK_open, which is
1324
1629
      already locked.
1325
1630
    */
1326
1631
    some_tables_deleted= false;
1327
1632
 
1328
 
    if ((local_lock= lockTables(tables, (uint32_t) (tables_ptr - tables), flags)))
 
1633
    if ((local_lock= mysql_lock_tables(this, tables, (uint32_t) (tables_ptr - tables),
 
1634
                                 flags, &not_used)))
1329
1635
    {
1330
1636
      /* unused */
1331
1637
    }
1341
1647
    }
1342
1648
  }
1343
1649
 
1344
 
  delete [] tables;
1345
 
 
1346
 
  locking::broadcast_refresh();
1347
 
 
1348
 
  return error;
 
1650
  if (get_locks && tables)
 
1651
    delete [] tables;
 
1652
 
 
1653
  broadcast_refresh();
 
1654
 
 
1655
  return(error);
1349
1656
}
1350
1657
 
1351
1658
 
1369
1676
 
1370
1677
  Table *table= open_tables;
1371
1678
 
1372
 
  for (; table ; table=table->getNext())
 
1679
  for (; table ; table=table->next)
1373
1680
  {
1374
1681
    /*
1375
1682
      Reopen marked for flush.
1376
1683
    */
1377
1684
    if (table->needs_reopen_or_name_lock())
1378
1685
    {
1379
 
      found= true;
 
1686
      found=1;
1380
1687
      if (table->db_stat)
1381
1688
      {
1382
1689
        if (morph_locks)
1390
1697
              lock on it. This will also give them a chance to close their
1391
1698
              instances of this table.
1392
1699
            */
1393
 
            abortLock(ulcktbl);
1394
 
            removeLock(ulcktbl);
 
1700
            mysql_lock_abort(this, ulcktbl);
 
1701
            mysql_lock_remove(this, ulcktbl);
1395
1702
            ulcktbl->lock_count= 0;
1396
1703
          }
1397
1704
          if ((ulcktbl != table) && ulcktbl->db_stat)
1431
1738
    }
1432
1739
  }
1433
1740
  if (found)
1434
 
    locking::broadcast_refresh();
 
1741
    broadcast_refresh();
 
1742
}
 
1743
 
 
1744
 
 
1745
/*
 
1746
  Wait until all threads has closed the tables in the list
 
1747
  We have also to wait if there is thread that has a lock on this table even
 
1748
  if the table is closed
 
1749
*/
 
1750
 
 
1751
bool table_is_used(Table *table, bool wait_for_name_lock)
 
1752
{
 
1753
  do
 
1754
  {
 
1755
    char *key= table->s->table_cache_key.str;
 
1756
    uint32_t key_length= table->s->table_cache_key.length;
 
1757
 
 
1758
    HASH_SEARCH_STATE state;
 
1759
    for (Table *search= (Table*) hash_first(&open_cache, (unsigned char*) key,
 
1760
                                            key_length, &state);
 
1761
         search ;
 
1762
         search= (Table*) hash_next(&open_cache, (unsigned char*) key,
 
1763
                                    key_length, &state))
 
1764
    {
 
1765
      if (search->in_use == table->in_use)
 
1766
        continue;                               // Name locked by this thread
 
1767
      /*
 
1768
        We can't use the table under any of the following conditions:
 
1769
        - There is an name lock on it (Table is to be deleted or altered)
 
1770
        - If we are in flush table and we didn't execute the flush
 
1771
        - If the table engine is open and it's an old version
 
1772
        (We must wait until all engines are shut down to use the table)
 
1773
      */
 
1774
      if ( (search->locked_by_name && wait_for_name_lock) ||
 
1775
           (search->is_name_opened() && search->needs_reopen_or_name_lock()))
 
1776
        return 1;
 
1777
    }
 
1778
  } while ((table=table->next));
 
1779
  return 0;
 
1780
}
 
1781
 
 
1782
 
 
1783
/* Wait until all used tables are refreshed */
 
1784
 
 
1785
bool wait_for_tables(Session *session)
 
1786
{
 
1787
  bool result;
 
1788
 
 
1789
  session->set_proc_info("Waiting for tables");
 
1790
  pthread_mutex_lock(&LOCK_open); /* Lock for all tables to be refreshed */
 
1791
  while (!session->killed)
 
1792
  {
 
1793
    session->some_tables_deleted= false;
 
1794
    session->close_old_data_files(false, dropping_tables != 0);
 
1795
    if (!table_is_used(session->open_tables, 1))
 
1796
      break;
 
1797
    (void) pthread_cond_wait(&COND_refresh,&LOCK_open);
 
1798
  }
 
1799
  if (session->killed)
 
1800
    result= true;                                       // aborted
 
1801
  else
 
1802
  {
 
1803
    /* Now we can open all tables without any interference */
 
1804
    session->set_proc_info("Reopen tables");
 
1805
    session->version= refresh_version;
 
1806
    result= session->reopen_tables(false, false);
 
1807
  }
 
1808
  pthread_mutex_unlock(&LOCK_open);
 
1809
  session->set_proc_info(0);
 
1810
 
 
1811
  return result;
1435
1812
}
1436
1813
 
1437
1814
 
1459
1836
*/
1460
1837
 
1461
1838
 
1462
 
Table *drop_locked_tables(Session *session, const drizzled::identifier::Table &identifier)
 
1839
Table *drop_locked_tables(Session *session,const char *db, const char *table_name)
1463
1840
{
1464
1841
  Table *table,*next,**prev, *found= 0;
1465
1842
  prev= &session->open_tables;
1466
1843
 
1467
1844
  /*
1468
 
    Note that we need to hold table::Cache::singleton().mutex() while changing the
 
1845
    Note that we need to hold LOCK_open while changing the
1469
1846
    open_tables list. Another thread may work on it.
1470
 
    (See: table::Cache::singleton().removeTable(), wait_completed_table())
 
1847
    (See: remove_table_from_cache(), mysql_wait_completed_table())
1471
1848
    Closing a MERGE child before the parent would be fatal if the
1472
1849
    other thread tries to abort the MERGE lock in between.
1473
1850
  */
1474
1851
  for (table= session->open_tables; table ; table=next)
1475
1852
  {
1476
 
    next=table->getNext();
1477
 
    if (table->getShare()->getCacheKey() == identifier.getKey())
 
1853
    next=table->next;
 
1854
    if (!strcmp(table->s->table_name.str, table_name) &&
 
1855
        !strcmp(table->s->db.str, db))
1478
1856
    {
1479
 
      session->removeLock(table);
 
1857
      mysql_lock_remove(session, table);
1480
1858
 
1481
1859
      if (!found)
1482
1860
      {
1491
1869
      else
1492
1870
      {
1493
1871
        /* We already have a name lock, remove copy */
1494
 
        table::remove_table(static_cast<table::Concurrent *>(table));
 
1872
        hash_delete(&open_cache,(unsigned char*) table);
1495
1873
      }
1496
1874
    }
1497
1875
    else
1498
1876
    {
1499
1877
      *prev=table;
1500
 
      prev= table->getNextPtr();
 
1878
      prev= &table->next;
1501
1879
    }
1502
1880
  }
1503
1881
  *prev=0;
1504
 
 
1505
1882
  if (found)
1506
 
    locking::broadcast_refresh();
 
1883
    broadcast_refresh();
1507
1884
 
1508
 
  return found;
 
1885
  return(found);
1509
1886
}
1510
1887
 
1511
1888
 
1515
1892
  other threads trying to get the lock.
1516
1893
*/
1517
1894
 
1518
 
void abort_locked_tables(Session *session, const drizzled::identifier::Table &identifier)
 
1895
void abort_locked_tables(Session *session,const char *db, const char *table_name)
1519
1896
{
1520
1897
  Table *table;
1521
 
  for (table= session->open_tables; table ; table= table->getNext())
 
1898
  for (table= session->open_tables; table ; table= table->next)
1522
1899
  {
1523
 
    if (table->getShare()->getCacheKey() == identifier.getKey())
 
1900
    if (!strcmp(table->s->table_name.str, table_name) &&
 
1901
        !strcmp(table->s->db.str, db))
1524
1902
    {
1525
1903
      /* If MERGE child, forward lock handling to parent. */
1526
 
      session->abortLock(table);
1527
 
      assert(0);
 
1904
      mysql_lock_abort(session, table);
1528
1905
      break;
1529
1906
    }
1530
1907
  }
1531
1908
}
1532
1909
 
 
1910
/*
 
1911
  Load a table definition from cursor and open unireg table
 
1912
 
 
1913
  SYNOPSIS
 
1914
  open_unireg_entry()
 
1915
  session                       Thread handle
 
1916
  entry         Store open table definition here
 
1917
  table_list            TableList with db, table_name
 
1918
  alias         Alias name
 
1919
  cache_key             Key for share_cache
 
1920
  cache_key_length      length of cache_key
 
1921
 
 
1922
  NOTES
 
1923
  Extra argument for open is taken from session->open_options
 
1924
  One must have a lock on LOCK_open when calling this function
 
1925
 
 
1926
  RETURN
 
1927
  0     ok
 
1928
#       Error
 
1929
*/
 
1930
 
 
1931
static int open_unireg_entry(Session *session, Table *entry, TableList *table_list,
 
1932
                             const char *alias,
 
1933
                             char *cache_key, uint32_t cache_key_length)
 
1934
{
 
1935
  int error;
 
1936
  TableShare *share;
 
1937
  uint32_t discover_retry_count= 0;
 
1938
 
 
1939
  safe_mutex_assert_owner(&LOCK_open);
 
1940
retry:
 
1941
  if (!(share= TableShare::getShare(session, table_list, cache_key,
 
1942
                                    cache_key_length,
 
1943
                                    table_list->i_s_requested_object,
 
1944
                                    &error)))
 
1945
    return 1;
 
1946
 
 
1947
  while ((error= open_table_from_share(session, share, alias,
 
1948
                                       (uint32_t) (HA_OPEN_KEYFILE |
 
1949
                                                   HA_OPEN_RNDFILE |
 
1950
                                                   HA_GET_INDEX |
 
1951
                                                   HA_TRY_READ_ONLY),
 
1952
                                       (EXTRA_RECORD),
 
1953
                                       session->open_options, entry)))
 
1954
  {
 
1955
    if (error == 7)                             // Table def changed
 
1956
    {
 
1957
      share->version= 0;                        // Mark share as old
 
1958
      if (discover_retry_count++)               // Retry once
 
1959
        goto err;
 
1960
 
 
1961
      /*
 
1962
        TODO->
 
1963
        Here we should wait until all threads has released the table.
 
1964
        For now we do one retry. This may cause a deadlock if there
 
1965
        is other threads waiting for other tables used by this thread.
 
1966
 
 
1967
        Proper fix would be to if the second retry failed:
 
1968
        - Mark that table def changed
 
1969
        - Return from open table
 
1970
        - Close all tables used by this thread
 
1971
        - Start waiting that the share is released
 
1972
        - Retry by opening all tables again
 
1973
      */
 
1974
 
 
1975
      /*
 
1976
        TO BE FIXED
 
1977
        To avoid deadlock, only wait for release if no one else is
 
1978
        using the share.
 
1979
      */
 
1980
      if (share->ref_count != 1)
 
1981
        goto err;
 
1982
      /* Free share and wait until it's released by all threads */
 
1983
      TableShare::release(share);
 
1984
 
 
1985
      if (!session->killed)
 
1986
      {
 
1987
        drizzle_reset_errors(session, 1);         // Clear warnings
 
1988
        session->clear_error();                 // Clear error message
 
1989
        goto retry;
 
1990
      }
 
1991
      return 1;
 
1992
    }
 
1993
    if (!entry->s || !entry->s->crashed)
 
1994
      goto err;
 
1995
    // Code below is for repairing a crashed cursor
 
1996
    if ((error= lock_table_name(session, table_list, true)))
 
1997
    {
 
1998
      if (error < 0)
 
1999
        goto err;
 
2000
      if (wait_for_locked_table_names(session, table_list))
 
2001
      {
 
2002
        unlock_table_name(table_list);
 
2003
        goto err;
 
2004
      }
 
2005
    }
 
2006
    pthread_mutex_unlock(&LOCK_open);
 
2007
    session->clear_error();                             // Clear error message
 
2008
    error= 0;
 
2009
    if (open_table_from_share(session, share, alias,
 
2010
                              (uint32_t) (HA_OPEN_KEYFILE | HA_OPEN_RNDFILE |
 
2011
                                          HA_GET_INDEX |
 
2012
                                          HA_TRY_READ_ONLY),
 
2013
                              EXTRA_RECORD,
 
2014
                              ha_open_options | HA_OPEN_FOR_REPAIR,
 
2015
                              entry) || ! entry->cursor)
 
2016
    {
 
2017
      /* Give right error message */
 
2018
      session->clear_error();
 
2019
      my_error(ER_NOT_KEYFILE, MYF(0), share->table_name.str, my_errno);
 
2020
      errmsg_printf(ERRMSG_LVL_ERROR, _("Couldn't repair table: %s.%s"), share->db.str,
 
2021
                    share->table_name.str);
 
2022
      if (entry->cursor)
 
2023
        entry->closefrm(false);
 
2024
      error=1;
 
2025
    }
 
2026
    else
 
2027
      session->clear_error();                   // Clear error message
 
2028
    pthread_mutex_lock(&LOCK_open);
 
2029
    unlock_table_name(table_list);
 
2030
 
 
2031
    if (error)
 
2032
      goto err;
 
2033
    break;
 
2034
  }
 
2035
 
 
2036
  /*
 
2037
    If we are here, there was no fatal error (but error may be still
 
2038
    unitialized).
 
2039
  */
 
2040
  if (unlikely(entry->cursor->implicit_emptied))
 
2041
  {
 
2042
    ReplicationServices &replication_services= ReplicationServices::singleton();
 
2043
    entry->cursor->implicit_emptied= 0;
 
2044
    {
 
2045
      char *query, *end;
 
2046
      uint32_t query_buf_size= 20 + share->db.length + share->table_name.length +1;
 
2047
      if ((query= (char*) malloc(query_buf_size)))
 
2048
      {
 
2049
        /* 
 
2050
          "this DELETE FROM is needed even with row-based binlogging"
 
2051
 
 
2052
          We inherited this from MySQL. TODO: fix it to issue a propper truncate
 
2053
          of the table (though that may not be completely right sematics).
 
2054
        */
 
2055
        end= query;
 
2056
        end+= sprintf(query, "DELETE FROM `%s`.`%s`", share->db.str,
 
2057
                      share->table_name.str);
 
2058
        replication_services.rawStatement(session, query, (size_t)(end - query)); 
 
2059
        free(query);
 
2060
      }
 
2061
      else
 
2062
      {
 
2063
        errmsg_printf(ERRMSG_LVL_ERROR, _("When opening HEAP table, could not allocate memory "
 
2064
                                          "to write 'DELETE FROM `%s`.`%s`' to replication"),
 
2065
                      table_list->db, table_list->table_name);
 
2066
        my_error(ER_OUTOFMEMORY, MYF(0), query_buf_size);
 
2067
        entry->closefrm(false);
 
2068
        goto err;
 
2069
      }
 
2070
    }
 
2071
  }
 
2072
  return 0;
 
2073
 
 
2074
err:
 
2075
  TableShare::release(share);
 
2076
 
 
2077
  return 1;
 
2078
}
 
2079
 
1533
2080
 
1534
2081
/*
1535
2082
  Open all tables in list
1590
2137
    {
1591
2138
      continue;
1592
2139
    }
 
2140
    /*
 
2141
      If this TableList object is a placeholder for an information_schema
 
2142
      table, create a temporary table to represent the information_schema
 
2143
      table in the query. Do not fill it yet - will be filled during
 
2144
      execution.
 
2145
    */
 
2146
    if (tables->schema_table)
 
2147
    {
 
2148
      if (mysql_schema_table(this, lex, tables) == false)
 
2149
        continue;
 
2150
      return -1;
 
2151
    }
1593
2152
    (*counter)++;
1594
2153
 
1595
2154
    /*
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
2155
      Not a placeholder: must be a base table or a view, and the table is
1610
2156
      not opened yet. Try to open the table.
1611
2157
    */
1644
2190
    {
1645
2191
      if (tables->lock_type == TL_WRITE_DEFAULT)
1646
2192
        tables->table->reginfo.lock_type= update_lock_default;
1647
 
      else if (tables->table->getShare()->getType() == message::Table::STANDARD)
 
2193
      else if (tables->table->s->tmp_table == NO_TMP_TABLE)
1648
2194
        tables->table->reginfo.lock_type= tables->lock_type;
1649
2195
    }
1650
2196
  }
1695
2241
 
1696
2242
  set_proc_info("Opening table");
1697
2243
  current_tablenr= 0;
1698
 
  while (!(table= openTable(table_list, &refresh)) && refresh) ;
 
2244
  while (!(table= openTable(table_list, &refresh)) &&
 
2245
         refresh)
 
2246
    ;
1699
2247
 
1700
2248
  if (table)
1701
2249
  {
1704
2252
 
1705
2253
    assert(lock == 0);  // You must lock everything at once
1706
2254
    if ((table->reginfo.lock_type= lock_type) != TL_UNLOCK)
1707
 
    {
1708
 
      if (not (lock= lockTables(&table_list->table, 1, 0)))
1709
 
        table= NULL;
1710
 
    }
 
2255
      if (! (lock= mysql_lock_tables(this, &table_list->table, 1, 0, &refresh)))
 
2256
        table= 0;
1711
2257
  }
1712
2258
 
1713
2259
  set_proc_info(0);
1761
2307
  Table **start,**ptr;
1762
2308
  uint32_t lock_flag= DRIZZLE_LOCK_NOTIFY_IF_NEED_REOPEN;
1763
2309
 
1764
 
  if (!(ptr=start=(Table**) session->getMemRoot()->allocate(sizeof(Table*)*count)))
 
2310
  if (!(ptr=start=(Table**) session->alloc(sizeof(Table*)*count)))
1765
2311
    return -1;
1766
 
 
1767
2312
  for (table= tables; table; table= table->next_global)
1768
2313
  {
1769
2314
    if (!table->placeholder())
1770
2315
      *(ptr++)= table->table;
1771
2316
  }
1772
2317
 
1773
 
  if (not (session->lock= session->lockTables(start, (uint32_t) (ptr - start), lock_flag)))
 
2318
  if (!(session->lock= mysql_lock_tables(session, start, (uint32_t) (ptr - start),
 
2319
                                         lock_flag, need_reopen)))
1774
2320
  {
1775
2321
    return -1;
1776
2322
  }
1799
2345
#  Table object
1800
2346
*/
1801
2347
 
1802
 
Table *Open_tables_state::open_temporary_table(const identifier::Table &identifier,
1803
 
                                               bool link_in_list)
 
2348
Table *Session::open_temporary_table(const char *path, const char *db_arg,
 
2349
                                     const char *table_name_arg, bool link_in_list)
1804
2350
{
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)
 
2351
  Table *new_tmp_table;
 
2352
  TableShare *share;
 
2353
  char cache_key[MAX_DBKEY_LENGTH], *saved_cache_key, *tmp_path;
 
2354
  uint32_t key_length, path_length;
 
2355
  TableList table_list;
 
2356
 
 
2357
  table_list.db=         (char*) db_arg;
 
2358
  table_list.table_name= (char*) table_name_arg;
 
2359
  /* Create the cache_key for temporary tables */
 
2360
  key_length= table_list.create_table_def_key(cache_key);
 
2361
  path_length= strlen(path);
 
2362
 
 
2363
  if (!(new_tmp_table= (Table*) malloc(sizeof(*new_tmp_table) + sizeof(*share) +
 
2364
                                       path_length + 1 + key_length)))
1813
2365
    return NULL;
1814
2366
 
 
2367
  share= (TableShare*) (new_tmp_table+1);
 
2368
  tmp_path= (char*) (share+1);
 
2369
  saved_cache_key= strcpy(tmp_path, path)+path_length+1;
 
2370
  memcpy(saved_cache_key, cache_key, key_length);
 
2371
 
 
2372
  share->init(saved_cache_key, key_length, strchr(saved_cache_key, '\0')+1, tmp_path);
 
2373
 
1815
2374
  /*
1816
2375
    First open the share, and then open the table from the share we just opened.
1817
2376
  */
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))
 
2377
  if (open_table_def(*this, share) ||
 
2378
      open_table_from_share(this, share, table_name_arg,
 
2379
                            (uint32_t) (HA_OPEN_KEYFILE | HA_OPEN_RNDFILE |
 
2380
                                        HA_GET_INDEX),
 
2381
                            (EXTRA_RECORD),
 
2382
                            ha_open_options,
 
2383
                            new_tmp_table))
1824
2384
  {
1825
2385
    /* 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
 
 
 
2386
    share->free_table_share();
 
2387
    free((char*) new_tmp_table);
1829
2388
    return 0;
1830
2389
  }
1831
2390
 
1832
2391
  new_tmp_table->reginfo.lock_type= TL_WRITE;    // Simulate locked
 
2392
  share->tmp_table= (new_tmp_table->cursor->has_transactions() ?
 
2393
                     TRANSACTIONAL_TMP_TABLE : NON_TRANSACTIONAL_TMP_TABLE);
1833
2394
 
1834
2395
  if (link_in_list)
1835
2396
  {
1836
2397
    /* 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
 
    }
 
2398
    new_tmp_table->next= this->temporary_tables;
 
2399
    if (new_tmp_table->next)
 
2400
      new_tmp_table->next->prev= new_tmp_table;
1842
2401
    this->temporary_tables= new_tmp_table;
1843
 
    this->temporary_tables->setPrev(0);
 
2402
    this->temporary_tables->prev= 0;
1844
2403
  }
1845
2404
  new_tmp_table->pos_in_table_list= 0;
1846
2405
 
1865
2424
{
1866
2425
  if (session->mark_used_columns != MARK_COLUMNS_NONE)
1867
2426
  {
1868
 
    boost::dynamic_bitset<> *current_bitmap= NULL;
 
2427
    MyBitmap *current_bitmap, *other_bitmap;
1869
2428
 
1870
2429
    /*
1871
2430
      We always want to register the used keys, as the column bitmap may have
1878
2437
    if (session->mark_used_columns == MARK_COLUMNS_READ)
1879
2438
    {
1880
2439
      current_bitmap= table->read_set;
 
2440
      other_bitmap=   table->write_set;
1881
2441
    }
1882
2442
    else
1883
2443
    {
1884
2444
      current_bitmap= table->write_set;
 
2445
      other_bitmap=   table->read_set;
1885
2446
    }
1886
2447
 
1887
 
    //if (current_bitmap->testAndSet(field->position()))
1888
 
    if (current_bitmap->test(field->position()))
 
2448
    if (current_bitmap->testAndSet(field->field_index))
1889
2449
    {
1890
2450
      if (session->mark_used_columns == MARK_COLUMNS_WRITE)
1891
2451
        session->dup_field= field;
1944
2504
    {
1945
2505
      if (nj_col)
1946
2506
      {
1947
 
        my_error(ER_NON_UNIQ_ERROR, MYF(0), name, session->where());
 
2507
        my_error(ER_NON_UNIQ_ERROR, MYF(0), name, session->where);
1948
2508
        return NULL;
1949
2509
      }
1950
2510
      nj_col= curr_nj_col;
1954
2514
    return NULL;
1955
2515
  {
1956
2516
    /* This is a base table. */
1957
 
    assert(nj_col->table_ref->table == nj_col->table_field->getTable());
 
2517
    assert(nj_col->table_ref->table == nj_col->table_field->table);
1958
2518
    found_field= nj_col->table_field;
1959
2519
    update_field_dependencies(session, found_field, nj_col->table_ref->table);
1960
2520
  }
1991
2551
  uint32_t cached_field_index= *cached_field_index_ptr;
1992
2552
 
1993
2553
  /* We assume here that table->field < NO_CACHED_FIELD_INDEX = UINT_MAX */
1994
 
  if (cached_field_index < table->getShare()->sizeFields() &&
 
2554
  if (cached_field_index < table->s->fields &&
1995
2555
      !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));
 
2556
                     table->field[cached_field_index]->field_name, name))
 
2557
    field_ptr= table->field + cached_field_index;
 
2558
  else if (table->s->name_hash.records)
 
2559
  {
 
2560
    field_ptr= (Field**) hash_search(&table->s->name_hash, (unsigned char*) name,
 
2561
                                     length);
2003
2562
    if (field_ptr)
2004
2563
    {
2005
2564
      /*
2006
2565
        field_ptr points to field in TableShare. Convert it to the matching
2007
2566
        field in table
2008
2567
      */
2009
 
      field_ptr= (table->getFields() + table->getShare()->positionFields(field_ptr));
 
2568
      field_ptr= (table->field + (field_ptr - table->s->field));
2010
2569
    }
2011
2570
  }
2012
2571
  else
2013
2572
  {
2014
 
    if (!(field_ptr= table->getFields()))
 
2573
    if (!(field_ptr= table->field))
2015
2574
      return((Field *)0);
2016
2575
    for (; *field_ptr; ++field_ptr)
2017
2576
      if (!my_strcasecmp(system_charset_info, (*field_ptr)->field_name, name))
2020
2579
 
2021
2580
  if (field_ptr && *field_ptr)
2022
2581
  {
2023
 
    *cached_field_index_ptr= field_ptr - table->getFields();
 
2582
    *cached_field_index_ptr= field_ptr - table->field;
2024
2583
    field= *field_ptr;
2025
2584
  }
2026
2585
  else
2027
2586
  {
2028
2587
    if (!allow_rowid ||
2029
2588
        my_strcasecmp(system_charset_info, name, "_rowid") ||
2030
 
        table->getShare()->rowid_field_offset == 0)
 
2589
        table->s->rowid_field_offset == 0)
2031
2590
      return((Field*) 0);
2032
 
    field= table->getField(table->getShare()->rowid_field_offset-1);
 
2591
    field= table->field[table->s->rowid_field_offset-1];
2033
2592
  }
2034
2593
 
2035
2594
  update_field_dependencies(session, field, table);
2108
2667
    inside the view, but we want to search directly in the view columns
2109
2668
    which are represented as a 'field_translation'.
2110
2669
 
2111
 
    TODO-> Ensure that table_name, db_name and tables->db always points to something !
 
2670
TODO: Ensure that table_name, db_name and tables->db always points to
 
2671
something !
2112
2672
  */
2113
2673
  if (/* Exclude nested joins. */
2114
 
      (!table_list->getNestedJoin()) &&
 
2674
      (!table_list->nested_join) &&
2115
2675
      /* Include merge views and information schema tables. */
2116
2676
      /*
2117
2677
        Test if the field qualifiers match the table reference we plan
2119
2679
      */
2120
2680
      table_name && table_name[0] &&
2121
2681
      (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()))))
 
2682
       (db_name && db_name[0] && table_list->db && table_list->db[0] &&
 
2683
        strcmp(db_name, table_list->db))))
2124
2684
    return 0;
2125
2685
 
2126
2686
  *actual_table= NULL;
2127
2687
 
2128
 
  if (!table_list->getNestedJoin())
 
2688
  if (!table_list->nested_join)
2129
2689
  {
2130
2690
    /* 'table_list' is a stored table. */
2131
2691
    assert(table_list->table);
2145
2705
    */
2146
2706
    if (table_name && table_name[0])
2147
2707
    {
2148
 
      List_iterator<TableList> it(table_list->getNestedJoin()->join_list);
 
2708
      List_iterator<TableList> it(table_list->nested_join->join_list);
2149
2709
      TableList *table;
2150
2710
      while ((table= it++))
2151
2711
      {
2193
2753
        field_to_set= fld;
2194
2754
      if (field_to_set)
2195
2755
      {
2196
 
        Table *table= field_to_set->getTable();
 
2756
        Table *table= field_to_set->table;
2197
2757
        if (session->mark_used_columns == MARK_COLUMNS_READ)
2198
 
          table->setReadSet(field_to_set->position());
 
2758
          table->setReadSet(field_to_set->field_index);
2199
2759
        else
2200
 
          table->setWriteSet(field_to_set->position());
 
2760
          table->setWriteSet(field_to_set->field_index);
2201
2761
      }
2202
2762
    }
2203
2763
  }
2341
2901
      */
2342
2902
      item->cached_table= found ?  0 : actual_table;
2343
2903
 
2344
 
      assert(session->where());
 
2904
      assert(session->where);
2345
2905
      /*
2346
2906
        If we found a fully qualified field we return it directly as it can't
2347
2907
        have duplicates.
2354
2914
        if (report_error == REPORT_ALL_ERRORS ||
2355
2915
            report_error == IGNORE_EXCEPT_NON_UNIQUE)
2356
2916
          my_error(ER_NON_UNIQ_ERROR, MYF(0),
2357
 
                   table_name ? item->full_name() : name, session->where());
 
2917
                   table_name ? item->full_name() : name, session->where);
2358
2918
        return (Field*) 0;
2359
2919
      }
2360
2920
      found= cur_field;
2387
2947
      strcat(buff, table_name);
2388
2948
      table_name=buff;
2389
2949
    }
2390
 
    my_error(ER_UNKNOWN_TABLE, MYF(0), table_name, session->where());
 
2950
    my_error(ER_UNKNOWN_TABLE, MYF(0), table_name, session->where);
2391
2951
  }
2392
2952
  else
2393
2953
  {
2394
2954
    if (report_error == REPORT_ALL_ERRORS ||
2395
2955
        report_error == REPORT_EXCEPT_NON_UNIQUE)
2396
 
      my_error(ER_BAD_FIELD_ERROR, MYF(0), item->full_name(), session->where());
 
2956
      my_error(ER_BAD_FIELD_ERROR, MYF(0), item->full_name(), session->where);
2397
2957
    else
2398
2958
      found= not_found_field;
2399
2959
  }
2439
2999
 
2440
3000
 
2441
3001
Item **
2442
 
find_item_in_list(Session *session,
2443
 
                  Item *find, List<Item> &items, uint32_t *counter,
 
3002
find_item_in_list(Item *find, List<Item> &items, uint32_t *counter,
2444
3003
                  find_item_error_report_type report_error,
2445
3004
                  enum_resolution_type *resolution)
2446
3005
{
2520
3079
            */
2521
3080
            if (report_error != IGNORE_ERRORS)
2522
3081
              my_error(ER_NON_UNIQ_ERROR, MYF(0),
2523
 
                       find->full_name(), session->where());
 
3082
                       find->full_name(), current_session->where);
2524
3083
            return (Item**) 0;
2525
3084
          }
2526
3085
          found_unaliased= li.ref();
2551
3110
              continue;                           // Same field twice
2552
3111
            if (report_error != IGNORE_ERRORS)
2553
3112
              my_error(ER_NON_UNIQ_ERROR, MYF(0),
2554
 
                       find->full_name(), session->where());
 
3113
                       find->full_name(), current_session->where);
2555
3114
            return (Item**) 0;
2556
3115
          }
2557
3116
          found= li.ref();
2603
3162
    {
2604
3163
      if (report_error != IGNORE_ERRORS)
2605
3164
        my_error(ER_NON_UNIQ_ERROR, MYF(0),
2606
 
                 find->full_name(), session->where());
 
3165
                 find->full_name(), current_session->where);
2607
3166
      return (Item **) 0;
2608
3167
    }
2609
3168
    if (found_unaliased)
2619
3178
  {
2620
3179
    if (report_error == REPORT_ALL_ERRORS)
2621
3180
      my_error(ER_BAD_FIELD_ERROR, MYF(0),
2622
 
               find->full_name(), session->where());
 
3181
               find->full_name(), current_session->where);
2623
3182
    return (Item **) 0;
2624
3183
  }
2625
3184
  else
2737
3296
    Leaf table references to which new natural join columns are added
2738
3297
    if the leaves are != NULL.
2739
3298
  */
2740
 
  TableList *leaf_1= (table_ref_1->getNestedJoin() &&
2741
 
                      ! table_ref_1->is_natural_join) ?
 
3299
  TableList *leaf_1= (table_ref_1->nested_join &&
 
3300
                      !table_ref_1->is_natural_join) ?
2742
3301
    NULL : table_ref_1;
2743
 
  TableList *leaf_2= (table_ref_2->getNestedJoin() &&
2744
 
                      ! table_ref_2->is_natural_join) ?
 
3302
  TableList *leaf_2= (table_ref_2->nested_join &&
 
3303
                      !table_ref_2->is_natural_join) ?
2745
3304
    NULL : table_ref_2;
2746
3305
 
2747
3306
  *found_using_fields= 0;
2753
3312
    /* true if field_name_1 is a member of using_fields */
2754
3313
    bool is_using_column_1;
2755
3314
    if (!(nj_col_1= it_1.get_or_create_column_ref(leaf_1)))
2756
 
      return(result);
 
3315
      goto err;
2757
3316
    field_name_1= nj_col_1->name();
2758
3317
    is_using_column_1= using_fields &&
2759
3318
      test_if_string_in_list(field_name_1, using_fields);
2771
3330
      Natural_join_column *cur_nj_col_2;
2772
3331
      const char *cur_field_name_2;
2773
3332
      if (!(cur_nj_col_2= it_2.get_or_create_column_ref(leaf_2)))
2774
 
        return(result);
 
3333
        goto err;
2775
3334
      cur_field_name_2= cur_nj_col_2->name();
2776
3335
 
2777
3336
      /*
2790
3349
        if (cur_nj_col_2->is_common ||
2791
3350
            (found && (!using_fields || is_using_column_1)))
2792
3351
        {
2793
 
          my_error(ER_NON_UNIQ_ERROR, MYF(0), field_name_1, session->where());
2794
 
          return(result);
 
3352
          my_error(ER_NON_UNIQ_ERROR, MYF(0), field_name_1, session->where);
 
3353
          goto err;
2795
3354
        }
2796
3355
        nj_col_2= cur_nj_col_2;
2797
3356
        found= true;
2824
3383
      Item_func_eq *eq_cond;
2825
3384
 
2826
3385
      if (!item_1 || !item_2)
2827
 
        return(result); // out of memory
 
3386
        goto err;                               // out of memory
2828
3387
 
2829
3388
      /*
2830
3389
        In the case of no_wrap_view_item == 0, the created items must be
2849
3408
      */
2850
3409
      if (set_new_item_local_context(session, item_ident_1, nj_col_1->table_ref) ||
2851
3410
          set_new_item_local_context(session, item_ident_2, nj_col_2->table_ref))
2852
 
        return(result);
 
3411
        goto err;
2853
3412
 
2854
3413
      if (!(eq_cond= new Item_func_eq(item_ident_1, item_ident_2)))
2855
 
        return(result);                               /* Out of memory. */
 
3414
        goto err;                               /* Out of memory. */
2856
3415
 
2857
3416
      /*
2858
3417
        Add the new equi-join condition to the ON clause. Notice that
2869
3428
      {
2870
3429
        Table *table_1= nj_col_1->table_ref->table;
2871
3430
        /* Mark field_1 used for table cache. */
2872
 
        table_1->setReadSet(field_1->position());
 
3431
        table_1->setReadSet(field_1->field_index);
2873
3432
        table_1->covering_keys&= field_1->part_of_key;
2874
3433
        table_1->merge_keys|= field_1->part_of_key;
2875
3434
      }
2877
3436
      {
2878
3437
        Table *table_2= nj_col_2->table_ref->table;
2879
3438
        /* Mark field_2 used for table cache. */
2880
 
        table_2->setReadSet(field_2->position());
 
3439
        table_2->setReadSet(field_2->field_index);
2881
3440
        table_2->covering_keys&= field_2->part_of_key;
2882
3441
        table_2->merge_keys|= field_2->part_of_key;
2883
3442
      }
2898
3457
  */
2899
3458
  result= false;
2900
3459
 
 
3460
err:
2901
3461
  return(result);
2902
3462
}
2903
3463
 
2939
3499
*/
2940
3500
 
2941
3501
static bool
2942
 
store_natural_using_join_columns(Session *session,
 
3502
store_natural_using_join_columns(Session *,
2943
3503
                                 TableList *natural_using_join,
2944
3504
                                 TableList *table_ref_1,
2945
3505
                                 TableList *table_ref_2,
2955
3515
 
2956
3516
  if (!(non_join_columns= new List<Natural_join_column>) ||
2957
3517
      !(natural_using_join->join_columns= new List<Natural_join_column>))
2958
 
  {
2959
 
    return(result);
2960
 
  }
 
3518
    goto err;
2961
3519
 
2962
3520
  /* Append the columns of the first join operand. */
2963
3521
  for (it_1.set(table_ref_1); !it_1.end_of_fields(); it_1.next())
2995
3553
        if (!(common_field= it++))
2996
3554
        {
2997
3555
          my_error(ER_BAD_FIELD_ERROR, MYF(0), using_field_name_ptr,
2998
 
                   session->where());
2999
 
          return(result);
 
3556
                   current_session->where);
 
3557
          goto err;
3000
3558
        }
3001
3559
        if (!my_strcasecmp(system_charset_info,
3002
3560
                           common_field->name(), using_field_name_ptr))
3024
3582
 
3025
3583
  result= false;
3026
3584
 
 
3585
err:
3027
3586
  return(result);
3028
3587
}
3029
3588
 
3066
3625
  bool result= true;
3067
3626
 
3068
3627
  /* Call the procedure recursively for each nested table reference. */
3069
 
  if (table_ref->getNestedJoin())
 
3628
  if (table_ref->nested_join)
3070
3629
  {
3071
 
    List_iterator_fast<TableList> nested_it(table_ref->getNestedJoin()->join_list);
 
3630
    List_iterator_fast<TableList> nested_it(table_ref->nested_join->join_list);
3072
3631
    TableList *same_level_left_neighbor= nested_it++;
3073
3632
    TableList *same_level_right_neighbor= NULL;
3074
3633
    /* Left/right-most neighbors, possibly at higher levels in the join tree. */
3093
3652
          cur_table_ref->outer_join & JOIN_TYPE_RIGHT)
3094
3653
      {
3095
3654
        /* This can happen only for JOIN ... ON. */
3096
 
        assert(table_ref->getNestedJoin()->join_list.elements == 2);
 
3655
        assert(table_ref->nested_join->join_list.elements == 2);
3097
3656
        std::swap(same_level_left_neighbor, cur_table_ref);
3098
3657
      }
3099
3658
 
3106
3665
      real_right_neighbor= (same_level_right_neighbor) ?
3107
3666
        same_level_right_neighbor : right_neighbor;
3108
3667
 
3109
 
      if (cur_table_ref->getNestedJoin() &&
 
3668
      if (cur_table_ref->nested_join &&
3110
3669
          store_top_level_join_columns(session, cur_table_ref,
3111
3670
                                       real_left_neighbor, real_right_neighbor))
3112
 
        return(result);
 
3671
        goto err;
3113
3672
      same_level_right_neighbor= cur_table_ref;
3114
3673
    }
3115
3674
  }
3120
3679
  */
3121
3680
  if (table_ref->is_natural_join)
3122
3681
  {
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);
 
3682
    assert(table_ref->nested_join &&
 
3683
           table_ref->nested_join->join_list.elements == 2);
 
3684
    List_iterator_fast<TableList> operand_it(table_ref->nested_join->join_list);
3126
3685
    /*
3127
3686
      Notice that the order of join operands depends on whether table_ref
3128
3687
      represents a LEFT or a RIGHT join. In a RIGHT join, the operands are
3141
3700
      std::swap(table_ref_1, table_ref_2);
3142
3701
    if (mark_common_columns(session, table_ref_1, table_ref_2,
3143
3702
                            using_fields, &found_using_fields))
3144
 
      return(result);
 
3703
      goto err;
3145
3704
 
3146
3705
    /*
3147
3706
      Swap the join operands back, so that we pick the columns of the second
3153
3712
    if (store_natural_using_join_columns(session, table_ref, table_ref_1,
3154
3713
                                         table_ref_2, using_fields,
3155
3714
                                         found_using_fields))
3156
 
      return(result);
 
3715
      goto err;
3157
3716
 
3158
3717
    /*
3159
3718
      Change NATURAL JOIN to JOIN ... ON. We do this for both operands
3186
3745
  }
3187
3746
  result= false; /* All is OK. */
3188
3747
 
 
3748
err:
3189
3749
  return(result);
3190
3750
}
3191
3751
 
3218
3778
                                         List<TableList> *from_clause,
3219
3779
                                         Name_resolution_context *context)
3220
3780
{
3221
 
  session->setWhere("from clause");
 
3781
  session->where= "from clause";
3222
3782
  if (from_clause->elements == 0)
3223
3783
    return false; /* We come here in the case of UNIONs. */
3224
3784
 
3339
3899
  session->mark_used_columns= mark_used_columns;
3340
3900
  if (allow_sum_func)
3341
3901
    session->lex->allow_sum_func|= 1 << session->lex->current_select->nest_level;
3342
 
  session->setWhere(Session::DEFAULT_WHERE);
 
3902
  session->where= Session::DEFAULT_WHERE;
3343
3903
  save_is_item_list_lookup= session->lex->current_select->is_item_list_lookup;
3344
3904
  session->lex->current_select->is_item_list_lookup= 0;
3345
3905
 
3351
3911
    There is other way to solve problem: fill array with pointers to list,
3352
3912
    but it will be slower.
3353
3913
 
3354
 
    TODO-> remove it when (if) we made one list for allfields and ref_pointer_array
 
3914
TODO: remove it when (if) we made one list for allfields and
 
3915
ref_pointer_array
3355
3916
  */
3356
3917
  if (ref_pointer_array)
3357
 
  {
3358
3918
    memset(ref_pointer_array, 0, sizeof(Item *) * fields.elements);
3359
 
  }
3360
3919
 
3361
3920
  Item **ref= ref_pointer_array;
3362
3921
  session->lex->current_select->cur_pos_in_select_list= 0;
3588
4147
    assert(tables->is_leaf_for_name_resolution());
3589
4148
 
3590
4149
    if ((table_name && my_strcasecmp(table_alias_charset, table_name, tables->alias)) ||
3591
 
        (db_name && my_strcasecmp(system_charset_info, tables->getSchemaName(),db_name)))
 
4150
        (db_name && strcmp(tables->db,db_name)))
3592
4151
      continue;
3593
4152
 
3594
4153
    /*
3624
4183
      if ((field= field_iterator.field()))
3625
4184
      {
3626
4185
        /* Mark fields as used to allow storage engine to optimze access */
3627
 
        field->getTable()->setReadSet(field->position());
 
4186
        field->table->setReadSet(field->field_index);
3628
4187
        if (table)
3629
4188
        {
3630
4189
          table->covering_keys&= field->part_of_key;
3652
4211
        }
3653
4212
      }
3654
4213
      else
3655
 
      {
3656
4214
        session->used_tables|= item->used_tables();
3657
 
      }
3658
 
 
3659
4215
      session->lex->current_select->cur_pos_in_select_list++;
3660
4216
    }
3661
4217
    /*
3665
4221
      For NATURAL joins, used_tables is updated in the IF above.
3666
4222
    */
3667
4223
    if (table)
3668
 
      table->used_fields= table->getShare()->sizeFields();
 
4224
      table->used_fields= table->s->fields;
3669
4225
  }
3670
4226
  if (found)
3671
4227
    return false;
3672
4228
 
3673
4229
  /*
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.
 
4230
TODO: in the case when we skipped all columns because there was a
 
4231
qualified '*', and all columns were coalesced, we have to give a more
 
4232
meaningful message than ER_BAD_TABLE_ERROR.
3677
4233
  */
3678
 
  if (not table_name)
3679
 
  {
 
4234
  if (!table_name)
3680
4235
    my_message(ER_NO_TABLES_USED, ER(ER_NO_TABLES_USED), MYF(0));
3681
 
  }
3682
4236
  else
3683
 
  {
3684
4237
    my_error(ER_BAD_TABLE_ERROR, MYF(0), table_name);
3685
 
  }
3686
4238
 
3687
4239
  return true;
3688
4240
}
3731
4283
  session->session_marker= (void*)1;
3732
4284
  if (*conds)
3733
4285
  {
3734
 
    session->setWhere("where clause");
 
4286
    session->where="where clause";
3735
4287
    if ((!(*conds)->fixed && (*conds)->fix_fields(session, conds)) ||
3736
4288
        (*conds)->check_cols(1))
3737
4289
      goto err_no_arena;
3753
4305
      {
3754
4306
        /* Make a join an a expression */
3755
4307
        session->session_marker= (void*)embedded;
3756
 
        session->setWhere("on clause");
 
4308
        session->where="on clause";
3757
4309
        if ((!embedded->on_expr->fixed && embedded->on_expr->fix_fields(session, &embedded->on_expr)) ||
3758
4310
            embedded->on_expr->check_cols(1))
3759
4311
          goto err_no_arena;
3760
4312
        select_lex->cond_count++;
3761
4313
      }
3762
 
      embedding= embedded->getEmbedding();
 
4314
      embedding= embedded->embedding;
3763
4315
    }
3764
4316
    while (embedding &&
3765
 
           embedding->getNestedJoin()->join_list.head() == embedded);
 
4317
           embedding->nested_join->join_list.head() == embedded);
3766
4318
 
3767
4319
  }
3768
4320
  session->session_marker= save_session_marker;
3788
4340
 
3789
4341
  SYNOPSIS
3790
4342
  fill_record()
 
4343
  session           thread Cursor
3791
4344
  fields        Item_fields list to be filled
3792
4345
  values        values to fill with
3793
4346
  ignore_errors true if we should ignore errors
3803
4356
*/
3804
4357
 
3805
4358
bool
3806
 
fill_record(Session *session, List<Item> &fields, List<Item> &values, bool ignore_errors)
 
4359
fill_record(Session * session, List<Item> &fields, List<Item> &values, bool ignore_errors)
3807
4360
{
3808
4361
  List_iterator_fast<Item> f(fields),v(values);
3809
 
  Item *value;
 
4362
  Item *value, *fld;
3810
4363
  Item_field *field;
3811
 
  Table *table;
 
4364
  Table *table= 0;
 
4365
  List<Table> tbl_list;
 
4366
  bool abort_on_warning_saved= session->abort_on_warning;
 
4367
  tbl_list.empty();
3812
4368
 
3813
4369
  /*
3814
4370
    Reset the table->auto_increment_field_not_null as it is valid for
3820
4376
      On INSERT or UPDATE fields are checked to be from the same table,
3821
4377
      thus we safely can take table from the first field.
3822
4378
    */
3823
 
    field= static_cast<Item_field *>(f++);
3824
 
    table= field->field->getTable();
 
4379
    fld= (Item_field*)f++;
 
4380
    if (!(field= fld->filed_for_view_update()))
 
4381
    {
 
4382
      my_error(ER_NONUPDATEABLE_COLUMN, MYF(0), fld->name);
 
4383
      goto err;
 
4384
    }
 
4385
    table= field->field->table;
3825
4386
    table->auto_increment_field_not_null= false;
3826
4387
    f.rewind();
3827
4388
  }
3828
 
 
3829
 
  while ((field= static_cast<Item_field *>(f++)))
 
4389
  while ((fld= f++))
3830
4390
  {
3831
 
    value= v++;
3832
 
 
 
4391
    if (!(field= fld->filed_for_view_update()))
 
4392
    {
 
4393
      my_error(ER_NONUPDATEABLE_COLUMN, MYF(0), fld->name);
 
4394
      goto err;
 
4395
    }
 
4396
    value=v++;
3833
4397
    Field *rfield= field->field;
3834
 
    table= rfield->getTable();
3835
 
 
 
4398
    table= rfield->table;
3836
4399
    if (rfield == table->next_number_field)
3837
4400
      table->auto_increment_field_not_null= true;
3838
4401
    if ((value->save_in_field(rfield, 0) < 0) && !ignore_errors)
3839
4402
    {
3840
4403
      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();
 
4404
      goto err;
 
4405
    }
 
4406
    tbl_list.push_back(table);
 
4407
  }
 
4408
  /* Update virtual fields*/
 
4409
  session->abort_on_warning= false;
 
4410
  if (tbl_list.head())
 
4411
  {
 
4412
    List_iterator_fast<Table> t(tbl_list);
 
4413
    Table *prev_table= 0;
 
4414
    while ((table= t++))
 
4415
    {
 
4416
      /*
 
4417
        Do simple optimization to prevent unnecessary re-generating
 
4418
        values for virtual fields
 
4419
      */
 
4420
      if (table != prev_table)
 
4421
        prev_table= table;
 
4422
    }
 
4423
  }
 
4424
  session->abort_on_warning= abort_on_warning_saved;
 
4425
  return(session->is_error());
 
4426
err:
 
4427
  session->abort_on_warning= abort_on_warning_saved;
 
4428
  if (table)
 
4429
    table->auto_increment_field_not_null= false;
 
4430
  return true;
3849
4431
}
3850
4432
 
3851
4433
 
3854
4436
 
3855
4437
  SYNOPSIS
3856
4438
  fill_record()
 
4439
  session           thread Cursor
3857
4440
  ptr           pointer on pointer to record
3858
4441
  values        list of fields
3859
4442
  ignore_errors true if we should ignore errors
3868
4451
  true    error occured
3869
4452
*/
3870
4453
 
3871
 
bool fill_record(Session *session, Field **ptr, List<Item> &values, bool)
 
4454
bool
 
4455
fill_record(Session *session, Field **ptr, List<Item> &values,
 
4456
            bool )
3872
4457
{
3873
4458
  List_iterator_fast<Item> v(values);
3874
4459
  Item *value;
3875
4460
  Table *table= 0;
3876
4461
  Field *field;
 
4462
  List<Table> tbl_list;
 
4463
  bool abort_on_warning_saved= session->abort_on_warning;
3877
4464
 
 
4465
  tbl_list.empty();
3878
4466
  /*
3879
4467
    Reset the table->auto_increment_field_not_null as it is valid for
3880
4468
    only one row.
3885
4473
      On INSERT or UPDATE fields are checked to be from the same table,
3886
4474
      thus we safely can take table from the first field.
3887
4475
    */
3888
 
    table= (*ptr)->getTable();
 
4476
    table= (*ptr)->table;
3889
4477
    table->auto_increment_field_not_null= false;
3890
4478
  }
3891
 
 
3892
4479
  while ((field = *ptr++) && ! session->is_error())
3893
4480
  {
3894
4481
    value=v++;
3895
 
    table= field->getTable();
3896
 
 
 
4482
    table= field->table;
3897
4483
    if (field == table->next_number_field)
3898
4484
      table->auto_increment_field_not_null= true;
3899
 
 
3900
4485
    if (value->save_in_field(field, 0) < 0)
 
4486
      goto err;
 
4487
    tbl_list.push_back(table);
 
4488
  }
 
4489
  /* Update virtual fields*/
 
4490
  session->abort_on_warning= false;
 
4491
  if (tbl_list.head())
 
4492
  {
 
4493
    List_iterator_fast<Table> t(tbl_list);
 
4494
    Table *prev_table= 0;
 
4495
    while ((table= t++))
3901
4496
    {
3902
 
      if (table)
3903
 
        table->auto_increment_field_not_null= false;
3904
 
 
3905
 
      return true;
 
4497
      /*
 
4498
        Do simple optimization to prevent unnecessary re-generating
 
4499
        values for virtual fields
 
4500
      */
 
4501
      if (table != prev_table)
 
4502
      {
 
4503
        prev_table= table;
 
4504
      }
3906
4505
    }
3907
4506
  }
3908
 
 
 
4507
  session->abort_on_warning= abort_on_warning_saved;
3909
4508
  return(session->is_error());
 
4509
 
 
4510
err:
 
4511
  session->abort_on_warning= abort_on_warning_saved;
 
4512
  if (table)
 
4513
    table->auto_increment_field_not_null= false;
 
4514
  return true;
3910
4515
}
3911
4516
 
3912
4517
 
3913
4518
bool drizzle_rm_tmp_tables()
3914
4519
{
3915
 
 
3916
 
  assert(drizzle_tmpdir.size());
3917
 
  Session::shared_ptr session= Session::make_shared(plugin::Listen::getNullClient(), catalog::local());
3918
 
 
3919
 
  if (not session)
 
4520
  Session *session;
 
4521
 
 
4522
  assert(drizzle_tmpdir);
 
4523
 
 
4524
  if (!(session= new Session(plugin::Listen::getNullClient())))
3920
4525
    return true;
3921
 
  session->thread_stack= (char*) session.get();
 
4526
  session->thread_stack= (char*) &session;
3922
4527
  session->storeGlobals();
3923
4528
 
3924
 
  plugin::StorageEngine::removeLostTemporaryTables(*session, drizzle_tmpdir.c_str());
 
4529
  plugin::StorageEngine::removeLostTemporaryTables(*session, drizzle_tmpdir);
 
4530
 
 
4531
  delete session;
3925
4532
 
3926
4533
  return false;
3927
4534
}
3932
4539
  unireg support functions
3933
4540
 *****************************************************************************/
3934
4541
 
3935
 
 
 
4542
/*
 
4543
  Invalidate any cache entries that are for some DB
 
4544
 
 
4545
  SYNOPSIS
 
4546
  remove_db_from_cache()
 
4547
  db            Database name. This will be in lower case if
 
4548
  lower_case_table_name is set
 
4549
 
 
4550
NOTE:
 
4551
We can't use hash_delete when looping hash_elements. We mark them first
 
4552
and afterwards delete those marked unused.
 
4553
*/
 
4554
 
 
4555
void remove_db_from_cache(const char *db)
 
4556
{
 
4557
  safe_mutex_assert_owner(&LOCK_open);
 
4558
 
 
4559
  for (uint32_t idx=0 ; idx < open_cache.records ; idx++)
 
4560
  {
 
4561
    Table *table=(Table*) hash_element(&open_cache,idx);
 
4562
    if (!strcmp(table->s->db.str, db))
 
4563
    {
 
4564
      table->s->version= 0L;                    /* Free when thread is ready */
 
4565
      if (!table->in_use)
 
4566
        relink_unused(table);
 
4567
    }
 
4568
  }
 
4569
  while (unused_tables && !unused_tables->s->version)
 
4570
    hash_delete(&open_cache,(unsigned char*) unused_tables);
 
4571
}
 
4572
 
 
4573
 
 
4574
/*
 
4575
  Mark all entries with the table as deleted to force an reopen of the table
 
4576
 
 
4577
  The table will be closed (not stored in cache) by the current thread when
 
4578
  close_thread_tables() is called.
 
4579
 
 
4580
  PREREQUISITES
 
4581
  Lock on LOCK_open()
 
4582
 
 
4583
  RETURN
 
4584
  0  This thread now have exclusive access to this table and no other thread
 
4585
  can access the table until close_thread_tables() is called.
 
4586
  1  Table is in use by another thread
 
4587
*/
 
4588
 
 
4589
bool remove_table_from_cache(Session *session, const char *db, const char *table_name,
 
4590
                             uint32_t flags)
 
4591
{
 
4592
  char key[MAX_DBKEY_LENGTH];
 
4593
  char *key_pos= key;
 
4594
  uint32_t key_length;
 
4595
  Table *table;
 
4596
  bool result= false; 
 
4597
  bool signalled= false;
 
4598
 
 
4599
  key_pos= strcpy(key_pos, db) + strlen(db);
 
4600
  key_pos= strcpy(key_pos+1, table_name) + strlen(table_name);
 
4601
  key_length= (uint32_t) (key_pos-key)+1;
 
4602
 
 
4603
  for (;;)
 
4604
  {
 
4605
    HASH_SEARCH_STATE state;
 
4606
    result= signalled= false;
 
4607
 
 
4608
    for (table= (Table*) hash_first(&open_cache, (unsigned char*) key, key_length,
 
4609
                                    &state);
 
4610
         table;
 
4611
         table= (Table*) hash_next(&open_cache, (unsigned char*) key, key_length,
 
4612
                                   &state))
 
4613
    {
 
4614
      Session *in_use;
 
4615
 
 
4616
      table->s->version=0L;             /* Free when thread is ready */
 
4617
      if (!(in_use=table->in_use))
 
4618
      {
 
4619
        relink_unused(table);
 
4620
      }
 
4621
      else if (in_use != session)
 
4622
      {
 
4623
        /*
 
4624
          Mark that table is going to be deleted from cache. This will
 
4625
          force threads that are in mysql_lock_tables() (but not yet
 
4626
          in thr_multi_lock()) to abort it's locks, close all tables and retry
 
4627
        */
 
4628
        in_use->some_tables_deleted= true;
 
4629
        if (table->is_name_opened())
 
4630
        {
 
4631
          result= true;
 
4632
        }
 
4633
        /*
 
4634
          Now we must abort all tables locks used by this thread
 
4635
          as the thread may be waiting to get a lock for another table.
 
4636
          Note that we need to hold LOCK_open while going through the
 
4637
          list. So that the other thread cannot change it. The other
 
4638
          thread must also hold LOCK_open whenever changing the
 
4639
          open_tables list. Aborting the MERGE lock after a child was
 
4640
          closed and before the parent is closed would be fatal.
 
4641
        */
 
4642
        for (Table *session_table= in_use->open_tables;
 
4643
             session_table ;
 
4644
             session_table= session_table->next)
 
4645
        {
 
4646
          /* Do not handle locks of MERGE children. */
 
4647
          if (session_table->db_stat)   // If table is open
 
4648
            signalled|= mysql_lock_abort_for_thread(session, session_table);
 
4649
        }
 
4650
      }
 
4651
      else
 
4652
        result= result || (flags & RTFC_OWNED_BY_Session_FLAG);
 
4653
    }
 
4654
    while (unused_tables && !unused_tables->s->version)
 
4655
      hash_delete(&open_cache,(unsigned char*) unused_tables);
 
4656
 
 
4657
    /* Remove table from table definition cache if it's not in use */
 
4658
    TableShare::release(key, key_length);
 
4659
 
 
4660
    if (result && (flags & RTFC_WAIT_OTHER_THREAD_FLAG))
 
4661
    {
 
4662
      /*
 
4663
        Signal any thread waiting for tables to be freed to
 
4664
        reopen their tables
 
4665
      */
 
4666
      broadcast_refresh();
 
4667
      if (!(flags & RTFC_CHECK_KILLED_FLAG) || !session->killed)
 
4668
      {
 
4669
        dropping_tables++;
 
4670
        if (likely(signalled))
 
4671
          (void) pthread_cond_wait(&COND_refresh, &LOCK_open);
 
4672
        else
 
4673
        {
 
4674
          struct timespec abstime;
 
4675
          /*
 
4676
            It can happen that another thread has opened the
 
4677
            table but has not yet locked any table at all. Since
 
4678
            it can be locked waiting for a table that our thread
 
4679
            has done LOCK Table x WRITE on previously, we need to
 
4680
            ensure that the thread actually hears our signal
 
4681
            before we go to sleep. Thus we wait for a short time
 
4682
            and then we retry another loop in the
 
4683
            remove_table_from_cache routine.
 
4684
          */
 
4685
          set_timespec(abstime, 10);
 
4686
          pthread_cond_timedwait(&COND_refresh, &LOCK_open, &abstime);
 
4687
        }
 
4688
        dropping_tables--;
 
4689
        continue;
 
4690
      }
 
4691
    }
 
4692
    break;
 
4693
  }
 
4694
  return result;
 
4695
}
3936
4696
 
3937
4697
 
3938
4698
/**
3944
4704
  pthread_kill(signal_thread, SIGTERM);
3945
4705
  shutdown_in_progress= 1;                      // Safety if kill didn't work
3946
4706
}
3947
 
 
3948
 
} /* namespace drizzled */