~drizzle-trunk/drizzle/development

« back to all changes in this revision

Viewing changes to drizzled/sql_base.cc

  • Committer: Brian Aker
  • Date: 2009-08-04 06:21:17 UTC
  • mfrom: (1108.2.2 merge)
  • Revision ID: brian@gaz-20090804062117-fef8x6y3ydzrvab3
Merge Brian

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/listen.h>
 
48
#include <mysys/cached_directory.h>
62
49
 
63
50
using namespace std;
64
51
 
65
 
namespace drizzled
66
 
{
67
 
 
68
 
extern bool volatile shutdown_in_progress;
 
52
extern drizzled::ReplicationServices replication_services;
 
53
 
 
54
/**
 
55
  @defgroup Data_Dictionary Data Dictionary
 
56
  @{
 
57
*/
 
58
Table *unused_tables;                           /* Used by mysql_test */
 
59
HASH open_cache;                                /* Used by mysql_test */
 
60
static int open_unireg_entry(Session *session, Table *entry, TableList *table_list,
 
61
                             const char *alias,
 
62
                             char *cache_key, uint32_t cache_key_length);
 
63
extern "C"
 
64
{
 
65
  void free_cache_entry(void *entry);
 
66
  unsigned char *table_cache_key(const unsigned char *record,
 
67
                                 size_t *length,
 
68
                                 bool );
 
69
  unsigned char *table_def_key(const unsigned char *record,
 
70
                               size_t *length,
 
71
                               bool );
 
72
}
 
73
 
 
74
 
 
75
 
 
76
unsigned char *table_cache_key(const unsigned char *record,
 
77
                               size_t *length,
 
78
                               bool )
 
79
{
 
80
  Table *entry=(Table*) record;
 
81
  *length= entry->s->table_cache_key.length;
 
82
  return (unsigned char*) entry->s->table_cache_key.str;
 
83
}
 
84
 
69
85
 
70
86
bool table_cache_init(void)
71
87
{
72
 
  return false;
 
88
  return hash_init(&open_cache, &my_charset_bin,
 
89
                   (size_t) table_cache_size+16,
 
90
                   0, 0, table_cache_key,
 
91
                   free_cache_entry, 0);
 
92
}
 
93
 
 
94
void table_cache_free(void)
 
95
{
 
96
  close_cached_tables(NULL, NULL, false, false);
 
97
  if (!open_cache.records)                      // Safety first
 
98
    hash_free(&open_cache);
73
99
}
74
100
 
75
101
uint32_t cached_open_tables(void)
76
102
{
77
 
  return table::getCache().size();
78
 
}
79
 
 
80
 
void table_cache_free(void)
81
 
{
82
 
  refresh_version++;                            // Force close of open tables
83
 
 
84
 
  table::getUnused().clear();
85
 
  table::getCache().clear();
86
 
}
 
103
  return open_cache.records;
 
104
}
 
105
 
87
106
 
88
107
/*
89
 
  Close cursor handle, but leave the table in the table cache
 
108
  Close file handle, but leave the table in the table cache
90
109
 
91
110
  SYNOPSIS
92
111
  close_handle_and_leave_table_as_lock()
93
 
  table         Table Cursor
 
112
  table         Table handler
94
113
 
95
114
  NOTES
96
115
  By leaving the table in the table cache, it disallows any other thread
97
116
  to open the table
98
117
 
99
 
  session->getKilled() will be set if we run out of memory
 
118
  session->killed will be set if we run out of memory
100
119
 
101
120
  If closing a MERGE child, the calling function has to take care for
102
121
  closing the parent too, if necessary.
105
124
 
106
125
void close_handle_and_leave_table_as_lock(Table *table)
107
126
{
 
127
  TableShare *share, *old_share= table->s;
 
128
  char *key_buff;
 
129
  MEM_ROOT *mem_root= &table->mem_root;
 
130
 
108
131
  assert(table->db_stat);
109
 
  assert(table->getShare()->getType() == message::Table::STANDARD);
110
132
 
111
133
  /*
112
134
    Make a local copy of the table share and free the current one.
113
135
    This has to be done to ensure that the table share is removed from
114
136
    the table defintion cache as soon as the last instance is removed
115
137
  */
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
 
 
 
138
  if (multi_alloc_root(mem_root,
 
139
                       &share, sizeof(*share),
 
140
                       &key_buff, old_share->table_cache_key.length,
 
141
                       NULL))
 
142
  {
 
143
    memset(share, 0, sizeof(*share));
 
144
    share->set_table_cache_key(key_buff, old_share->table_cache_key.str,
 
145
                               old_share->table_cache_key.length);
 
146
    share->tmp_table= INTERNAL_TMP_TABLE;       // for intern_close_table()
 
147
  }
 
148
 
 
149
  table->file->close();
 
150
  table->db_stat= 0;                            // Mark file closed
 
151
  TableShare::release(table->s);
 
152
  table->s= share;
 
153
  table->file->change_table_ptr(table, table->s);
 
154
}
 
155
 
 
156
 
 
157
 
 
158
/*
 
159
  Create a list for all open tables matching SQL expression
 
160
 
 
161
  SYNOPSIS
 
162
  list_open_tables()
 
163
  wild          SQL like expression
 
164
 
 
165
  NOTES
 
166
  One gets only a list of tables for which one has any kind of privilege.
 
167
  db and table names are allocated in result struct, so one doesn't need
 
168
  a lock on LOCK_open when traversing the return list.
 
169
 
 
170
  RETURN VALUES
 
171
  true  Error 
 
172
*/
 
173
 
 
174
bool list_open_tables(const char *db, const char *wild, bool(*func)(Table *table, open_table_list_st& open_list), Table *display)
 
175
{
 
176
  vector<open_table_list_st> open_list;
 
177
  vector<open_table_list_st>::iterator it;
 
178
  open_table_list_st table;
 
179
 
 
180
  /* What we really need is an optimization for knowing unique tables */
 
181
  if (db && wild)
 
182
    open_list.reserve(sizeof(open_table_list_st) * (open_cache.records % 2));
 
183
  else
 
184
    open_list.reserve(sizeof(open_table_list_st) * open_cache.records);
 
185
 
 
186
  pthread_mutex_lock(&LOCK_open); /* List all open tables */
 
187
 
 
188
  for (uint32_t idx= 0; idx < open_cache.records; idx++)
 
189
  {
 
190
    bool found= false;
 
191
    Table *entry=(Table*) hash_element(&open_cache,idx);
 
192
 
 
193
    if (db && my_strcasecmp(system_charset_info, db, entry->s->db.str))
 
194
      continue;
 
195
    if (wild && wild_compare(entry->s->table_name.str, wild, 0))
 
196
      continue;
 
197
 
 
198
    for (it= open_list.begin(); it < open_list.end(); it++)
 
199
    {
 
200
      if (!(*it).table.compare(entry->s->table_name.str) &&
 
201
          !(*it).db.compare(entry->s->db.str))
 
202
      {
 
203
        if (entry->in_use)
 
204
          (*it).in_use++;
 
205
        if (entry->locked_by_name)
 
206
          (*it).locked++;
 
207
 
 
208
        found= true;
 
209
 
 
210
        break;
 
211
      }
 
212
    }
 
213
 
 
214
    if (found)
 
215
      continue;
 
216
 
 
217
    table.db= entry->s->db.str;
 
218
    table.table= entry->s->table_name.str;
 
219
    open_list.push_back(table);
 
220
  }
 
221
  pthread_mutex_unlock(&LOCK_open);
 
222
 
 
223
  for (it= open_list.begin(); it < open_list.end(); it++)
 
224
  {
 
225
    if (func(display, *it))
 
226
      return true;
 
227
  }
 
228
 
 
229
  return false;
 
230
}
128
231
 
129
232
/*****************************************************************************
130
233
 *       Functions to free open table cache
131
234
 ****************************************************************************/
132
235
 
133
236
 
134
 
void Table::intern_close_table()
 
237
void intern_close_table(Table *table)
135
238
{                                               // Free all structures
136
 
  free_io_cache();
137
 
  if (cursor)                              // Not true if name lock
 
239
  free_io_cache(table);
 
240
  if (table->file)                              // Not true if name lock
 
241
    table->closefrm(true);                      // close file
 
242
}
 
243
 
 
244
/*
 
245
  Remove table from the open table cache
 
246
 
 
247
  SYNOPSIS
 
248
  free_cache_entry()
 
249
  entry         Table to remove
 
250
 
 
251
  NOTE
 
252
  We need to have a lock on LOCK_open when calling this
 
253
*/
 
254
 
 
255
void free_cache_entry(void *entry)
 
256
{
 
257
  Table *table= static_cast<Table *>(entry);
 
258
  intern_close_table(table);
 
259
  if (!table->in_use)
138
260
  {
139
 
    delete_table(true);                 // close cursor
 
261
    table->next->prev=table->prev;              /* remove from used chain */
 
262
    table->prev->next=table->next;
 
263
    if (table == unused_tables)
 
264
    {
 
265
      unused_tables=unused_tables->next;
 
266
      if (table == unused_tables)
 
267
        unused_tables= NULL;
 
268
    }
140
269
  }
 
270
  free(table);
141
271
}
142
272
 
143
273
/* Free resources allocated by filesort() and read_record() */
144
274
 
145
 
void Table::free_io_cache()
 
275
void free_io_cache(Table *table)
146
276
{
147
 
  if (sort.io_cache)
 
277
  if (table->sort.io_cache)
148
278
  {
149
 
    sort.io_cache->close_cached_file();
150
 
    delete sort.io_cache;
151
 
    sort.io_cache= 0;
 
279
    close_cached_file(table->sort.io_cache);
 
280
    delete table->sort.io_cache;
 
281
    table->sort.io_cache= 0;
152
282
  }
153
283
}
154
284
 
158
288
 
159
289
  @param session Thread context (may be NULL)
160
290
  @param tables List of tables to remove from the cache
161
 
  @param have_lock If table::Cache::singleton().mutex() is locked
 
291
  @param have_lock If LOCK_open is locked
162
292
  @param wait_for_refresh Wait for a impending flush
163
293
  @param wait_for_placeholders Wait for tables being reopened so that the GRL
164
294
  won't proceed while write-locked tables are being reopened by other
168
298
  and tables must be NULL.
169
299
*/
170
300
 
171
 
bool Session::close_cached_tables(TableList *tables, bool wait_for_refresh, bool wait_for_placeholders)
 
301
bool close_cached_tables(Session *session, TableList *tables,
 
302
                         bool wait_for_refresh, bool wait_for_placeholders)
172
303
{
173
304
  bool result= false;
174
 
  Session *session= this;
175
 
 
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
 
      {
 
305
  assert(session || (!wait_for_refresh && !tables));
 
306
 
 
307
  pthread_mutex_lock(&LOCK_open); /* Optionally lock for remove tables from open_cahe if not in use */
 
308
 
 
309
  if (tables == NULL)
 
310
  {
 
311
    refresh_version++;                          // Force close of open tables
 
312
    while (unused_tables)
 
313
    {
 
314
#ifdef EXTRA_DEBUG
 
315
      if (hash_delete(&open_cache,(unsigned char*) unused_tables))
 
316
        printf("Warning: Couldn't delete open table from hash\n");
 
317
#else
 
318
      hash_delete(&open_cache,(unsigned char*) unused_tables);
 
319
#endif
 
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
        open_and_lock_tables() 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 open_and_lock_tables()
 
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
    assert(session);
 
384
    /*
 
385
      If there is any table that has a lower refresh_version, wait until
 
386
      this is closed (or this thread is killed) before returning
 
387
    */
 
388
    session->mysys_var->current_mutex= &LOCK_open;
 
389
    session->mysys_var->current_cond= &COND_refresh;
 
390
    session->set_proc_info("Flushing tables");
 
391
 
 
392
    session->close_old_data_files();
 
393
 
 
394
    bool found= true;
 
395
    /* Wait until all threads has closed all the tables we had locked */
 
396
    while (found && ! session->killed)
 
397
    {
 
398
      found= false;
 
399
      for (uint32_t idx=0 ; idx < open_cache.records ; idx++)
 
400
      {
 
401
        Table *table=(Table*) hash_element(&open_cache,idx);
 
402
        /* Avoid a self-deadlock. */
 
403
        if (table->in_use == session)
 
404
          continue;
187
405
        /*
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.
 
406
          Note that we wait here only for tables which are actually open, and
 
407
          not for placeholders with Table::open_placeholder set. Waiting for
 
408
          latter will cause deadlock in the following scenario, for example:
 
409
 
 
410
conn1: lock table t1 write;
 
411
conn2: lock table t2 write;
 
412
conn1: flush tables;
 
413
conn2: flush tables;
 
414
 
 
415
It also does not make sense to wait for those of placeholders that
 
416
are employed by CREATE TABLE as in this case table simply does not
 
417
exist yet.
223
418
        */
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))
 
419
        if (table->needs_reopen_or_name_lock() && (table->db_stat ||
 
420
                                                   (table->open_placeholder && wait_for_placeholders)))
242
421
        {
243
422
          found= true;
 
423
          pthread_cond_wait(&COND_refresh,&LOCK_open);
 
424
          break;
244
425
        }
245
426
      }
246
 
      if (!found)
247
 
        wait_for_refresh= false;                        // Nothing to wait for
248
427
    }
 
428
    /*
 
429
      No other thread has the locked tables open; reopen them and get the
 
430
      old locks. This should always succeed (unless some external process
 
431
      has removed the tables)
 
432
    */
 
433
    result= session->reopen_tables(true, true);
249
434
 
250
 
    if (wait_for_refresh)
 
435
    /* Set version for table */
 
436
    for (Table *table=session->open_tables; table ; table= table->next)
251
437
    {
252
438
      /*
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
 
      }
 
439
        Preserve the version (0) of write locked tables so that a impending
 
440
        global read lock won't sneak in.
 
441
      */
 
442
      if (table->reginfo.lock_type < TL_WRITE_ALLOW_WRITE)
 
443
        table->s->version= refresh_version;
315
444
    }
316
445
  }
317
446
 
 
447
  pthread_mutex_unlock(&LOCK_open);
 
448
 
318
449
  if (wait_for_refresh)
319
450
  {
320
 
    boost_unique_lock_t scopedLock(session->mysys_var->mutex);
 
451
    assert(session);
 
452
 
 
453
    pthread_mutex_lock(&session->mysys_var->mutex);
321
454
    session->mysys_var->current_mutex= 0;
322
455
    session->mysys_var->current_cond= 0;
323
456
    session->set_proc_info(0);
 
457
    pthread_mutex_unlock(&session->mysys_var->mutex);
324
458
  }
325
459
 
326
460
  return result;
331
465
  move one table to free list 
332
466
*/
333
467
 
334
 
bool Session::free_cached_table(boost::mutex::scoped_lock &scopedLock)
 
468
bool Session::free_cached_table()
335
469
{
336
470
  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());
 
471
  Table *table= open_tables;
 
472
 
 
473
  safe_mutex_assert_owner(&LOCK_open);
343
474
  assert(table->key_read == 0);
344
 
  assert(!table->cursor || table->cursor->inited == Cursor::NONE);
 
475
  assert(!table->file || table->file->inited == handler::NONE);
345
476
 
346
 
  open_tables= table->getNext();
 
477
  open_tables= table->next;
347
478
 
348
479
  if (table->needs_reopen_or_name_lock() ||
349
480
      version != refresh_version || !table->db_stat)
350
481
  {
351
 
    table::remove_table(table);
 
482
    hash_delete(&open_cache,(unsigned char*) table);
352
483
    found_old_table= true;
353
484
  }
354
485
  else
357
488
      Open placeholders have Table::db_stat set to 0, so they should be
358
489
      handled by the first alternative.
359
490
    */
360
 
    assert(not table->open_placeholder);
 
491
    assert(!table->open_placeholder);
361
492
 
362
493
    /* Free memory and reset for next loop */
363
 
    table->cursor->ha_reset();
364
 
    table->in_use= NULL;
 
494
    table->file->ha_reset();
 
495
    table->in_use= false;
365
496
 
366
 
    table::getUnused().link(table);
 
497
    if (unused_tables)
 
498
    {
 
499
      table->next= unused_tables;               /* Link in last */
 
500
      table->prev= unused_tables->prev;
 
501
      unused_tables->prev= table;
 
502
      table->prev->next= table;
 
503
    }
 
504
    else
 
505
      unused_tables= table->next=table->prev=table;
367
506
  }
368
507
 
369
508
  return found_old_table;
382
521
{
383
522
  bool found_old_table= false;
384
523
 
385
 
  safe_mutex_assert_not_owner(table::Cache::singleton().mutex().native_handle());
 
524
  safe_mutex_assert_not_owner(&LOCK_open);
386
525
 
387
 
  boost_unique_lock_t scoped_lock(table::Cache::singleton().mutex()); /* Close all open tables on Session */
 
526
  pthread_mutex_lock(&LOCK_open); /* Close all open tables on Session */
388
527
 
389
528
  while (open_tables)
390
 
  {
391
 
    found_old_table|= free_cached_table(scoped_lock);
392
 
  }
 
529
    found_old_table|= free_cached_table();
393
530
  some_tables_deleted= false;
394
531
 
395
532
  if (found_old_table)
396
533
  {
397
534
    /* Tell threads waiting for refresh that something has happened */
398
 
    locking::broadcast_refresh();
 
535
    broadcast_refresh();
399
536
  }
 
537
 
 
538
  pthread_mutex_unlock(&LOCK_open);
400
539
}
401
540
 
