~drizzle-trunk/drizzle/development

« back to all changes in this revision

Viewing changes to drizzled/sql_base.cc

  • Committer: Stewart Smith
  • Date: 2009-06-16 00:44:35 UTC
  • mto: (1119.2.6 merge)
  • mto: This revision was merged to the branch mainline in revision 1124.
  • Revision ID: stewart@flamingspork.com-20090616004435-t1vust6erhco7edc
make comment_index test not leave tables behind after running

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