402
541
/*
410
549
  table_name            Table name
411
550
 
412
551
NOTES:
413
 
This is called by find_table_in_global_list().
 
552
This is called by find_table_in_local_list() and
 
553
find_table_in_global_list().
414
554
 
415
555
RETURN VALUES
416
556
NULL    Table not found
424
564
{
425
565
  for (; table; table= table->*link )
426
566
  {
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
 
    {
 
567
    if ((table->table == 0 || table->table->s->tmp_table == NO_TMP_TABLE) &&
 
568
        strcmp(table->db, db_name) == 0 &&
 
569
        strcmp(table->table_name, table_name) == 0)
431
570
      break;
432
 
    }
433
571
  }
434
572
  return table;
435
573
}
471
609
0 if table is unique
472
610
*/
473
611
 
474
 
TableList* unique_table(TableList *table, TableList *table_list,
 
612
TableList* unique_table(Session *session, TableList *table, TableList *table_list,
475
613
                        bool check_alias)
476
614
{
477
615
  TableList *res;
490
628
  if (table->table)
491
629
  {
492
630
    /* temporary table is always unique */
493
 
    if (table->table && table->table->getShare()->getType() != message::Table::STANDARD)
 
631
    if (table->table && table->table->s->tmp_table != NO_TMP_TABLE)
494
632
      return 0;
495
633
    table= table->find_underlying_table(table->table);
496
634
    /*
499
637
    */
500
638
    assert(table);
501
639
  }
502
 
  d_name= table->getSchemaName();
503
 
  t_name= table->getTableName();
 
640
  d_name= table->db;
 
641
  t_name= table->table_name;
504
642
  t_alias= table->alias;
505
643
 
506
644
  for (;;)
507
645
  {
508
 
    if ((! (res= find_table_in_global_list(table_list, d_name, t_name))) ||
 
646
    if (((! (res= find_table_in_global_list(table_list, d_name, t_name))) &&
 
647
         (! (res= mysql_lock_have_duplicate(session, table, table_list)))) ||
509
648
        ((!res->table || res->table != table->table) &&
510
649
         (!check_alias || !(my_strcasecmp(files_charset_info, t_alias, res->alias))) &&
511
650
         res->select_lex && !res->select_lex->exclude_from_table_unique_test))
521
660
}
522
661
 
523
662
 
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())
 
663
Table *Session::find_temporary_table(const char *new_db, const char *table_name)
 
664
{
 
665
  char  key[MAX_DBKEY_LENGTH];
 
666
  uint  key_length;
 
667
  Table *table;
 
668
 
 
669
  key_length= TableShare::createKey(key, new_db, table_name);
 
670
 
 
671
  for (table= temporary_tables ; table ; table= table->next)
 
672
  {
 
673
    if (table->s->table_cache_key.length == key_length &&
 
674
        !memcmp(table->s->table_cache_key.str, key, key_length))
604
675
      return table;
605
676
  }
606
 
 
607
677
  return NULL;                               // Not a temporary table
608
678
}
609
679
 
 
680
Table *Session::find_temporary_table(TableList *table_list)
 
681
{
 
682
  return find_temporary_table(table_list->db, table_list->table_name);
 
683
}
 
684
 
610
685
 
611
686
/**
612
687
  Drop a temporary table.
634
709
  @retval -1  the table is in use by a outer query
635
710
*/
636
711
 
637
 
int Open_tables_state::drop_temporary_table(const drizzled::identifier::Table &identifier)
 
712
int Session::drop_temporary_table(TableList *table_list)
638
713
{
639
714
  Table *table;
640
715
 
641
 
  if (not (table= find_temporary_table(identifier)))
 
716
  if (!(table= find_temporary_table(table_list)))
642
717
    return 1;
643
718
 
644
719
  /* Table might be in use by some outer statement. */
645
 
  if (table->query_id && table->query_id != getQueryId())
 
720
  if (table->query_id && table->query_id != query_id)
646
721
  {
647
 
    my_error(ER_CANT_REOPEN_TABLE, MYF(0), table->getAlias());
 
722
    my_error(ER_CANT_REOPEN_TABLE, MYF(0), table->alias);
648
723
    return -1;
649
724
  }
650
725
 
651
 
  close_temporary_table(table);
 
726
  close_temporary_table(table, true, true);
652
727
 
653
728
  return 0;
654
729
}
655
730
 
 
731
/*
 
732
  unlink from session->temporary tables and close temporary table
 
733
*/
 
734
 
 
735
void Session::close_temporary_table(Table *table,
 
736
                                    bool free_share, bool delete_table)
 
737
{
 
738
  if (table->prev)
 
739
  {
 
740
    table->prev->next= table->next;
 
741
    if (table->prev->next)
 
742
      table->next->prev= table->prev;
 
743
  }
 
744
  else
 
745
  {
 
746
    /* removing the item from the list */
 
747
    assert(table == temporary_tables);
 
748
    /*
 
749
      slave must reset its temporary list pointer to zero to exclude
 
750
      passing non-zero value to end_slave via rli->save_temporary_tables
 
751
      when no temp tables opened, see an invariant below.
 
752
    */
 
753
    temporary_tables= table->next;
 
754
    if (temporary_tables)
 
755
      table->next->prev= NULL;
 
756
  }
 
757
  close_temporary(table, free_share, delete_table);
 
758
}
 
759
 
 
760
 
 
761
/*
 
762
  Close and delete a temporary table
 
763
 
 
764
  NOTE
 
765
  This dosn't unlink table from session->temporary
 
766
  If this is needed, use close_temporary_table()
 
767
*/
 
768
 
 
769
void close_temporary(Table *table, bool free_share, bool delete_table)
 
770
{
 
771
  StorageEngine *table_type= table->s->db_type();
 
772
 
 
773
  free_io_cache(table);
 
774
  table->closefrm(false);
 
775
 
 
776
  if (delete_table)
 
777
    rm_temporary_table(table_type, table->s->path.str);
 
778
 
 
779
  if (free_share)
 
780
  {
 
781
    table->s->free_table_share();
 
782
    /* This makes me sad, but we're allocating it via malloc */
 
783
    free(table);
 
784
  }
 
785
}
 
786
 
 
787
 
 
788
/*
 
789
  Used by ALTER Table when the table is a temporary one. It changes something
 
790
  only if the ALTER contained a RENAME clause (otherwise, table_name is the old
 
791
  name).
 
792
  Prepares a table cache key, which is the concatenation of db, table_name and
 
793
  session->slave_proxy_id, separated by '\0'.
 
794
*/
 
795
 
 
796
bool rename_temporary_table(Table *table, const char *db, const char *table_name)
 
797
{
 
798
  char *key;
 
799
  uint32_t key_length;
 
800
  TableShare *share= table->s;
 
801
 
 
802
  if (!(key=(char*) alloc_root(&share->mem_root, MAX_DBKEY_LENGTH)))
 
803
    return true;                                /* purecov: inspected */
 
804
 
 
805
  key_length= TableShare::createKey(key, db, table_name);
 
806
  share->set_table_cache_key(key, key_length);
 
807
 
 
808
  return false;
 
809
}
 
810
 
 
811
 
 
812
/* move table first in unused links */
 
813
 
 
814
static void relink_unused(Table *table)
 
815
{
 
816
  if (table != unused_tables)
 
817
  {
 
818
    table->prev->next=table->next;              /* Remove from unused list */
 
819
    table->next->prev=table->prev;
 
820
    table->next=unused_tables;                  /* Link in unused tables */
 
821
    table->prev=unused_tables->prev;
 
822
    unused_tables->prev->next=table;
 
823
    unused_tables->prev=table;
 
824
    unused_tables=table;
 
825
  }
 
826
}
 
827
 
656
828
 
657
829
/**
658
830
  Remove all instances of table from thread's open list and
660
832
 
661
833
  @param  session     Thread context
662
834
  @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
835
*/
666
836
 
667
837
void Session::unlink_open_table(Table *find)
668
838
{
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
 
 
 
839
  char key[MAX_DBKEY_LENGTH];
 
840
  uint32_t key_length= find->s->table_cache_key.length;
 
841
  Table *list, **prev;
 
842
 
 
843
  safe_mutex_assert_owner(&LOCK_open);
 
844
 
 
845
  memcpy(key, find->s->table_cache_key.str, key_length);
673
846
  /*
674
 
    Note that we need to hold table::Cache::singleton().mutex() while changing the
 
847
    Note that we need to hold LOCK_open while changing the
675
848
    open_tables list. Another thread may work on it.
676
 
    (See: table::Cache::singleton().removeTable(), wait_completed_table())
 
849
    (See: remove_table_from_cache(), mysql_wait_completed_table())
677
850
    Closing a MERGE child before the parent would be fatal if the
678
851
    other thread tries to abort the MERGE lock in between.
679
852
  */
680
853
  for (prev= &open_tables; *prev; )
681
854
  {
682
 
    Table *list= *prev;
 
855
    list= *prev;
683
856
 
684
 
    if (list->getShare()->getCacheKey() == find_key)
 
857
    if (list->s->table_cache_key.length == key_length &&
 
858
        !memcmp(list->s->table_cache_key.str, key, key_length))
685
859
    {
686
860
      /* Remove table from open_tables list. */
687
 
      *prev= list->getNext();
688
 
 
 
861
      *prev= list->next;
689
862
      /* Close table. */
690
 
      table::remove_table(static_cast<table::Concurrent *>(list));
 
863
      hash_delete(&open_cache,(unsigned char*) list); // Close table
691
864
    }
692
865
    else
693
866
    {
694
867
      /* Step to next entry in open_tables list. */
695
 
      prev= list->getNextPtr();
 
868
      prev= &list->next;
696
869
    }
697
870
  }
698
871
 
699
872
  // Notify any 'refresh' threads
700
 
  locking::broadcast_refresh();
 
873
  broadcast_refresh();
701
874
}
702
875
 
703
876
 
720
893
  table that was locked with LOCK TABLES.
721
894
*/
722
895
 
723
 
void Session::drop_open_table(Table *table, const identifier::Table &identifier)
 
896
void Session::drop_open_table(Table *table, const char *db_name,
 
897
                              const char *table_name)
724
898
{
725
 
  if (table->getShare()->getType())
726
 
  {
727
 
    close_temporary_table(table);
728
 
  }
 
899
  if (table->s->tmp_table)
 
900
    close_temporary_table(table, true, true);
729
901
  else
730
902
  {
731
 
    boost_unique_lock_t scoped_lock(table::Cache::singleton().mutex()); /* Close and drop a table (AUX routine) */
 
903
    StorageEngine *table_type= table->s->db_type();
 
904
    pthread_mutex_lock(&LOCK_open); /* Close and drop a table (AUX routine) */
732
905
    /*
733
906
      unlink_open_table() also tells threads waiting for refresh or close
734
907
      that something has happened.
735
908
    */
736
909
    unlink_open_table(table);
737
 
    (void)plugin::StorageEngine::dropTable(*this, identifier);
 
910
    quick_rm_table(table_type, db_name, table_name, false);
 
911
    pthread_mutex_unlock(&LOCK_open);
738
912
  }
739
913
}
740
914
 
744
918
 
745
919
  SYNOPSIS
746
920
  wait_for_condition()
747
 
  session       Thread Cursor
 
921
  session       Thread handler
748
922
  mutex mutex that is currently hold that is associated with condition
749
923
  Will be unlocked on return
750
924
  cond  Condition to wait for
751
925
*/
752
926
 
753
 
void Session::wait_for_condition(boost::mutex &mutex, boost::condition_variable_any &cond)
 
927
void Session::wait_for_condition(pthread_mutex_t *mutex, pthread_cond_t *cond)
754
928
{
755
929
  /* Wait until the current table is up to date */
756
930
  const char *saved_proc_info;
757
 
  mysys_var->current_mutex= &mutex;
758
 
  mysys_var->current_cond= &cond;
 
931
  mysys_var->current_mutex= mutex;
 
932
  mysys_var->current_cond= cond;
759
933
  saved_proc_info= get_proc_info();
760
934
  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);
 
935
  if (!killed)
 
936
    (void) pthread_cond_wait(cond, mutex);
 
937
 
 
938
  /*
 
939
    We must unlock mutex first to avoid deadlock becasue conditions are
 
940
    sent to this thread by doing locks in the following order:
 
941
    lock(mysys_var->mutex)
 
942
    lock(mysys_var->current_mutex)
 
943
 
 
944
    One by effect of this that one can only use wait_for_condition with
 
945
    condition variables that are guranteed to not disapper (freed) even if this
 
946
    mutex is unlocked
 
947
  */
 
948
 
 
949
  pthread_mutex_unlock(mutex);
 
950
  pthread_mutex_lock(&mysys_var->mutex);
779
951
  mysys_var->current_mutex= 0;
780
952
  mysys_var->current_cond= 0;
781
953
  set_proc_info(saved_proc_info);
 
954
  pthread_mutex_unlock(&mysys_var->mutex);
 
955
}
 
956
 
 
957
 
 
958
/**
 
959
  Exclusively name-lock a table that is already write-locked by the
 
960
  current thread.
 
961
 
 
962
  @param session current thread context
 
963
  @param tables table list containing one table to open.
 
964
 
 
965
  @return false on success, true otherwise.
 
966
*/
 
967
 
 
968
bool name_lock_locked_table(Session *session, TableList *tables)
 
969
{
 
970
  /* Under LOCK TABLES we must only accept write locked tables. */
 
971
  tables->table= find_locked_table(session, tables->db, tables->table_name);
 
972
 
 
973
  if (!tables->table)
 
974
    my_error(ER_TABLE_NOT_LOCKED, MYF(0), tables->alias);
 
975
  else if (tables->table->reginfo.lock_type <= TL_WRITE_DEFAULT)
 
976
    my_error(ER_TABLE_NOT_LOCKED_FOR_WRITE, MYF(0), tables->alias);
 
977
  else
 
978
  {
 
979
    /*
 
980
      Ensures that table is opened only by this thread and that no
 
981
      other statement will open this table.
 
982
    */
 
983
    wait_while_table_is_used(session, tables->table, HA_EXTRA_FORCE_REOPEN);
 
984
    return false;
 
985
  }
 
986
 
 
987
  return true;
 
988
}
 
989
 
 
990
 
 
991
/*
 
992
  Open table which is already name-locked by this thread.
 
993
 
 
994
  SYNOPSIS
 
995
  reopen_name_locked_table()
 
996
  session         Thread handle
 
997
  table_list  TableList object for table to be open, TableList::table
 
998
  member should point to Table object which was used for
 
999
  name-locking.
 
1000
  link_in     true  - if Table object for table to be opened should be
 
1001
  linked into Session::open_tables list.
 
1002
  false - placeholder used for name-locking is already in
 
1003
  this list so we only need to preserve Table::next
 
1004
  pointer.
 
1005
 
 
1006
  NOTE
 
1007
  This function assumes that its caller already acquired LOCK_open mutex.
 
1008
 
 
1009
  RETURN VALUE
 
1010
  false - Success
 
1011
  true  - Error
 
1012
*/
 
1013
 
 
1014
bool Session::reopen_name_locked_table(TableList* table_list, bool link_in)
 
1015
{
 
1016
  Table *table= table_list->table;
 
1017
  TableShare *share;
 
1018
  char *table_name= table_list->table_name;
 
1019
  Table orig_table;
 
1020
 
 
1021
  safe_mutex_assert_owner(&LOCK_open);
 
1022
 
 
1023
  if (killed || !table)
 
1024
    return true;
 
1025
 
 
1026
  orig_table= *table;
 
1027
 
 
1028
  if (open_unireg_entry(this, table, table_list, table_name,
 
1029
                        table->s->table_cache_key.str,
 
1030
                        table->s->table_cache_key.length))
 
1031
  {
 
1032
    intern_close_table(table);
 
1033
    /*
 
1034
      If there was an error during opening of table (for example if it
 
1035
      does not exist) '*table' object can be wiped out. To be able
 
1036
      properly release name-lock in this case we should restore this
 
1037
      object to its original state.
 
1038
    */
 
1039
    *table= orig_table;
 
1040
    return true;
 
1041
  }
 
1042
 
 
1043
  share= table->s;
 
1044
  /*
 
1045
    We want to prevent other connections from opening this table until end
 
1046
    of statement as it is likely that modifications of table's metadata are
 
1047
    not yet finished (for example CREATE TRIGGER have to change .TRG file,
 
1048
    or we might want to drop table if CREATE TABLE ... SELECT fails).
 
1049
    This also allows us to assume that no other connection will sneak in
 
1050
    before we will get table-level lock on this table.
 
1051
  */
 
1052
  share->version=0;
 
1053
  table->in_use = this;
 
1054
 
 
1055
  if (link_in)
 
1056
  {
 
1057
    table->next= open_tables;
 
1058
    open_tables= table;
 
1059
  }
 
1060
  else
 
1061
  {
 
1062
    /*
 
1063
      Table object should be already in Session::open_tables list so we just
 
1064
      need to set Table::next correctly.
 
1065
    */
 
1066
    table->next= orig_table.next;
 
1067
  }
 
1068
 
 
1069
  table->tablenr= current_tablenr++;
 
1070
  table->used_fields= 0;
 
1071
  table->const_table= 0;
 
1072
  table->null_row= false;
 
1073
  table->maybe_null= false;
 
1074
  table->force_index= false;
 
1075
  table->status= STATUS_NO_RECORD;
 
1076
 
 
1077
  return false;
782
1078
}
783
1079
 
784
1080
 
795
1091
  case of failure.
796
1092
*/
797
1093
 
798
 
table::Placeholder *Session::table_cache_insert_placeholder(const drizzled::identifier::Table &arg)
 
1094
Table *Session::table_cache_insert_placeholder(const char *key, uint32_t key_length)
799
1095
{
800
 
  safe_mutex_assert_owner(table::Cache::singleton().mutex().native_handle());
 
1096
  Table *table;
 
1097
  TableShare *share;
 
1098
  char *key_buff;
 
1099
 
 
1100
  safe_mutex_assert_owner(&LOCK_open);
801
1101
 
802
1102
  /*
803
1103
    Create a table entry with the right key and with an old refresh version
 
1104
    Note that we must use my_multi_malloc() here as this is freed by the
 
1105
    table cache
804
1106
  */
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))
 
1107
  if (!my_multi_malloc(MYF(MY_WME | MY_ZEROFILL),
 
1108
                       &table, sizeof(*table),
 
1109
                       &share, sizeof(*share),
 
1110
                       &key_buff, key_length,
 
1111
                       NULL))
 
1112
    return NULL;
 
1113
 
 
1114
  table->s= share;
 
1115
  share->set_table_cache_key(key_buff, key, key_length);
 
1116
  share->tmp_table= INTERNAL_TMP_TABLE;  // for intern_close_table
 
1117
  table->in_use= this;
 
1118
  table->locked_by_name=1;
 
1119
 
 
1120
  if (my_hash_insert(&open_cache, (unsigned char*)table))
809
1121
  {
810
 
    delete table;
811
 
 
 
1122
    free((unsigned char*) table);
812
1123
    return NULL;
813
1124
  }
814
1125
 
837
1148
  @retval  true   Error occured (OOM)
838
1149
  @retval  false  Success. 'table' parameter set according to above rules.
839
1150
*/
840
 
bool Session::lock_table_name_if_not_cached(const identifier::Table &identifier, Table **table)
 
1151
 
 
1152
bool Session::lock_table_name_if_not_cached(const char *new_db,
 
1153
                                            const char *table_name, Table **table)
841
1154
{
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())
 
1155
  char key[MAX_DBKEY_LENGTH];
 
1156
  char *key_pos= key;
 
1157
  uint32_t key_length;
 
1158
 
 
1159
  key_pos= strcpy(key_pos, new_db) + strlen(new_db);
 
1160
  key_pos= strcpy(key_pos+1, table_name) + strlen(table_name);
 
1161
  key_length= (uint32_t) (key_pos-key)+1;
 
1162
 
 
1163
  pthread_mutex_lock(&LOCK_open); /* Obtain a name lock even though table is not in cache (like for create table)  */
 
1164
 
 
1165
  if (hash_search(&open_cache, (unsigned char *)key, key_length))
851
1166
  {
 
1167
    pthread_mutex_unlock(&LOCK_open);
852
1168
    *table= 0;
853
1169
    return false;
854
1170
  }
855
 
 
856
 
  if (not (*table= table_cache_insert_placeholder(identifier)))
 
1171
  if (!(*table= table_cache_insert_placeholder(key, key_length)))
857
1172
  {
 
1173
    pthread_mutex_unlock(&LOCK_open);
858
1174
    return true;
859
1175
  }
860
1176
  (*table)->open_placeholder= true;
861
 
  (*table)->setNext(open_tables);
 
1177
  (*table)->next= open_tables;
862
1178
  open_tables= *table;
 
1179
  pthread_mutex_unlock(&LOCK_open);
863
1180
 
864
1181
  return false;
865
1182
}
897
1214
*/
898
1215
 
899
1216
 
900
 
Table *Session::openTable(TableList *table_list, bool *refresh, uint32_t flags)
 
1217
Table *Session::open_table(TableList *table_list, bool *refresh, uint32_t flags)
901
1218
{
902
 
  Table *table;
 
1219
  register Table *table;
 
1220
  char key[MAX_DBKEY_LENGTH];
 
1221
  unsigned int key_length;
903
1222
  const char *alias= table_list->alias;
 
1223
  HASH_SEARCH_STATE state;
904
1224
 
905
1225
  /* Parsing of partitioning information from .frm needs session->lex set up. */
906
1226
  assert(lex->is_lex_started);
913
1233
  if (check_stack_overrun(this, STACK_MIN_SIZE_FOR_OPEN, (unsigned char *)&alias))
914
1234
    return NULL;
915
1235
 
916
 
  if (getKilled())
 
1236
  if (killed)
917
1237
    return NULL;
918
1238
 
919
 
  identifier::Table identifier(table_list->getSchemaName(), table_list->getTableName());
920
 
  const identifier::Table::Key &key(identifier.getKey());
921
 
  table::CacheRange ppp;
 
1239
  key_length= table_list->create_table_def_key(key);
922
1240
 
923
1241
  /*
924
1242
    Unless requested otherwise, try to resolve this table in the list
927
1245
    same name. This block implements the behaviour.
928
1246
    TODO -> move this block into a separate function.
929
1247
  */
930
 
  bool reset= false;
931
 
  for (table= getTemporaryTables(); table ; table=table->getNext())
 
1248
  for (table= temporary_tables; table ; table=table->next)
932
1249
  {
933
 
    if (table->getShare()->getCacheKey() == key)
 
1250
    if (table->s->table_cache_key.length == key_length && !memcmp(table->s->table_cache_key.str, key, key_length))
934
1251
    {
935
1252
      /*
936
1253
        We're trying to use the same temporary table twice in a query.
940
1257
      */
941
1258
      if (table->query_id)
942
1259
      {
943
 
        my_error(ER_CANT_REOPEN_TABLE, MYF(0), table->getAlias());
 
1260
        my_error(ER_CANT_REOPEN_TABLE, MYF(0), table->alias);
944
1261
        return NULL;
945
1262
      }
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
 
 
 
1263
      table->query_id= query_id;
 
1264
      goto reset;
 
1265
    }
 
1266
  }
 
1267
 
 
1268
  if (flags & DRIZZLE_OPEN_TEMPORARY_ONLY)
 
1269
  {
 
1270
    my_error(ER_NO_SUCH_TABLE, MYF(0), table_list->db, table_list->table_name);
 
1271
    return NULL;
 
1272
  }
 
1273
 
 
1274
  /*
 
1275
    If it's the first table from a list of tables used in a query,
 
1276
    remember refresh_version (the version of open_cache state).
 
1277
    If the version changes while we're opening the remaining tables,
 
1278
    we will have to back off, close all the tables opened-so-far,
 
1279
    and try to reopen them.
 
1280
 
 
1281
    Note-> refresh_version is currently changed only during FLUSH TABLES.
 
1282
  */
 
1283
  if (!open_tables)
 
1284
    version= refresh_version;
 
1285
  else if ((version != refresh_version) &&
 
1286
           ! (flags & DRIZZLE_LOCK_IGNORE_FLUSH))
 
1287
  {
 
1288
    /* Someone did a refresh while thread was opening tables */
 
1289
    if (refresh)
 
1290
      *refresh= true;
 
1291
 
 
1292
    return NULL;
 
1293
  }
 
1294
 
 
1295
  /*
 
1296
    Before we test the global cache, we test our local session cache.
 
1297
  */
 
1298
  if (cached_table)
 
1299
  {
 
1300
    assert(false); /* Not implemented yet */
 
1301
  }
 
1302
 
 
1303
  /*
 
1304
    Non pre-locked/LOCK TABLES mode, and the table is not temporary:
 
1305
    this is the normal use case.
 
1306
    Now we should:
 
1307
    - try to find the table in the table cache.
 
1308
    - if one of the discovered Table instances is name-locked
 
1309
    (table->s->version == 0) back off -- we have to wait
 
1310
    until no one holds a name lock on the table.
 
1311
    - if there is no such Table in the name cache, read the table definition
 
1312
    and insert it into the cache.
 
1313
    We perform all of the above under LOCK_open which currently protects
 
1314
    the open cache (also known as table cache) and table definitions stored
 
1315
    on disk.
 
1316
  */
 
1317
 
 
1318
  pthread_mutex_lock(&LOCK_open); /* Lock for FLUSH TABLES for open table */
 
1319
 
 
1320
  /*
 
1321
    Actually try to find the table in the open_cache.
 
1322
    The cache may contain several "Table" instances for the same
 
1323
    physical table. The instances that are currently "in use" by
 
1324
    some thread have their "in_use" member != NULL.
 
1325
    There is no good reason for having more than one entry in the
 
1326
    hash for the same physical table, except that we use this as
 
1327
    an implicit "pending locks queue" - see
 
1328
    wait_for_locked_table_names for details.
 
1329
  */
 
1330
  for (table= (Table*) hash_first(&open_cache, (unsigned char*) key, key_length,
 
1331
                                  &state);
 
1332
       table && table->in_use ;
 
1333
       table= (Table*) hash_next(&open_cache, (unsigned char*) key, key_length,
 
1334
                                 &state))
 
1335
  {
960
1336
    /*
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.
 
1337
      Here we flush tables marked for flush.
 
1338
      Normally, table->s->version contains the value of
 
1339
      refresh_version from the moment when this table was
 
1340
      (re-)opened and added to the cache.
 
1341
      If since then we did (or just started) FLUSH TABLES
 
1342
      statement, refresh_version has been increased.
 
1343
      For "name-locked" Table instances, table->s->version is set
 
1344
      to 0 (see lock_table_name for details).
 
1345
      In case there is a pending FLUSH TABLES or a name lock, we
 
1346
      need to back off and re-start opening tables.
 
1347
      If we do not back off now, we may dead lock in case of lock
 
1348
      order mismatch with some other thread:
 
1349
c1: name lock t1; -- sort of exclusive lock
 
1350
c2: open t2;      -- sort of shared lock
 
1351
c1: name lock t2; -- blocks
 
1352
c2: open t1; -- blocks
968
1353
    */
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 */
 
1354
    if (table->needs_reopen_or_name_lock())
 
1355
    {
 
1356
      if (flags & DRIZZLE_LOCK_IGNORE_FLUSH)
 
1357
      {
 
1358
        /* Force close at once after usage */
 
1359
        version= table->s->version;
 
1360
        continue;
 
1361
      }
 
1362
 
 
1363
      /* Avoid self-deadlocks by detecting self-dependencies. */
 
1364
      if (table->open_placeholder && table->in_use == this)
 
1365
      {
 
1366
        pthread_mutex_unlock(&LOCK_open);
 
1367
        my_error(ER_UPDATE_TABLE_USED, MYF(0), table->s->table_name.str);
 
1368
        return NULL;
 
1369
      }
 
1370
 
 
1371
      /*
 
1372
        Back off, part 1: mark the table as "unused" for the
 
1373
        purpose of name-locking by setting table->db_stat to 0. Do
 
1374
        that only for the tables in this thread that have an old
 
1375
        table->s->version (this is an optimization (?)).
 
1376
        table->db_stat == 0 signals wait_for_locked_table_names
 
1377
        that the tables in question are not used any more. See
 
1378
        table_is_used call for details.
 
1379
      */
 
1380
      close_old_data_files(false, false);
 
1381
 
 
1382
      /*
 
1383
        Back-off part 2: try to avoid "busy waiting" on the table:
 
1384
        if the table is in use by some other thread, we suspend
 
1385
        and wait till the operation is complete: when any
 
1386
        operation that juggles with table->s->version completes,
 
1387
        it broadcasts COND_refresh condition variable.
 
1388
        If 'old' table we met is in use by current thread we return
 
1389
        without waiting since in this situation it's this thread
 
1390
        which is responsible for broadcasting on COND_refresh
 
1391
        (and this was done already in Session::close_old_data_files()).
 
1392
        Good example of such situation is when we have statement
 
1393
        that needs two instances of table and FLUSH TABLES comes
 
1394
        after we open first instance but before we open second
 
1395
        instance.
 
1396
      */
 
1397
      if (table->in_use != this)
 
1398
      {
 
1399
        /* wait_for_conditionwill unlock LOCK_open for us */
 
1400
        wait_for_condition(&LOCK_open, &COND_refresh);
 
1401
      }
 
1402
      else
 
1403
      {
 
1404
        pthread_mutex_unlock(&LOCK_open);
 
1405
      }
 
1406
      /*
 
1407
        There is a refresh in progress for this table.
 
1408
        Signal the caller that it has to try again.
 
1409
      */
977
1410
      if (refresh)
978
1411
        *refresh= true;
979
 
 
980
1412
      return NULL;
981
1413
    }
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 */
 
1414
  }
 
1415
  if (table)
 
1416
  {
 
1417
    /* Unlink the table from "unused_tables" list. */
 
1418
    if (table == unused_tables)
 
1419
    {  // First unused
 
1420
      unused_tables=unused_tables->next; // Remove from link
 
1421
      if (table == unused_tables)
 
1422
        unused_tables= NULL;
989
1423
    }
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
 
 
 
1424
    table->prev->next=table->next; /* Remove from unused list */
 
1425
    table->next->prev=table->prev;
 
1426
    table->in_use= this;
 
1427
  }
 
1428
  else
 
1429
  {
 
1430
    /* Insert a new Table instance into the open cache */
 
1431
    int error;
 
1432
    /* Free cache if too big */
 
1433
    while (open_cache.records > table_cache_size && unused_tables)
 
1434
      hash_delete(&open_cache,(unsigned char*) unused_tables); /* purecov: tested */
 
1435
 
 
1436
    if (table_list->create)
1006
1437
    {
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)
 
1438
      char path[FN_REFLEN];
 
1439
      size_t length;
 
1440
 
 
1441
      length= build_table_filename(path, sizeof(path),
 
1442
                                   table_list->db, table_list->table_name,
 
1443
                                   false);
 
1444
 
 
1445
      if (StorageEngine::getTableProto(path, NULL) != EEXIST)
1024
1446
      {
1025
 
        table= (*iter).second;
1026
 
 
1027
 
        if (not table->in_use)
1028
 
          break;
1029
1447
        /*
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
 
1448
          Table to be created, so we need to create placeholder in table-cache.
1046
1449
        */
1047
 
        if (table->needs_reopen_or_name_lock())
 
1450
        if (!(table= table_cache_insert_placeholder(key, key_length)))
1048
1451
        {
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
 
 
 
1452
          pthread_mutex_unlock(&LOCK_open);
1107
1453
          return NULL;
1108
1454
        }
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
 
 
 
1455
        /*
 
1456
          Link placeholder to the open tables list so it will be automatically
 
1457
          removed once tables are closed. Also mark it so it won't be ignored
 
1458
          by other trying to take name-lock.
 
1459
        */
 
1460
        table->open_placeholder= true;
 
1461
        table->next= open_tables;
 
1462
        open_tables= table;
 
1463
        pthread_mutex_unlock(&LOCK_open);
 
1464
 
 
1465
        return table ;
 
1466
      }
 
1467
      /* Table exists. Let us try to open it. */
 
1468
    }
 
1469
 
 
1470
    /* make a new table */
 
1471
    table= (Table *)malloc(sizeof(Table));
 
1472
    if (table == NULL)
 
1473
    {
 
1474
      pthread_mutex_unlock(&LOCK_open);
 
1475
      return NULL;
 
1476
    }
 
1477
 
 
1478
    error= open_unireg_entry(this, table, table_list, alias, key, key_length);
 
1479
    if (error != 0)
 
1480
    {
 
1481
      free(table);
 
1482
      pthread_mutex_unlock(&LOCK_open);
 
1483
      return NULL;
 
1484
    }
 
1485
    my_hash_insert(&open_cache, (unsigned char*) table);
 
1486
  }
 
1487
 
 
1488
  pthread_mutex_unlock(&LOCK_open);
 
1489
  if (refresh)
 
1490
  {
 
1491
    table->next= open_tables; /* Link into simple list */
 
1492
    open_tables=table;
 
1493
  }
 
1494
  table->reginfo.lock_type= TL_READ; /* Assume read */
 
1495
 
 
1496
reset:
 
1497
  assert(table->s->ref_count > 0 || table->s->tmp_table != NO_TMP_TABLE);
 
1498
 
 
1499
  if (lex->need_correct_ident())
 
1500
    table->alias_name_used= my_strcasecmp(table_alias_charset,
 
1501
                                          table->s->table_name.str, alias);
1180
1502
  /* Fix alias if table name changes */
1181
 
  if (strcmp(table->getAlias(), alias))
 
1503
  if (strcmp(table->alias, alias))
1182
1504
  {
1183
 
    table->setAlias(alias);
 
1505
    uint32_t length=(uint32_t) strlen(alias)+1;
 
1506
    table->alias= (char*) realloc((char*) table->alias, length);
 
1507
    memcpy((void*) table->alias, alias, length);
1184
1508
  }
1185
1509
 
1186
1510
  /* These variables are also set in reopen_table() */
1191
1515
  table->maybe_null= false;
1192
1516
  table->force_index= false;
1193
1517
  table->status=STATUS_NO_RECORD;
1194
 
  table->insert_values.clear();
 
1518
  table->insert_values= 0;
1195
1519
  /* Catch wrong handling of the auto_increment_field_not_null. */
1196
1520
  assert(!table->auto_increment_field_not_null);
1197
1521
  table->auto_increment_field_not_null= false;
1198
1522
  if (table->timestamp_field)
1199
 
  {
1200
1523
    table->timestamp_field_type= table->timestamp_field->get_auto_set_type();
1201
 
  }
1202
1524
  table->pos_in_table_list= table_list;
1203
1525
  table->clear_column_bitmaps();
1204
1526
  assert(table->key_read == 0);
1207
1529
}
1208
1530
 
1209
1531
 
 
1532
Table *find_locked_table(Session *session, const char *db,const char *table_name)
 
1533
{
 
1534
  char key[MAX_DBKEY_LENGTH];
 
1535
  char *key_pos= key;
 
1536
  uint32_t key_length;
 
1537
 
 
1538
  key_pos= strcpy(key_pos, db) + strlen(db);
 
1539
  key_pos= strcpy(key_pos+1, table_name) + strlen(table_name);
 
1540
  key_length= (uint32_t)(key_pos-key)+1;
 
1541
 
 
1542
  for (Table *table=session->open_tables; table ; table=table->next)
 
1543
  {
 
1544
    if (table->s->table_cache_key.length == key_length &&
 
1545
        !memcmp(table->s->table_cache_key.str, key, key_length))
 
1546
      return table;
 
1547
  }
 
1548
  return 0;
 
1549
}
 
1550
 
 
1551
 
 
1552
/*
 
1553
  Reopen an table because the definition has changed.
 
1554
 
 
1555
  SYNOPSIS
 
1556
  reopen_table()
 
1557
  table Table object
 
1558
 
 
1559
  NOTES
 
1560
  The data file for the table is already closed and the share is released
 
1561
  The table has a 'dummy' share that mainly contains database and table name.
 
1562
 
 
1563
  RETURN
 
1564
  0  ok
 
1565
  1  error. The old table object is not changed.
 
1566
*/
 
1567
 
 
1568
bool reopen_table(Table *table)
 
1569
{
 
1570
  Table tmp;
 
1571
  bool error= 1;
 
1572
  Field **field;
 
1573
  uint32_t key,part;
 
1574
  TableList table_list;
 
1575
  Session *session= table->in_use;
 
1576
 
 
1577
  assert(table->s->ref_count == 0);
 
1578
  assert(!table->sort.io_cache);
 
1579
 
 
1580
#ifdef EXTRA_DEBUG
 
1581
  if (table->db_stat)
 
1582
    errmsg_printf(ERRMSG_LVL_ERROR, _("Table %s had a open data handler in reopen_table"),
 
1583
                  table->alias);
 
1584
#endif
 
1585
  table_list.db=         table->s->db.str;
 
1586
  table_list.table_name= table->s->table_name.str;
 
1587
  table_list.table=      table;
 
1588
 
 
1589
  if (wait_for_locked_table_names(session, &table_list))
 
1590
    return true;                             // Thread was killed
 
1591
 
 
1592
  if (open_unireg_entry(session, &tmp, &table_list,
 
1593
                        table->alias,
 
1594
                        table->s->table_cache_key.str,
 
1595
                        table->s->table_cache_key.length))
 
1596
    goto end;
 
1597
 
 
1598
  /* This list copies variables set by open_table */
 
1599
  tmp.tablenr=          table->tablenr;
 
1600
  tmp.used_fields=      table->used_fields;
 
1601
  tmp.const_table=      table->const_table;
 
1602
  tmp.null_row=         table->null_row;
 
1603
  tmp.maybe_null=       table->maybe_null;
 
1604
  tmp.status=           table->status;
 
1605
 
 
1606
  /* Get state */
 
1607
  tmp.in_use=           session;
 
1608
  tmp.reginfo.lock_type=table->reginfo.lock_type;
 
1609
 
 
1610
  /* Replace table in open list */
 
1611
  tmp.next=             table->next;
 
1612
  tmp.prev=             table->prev;
 
1613
 
 
1614
  if (table->file)
 
1615
    table->closefrm(true);              // close file, free everything
 
1616
 
 
1617
  *table= tmp;
 
1618
  table->default_column_bitmaps();
 
1619
  table->file->change_table_ptr(table, table->s);
 
1620
 
 
1621
  assert(table->alias != 0);
 
1622
  for (field=table->field ; *field ; field++)
 
1623
  {
 
1624
    (*field)->table= (*field)->orig_table= table;
 
1625
    (*field)->table_name= &table->alias;
 
1626
  }
 
1627
  for (key=0 ; key < table->s->keys ; key++)
 
1628
  {
 
1629
    for (part=0 ; part < table->key_info[key].usable_key_parts ; part++)
 
1630
      table->key_info[key].key_part[part].field->table= table;
 
1631
  }
 
1632
 
 
1633
  broadcast_refresh();
 
1634
  error= false;
 
1635
 
 
1636
end:
 
1637
  return(error);
 
1638
}
 
1639
 
 
1640
 
1210
1641
/**
1211
1642
  Close all instances of a table open by this thread and replace
1212
1643
  them with exclusive name-locks.
1224
1655
  the strings are used in a loop even after the share may be freed.
1225
1656
*/
1226
1657
 
1227
 
void Session::close_data_files_and_morph_locks(const identifier::Table &identifier)
 
1658
void Session::close_data_files_and_morph_locks(const char *new_db, const char *new_table_name)
1228
1659
{
1229
 
  safe_mutex_assert_owner(table::Cache::singleton().mutex().native_handle()); /* Adjust locks at the end of ALTER TABLEL */
 
1660
  Table *table;
 
1661
 
 
1662
  safe_mutex_assert_owner(&LOCK_open); /* Adjust locks at the end of ALTER TABLEL */
1230
1663
 
1231
1664
  if (lock)
1232
1665
  {
1234
1667
      If we are not under LOCK TABLES we should have only one table
1235
1668
      open and locked so it makes sense to remove the lock at once.
1236
1669
    */
1237
 
    unlockTables(lock);
 
1670
    mysql_unlock_tables(this, lock);
1238
1671
    lock= 0;
1239
1672
  }
1240
1673
 
1243
1676
    for target table name if we process ALTER Table ... RENAME.
1244
1677
    So loop below makes sense even if we are not under LOCK TABLES.
1245
1678
  */
1246
 
  for (Table *table= open_tables; table ; table=table->getNext())
 
1679
  for (table= open_tables; table ; table=table->next)
1247
1680
  {
1248
 
    if (table->getShare()->getCacheKey() == identifier.getKey())
 
1681
    if (!strcmp(table->s->table_name.str, new_table_name) &&
 
1682
        !strcmp(table->s->db.str, new_db))
1249
1683
    {
1250
1684
      table->open_placeholder= true;
1251
1685
      close_handle_and_leave_table_as_lock(table);
1267
1701
  situations like FLUSH TABLES or ALTER Table. In general
1268
1702
  case one should just repeat open_tables()/lock_tables()
1269
1703
  combination when one needs tables to be reopened (for
1270
 
  example see openTablesLock()).
 
1704
  example see open_and_lock_tables()).
1271
1705
 
1272
 
  @note One should have lock on table::Cache::singleton().mutex() when calling this.
 
1706
  @note One should have lock on LOCK_open when calling this.
1273
1707
 
1274
1708
  @return false in case of success, true - otherwise.
1275
1709
*/
1276
1710
 
1277
 
bool Session::reopen_tables()
 
1711
bool Session::reopen_tables(bool get_locks, bool mark_share_as_old)
1278
1712
{
1279
1713
  Table *table,*next,**prev;
1280
 
  Table **tables= 0;                    // For locks
1281
 
  Table **tables_ptr= 0;                        // For locks
1282
 
  bool error= false;
 
1714
  Table **tables,**tables_ptr;                  // For locks
 
1715
  bool error=0, not_used;
1283
1716
  const uint32_t flags= DRIZZLE_LOCK_NOTIFY_IF_NEED_REOPEN |
1284
1717
    DRIZZLE_LOCK_IGNORE_GLOBAL_READ_LOCK |
1285
1718
    DRIZZLE_LOCK_IGNORE_FLUSH;
1287
1720
  if (open_tables == NULL)
1288
1721
    return false;
1289
1722
 
1290
 
  safe_mutex_assert_owner(table::Cache::singleton().mutex().native_handle());
 
1723
  safe_mutex_assert_owner(&LOCK_open);
 
1724
  if (get_locks)
1291
1725
  {
1292
1726
    /*
1293
1727
      The ptr is checked later
1295
1729
    */
1296
1730
    uint32_t opens= 0;
1297
1731
 
1298
 
    for (table= open_tables; table ; table=table->getNext())
1299
 
    {
 
1732
    for (table= open_tables; table ; table=table->next)
1300
1733
      opens++;
1301
 
    }
1302
1734
    tables= new Table *[opens];
1303
1735
  }
1304
 
 
 
1736
  else
 
1737
    tables= &open_tables;
1305
1738
  tables_ptr =tables;
1306
1739
 
1307
1740
  prev= &open_tables;
1308
1741
  for (table= open_tables; table ; table=next)
1309
1742
  {
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;
 
1743
    uint32_t db_stat= table->db_stat;
 
1744
    next= table->next;
 
1745
    if (!tables || (!db_stat && reopen_table(table)))
 
1746
    {
 
1747
      my_error(ER_CANT_REOPEN_TABLE, MYF(0), table->alias);
 
1748
      hash_delete(&open_cache,(unsigned char*) table);
 
1749
      error= 1;
 
1750
    }
 
1751
    else
 
1752
    {
 
1753
      *prev= table;
 
1754
      prev= &table->next;
 
1755
      /* Do not handle locks of MERGE children. */
 
1756
      if (get_locks && !db_stat)
 
1757
        *tables_ptr++= table;                   // need new lock on this
 
1758
      if (mark_share_as_old)
 
1759
      {
 
1760
        table->s->version= 0;
 
1761
        table->open_placeholder= false;
 
1762
      }
 
1763
    }
1315
1764
  }
1316
1765
  *prev=0;
1317
 
 
1318
1766
  if (tables != tables_ptr)                     // Should we get back old locks
1319
1767
  {
1320
 
    DrizzleLock *local_lock;
 
1768
    DRIZZLE_LOCK *local_lock;
1321
1769
    /*
1322
1770
      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
 
1771
      wait_for_tables() as it tries to acquire LOCK_open, which is
1324
1772
      already locked.
1325
1773
    */
1326
1774
    some_tables_deleted= false;
1327
1775
 
1328
 
    if ((local_lock= lockTables(tables, (uint32_t) (tables_ptr - tables), flags)))
 
1776
    if ((local_lock= mysql_lock_tables(this, tables, (uint32_t) (tables_ptr - tables),
 
1777
                                 flags, &not_used)))
1329
1778
    {
1330
1779
      /* unused */
1331
1780
    }
1341
1790
    }
1342
1791
  }
1343
1792
 
1344
 
  delete [] tables;
1345
 
 
1346
 
  locking::broadcast_refresh();
1347
 
 
1348
 
  return error;
 
1793
  if (get_locks && tables)
 
1794
    delete [] tables;
 
1795
 
 
1796
  broadcast_refresh();
 
1797
 
 
1798
  return(error);
1349
1799
}
1350
1800
 
1351
1801
 
1369
1819
 
1370
1820
  Table *table= open_tables;
1371
1821
 
1372
 
  for (; table ; table=table->getNext())
 
1822
  for (; table ; table=table->next)
1373
1823
  {
1374
1824
    /*
1375
1825
      Reopen marked for flush.
1376
1826
    */
1377
1827
    if (table->needs_reopen_or_name_lock())
1378
1828
    {
1379
 
      found= true;
 
1829
      found=1;
1380
1830
      if (table->db_stat)
1381
1831
      {
1382
1832
        if (morph_locks)
1390
1840
              lock on it. This will also give them a chance to close their
1391
1841
              instances of this table.
1392
1842
            */
1393
 
            abortLock(ulcktbl);
1394
 
            removeLock(ulcktbl);
 
1843
            mysql_lock_abort(this, ulcktbl, true);
 
1844
            mysql_lock_remove(this, NULL, ulcktbl, true);
1395
1845
            ulcktbl->lock_count= 0;
1396
1846
          }
1397
1847
          if ((ulcktbl != table) && ulcktbl->db_stat)
1431
1881
    }
1432
1882
  }
1433
1883
  if (found)
1434
 
    locking::broadcast_refresh();
 
1884
    broadcast_refresh();
 
1885
}
 
1886
 
 
1887
 
 
1888
/*
 
1889
  Wait until all threads has closed the tables in the list
 
1890
  We have also to wait if there is thread that has a lock on this table even
 
1891
  if the table is closed
 
1892
*/
 
1893
 
 
1894
bool table_is_used(Table *table, bool wait_for_name_lock)
 
1895
{
 
1896
  do
 
1897
  {
 
1898
    char *key= table->s->table_cache_key.str;
 
1899
    uint32_t key_length= table->s->table_cache_key.length;
 
1900
 
 
1901
    HASH_SEARCH_STATE state;
 
1902
    for (Table *search= (Table*) hash_first(&open_cache, (unsigned char*) key,
 
1903
                                            key_length, &state);
 
1904
         search ;
 
1905
         search= (Table*) hash_next(&open_cache, (unsigned char*) key,
 
1906
                                    key_length, &state))
 
1907
    {
 
1908
      if (search->in_use == table->in_use)
 
1909
        continue;                               // Name locked by this thread
 
1910
      /*
 
1911
        We can't use the table under any of the following conditions:
 
1912
        - There is an name lock on it (Table is to be deleted or altered)
 
1913
        - If we are in flush table and we didn't execute the flush
 
1914
        - If the table engine is open and it's an old version
 
1915
        (We must wait until all engines are shut down to use the table)
 
1916
      */
 
1917
      if ( (search->locked_by_name && wait_for_name_lock) ||
 
1918
           (search->is_name_opened() && search->needs_reopen_or_name_lock()))
 
1919
        return 1;
 
1920
    }
 
1921
  } while ((table=table->next));
 
1922
  return 0;
 
1923
}
 
1924
 
 
1925
 
 
1926
/* Wait until all used tables are refreshed */
 
1927
 
 
1928
bool wait_for_tables(Session *session)
 
1929
{
 
1930
  bool result;
 
1931
 
 
1932
  session->set_proc_info("Waiting for tables");
 
1933
  pthread_mutex_lock(&LOCK_open); /* Lock for all tables to be refreshed */
 
1934
  while (!session->killed)
 
1935
  {
 
1936
    session->some_tables_deleted= false;
 
1937
    session->close_old_data_files(false, dropping_tables != 0);
 
1938
    if (!table_is_used(session->open_tables, 1))
 
1939
      break;
 
1940
    (void) pthread_cond_wait(&COND_refresh,&LOCK_open);
 
1941
  }
 
1942
  if (session->killed)
 
1943
    result= true;                                       // aborted
 
1944
  else
 
1945
  {
 
1946
    /* Now we can open all tables without any interference */
 
1947
    session->set_proc_info("Reopen tables");
 
1948
    session->version= refresh_version;
 
1949
    result= session->reopen_tables(false, false);
 
1950
  }
 
1951
  pthread_mutex_unlock(&LOCK_open);
 
1952
  session->set_proc_info(0);
 
1953
 
 
1954
  return result;
1435
1955
}
1436
1956
 
1437
1957
 
1459
1979
*/
1460
1980
 
1461
1981
 
1462
 
Table *drop_locked_tables(Session *session, const drizzled::identifier::Table &identifier)
 
1982
Table *drop_locked_tables(Session *session,const char *db, const char *table_name)
1463
1983
{
1464
1984
  Table *table,*next,**prev, *found= 0;
1465
1985
  prev= &session->open_tables;
1466
1986
 
1467
1987
  /*
1468
 
    Note that we need to hold table::Cache::singleton().mutex() while changing the
 
1988
    Note that we need to hold LOCK_open while changing the
1469
1989
    open_tables list. Another thread may work on it.
1470
 
    (See: table::Cache::singleton().removeTable(), wait_completed_table())
 
1990
    (See: remove_table_from_cache(), mysql_wait_completed_table())
1471
1991
    Closing a MERGE child before the parent would be fatal if the
1472
1992
    other thread tries to abort the MERGE lock in between.
1473
1993
  */
1474
1994
  for (table= session->open_tables; table ; table=next)
1475
1995
  {
1476
 
    next=table->getNext();
1477
 
    if (table->getShare()->getCacheKey() == identifier.getKey())
 
1996
    next=table->next;
 
1997
    if (!strcmp(table->s->table_name.str, table_name) &&
 
1998
        !strcmp(table->s->db.str, db))
1478
1999
    {
1479
 
      session->removeLock(table);
 
2000
      mysql_lock_remove(session, NULL, table, true);
1480
2001
 
1481
2002
      if (!found)
1482
2003
      {
1485
2006
        if (table->db_stat)
1486
2007
        {
1487
2008
          table->db_stat= 0;
1488
 
          table->cursor->close();
 
2009
          table->file->close();
1489
2010
        }
1490
2011
      }
1491
2012
      else
1492
2013
      {
1493
2014
        /* We already have a name lock, remove copy */
1494
 
        table::remove_table(static_cast<table::Concurrent *>(table));
 
2015
        hash_delete(&open_cache,(unsigned char*) table);
1495
2016
      }
1496
2017
    }
1497
2018
    else
1498
2019
    {
1499
2020
      *prev=table;
1500
 
      prev= table->getNextPtr();
 
2021
      prev= &table->next;
1501
2022
    }
1502
2023
  }
1503
2024
  *prev=0;
1504
 
 
1505
2025
  if (found)
1506
 
    locking::broadcast_refresh();
 
2026
    broadcast_refresh();
1507
2027
 
1508
 
  return found;
 
2028
  return(found);
1509
2029
}
1510
2030
 
1511
2031
 
1515
2035
  other threads trying to get the lock.
1516
2036
*/
1517
2037
 
1518
 
void abort_locked_tables(Session *session, const drizzled::identifier::Table &identifier)
 
2038
void abort_locked_tables(Session *session,const char *db, const char *table_name)
1519
2039
{
1520
2040
  Table *table;
1521
 
  for (table= session->open_tables; table ; table= table->getNext())
 
2041
  for (table= session->open_tables; table ; table= table->next)
1522
2042
  {
1523
 
    if (table->getShare()->getCacheKey() == identifier.getKey())
 
2043
    if (!strcmp(table->s->table_name.str, table_name) &&
 
2044
        !strcmp(table->s->db.str, db))
1524
2045
    {
1525
2046
      /* If MERGE child, forward lock handling to parent. */
1526
 
      session->abortLock(table);
1527
 
      assert(0);
 
2047
      mysql_lock_abort(session, table, true);
1528
2048
      break;
1529
2049
    }
1530
2050
  }
1531
2051
}
1532
2052
 
 
2053
/*
 
2054
  Load a table definition from file and open unireg table
 
2055
 
 
2056
  SYNOPSIS
 
2057
  open_unireg_entry()
 
2058
  session                       Thread handle
 
2059
  entry         Store open table definition here
 
2060
  table_list            TableList with db, table_name
 
2061
  alias         Alias name
 
2062
  cache_key             Key for share_cache
 
2063
  cache_key_length      length of cache_key
 
2064
 
 
2065
  NOTES
 
2066
  Extra argument for open is taken from session->open_options
 
2067
  One must have a lock on LOCK_open when calling this function
 
2068
 
 
2069
  RETURN
 
2070
  0     ok
 
2071
#       Error
 
2072
*/
 
2073
 
 
2074
static int open_unireg_entry(Session *session, Table *entry, TableList *table_list,
 
2075
                             const char *alias,
 
2076
                             char *cache_key, uint32_t cache_key_length)
 
2077
{
 
2078
  int error;
 
2079
  TableShare *share;
 
2080
  uint32_t discover_retry_count= 0;
 
2081
 
 
2082
  safe_mutex_assert_owner(&LOCK_open);
 
2083
retry:
 
2084
  if (!(share= TableShare::getShare(session, table_list, cache_key,
 
2085
                                    cache_key_length,
 
2086
                                    table_list->i_s_requested_object,
 
2087
                                    &error)))
 
2088
    return 1;
 
2089
 
 
2090
  while ((error= open_table_from_share(session, share, alias,
 
2091
                                       (uint32_t) (HA_OPEN_KEYFILE |
 
2092
                                                   HA_OPEN_RNDFILE |
 
2093
                                                   HA_GET_INDEX |
 
2094
                                                   HA_TRY_READ_ONLY),
 
2095
                                       (EXTRA_RECORD),
 
2096
                                       session->open_options, entry, OTM_OPEN)))
 
2097
  {
 
2098
    if (error == 7)                             // Table def changed
 
2099
    {
 
2100
      share->version= 0;                        // Mark share as old
 
2101
      if (discover_retry_count++)               // Retry once
 
2102
        goto err;
 
2103
 
 
2104
      /*
 
2105
        TODO->
 
2106
        Here we should wait until all threads has released the table.
 
2107
        For now we do one retry. This may cause a deadlock if there
 
2108
        is other threads waiting for other tables used by this thread.
 
2109
 
 
2110
        Proper fix would be to if the second retry failed:
 
2111
        - Mark that table def changed
 
2112
        - Return from open table
 
2113
        - Close all tables used by this thread
 
2114
        - Start waiting that the share is released
 
2115
        - Retry by opening all tables again
 
2116
      */
 
2117
 
 
2118
      /*
 
2119
        TO BE FIXED
 
2120
        To avoid deadlock, only wait for release if no one else is
 
2121
        using the share.
 
2122
      */
 
2123
      if (share->ref_count != 1)
 
2124
        goto err;
 
2125
      /* Free share and wait until it's released by all threads */
 
2126
      TableShare::release(share);
 
2127
 
 
2128
      if (!session->killed)
 
2129
      {
 
2130
        drizzle_reset_errors(session, 1);         // Clear warnings
 
2131
        session->clear_error();                 // Clear error message
 
2132
        goto retry;
 
2133
      }
 
2134
      return 1;
 
2135
    }
 
2136
    if (!entry->s || !entry->s->crashed)
 
2137
      goto err;
 
2138
    // Code below is for repairing a crashed file
 
2139
    if ((error= lock_table_name(session, table_list, true)))
 
2140
    {
 
2141
      if (error < 0)
 
2142
        goto err;
 
2143
      if (wait_for_locked_table_names(session, table_list))
 
2144
      {
 
2145
        unlock_table_name(table_list);
 
2146
        goto err;
 
2147
      }
 
2148
    }
 
2149
    pthread_mutex_unlock(&LOCK_open);
 
2150
    session->clear_error();                             // Clear error message
 
2151
    error= 0;
 
2152
    if (open_table_from_share(session, share, alias,
 
2153
                              (uint32_t) (HA_OPEN_KEYFILE | HA_OPEN_RNDFILE |
 
2154
                                          HA_GET_INDEX |
 
2155
                                          HA_TRY_READ_ONLY),
 
2156
                              EXTRA_RECORD,
 
2157
                              ha_open_options | HA_OPEN_FOR_REPAIR,
 
2158
                              entry, OTM_OPEN) || ! entry->file)
 
2159
    {
 
2160
      /* Give right error message */
 
2161
      session->clear_error();
 
2162
      my_error(ER_NOT_KEYFILE, MYF(0), share->table_name.str, my_errno);
 
2163
      errmsg_printf(ERRMSG_LVL_ERROR, _("Couldn't repair table: %s.%s"), share->db.str,
 
2164
                    share->table_name.str);
 
2165
      if (entry->file)
 
2166
        entry->closefrm(false);
 
2167
      error=1;
 
2168
    }
 
2169
    else
 
2170
      session->clear_error();                   // Clear error message
 
2171
    pthread_mutex_lock(&LOCK_open);
 
2172
    unlock_table_name(table_list);
 
2173
 
 
2174
    if (error)
 
2175
      goto err;
 
2176
    break;
 
2177
  }
 
2178
 
 
2179
  /*
 
2180
    If we are here, there was no fatal error (but error may be still
 
2181
    unitialized).
 
2182
  */
 
2183
  if (unlikely(entry->file->implicit_emptied))
 
2184
  {
 
2185
    entry->file->implicit_emptied= 0;
 
2186
    {
 
2187
      char *query, *end;
 
2188
      uint32_t query_buf_size= 20 + share->db.length + share->table_name.length +1;
 
2189
      if ((query= (char*) malloc(query_buf_size)))
 
2190
      {
 
2191
        /* 
 
2192
          "this DELETE FROM is needed even with row-based binlogging"
 
2193
 
 
2194
          We inherited this from MySQL. TODO: fix it to issue a propper truncate
 
2195
          of the table (though that may not be completely right sematics).
 
2196
        */
 
2197
        end= query;
 
2198
        end+= sprintf(query, "DELETE FROM `%s`.`%s`", share->db.str,
 
2199
                      share->table_name.str);
 
2200
        replication_services.rawStatement(session, query, (size_t)(end - query)); 
 
2201
        free(query);
 
2202
      }
 
2203
      else
 
2204
      {
 
2205
        errmsg_printf(ERRMSG_LVL_ERROR, _("When opening HEAP table, could not allocate memory "
 
2206
                                          "to write 'DELETE FROM `%s`.`%s`' to replication"),
 
2207
                      table_list->db, table_list->table_name);
 
2208
        my_error(ER_OUTOFMEMORY, MYF(0), query_buf_size);
 
2209
        entry->closefrm(false);
 
2210
        goto err;
 
2211
      }
 
2212
    }
 
2213
  }
 
2214
  return 0;
 
2215
 
 
2216
err:
 
2217
  TableShare::release(share);
 
2218
 
 
2219
  return 1;
 
2220
}
 
2221
 
1533
2222
 
1534
2223
/*
1535
2224
  Open all tables in list
1536
2225
 
1537
2226
  SYNOPSIS
1538
2227
  open_tables()
1539
 
  session - thread Cursor
 
2228
  session - thread handler
1540
2229
  start - list of tables in/out
1541
2230
  counter - number of opened tables will be return using this parameter
1542
2231
  flags   - bitmap of flags to modify how the tables will be open:
1590
2279
    {
1591
2280
      continue;
1592
2281
    }
 
2282
    /*
 
2283
      If this TableList object is a placeholder for an information_schema
 
2284
      table, create a temporary table to represent the information_schema
 
2285
      table in the query. Do not fill it yet - will be filled during
 
2286
      execution.
 
2287
    */
 
2288
    if (tables->schema_table)
 
2289
    {
 
2290
      if (mysql_schema_table(this, lex, tables) == false)
 
2291
        continue;
 
2292
      return -1;
 
2293
    }
1593
2294
    (*counter)++;
1594
2295
 
1595
2296
    /*
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
2297
      Not a placeholder: must be a base table or a view, and the table is
1610
2298
      not opened yet. Try to open the table.
1611
2299
    */
1612
2300
    if (tables->table == NULL)
1613
 
      tables->table= openTable(tables, &refresh, flags);
 
2301
      tables->table= open_table(tables, &refresh, flags);
1614
2302
 
1615
2303
    if (tables->table == NULL)
1616
2304
    {
1644
2332
    {
1645
2333
      if (tables->lock_type == TL_WRITE_DEFAULT)
1646
2334
        tables->table->reginfo.lock_type= update_lock_default;
1647
 
      else if (tables->table->getShare()->getType() == message::Table::STANDARD)
 
2335
      else if (tables->table->s->tmp_table == NO_TMP_TABLE)
1648
2336
        tables->table->reginfo.lock_type= tables->lock_type;
1649
2337
    }
1650
2338
  }
1668
2356
  Open and lock one table
1669
2357
 
1670
2358
  SYNOPSIS
1671
 
  openTableLock()
1672
 
  session                       Thread Cursor
 
2359
  open_ltable()
 
2360
  session                       Thread handler
1673
2361
  table_list            Table to open is first table in this list
1674
2362
  lock_type             Lock to use for open
1675
2363
  lock_flags          Flags passed to mysql_lock_table
1688
2376
  table_list->table             table
1689
2377
*/
1690
2378
 
1691
 
Table *Session::openTableLock(TableList *table_list, thr_lock_type lock_type)
 
2379
Table *Session::open_ltable(TableList *table_list, thr_lock_type lock_type)
1692
2380
{
1693
2381
  Table *table;
1694
2382
  bool refresh;
1695
2383
 
1696
2384
  set_proc_info("Opening table");
1697
2385
  current_tablenr= 0;
1698
 
  while (!(table= openTable(table_list, &refresh)) && refresh) ;
 
2386
  while (!(table= open_table(table_list, &refresh, 0)) &&
 
2387
         refresh)
 
2388
    ;
1699
2389
 
1700
2390
  if (table)
1701
2391
  {
1704
2394
 
1705
2395
    assert(lock == 0);  // You must lock everything at once
1706
2396
    if ((table->reginfo.lock_type= lock_type) != TL_UNLOCK)
1707
 
    {
1708
 
      if (not (lock= lockTables(&table_list->table, 1, 0)))
1709
 
        table= NULL;
1710
 
    }
 
2397
      if (! (lock= mysql_lock_tables(this, &table_list->table, 1, 0, &refresh)))
 
2398
        table= 0;
1711
2399
  }
1712
2400
 
1713
2401
  set_proc_info(0);
1720
2408
 
1721
2409
  SYNOPSIS
1722
2410
  lock_tables()
1723
 
  session                       Thread Cursor
 
2411
  session                       Thread handler
1724
2412
  tables                Tables to lock
1725
2413
  count         Number of opened tables
1726
2414
  need_reopen         Out parameter which if true indicates that some
1743
2431
  -1    Error
1744
2432
*/
1745
2433
 
1746
 
int Session::lock_tables(TableList *tables, uint32_t count, bool *need_reopen)
 
2434
int lock_tables(Session *session, TableList *tables, uint32_t count, bool *need_reopen)
1747
2435
{
1748
2436
  TableList *table;
1749
 
  Session *session= this;
1750
2437
 
1751
2438
  /*
1752
2439
    We can't meet statement requiring prelocking if we already
1761
2448
  Table **start,**ptr;
1762
2449
  uint32_t lock_flag= DRIZZLE_LOCK_NOTIFY_IF_NEED_REOPEN;
1763
2450
 
1764
 
  if (!(ptr=start=(Table**) session->getMemRoot()->allocate(sizeof(Table*)*count)))
 
2451
  if (!(ptr=start=(Table**) session->alloc(sizeof(Table*)*count)))
1765
2452
    return -1;
1766
 
 
1767
2453
  for (table= tables; table; table= table->next_global)
1768
2454
  {
1769
2455
    if (!table->placeholder())
1770
2456
      *(ptr++)= table->table;
1771
2457
  }
1772
2458
 
1773
 
  if (not (session->lock= session->lockTables(start, (uint32_t) (ptr - start), lock_flag)))
 
2459
  if (!(session->lock= mysql_lock_tables(session, start, (uint32_t) (ptr - start),
 
2460
                                         lock_flag, need_reopen)))
1774
2461
  {
1775
2462
    return -1;
1776
2463
  }
1799
2486
#  Table object
1800
2487
*/
1801
2488
 
1802
 
Table *Open_tables_state::open_temporary_table(const identifier::Table &identifier,
1803
 
                                               bool link_in_list)
 
2489
Table *open_temporary_table(Session *session, const char *path, const char *db,
 
2490
                            const char *table_name, bool link_in_list,
 
2491
                            open_table_mode open_mode)
1804
2492
{
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)
 
2493
  Table *tmp_table;
 
2494
  TableShare *share;
 
2495
  char cache_key[MAX_DBKEY_LENGTH], *saved_cache_key, *tmp_path;
 
2496
  uint32_t key_length, path_length;
 
2497
  TableList table_list;
 
2498
 
 
2499
  table_list.db=         (char*) db;
 
2500
  table_list.table_name= (char*) table_name;
 
2501
  /* Create the cache_key for temporary tables */
 
2502
  key_length= table_list.create_table_def_key(cache_key);
 
2503
  path_length= strlen(path);
 
2504
 
 
2505
  if (!(tmp_table= (Table*) malloc(sizeof(*tmp_table) + sizeof(*share) +
 
2506
                                   path_length + 1 + key_length)))
1813
2507
    return NULL;
1814
2508
 
 
2509
  share= (TableShare*) (tmp_table+1);
 
2510
  tmp_path= (char*) (share+1);
 
2511
  saved_cache_key= strcpy(tmp_path, path)+path_length+1;
 
2512
  memcpy(saved_cache_key, cache_key, key_length);
 
2513
 
 
2514
  share->init(saved_cache_key, key_length, strchr(saved_cache_key, '\0')+1, tmp_path);
 
2515
 
1815
2516
  /*
1816
2517
    First open the share, and then open the table from the share we just opened.
1817
2518
  */
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))
 
2519
  if (open_table_def(session, share) ||
 
2520
      open_table_from_share(session, share, table_name,
 
2521
                            (open_mode == OTM_ALTER) ? 0 :
 
2522
                            (uint32_t) (HA_OPEN_KEYFILE | HA_OPEN_RNDFILE |
 
2523
                                        HA_GET_INDEX),
 
2524
                            (open_mode == OTM_ALTER) ?
 
2525
                            (EXTRA_RECORD | OPEN_FRM_FILE_ONLY)
 
2526
                            : (EXTRA_RECORD),
 
2527
                            ha_open_options,
 
2528
                            tmp_table, open_mode))
1824
2529
  {
1825
2530
    /* 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
 
 
 
2531
    share->free_table_share();
 
2532
    free((char*) tmp_table);
1829
2533
    return 0;
1830
2534
  }
1831
2535
 
1832
 
  new_tmp_table->reginfo.lock_type= TL_WRITE;    // Simulate locked
 
2536
  tmp_table->reginfo.lock_type= TL_WRITE;        // Simulate locked
 
2537
  if (open_mode == OTM_ALTER)
 
2538
  {
 
2539
    /*
 
2540
      Temporary table has been created with frm_only
 
2541
      and has not been created in any storage engine
 
2542
    */
 
2543
    share->tmp_table= TMP_TABLE_FRM_FILE_ONLY;
 
2544
  }
 
2545
  else
 
2546
    share->tmp_table= (tmp_table->file->has_transactions() ?
 
2547
                       TRANSACTIONAL_TMP_TABLE : NON_TRANSACTIONAL_TMP_TABLE);
1833
2548
 
1834
2549
  if (link_in_list)
1835
2550
  {
1836
2551
    /* 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
 
    }
1842
 
    this->temporary_tables= new_tmp_table;
1843
 
    this->temporary_tables->setPrev(0);
1844
 
  }
1845
 
  new_tmp_table->pos_in_table_list= 0;
1846
 
 
1847
 
  return new_tmp_table;
 
2552
    tmp_table->next= session->temporary_tables;
 
2553
    if (tmp_table->next)
 
2554
      tmp_table->next->prev= tmp_table;
 
2555
    session->temporary_tables= tmp_table;
 
2556
    session->temporary_tables->prev= 0;
 
2557
  }
 
2558
  tmp_table->pos_in_table_list= 0;
 
2559
 
 
2560
  return tmp_table;
 
2561
}
 
2562
 
 
2563
 
 
2564
bool rm_temporary_table(StorageEngine *base, char *path)
 
2565
{
 
2566
  bool error=0;
 
2567
 
 
2568
  assert(base);
 
2569
 
 
2570
  if(delete_table_proto_file(path))
 
2571
    error=1; /* purecov: inspected */
 
2572
 
 
2573
  if (base->deleteTable(current_session, path))
 
2574
  {
 
2575
    error=1;
 
2576
    errmsg_printf(ERRMSG_LVL_WARN, _("Could not remove temporary table: '%s', error: %d"),
 
2577
                  path, my_errno);
 
2578
  }
 
2579
  return(error);
1848
2580
}
1849
2581
 
1850
2582
 
1861
2593
Field *not_found_field= (Field*) 0x1;
1862
2594
Field *view_ref_found= (Field*) 0x2;
1863
2595
 
 
2596
#define WRONG_GRANT (Field*) -1
 
2597
 
1864
2598
static void update_field_dependencies(Session *session, Field *field, Table *table)
1865
2599
{
1866
2600
  if (session->mark_used_columns != MARK_COLUMNS_NONE)
1867
2601
  {
1868
 
    boost::dynamic_bitset<> *current_bitmap= NULL;
 
2602
    MY_BITMAP *current_bitmap, *other_bitmap;
1869
2603
 
1870
2604
    /*
1871
2605
      We always want to register the used keys, as the column bitmap may have
1878
2612
    if (session->mark_used_columns == MARK_COLUMNS_READ)
1879
2613
    {
1880
2614
      current_bitmap= table->read_set;
 
2615
      other_bitmap=   table->write_set;
1881
2616
    }
1882
2617
    else
1883
2618
    {
1884
2619
      current_bitmap= table->write_set;
 
2620
      other_bitmap=   table->read_set;
1885
2621
    }
1886
2622
 
1887
 
    //if (current_bitmap->testAndSet(field->position()))
1888
 
    if (current_bitmap->test(field->position()))
 
2623
    if (bitmap_test_and_set(current_bitmap, field->field_index))
1889
2624
    {
1890
2625
      if (session->mark_used_columns == MARK_COLUMNS_WRITE)
1891
2626
        session->dup_field= field;
1901
2636
 
1902
2637
  SYNOPSIS
1903
2638
  find_field_in_natural_join()
1904
 
  session                        [in]  thread Cursor
 
2639
  session                        [in]  thread handler
1905
2640
  table_ref            [in]  table reference to search
1906
2641
  name           [in]  name of field
1907
2642
  length                 [in]  length of name
1921
2656
 
1922
2657
  RETURN
1923
2658
  NULL        if the field was not found
1924
 
  PTR         Pointer to the found Field
 
2659
  WRONG_GRANT if no access rights to the found field
 
2660
#           Pointer to the found Field
1925
2661
*/
1926
2662
 
1927
2663
static Field *
1944
2680
    {
1945
2681
      if (nj_col)
1946
2682
      {
1947
 
        my_error(ER_NON_UNIQ_ERROR, MYF(0), name, session->where());
 
2683
        my_error(ER_NON_UNIQ_ERROR, MYF(0), name, session->where);
1948
2684
        return NULL;
1949
2685
      }
1950
2686
      nj_col= curr_nj_col;
1954
2690
    return NULL;
1955
2691
  {
1956
2692
    /* This is a base table. */
1957
 
    assert(nj_col->table_ref->table == nj_col->table_field->getTable());
 
2693
    assert(nj_col->table_ref->table == nj_col->table_field->table);
1958
2694
    found_field= nj_col->table_field;
1959
2695
    update_field_dependencies(session, found_field, nj_col->table_ref->table);
1960
2696
  }
1970
2706
 
1971
2707
  SYNOPSIS
1972
2708
  find_field_in_table()
1973
 
  session                               thread Cursor
 
2709
  session                               thread handler
1974
2710
  table                 table where to search for the field
1975
2711
  name                  name of field
1976
2712
  length                        length of name
1991
2727
  uint32_t cached_field_index= *cached_field_index_ptr;
1992
2728
 
1993
2729
  /* We assume here that table->field < NO_CACHED_FIELD_INDEX = UINT_MAX */
1994
 
  if (cached_field_index < table->getShare()->sizeFields() &&
 
2730
  if (cached_field_index < table->s->fields &&
1995
2731
      !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));
 
2732
                     table->field[cached_field_index]->field_name, name))
 
2733
    field_ptr= table->field + cached_field_index;
 
2734
  else if (table->s->name_hash.records)
 
2735
  {
 
2736
    field_ptr= (Field**) hash_search(&table->s->name_hash, (unsigned char*) name,
 
2737
                                     length);
2003
2738
    if (field_ptr)
2004
2739
    {
2005
2740
      /*
2006
2741
        field_ptr points to field in TableShare. Convert it to the matching
2007
2742
        field in table
2008
2743
      */
2009
 
      field_ptr= (table->getFields() + table->getShare()->positionFields(field_ptr));
 
2744
      field_ptr= (table->field + (field_ptr - table->s->field));
2010
2745
    }
2011
2746
  }
2012
2747
  else
2013
2748
  {
2014
 
    if (!(field_ptr= table->getFields()))
 
2749
    if (!(field_ptr= table->field))
2015
2750
      return((Field *)0);
2016
2751
    for (; *field_ptr; ++field_ptr)
2017
2752
      if (!my_strcasecmp(system_charset_info, (*field_ptr)->field_name, name))
2020
2755
 
2021
2756
  if (field_ptr && *field_ptr)
2022
2757
  {
2023
 
    *cached_field_index_ptr= field_ptr - table->getFields();
 
2758
    *cached_field_index_ptr= field_ptr - table->field;
2024
2759
    field= *field_ptr;
2025
2760
  }
2026
2761
  else
2027
2762
  {
2028
2763
    if (!allow_rowid ||
2029
2764
        my_strcasecmp(system_charset_info, name, "_rowid") ||
2030
 
        table->getShare()->rowid_field_offset == 0)
 
2765
        table->s->rowid_field_offset == 0)
2031
2766
      return((Field*) 0);
2032
 
    field= table->getField(table->getShare()->rowid_field_offset-1);
 
2767
    field= table->field[table->s->rowid_field_offset-1];
2033
2768
  }
2034
2769
 
2035
2770
  update_field_dependencies(session, field, table);
2036
2771
 
2037
 
  return field;
 
2772
  return(field);
2038
2773
}
2039
2774
 
2040
2775
 
2043
2778
 
2044
2779
  SYNOPSIS
2045
2780
  find_field_in_table_ref()
2046
 
  session                          [in]  thread Cursor
 
2781
  session                          [in]  thread handler
2047
2782
  table_list               [in]  table reference to search
2048
2783
  name             [in]  name of field
2049
2784
  length                   [in]  field length of name
2052
2787
  table_name             [in]  optional table name that qualifies the field
2053
2788
  ref                  [in/out] if 'name' is resolved to a view field, ref
2054
2789
  is set to point to the found view field
 
2790
  check_privileges       [in]  check privileges
2055
2791
  allow_rowid              [in]  do allow finding of "_rowid" field?
2056
2792
  cached_field_index_ptr [in]  cached position in field list (used to
2057
2793
  speedup lookup for fields in prepared tables)
2084
2820
                        const char *name, uint32_t length,
2085
2821
                        const char *item_name, const char *db_name,
2086
2822
                        const char *table_name, Item **ref,
2087
 
                        bool allow_rowid,
 
2823
                        bool check_privileges, bool allow_rowid,
2088
2824
                        uint32_t *cached_field_index_ptr,
2089
2825
                        bool register_tree_change, TableList **actual_table)
2090
2826
{
2108
2844
    inside the view, but we want to search directly in the view columns
2109
2845
    which are represented as a 'field_translation'.
2110
2846
 
2111
 
    TODO-> Ensure that table_name, db_name and tables->db always points to something !
 
2847
TODO: Ensure that table_name, db_name and tables->db always points to
 
2848
something !
2112
2849
  */
2113
2850
  if (/* Exclude nested joins. */
2114
 
      (!table_list->getNestedJoin()) &&
 
2851
      (!table_list->nested_join) &&
2115
2852
      /* Include merge views and information schema tables. */
2116
2853
      /*
2117
2854
        Test if the field qualifiers match the table reference we plan
2119
2856
      */
2120
2857
      table_name && table_name[0] &&
2121
2858
      (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()))))
 
2859
       (db_name && db_name[0] && table_list->db && table_list->db[0] &&
 
2860
        strcmp(db_name, table_list->db))))
2124
2861
    return 0;
2125
2862
 
2126
2863
  *actual_table= NULL;
2127
2864
 
2128
 
  if (!table_list->getNestedJoin())
 
2865
  if (!table_list->nested_join)
2129
2866
  {
2130
2867
    /* 'table_list' is a stored table. */
2131
2868
    assert(table_list->table);
2145
2882
    */
2146
2883
    if (table_name && table_name[0])
2147
2884
    {
2148
 
      List_iterator<TableList> it(table_list->getNestedJoin()->join_list);
 
2885
      List_iterator<TableList> it(table_list->nested_join->join_list);
2149
2886
      TableList *table;
2150
2887
      while ((table= it++))
2151
2888
      {
2152
2889
        if ((fld= find_field_in_table_ref(session, table, name, length, item_name,
2153
2890
                                          db_name, table_name, ref,
2154
 
                                          allow_rowid,
 
2891
                                          check_privileges, allow_rowid,
2155
2892
                                          cached_field_index_ptr,
2156
2893
                                          register_tree_change, actual_table)))
2157
 
          return fld;
 
2894
          return(fld);
2158
2895
      }
2159
 
      return NULL;
 
2896
      return 0;
2160
2897
    }
2161
2898
    /*
2162
2899
      Non-qualified field, search directly in the result columns of the
2173
2910
    if (session->mark_used_columns != MARK_COLUMNS_NONE)
2174
2911
    {
2175
2912
      /*
2176
 
        Get rw_set correct for this field so that the Cursor
 
2913
        Get rw_set correct for this field so that the handler
2177
2914
        knows that this field is involved in the query and gets
2178
2915
        retrieved/updated
2179
2916
      */
2193
2930
        field_to_set= fld;
2194
2931
      if (field_to_set)
2195
2932
      {
2196
 
        Table *table= field_to_set->getTable();
 
2933
        Table *table= field_to_set->table;
2197
2934
        if (session->mark_used_columns == MARK_COLUMNS_READ)
2198
 
          table->setReadSet(field_to_set->position());
 
2935
          table->setReadSet(field_to_set->field_index);
2199
2936
        else
2200
 
          table->setWriteSet(field_to_set->position());
 
2937
          table->setWriteSet(field_to_set->field_index);
2201
2938
      }
2202
2939
    }
2203
2940
  }
2224
2961
  - REPORT_EXCEPT_NON_UNIQUE report all other errors
2225
2962
  except when non-unique fields were found
2226
2963
  - REPORT_ALL_ERRORS
 
2964
  check_privileges      need to check privileges
2227
2965
  register_tree_change  true if ref is not a stack variable and we
2228
2966
  to need register changes in item tree
2229
2967
 
2242
2980
find_field_in_tables(Session *session, Item_ident *item,
2243
2981
                     TableList *first_table, TableList *last_table,
2244
2982
                     Item **ref, find_item_error_report_type report_error,
2245
 
                     bool register_tree_change)
 
2983
                     bool check_privileges, bool register_tree_change)
2246
2984
{
2247
2985
  Field *found=0;
2248
2986
  const char *db= item->db_name;
2284
3022
                                 true, &(item->cached_field_index));
2285
3023
    else
2286
3024
      found= find_field_in_table_ref(session, table_ref, name, length, item->name,
2287
 
                                     NULL, NULL, ref,
 
3025
                                     NULL, NULL, ref, check_privileges,
2288
3026
                                     true, &(item->cached_field_index),
2289
3027
                                     register_tree_change,
2290
3028
                                     &actual_table);
2291
3029
    if (found)
2292
3030
    {
 
3031
      if (found == WRONG_GRANT)
 
3032
        return (Field*) 0;
 
3033
 
2293
3034
      /*
2294
3035
        Only views fields should be marked as dependent, not an underlying
2295
3036
        fields.
2329
3070
  {
2330
3071
    Field *cur_field= find_field_in_table_ref(session, cur_table, name, length,
2331
3072
                                              item->name, db, table_name, ref,
 
3073
                                              (session->lex->sql_command ==
 
3074
                                               SQLCOM_SHOW_FIELDS)
 
3075
                                              ? false : check_privileges,
2332
3076
                                              allow_rowid,
2333
3077
                                              &(item->cached_field_index),
2334
3078
                                              register_tree_change,
2335
3079
                                              &actual_table);
2336
3080
    if (cur_field)
2337
3081
    {
 
3082
      if (cur_field == WRONG_GRANT)
 
3083
      {
 
3084
        if (session->lex->sql_command != SQLCOM_SHOW_FIELDS)
 
3085
          return (Field*) 0;
 
3086
 
 
3087
        session->clear_error();
 
3088
        cur_field= find_field_in_table_ref(session, cur_table, name, length,
 
3089
                                           item->name, db, table_name, ref,
 
3090
                                           false,
 
3091
                                           allow_rowid,
 
3092
                                           &(item->cached_field_index),
 
3093
                                           register_tree_change,
 
3094
                                           &actual_table);
 
3095
        if (cur_field)
 
3096
        {
 
3097
          Field *nf=new Field_null(NULL,0,Field::NONE,
 
3098
                                   cur_field->field_name,
 
3099
                                   &my_charset_bin);
 
3100
          nf->init(cur_table->table);
 
3101
          cur_field= nf;
 
3102
        }
 
3103
      }
 
3104
 
2338
3105
      /*
2339
3106
        Store the original table of the field, which may be different from
2340
3107
        cur_table in the case of NATURAL/USING join.
2341
3108
      */
2342
3109
      item->cached_table= found ?  0 : actual_table;
2343
3110
 
2344
 
      assert(session->where());
 
3111
      assert(session->where);
2345
3112
      /*
2346
3113
        If we found a fully qualified field we return it directly as it can't
2347
3114
        have duplicates.
2354
3121
        if (report_error == REPORT_ALL_ERRORS ||
2355
3122
            report_error == IGNORE_EXCEPT_NON_UNIQUE)
2356
3123
          my_error(ER_NON_UNIQ_ERROR, MYF(0),
2357
 
                   table_name ? item->full_name() : name, session->where());
 
3124
                   table_name ? item->full_name() : name, session->where);
2358
3125
        return (Field*) 0;
2359
3126
      }
2360
3127
      found= cur_field;
2387
3154
      strcat(buff, table_name);
2388
3155
      table_name=buff;
2389
3156
    }
2390
 
    my_error(ER_UNKNOWN_TABLE, MYF(0), table_name, session->where());
 
3157
    my_error(ER_UNKNOWN_TABLE, MYF(0), table_name, session->where);
2391
3158
  }
2392
3159
  else
2393
3160
  {
2394
3161
    if (report_error == REPORT_ALL_ERRORS ||
2395
3162
        report_error == REPORT_EXCEPT_NON_UNIQUE)
2396
 
      my_error(ER_BAD_FIELD_ERROR, MYF(0), item->full_name(), session->where());
 
3163
      my_error(ER_BAD_FIELD_ERROR, MYF(0), item->full_name(), session->where);
2397
3164
    else
2398
3165
      found= not_found_field;
2399
3166
  }
2439
3206
 
2440
3207
 
2441
3208
Item **
2442
 
find_item_in_list(Session *session,
2443
 
                  Item *find, List<Item> &items, uint32_t *counter,
 
3209
find_item_in_list(Item *find, List<Item> &items, uint32_t *counter,
2444
3210
                  find_item_error_report_type report_error,
2445
3211
                  enum_resolution_type *resolution)
2446
3212
{
2520
3286
            */
2521
3287
            if (report_error != IGNORE_ERRORS)
2522
3288
              my_error(ER_NON_UNIQ_ERROR, MYF(0),
2523
 
                       find->full_name(), session->where());
 
3289
                       find->full_name(), current_session->where);
2524
3290
            return (Item**) 0;
2525
3291
          }
2526
3292
          found_unaliased= li.ref();
2551
3317
              continue;                           // Same field twice
2552
3318
            if (report_error != IGNORE_ERRORS)
2553
3319
              my_error(ER_NON_UNIQ_ERROR, MYF(0),
2554
 
                       find->full_name(), session->where());
 
3320
                       find->full_name(), current_session->where);
2555
3321
            return (Item**) 0;
2556
3322
          }
2557
3323
          found= li.ref();
2603
3369
    {
2604
3370
      if (report_error != IGNORE_ERRORS)
2605
3371
        my_error(ER_NON_UNIQ_ERROR, MYF(0),
2606
 
                 find->full_name(), session->where());
 
3372
                 find->full_name(), current_session->where);
2607
3373
      return (Item **) 0;
2608
3374
    }
2609
3375
    if (found_unaliased)
2619
3385
  {
2620
3386
    if (report_error == REPORT_ALL_ERRORS)
2621
3387
      my_error(ER_BAD_FIELD_ERROR, MYF(0),
2622
 
               find->full_name(), session->where());
 
3388
               find->full_name(), current_session->where);
2623
3389
    return (Item **) 0;
2624
3390
  }
2625
3391
  else
2737
3503
    Leaf table references to which new natural join columns are added
2738
3504
    if the leaves are != NULL.
2739
3505
  */
2740
 
  TableList *leaf_1= (table_ref_1->getNestedJoin() &&
2741
 
                      ! table_ref_1->is_natural_join) ?
 
3506
  TableList *leaf_1= (table_ref_1->nested_join &&
 
3507
                      !table_ref_1->is_natural_join) ?
2742
3508
    NULL : table_ref_1;
2743
 
  TableList *leaf_2= (table_ref_2->getNestedJoin() &&
2744
 
                      ! table_ref_2->is_natural_join) ?
 
3509
  TableList *leaf_2= (table_ref_2->nested_join &&
 
3510
                      !table_ref_2->is_natural_join) ?
2745
3511
    NULL : table_ref_2;
2746
3512
 
2747
3513
  *found_using_fields= 0;
2753
3519
    /* true if field_name_1 is a member of using_fields */
2754
3520
    bool is_using_column_1;
2755
3521
    if (!(nj_col_1= it_1.get_or_create_column_ref(leaf_1)))
2756
 
      return(result);
 
3522
      goto err;
2757
3523
    field_name_1= nj_col_1->name();
2758
3524
    is_using_column_1= using_fields &&
2759
3525
      test_if_string_in_list(field_name_1, using_fields);
2771
3537
      Natural_join_column *cur_nj_col_2;
2772
3538
      const char *cur_field_name_2;
2773
3539
      if (!(cur_nj_col_2= it_2.get_or_create_column_ref(leaf_2)))
2774
 
        return(result);
 
3540
        goto err;
2775
3541
      cur_field_name_2= cur_nj_col_2->name();
2776
3542
 
2777
3543
      /*
2790
3556
        if (cur_nj_col_2->is_common ||
2791
3557
            (found && (!using_fields || is_using_column_1)))
2792
3558
        {
2793
 
          my_error(ER_NON_UNIQ_ERROR, MYF(0), field_name_1, session->where());
2794
 
          return(result);
 
3559
          my_error(ER_NON_UNIQ_ERROR, MYF(0), field_name_1, session->where);
 
3560
          goto err;
2795
3561
        }
2796
3562
        nj_col_2= cur_nj_col_2;
2797
3563
        found= true;
2824
3590
      Item_func_eq *eq_cond;
2825
3591
 
2826
3592
      if (!item_1 || !item_2)
2827
 
        return(result); // out of memory
 
3593
        goto err;                               // out of memory
2828
3594
 
2829
3595
      /*
2830
3596
        In the case of no_wrap_view_item == 0, the created items must be
2849
3615
      */
2850
3616
      if (set_new_item_local_context(session, item_ident_1, nj_col_1->table_ref) ||
2851
3617
          set_new_item_local_context(session, item_ident_2, nj_col_2->table_ref))
2852
 
        return(result);
 
3618
        goto err;
2853
3619
 
2854
3620
      if (!(eq_cond= new Item_func_eq(item_ident_1, item_ident_2)))
2855
 
        return(result);                               /* Out of memory. */
 
3621
        goto err;                               /* Out of memory. */
2856
3622
 
2857
3623
      /*
2858
3624
        Add the new equi-join condition to the ON clause. Notice that
2869
3635
      {
2870
3636
        Table *table_1= nj_col_1->table_ref->table;
2871
3637
        /* Mark field_1 used for table cache. */
2872
 
        table_1->setReadSet(field_1->position());
 
3638
        table_1->setReadSet(field_1->field_index);
2873
3639
        table_1->covering_keys&= field_1->part_of_key;
2874
3640
        table_1->merge_keys|= field_1->part_of_key;
2875
3641
      }
2877
3643
      {
2878
3644
        Table *table_2= nj_col_2->table_ref->table;
2879
3645
        /* Mark field_2 used for table cache. */
2880
 
        table_2->setReadSet(field_2->position());
 
3646
        table_2->setReadSet(field_2->field_index);
2881
3647
        table_2->covering_keys&= field_2->part_of_key;
2882
3648
        table_2->merge_keys|= field_2->part_of_key;
2883
3649
      }
2898
3664
  */
2899
3665
  result= false;
2900
3666
 
 
3667
err:
2901
3668
  return(result);
2902
3669
}
2903
3670
 
2939
3706
*/
2940
3707
 
2941
3708
static bool
2942
 
store_natural_using_join_columns(Session *session,
 
3709
store_natural_using_join_columns(Session *,
2943
3710
                                 TableList *natural_using_join,
2944
3711
                                 TableList *table_ref_1,
2945
3712
                                 TableList *table_ref_2,
2955
3722
 
2956
3723
  if (!(non_join_columns= new List<Natural_join_column>) ||
2957
3724
      !(natural_using_join->join_columns= new List<Natural_join_column>))
2958
 
  {
2959
 
    return(result);
2960
 
  }
 
3725
    goto err;
2961
3726
 
2962
3727
  /* Append the columns of the first join operand. */
2963
3728
  for (it_1.set(table_ref_1); !it_1.end_of_fields(); it_1.next())
2995
3760
        if (!(common_field= it++))
2996
3761
        {
2997
3762
          my_error(ER_BAD_FIELD_ERROR, MYF(0), using_field_name_ptr,
2998
 
                   session->where());
2999
 
          return(result);
 
3763
                   current_session->where);
 
3764
          goto err;
3000
3765
        }
3001
3766
        if (!my_strcasecmp(system_charset_info,
3002
3767
                           common_field->name(), using_field_name_ptr))
3024
3789
 
3025
3790
  result= false;
3026
3791
 
 
3792
err:
3027
3793
  return(result);
3028
3794
}
3029
3795
 
3066
3832
  bool result= true;
3067
3833
 
3068
3834
  /* Call the procedure recursively for each nested table reference. */
3069
 
  if (table_ref->getNestedJoin())
 
3835
  if (table_ref->nested_join)
3070
3836
  {
3071
 
    List_iterator_fast<TableList> nested_it(table_ref->getNestedJoin()->join_list);
 
3837
    List_iterator_fast<TableList> nested_it(table_ref->nested_join->join_list);
3072
3838
    TableList *same_level_left_neighbor= nested_it++;
3073
3839
    TableList *same_level_right_neighbor= NULL;
3074
3840
    /* Left/right-most neighbors, possibly at higher levels in the join tree. */
3093
3859
          cur_table_ref->outer_join & JOIN_TYPE_RIGHT)
3094
3860
      {
3095
3861
        /* This can happen only for JOIN ... ON. */
3096
 
        assert(table_ref->getNestedJoin()->join_list.elements == 2);
 
3862
        assert(table_ref->nested_join->join_list.elements == 2);
3097
3863
        std::swap(same_level_left_neighbor, cur_table_ref);
3098
3864
      }
3099
3865
 
3106
3872
      real_right_neighbor= (same_level_right_neighbor) ?
3107
3873
        same_level_right_neighbor : right_neighbor;
3108
3874
 
3109
 
      if (cur_table_ref->getNestedJoin() &&
 
3875
      if (cur_table_ref->nested_join &&
3110
3876
          store_top_level_join_columns(session, cur_table_ref,
3111
3877
                                       real_left_neighbor, real_right_neighbor))
3112
 
        return(result);
 
3878
        goto err;
3113
3879
      same_level_right_neighbor= cur_table_ref;
3114
3880
    }
3115
3881
  }
3120
3886
  */
3121
3887
  if (table_ref->is_natural_join)
3122
3888
  {
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);
 
3889
    assert(table_ref->nested_join &&
 
3890
           table_ref->nested_join->join_list.elements == 2);
 
3891
    List_iterator_fast<TableList> operand_it(table_ref->nested_join->join_list);
3126
3892
    /*
3127
3893
      Notice that the order of join operands depends on whether table_ref
3128
3894
      represents a LEFT or a RIGHT join. In a RIGHT join, the operands are
3141
3907
      std::swap(table_ref_1, table_ref_2);
3142
3908
    if (mark_common_columns(session, table_ref_1, table_ref_2,
3143
3909
                            using_fields, &found_using_fields))
3144
 
      return(result);
 
3910
      goto err;
3145
3911
 
3146
3912
    /*
3147
3913
      Swap the join operands back, so that we pick the columns of the second
3153
3919
    if (store_natural_using_join_columns(session, table_ref, table_ref_1,
3154
3920
                                         table_ref_2, using_fields,
3155
3921
                                         found_using_fields))
3156
 
      return(result);
 
3922
      goto err;
3157
3923
 
3158
3924
    /*
3159
3925
      Change NATURAL JOIN to JOIN ... ON. We do this for both operands
3186
3952
  }
3187
3953
  result= false; /* All is OK. */
3188
3954
 
 
3955
err:
3189
3956
  return(result);
3190
3957
}
3191
3958
 
3218
3985
                                         List<TableList> *from_clause,
3219
3986
                                         Name_resolution_context *context)
3220
3987
{
3221
 
  session->setWhere("from clause");
 
3988
  session->where= "from clause";
3222
3989
  if (from_clause->elements == 0)
3223
3990
    return false; /* We come here in the case of UNIONs. */
3224
3991
 
3318
4085
      session->lex->current_select->cur_pos_in_select_list++;
3319
4086
  }
3320
4087
  session->lex->current_select->cur_pos_in_select_list= UNDEF_POS;
3321
 
 
3322
4088
  return 0;
3323
4089
}
3324
4090
 
3339
4105
  session->mark_used_columns= mark_used_columns;
3340
4106
  if (allow_sum_func)
3341
4107
    session->lex->allow_sum_func|= 1 << session->lex->current_select->nest_level;
3342
 
  session->setWhere(Session::DEFAULT_WHERE);
 
4108
  session->where= Session::DEFAULT_WHERE;
3343
4109
  save_is_item_list_lookup= session->lex->current_select->is_item_list_lookup;
3344
4110
  session->lex->current_select->is_item_list_lookup= 0;
3345
4111
 
3351
4117
    There is other way to solve problem: fill array with pointers to list,
3352
4118
    but it will be slower.
3353
4119
 
3354
 
    TODO-> remove it when (if) we made one list for allfields and ref_pointer_array
 
4120
TODO: remove it when (if) we made one list for allfields and
 
4121
ref_pointer_array
3355
4122
  */
3356
4123
  if (ref_pointer_array)
3357
 
  {
3358
4124
    memset(ref_pointer_array, 0, sizeof(Item *) * fields.elements);
3359
 
  }
3360
4125
 
3361
4126
  Item **ref= ref_pointer_array;
3362
4127
  session->lex->current_select->cur_pos_in_select_list= 0;
3367
4132
      session->lex->current_select->is_item_list_lookup= save_is_item_list_lookup;
3368
4133
      session->lex->allow_sum_func= save_allow_sum_func;
3369
4134
      session->mark_used_columns= save_mark_used_columns;
3370
 
      return true;
 
4135
      return true; /* purecov: inspected */
3371
4136
    }
3372
4137
    if (ref)
3373
4138
      *(ref++)= item;
3414
4179
 
3415
4180
  SYNOPSIS
3416
4181
  setup_tables()
3417
 
  session                 Thread Cursor
 
4182
  session                 Thread handler
3418
4183
  context       name resolution contest to setup table list there
3419
4184
  from_clause   Top-level list of table references in the FROM clause
3420
4185
  tables          Table list (select_lex->table_list)
3491
4256
 
3492
4257
  SYNOPSIS
3493
4258
  setup_tables_and_check_view_access()
3494
 
  session                 Thread Cursor
 
4259
  session                 Thread handler
3495
4260
  context       name resolution contest to setup table list there
3496
4261
  from_clause   Top-level list of table references in the FROM clause
3497
4262
  tables          Table list (select_lex->table_list)
3530
4295
 
3531
4296
 
3532
4297
/*
 
4298
  Create a key_map from a list of index names
 
4299
 
 
4300
  SYNOPSIS
 
4301
  get_key_map_from_key_list()
 
4302
  map           key_map to fill in
 
4303
  table         Table
 
4304
  index_list            List of index names
 
4305
 
 
4306
  RETURN
 
4307
  0     ok;  In this case *map will includes the choosed index
 
4308
  1     error
 
4309
*/
 
4310
 
 
4311
bool get_key_map_from_key_list(key_map *map, Table *table,
 
4312
                               List<String> *index_list)
 
4313
{
 
4314
  List_iterator_fast<String> it(*index_list);
 
4315
  String *name;
 
4316
  uint32_t pos;
 
4317
 
 
4318
  map->reset();
 
4319
  while ((name=it++))
 
4320
  {
 
4321
    if (table->s->keynames.type_names == 0 ||
 
4322
        (pos= find_type(&table->s->keynames, name->ptr(),
 
4323
                        name->length(), 1)) <=
 
4324
        0)
 
4325
    {
 
4326
      my_error(ER_KEY_DOES_NOT_EXITS, MYF(0), name->c_ptr(),
 
4327
               table->pos_in_table_list->alias);
 
4328
      map->set();
 
4329
      return 1;
 
4330
    }
 
4331
    map->set(pos-1);
 
4332
  }
 
4333
  return 0;
 
4334
}
 
4335
 
 
4336
 
 
4337
/*
3533
4338
  Drops in all fields instead of current '*' field
3534
4339
 
3535
4340
  SYNOPSIS
3536
4341
  insert_fields()
3537
 
  session                       Thread Cursor
 
4342
  session                       Thread handler
3538
4343
  context             Context for name resolution
3539
4344
  db_name               Database name in case of 'database_name.table_name.*'
3540
4345
  table_name            Table name in case of 'table_name.*'
3588
4393
    assert(tables->is_leaf_for_name_resolution());
3589
4394
 
3590
4395
    if ((table_name && my_strcasecmp(table_alias_charset, table_name, tables->alias)) ||
3591
 
        (db_name && my_strcasecmp(system_charset_info, tables->getSchemaName(),db_name)))
 
4396
        (db_name && strcmp(tables->db,db_name)))
3592
4397
      continue;
3593
4398
 
3594
4399
    /*
3624
4429
      if ((field= field_iterator.field()))
3625
4430
      {
3626
4431
        /* Mark fields as used to allow storage engine to optimze access */
3627
 
        field->getTable()->setReadSet(field->position());
 
4432
        field->table->setReadSet(field->field_index);
3628
4433
        if (table)
3629
4434
        {
3630
4435
          table->covering_keys&= field->part_of_key;
3652
4457
        }
3653
4458
      }
3654
4459
      else
3655
 
      {
3656
4460
        session->used_tables|= item->used_tables();
3657
 
      }
3658
 
 
3659
4461
      session->lex->current_select->cur_pos_in_select_list++;
3660
4462
    }
3661
4463
    /*
3665
4467
      For NATURAL joins, used_tables is updated in the IF above.
3666
4468
    */
3667
4469
    if (table)
3668
 
      table->used_fields= table->getShare()->sizeFields();
 
4470
      table->used_fields= table->s->fields;
3669
4471
  }
3670
4472
  if (found)
3671
4473
    return false;
3672
4474
 
3673
4475
  /*
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.
 
4476
TODO: in the case when we skipped all columns because there was a
 
4477
qualified '*', and all columns were coalesced, we have to give a more
 
4478
meaningful message than ER_BAD_TABLE_ERROR.
3677
4479
  */
3678
 
  if (not table_name)
3679
 
  {
 
4480
  if (!table_name)
3680
4481
    my_message(ER_NO_TABLES_USED, ER(ER_NO_TABLES_USED), MYF(0));
3681
 
  }
3682
4482
  else
3683
 
  {
3684
4483
    my_error(ER_BAD_TABLE_ERROR, MYF(0), table_name);
3685
 
  }
3686
4484
 
3687
4485
  return true;
3688
4486
}
3693
4491
 
3694
4492
  SYNOPSIS
3695
4493
  setup_conds()
3696
 
  session     thread Cursor
 
4494
  session     thread handler
3697
4495
  tables  list of tables for name resolving (select_lex->table_list)
3698
4496
  leaves  list of leaves of join table tree (select_lex->leaf_tables)
3699
4497
  conds   WHERE clause
3706
4504
  false if all is OK
3707
4505
*/
3708
4506
 
3709
 
int Session::setup_conds(TableList *leaves, COND **conds)
 
4507
int setup_conds(Session *session, TableList *leaves, COND **conds)
3710
4508
{
3711
 
  Session *session= this;
3712
4509
  Select_Lex *select_lex= session->lex->current_select;
3713
4510
  TableList *table= NULL;       // For HP compilers
3714
4511
  void *save_session_marker= session->session_marker;
3731
4528
  session->session_marker= (void*)1;
3732
4529
  if (*conds)
3733
4530
  {
3734
 
    session->setWhere("where clause");
 
4531
    session->where="where clause";
3735
4532
    if ((!(*conds)->fixed && (*conds)->fix_fields(session, conds)) ||
3736
4533
        (*conds)->check_cols(1))
3737
4534
      goto err_no_arena;
3753
4550
      {
3754
4551
        /* Make a join an a expression */
3755
4552
        session->session_marker= (void*)embedded;
3756
 
        session->setWhere("on clause");
 
4553
        session->where="on clause";
3757
4554
        if ((!embedded->on_expr->fixed && embedded->on_expr->fix_fields(session, &embedded->on_expr)) ||
3758
4555
            embedded->on_expr->check_cols(1))
3759
4556
          goto err_no_arena;
3760
4557
        select_lex->cond_count++;
3761
4558
      }
3762
 
      embedding= embedded->getEmbedding();
 
4559
      embedding= embedded->embedding;
3763
4560
    }
3764
4561
    while (embedding &&
3765
 
           embedding->getNestedJoin()->join_list.head() == embedded);
 
4562
           embedding->nested_join->join_list.head() == embedded);
3766
4563
 
3767
4564
  }
3768
4565
  session->session_marker= save_session_marker;
3788
4585
 
3789
4586
  SYNOPSIS
3790
4587
  fill_record()
 
4588
  session           thread handler
3791
4589
  fields        Item_fields list to be filled
3792
4590
  values        values to fill with
3793
4591
  ignore_errors true if we should ignore errors
3803
4601
*/
3804
4602
 
3805
4603
bool
3806
 
fill_record(Session *session, List<Item> &fields, List<Item> &values, bool ignore_errors)
 
4604
fill_record(Session * session, List<Item> &fields, List<Item> &values, bool ignore_errors)
3807
4605
{
3808
4606
  List_iterator_fast<Item> f(fields),v(values);
3809
 
  Item *value;
 
4607
  Item *value, *fld;
3810
4608
  Item_field *field;
3811
 
  Table *table;
 
4609
  Table *table= 0;
 
4610
  List<Table> tbl_list;
 
4611
  bool abort_on_warning_saved= session->abort_on_warning;
 
4612
  tbl_list.empty();
3812
4613
 
3813
4614
  /*
3814
4615
    Reset the table->auto_increment_field_not_null as it is valid for
3820
4621
      On INSERT or UPDATE fields are checked to be from the same table,
3821
4622
      thus we safely can take table from the first field.
3822
4623
    */
3823
 
    field= static_cast<Item_field *>(f++);
3824
 
    table= field->field->getTable();
 
4624
    fld= (Item_field*)f++;
 
4625
    if (!(field= fld->filed_for_view_update()))
 
4626
    {
 
4627
      my_error(ER_NONUPDATEABLE_COLUMN, MYF(0), fld->name);
 
4628
      goto err;
 
4629
    }
 
4630
    table= field->field->table;
3825
4631
    table->auto_increment_field_not_null= false;
3826
4632
    f.rewind();
3827
4633
  }
3828
 
 
3829
 
  while ((field= static_cast<Item_field *>(f++)))
 
4634
  while ((fld= f++))
3830
4635
  {
3831
 
    value= v++;
3832
 
 
 
4636
    if (!(field= fld->filed_for_view_update()))
 
4637
    {
 
4638
      my_error(ER_NONUPDATEABLE_COLUMN, MYF(0), fld->name);
 
4639
      goto err;
 
4640
    }
 
4641
    value=v++;
3833
4642
    Field *rfield= field->field;
3834
 
    table= rfield->getTable();
3835
 
 
 
4643
    table= rfield->table;
3836
4644
    if (rfield == table->next_number_field)
3837
4645
      table->auto_increment_field_not_null= true;
3838
4646
    if ((value->save_in_field(rfield, 0) < 0) && !ignore_errors)
3839
4647
    {
3840
4648
      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();
 
4649
      goto err;
 
4650
    }
 
4651
    tbl_list.push_back(table);
 
4652
  }
 
4653
  /* Update virtual fields*/
 
4654
  session->abort_on_warning= false;
 
4655
  if (tbl_list.head())
 
4656
  {
 
4657
    List_iterator_fast<Table> t(tbl_list);
 
4658
    Table *prev_table= 0;
 
4659
    while ((table= t++))
 
4660
    {
 
4661
      /*
 
4662
        Do simple optimization to prevent unnecessary re-generating
 
4663
        values for virtual fields
 
4664
      */
 
4665
      if (table != prev_table)
 
4666
        prev_table= table;
 
4667
    }
 
4668
  }
 
4669
  session->abort_on_warning= abort_on_warning_saved;
 
4670
  return(session->is_error());
 
4671
err:
 
4672
  session->abort_on_warning= abort_on_warning_saved;
 
4673
  if (table)
 
4674
    table->auto_increment_field_not_null= false;
 
4675
  return true;
3849
4676
}
3850
4677
 
3851
4678
 
3854
4681
 
3855
4682
  SYNOPSIS
3856
4683
  fill_record()
 
4684
  session           thread handler
3857
4685
  ptr           pointer on pointer to record
3858
4686
  values        list of fields
3859
4687
  ignore_errors true if we should ignore errors
3868
4696
  true    error occured
3869
4697
*/
3870
4698
 
3871
 
bool fill_record(Session *session, Field **ptr, List<Item> &values, bool)
 
4699
bool
 
4700
fill_record(Session *session, Field **ptr, List<Item> &values,
 
4701
            bool )
3872
4702
{
3873
4703
  List_iterator_fast<Item> v(values);
3874
4704
  Item *value;
3875
4705
  Table *table= 0;
3876
4706
  Field *field;
 
4707
  List<Table> tbl_list;
 
4708
  bool abort_on_warning_saved= session->abort_on_warning;
3877
4709
 
 
4710
  tbl_list.empty();
3878
4711
  /*
3879
4712
    Reset the table->auto_increment_field_not_null as it is valid for
3880
4713
    only one row.
3885
4718
      On INSERT or UPDATE fields are checked to be from the same table,
3886
4719
      thus we safely can take table from the first field.
3887
4720
    */
3888
 
    table= (*ptr)->getTable();
 
4721
    table= (*ptr)->table;
3889
4722
    table->auto_increment_field_not_null= false;
3890
4723
  }
3891
 
 
3892
4724
  while ((field = *ptr++) && ! session->is_error())
3893
4725
  {
3894
4726
    value=v++;
3895
 
    table= field->getTable();
3896
 
 
 
4727
    table= field->table;
3897
4728
    if (field == table->next_number_field)
3898
4729
      table->auto_increment_field_not_null= true;
3899
 
 
3900
4730
    if (value->save_in_field(field, 0) < 0)
 
4731
      goto err;
 
4732
    tbl_list.push_back(table);
 
4733
  }
 
4734
  /* Update virtual fields*/
 
4735
  session->abort_on_warning= false;
 
4736
  if (tbl_list.head())
 
4737
  {
 
4738
    List_iterator_fast<Table> t(tbl_list);
 
4739
    Table *prev_table= 0;
 
4740
    while ((table= t++))
3901
4741
    {
3902
 
      if (table)
3903
 
        table->auto_increment_field_not_null= false;
3904
 
 
3905
 
      return true;
 
4742
      /*
 
4743
        Do simple optimization to prevent unnecessary re-generating
 
4744
        values for virtual fields
 
4745
      */
 
4746
      if (table != prev_table)
 
4747
      {
 
4748
        prev_table= table;
 
4749
      }
3906
4750
    }
3907
4751
  }
3908
 
 
 
4752
  session->abort_on_warning= abort_on_warning_saved;
3909
4753
  return(session->is_error());
 
4754
 
 
4755
err:
 
4756
  session->abort_on_warning= abort_on_warning_saved;
 
4757
  if (table)
 
4758
    table->auto_increment_field_not_null= false;
 
4759
  return true;
3910
4760
}
3911
4761
 
3912
4762
 
3913
 
bool drizzle_rm_tmp_tables()
 
4763
bool drizzle_rm_tmp_tables(ListenHandler &listen_handler)
3914
4764
{
3915
 
 
3916
 
  assert(drizzle_tmpdir.size());
3917
 
  Session::shared_ptr session= Session::make_shared(plugin::Listen::getNullClient(), catalog::local());
3918
 
 
3919
 
  if (not session)
3920
 
    return true;
3921
 
  session->thread_stack= (char*) session.get();
3922
 
  session->storeGlobals();
3923
 
 
3924
 
  plugin::StorageEngine::removeLostTemporaryTables(*session, drizzle_tmpdir.c_str());
 
4765
  char  filePath[FN_REFLEN], filePathCopy[FN_REFLEN];
 
4766
  Session *session;
 
4767
 
 
4768
  assert(drizzle_tmpdir);
 
4769
 
 
4770
  if (!(session= new Session(listen_handler.getTmpProtocol())))
 
4771
    return true;
 
4772
  session->thread_stack= (char*) &session;
 
4773
  session->store_globals();
 
4774
 
 
4775
  CachedDirectory dir(drizzle_tmpdir);
 
4776
 
 
4777
  if (dir.fail())
 
4778
  {
 
4779
    my_errno= dir.getError();
 
4780
    my_error(ER_CANT_READ_DIR, MYF(0), drizzle_tmpdir, my_errno);
 
4781
    return true;
 
4782
  }
 
4783
 
 
4784
  CachedDirectory::Entries files= dir.getEntries();
 
4785
  CachedDirectory::Entries::iterator fileIter= files.begin();
 
4786
 
 
4787
  /* Remove all temp tables in the tmpdir */
 
4788
  while (fileIter != files.end())
 
4789
  {
 
4790
    CachedDirectory::Entry *entry= *fileIter;
 
4791
    string prefix= entry->filename.substr(0, TMP_FILE_PREFIX_LENGTH);
 
4792
 
 
4793
    if (prefix == TMP_FILE_PREFIX)
 
4794
    {
 
4795
      char *ext= fn_ext(entry->filename.c_str());
 
4796
      uint32_t ext_len= strlen(ext);
 
4797
      uint32_t filePath_len= snprintf(filePath, sizeof(filePath),
 
4798
                                      "%s%c%s", drizzle_tmpdir, FN_LIBCHAR,
 
4799
                                      entry->filename.c_str());
 
4800
 
 
4801
      if (ext_len && !memcmp(".dfe", ext, ext_len))
 
4802
      {
 
4803
        TableShare share;
 
4804
        /* We should cut file extention before deleting of table */
 
4805
        memcpy(filePathCopy, filePath, filePath_len - ext_len);
 
4806
        filePathCopy[filePath_len - ext_len]= 0;
 
4807
        share.init(NULL, filePathCopy);
 
4808
        if (!open_table_def(session, &share))
 
4809
        {
 
4810
          share.db_type()->deleteTable(session, filePathCopy);
 
4811
        }
 
4812
        share.free_table_share();
 
4813
      }
 
4814
      /*
 
4815
        File can be already deleted by tmp_table.file->delete_table().
 
4816
        So we hide error messages which happnes during deleting of these
 
4817
        files(MYF(0)).
 
4818
      */
 
4819
      my_delete(filePath, MYF(0));
 
4820
    }
 
4821
 
 
4822
    ++fileIter;
 
4823
  }
 
4824
 
 
4825
  delete session;
3925
4826
 
3926
4827
  return false;
3927
4828
}
3932
4833
  unireg support functions
3933
4834
 *****************************************************************************/
3934
4835
 
3935
 
 
3936
 
 
3937
 
 
 
4836
/*
 
4837
  Invalidate any cache entries that are for some DB
 
4838
 
 
4839
  SYNOPSIS
 
4840
  remove_db_from_cache()
 
4841
  db            Database name. This will be in lower case if
 
4842
  lower_case_table_name is set
 
4843
 
 
4844
NOTE:
 
4845
We can't use hash_delete when looping hash_elements. We mark them first
 
4846
and afterwards delete those marked unused.
 
4847
*/
 
4848
 
 
4849
void remove_db_from_cache(const char *db)
 
4850
{
 
4851
  safe_mutex_assert_owner(&LOCK_open);
 
4852
 
 
4853
  for (uint32_t idx=0 ; idx < open_cache.records ; idx++)
 
4854
  {
 
4855
    Table *table=(Table*) hash_element(&open_cache,idx);
 
4856
    if (!strcmp(table->s->db.str, db))
 
4857
    {
 
4858
      table->s->version= 0L;                    /* Free when thread is ready */
 
4859
      if (!table->in_use)
 
4860
        relink_unused(table);
 
4861
    }
 
4862
  }
 
4863
  while (unused_tables && !unused_tables->s->version)
 
4864
    hash_delete(&open_cache,(unsigned char*) unused_tables);
 
4865
}
 
4866
 
 
4867
 
 
4868
/*
 
4869
  Mark all entries with the table as deleted to force an reopen of the table
 
4870
 
 
4871
  The table will be closed (not stored in cache) by the current thread when
 
4872
  close_thread_tables() is called.
 
4873
 
 
4874
  PREREQUISITES
 
4875
  Lock on LOCK_open()
 
4876
 
 
4877
  RETURN
 
4878
  0  This thread now have exclusive access to this table and no other thread
 
4879
  can access the table until close_thread_tables() is called.
 
4880
  1  Table is in use by another thread
 
4881
*/
 
4882
 
 
4883
bool remove_table_from_cache(Session *session, const char *db, const char *table_name,
 
4884
                             uint32_t flags)
 
4885
{
 
4886
  char key[MAX_DBKEY_LENGTH];
 
4887
  char *key_pos= key;
 
4888
  uint32_t key_length;
 
4889
  Table *table;
 
4890
  bool result= false; 
 
4891
  bool signalled= false;
 
4892
 
 
4893
  key_pos= strcpy(key_pos, db) + strlen(db);
 
4894
  key_pos= strcpy(key_pos+1, table_name) + strlen(table_name);
 
4895
  key_length= (uint32_t) (key_pos-key)+1;
 
4896
 
 
4897
  for (;;)
 
4898
  {
 
4899
    HASH_SEARCH_STATE state;
 
4900
    result= signalled= false;
 
4901
 
 
4902
    for (table= (Table*) hash_first(&open_cache, (unsigned char*) key, key_length,
 
4903
                                    &state);
 
4904
         table;
 
4905
         table= (Table*) hash_next(&open_cache, (unsigned char*) key, key_length,
 
4906
                                   &state))
 
4907
    {
 
4908
      Session *in_use;
 
4909
 
 
4910
      table->s->version=0L;             /* Free when thread is ready */
 
4911
      if (!(in_use=table->in_use))
 
4912
      {
 
4913
        relink_unused(table);
 
4914
      }
 
4915
      else if (in_use != session)
 
4916
      {
 
4917
        /*
 
4918
          Mark that table is going to be deleted from cache. This will
 
4919
          force threads that are in mysql_lock_tables() (but not yet
 
4920
          in thr_multi_lock()) to abort it's locks, close all tables and retry
 
4921
        */
 
4922
        in_use->some_tables_deleted= true;
 
4923
        if (table->is_name_opened())
 
4924
        {
 
4925
          result= true;
 
4926
        }
 
4927
        /*
 
4928
          Now we must abort all tables locks used by this thread
 
4929
          as the thread may be waiting to get a lock for another table.
 
4930
          Note that we need to hold LOCK_open while going through the
 
4931
          list. So that the other thread cannot change it. The other
 
4932
          thread must also hold LOCK_open whenever changing the
 
4933
          open_tables list. Aborting the MERGE lock after a child was
 
4934
          closed and before the parent is closed would be fatal.
 
4935
        */
 
4936
        for (Table *session_table= in_use->open_tables;
 
4937
             session_table ;
 
4938
             session_table= session_table->next)
 
4939
        {
 
4940
          /* Do not handle locks of MERGE children. */
 
4941
          if (session_table->db_stat)   // If table is open
 
4942
            signalled|= mysql_lock_abort_for_thread(session, session_table);
 
4943
        }
 
4944
      }
 
4945
      else
 
4946
        result= result || (flags & RTFC_OWNED_BY_Session_FLAG);
 
4947
    }
 
4948
    while (unused_tables && !unused_tables->s->version)
 
4949
      hash_delete(&open_cache,(unsigned char*) unused_tables);
 
4950
 
 
4951
    /* Remove table from table definition cache if it's not in use */
 
4952
    TableShare::release(key, key_length);
 
4953
 
 
4954
    if (result && (flags & RTFC_WAIT_OTHER_THREAD_FLAG))
 
4955
    {
 
4956
      /*
 
4957
        Signal any thread waiting for tables to be freed to
 
4958
        reopen their tables
 
4959
      */
 
4960
      broadcast_refresh();
 
4961
      if (!(flags & RTFC_CHECK_KILLED_FLAG) || !session->killed)
 
4962
      {
 
4963
        dropping_tables++;
 
4964
        if (likely(signalled))
 
4965
          (void) pthread_cond_wait(&COND_refresh, &LOCK_open);
 
4966
        else
 
4967
        {
 
4968
          struct timespec abstime;
 
4969
          /*
 
4970
            It can happen that another thread has opened the
 
4971
            table but has not yet locked any table at all. Since
 
4972
            it can be locked waiting for a table that our thread
 
4973
            has done LOCK Table x WRITE on previously, we need to
 
4974
            ensure that the thread actually hears our signal
 
4975
            before we go to sleep. Thus we wait for a short time
 
4976
            and then we retry another loop in the
 
4977
            remove_table_from_cache routine.
 
4978
          */
 
4979
          set_timespec(abstime, 10);
 
4980
          pthread_cond_timedwait(&COND_refresh, &LOCK_open, &abstime);
 
4981
        }
 
4982
        dropping_tables--;
 
4983
        continue;
 
4984
      }
 
4985
    }
 
4986
    break;
 
4987
  }
 
4988
  return result;
 
4989
}
 
4990
 
 
4991
 
 
4992
bool is_equal(const LEX_STRING *a, const LEX_STRING *b)
 
4993
{
 
4994
  return a->length == b->length && !strncmp(a->str, b->str, a->length);
 
4995
}
3938
4996
/**
3939
4997
  @} (end of group Data_Dictionary)
3940
4998
*/
3944
5002
  pthread_kill(signal_thread, SIGTERM);
3945
5003
  shutdown_in_progress= 1;                      // Safety if kill didn't work
3946
5004
}
3947
 
 
3948
 
} /* namespace drizzled */