~drizzle-trunk/drizzle/development

« back to all changes in this revision

Viewing changes to drizzled/sql_base.cc

code clean move Item_func_num1 and Item_func_connection_id to functions directory

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
1
/* Copyright (C) 2000-2006 MySQL AB
2
2
 
3
 
  This program is free software; you can redistribute it and/or modify
4
 
  it under the terms of the GNU General Public License as published by
5
 
  the Free Software Foundation; version 2 of the License.
6
 
 
7
 
  This program is distributed in the hope that it will be useful,
8
 
  but WITHOUT ANY WARRANTY; without even the implied warranty of
9
 
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
10
 
  GNU General Public License for more details.
11
 
 
12
 
  You should have received a copy of the GNU General Public License
13
 
  along with this program; if not, write to the Free Software
14
 
  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA */
 
3
   This program is free software; you can redistribute it and/or modify
 
4
   it under the terms of the GNU General Public License as published by
 
5
   the Free Software Foundation; version 2 of the License.
 
6
 
 
7
   This program is distributed in the hope that it will be useful,
 
8
   but WITHOUT ANY WARRANTY; without even the implied warranty of
 
9
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
10
   GNU General Public License for more details.
 
11
 
 
12
   You should have received a copy of the GNU General Public License
 
13
   along with this program; if not, write to the Free Software
 
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"
19
 
#include <assert.h>
20
 
 
21
 
#include <signal.h>
 
18
#include <drizzled/server_includes.h>
 
19
#include <drizzled/sql_select.h>
 
20
#include <mysys/my_dir.h>
 
21
#include <drizzled/drizzled_error_messages.h>
 
22
#include <libdrizzle/gettext.h>
22
23
 
23
24
#if TIME_WITH_SYS_TIME
24
25
# include <sys/time.h>
30
31
#  include <time.h>
31
32
# endif
32
33
#endif
33
 
#include "drizzled/internal/my_pthread.h"
34
 
#include "drizzled/internal/thread_var.h"
35
 
 
36
 
#include <drizzled/sql_select.h>
37
 
#include <drizzled/error.h>
38
 
#include <drizzled/gettext.h>
39
 
#include <drizzled/nested_join.h>
40
 
#include <drizzled/sql_base.h>
41
 
#include <drizzled/show.h>
42
 
#include <drizzled/item/cmpfunc.h>
43
 
#include <drizzled/replication_services.h>
44
 
#include <drizzled/check_stack_overrun.h>
45
 
#include <drizzled/lock.h>
46
 
#include <drizzled/plugin/listen.h>
47
 
#include "drizzled/cached_directory.h"
48
 
#include <drizzled/field/timestamp.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_placeholder.h"
57
 
 
58
 
using namespace std;
59
 
 
60
 
namespace drizzled
61
 
{
62
 
 
63
 
extern bool volatile shutdown_in_progress;
64
 
 
65
 
TableOpenCache &get_open_cache()
66
 
{
67
 
  static TableOpenCache open_cache;                             /* Used by mysql_test */
68
 
 
69
 
  return open_cache;
 
34
 
 
35
#define FLAGSTR(S,F) ((S) & (F) ? #F " " : "")
 
36
 
 
37
/**
 
38
  return true if the table was created explicitly.
 
39
*/
 
40
inline bool is_user_table(Table * table)
 
41
{
 
42
  const char *name= table->s->table_name.str;
 
43
  return strncmp(name, tmp_file_prefix, tmp_file_prefix_length);
70
44
}
71
45
 
 
46
 
 
47
/**
 
48
  @defgroup Data_Dictionary Data Dictionary
 
49
  @{
 
50
*/
 
51
Table *unused_tables;                           /* Used by mysql_test */
 
52
HASH open_cache;                                /* Used by mysql_test */
 
53
static HASH table_def_cache;
 
54
static TABLE_SHARE *oldest_unused_share, end_of_unused_share;
 
55
static pthread_mutex_t LOCK_table_share;
 
56
static bool table_def_inited= 0;
 
57
 
 
58
static int open_unireg_entry(THD *thd, Table *entry, TableList *table_list,
 
59
                             const char *alias,
 
60
                             char *cache_key, uint32_t cache_key_length);
72
61
static void free_cache_entry(Table *entry);
73
 
 
74
 
void remove_table(Table *arg)
75
 
{
76
 
  TableOpenCacheRange ppp;
77
 
  ppp= get_open_cache().equal_range(arg->getShare()->getCacheKey());
78
 
 
79
 
  for (TableOpenCache::const_iterator iter= ppp.first;
80
 
         iter != ppp.second; ++iter)
81
 
  {
82
 
    Table *found_table= (*iter).second;
83
 
 
84
 
    if (found_table == arg)
85
 
    {
86
 
      free_cache_entry(arg);
87
 
      get_open_cache().erase(iter);
88
 
      return;
89
 
    }
90
 
  }
91
 
}
92
 
 
93
 
static bool add_table(Table *arg)
94
 
{
95
 
  TableOpenCache &open_cache(get_open_cache());
96
 
 
97
 
  TableOpenCache::iterator returnable= open_cache.insert(make_pair(arg->getShare()->getCacheKey(), arg));
98
 
 
99
 
  return not (returnable == open_cache.end());
100
 
}
101
 
 
102
 
class UnusedTables {
103
 
  Table *tables;                                /* Used by mysql_test */
104
 
 
105
 
  Table *getTable() const
106
 
  {
107
 
    return tables;
108
 
  }
109
 
 
110
 
  Table *setTable(Table *arg)
111
 
  {
112
 
    return tables= arg;
113
 
  }
114
 
 
115
 
public:
116
 
 
117
 
  void cull()
118
 
  {
119
 
    /* Free cache if too big */
120
 
    while (cached_open_tables() > table_cache_size && getTable())
121
 
      remove_table(getTable());
122
 
  }
123
 
 
124
 
  void cullByVersion()
125
 
  {
126
 
    while (getTable() && not getTable()->getShare()->getVersion())
127
 
      remove_table(getTable());
128
 
  }
129
 
  
130
 
  void link(Table *table)
131
 
  {
132
 
    if (getTable())
133
 
    {
134
 
      table->setNext(getTable());               /* Link in last */
135
 
      table->setPrev(getTable()->getPrev());
136
 
      getTable()->setPrev(table);
137
 
      table->getPrev()->setNext(table);
138
 
    }
139
 
    else
140
 
    {
141
 
      table->setPrev(setTable(table));
142
 
      table->setNext(table->getPrev());
143
 
      assert(table->getNext() == table && table->getPrev() == table);
144
 
    }
145
 
  }
146
 
 
147
 
 
148
 
  void unlink(Table *table)
149
 
  {
150
 
    table->unlink();
151
 
 
152
 
    /* Unlink the table from "unused_tables" list. */
153
 
    if (table == getTable())
154
 
    {  // First unused
155
 
      setTable(getTable()->getNext()); // Remove from link
156
 
      if (table == getTable())
157
 
        setTable(NULL);
158
 
    }
159
 
  }
160
 
 
161
 
/* move table first in unused links */
162
 
 
163
 
  void relink(Table *table)
164
 
  {
165
 
    if (table != getTable())
166
 
    {
167
 
      table->unlink();
168
 
 
169
 
      table->setNext(getTable());                       /* Link in unused tables */
170
 
      table->setPrev(getTable()->getPrev());
171
 
      getTable()->getPrev()->setNext(table);
172
 
      getTable()->setPrev(table);
173
 
      setTable(table);
174
 
    }
175
 
  }
176
 
 
177
 
 
178
 
  void clear()
179
 
  {
180
 
    while (getTable())
181
 
      remove_table(getTable());
182
 
  }
183
 
 
184
 
  UnusedTables():
185
 
    tables(NULL)
186
 
  { }
187
 
 
188
 
  ~UnusedTables()
189
 
  { 
190
 
  }
191
 
};
192
 
 
193
 
static UnusedTables unused_tables;
194
 
static int open_unireg_entry(Session *session,
195
 
                             Table *entry,
196
 
                             const char *alias,
197
 
                             TableIdentifier &identifier);
198
 
 
199
 
unsigned char *table_cache_key(const unsigned char *record,
200
 
                               size_t *length,
201
 
                               bool );
202
 
 
203
 
#if 0
204
 
static bool reopen_table(Table *table);
205
 
#endif
206
 
 
207
 
unsigned char *table_cache_key(const unsigned char *record,
208
 
                               size_t *length,
209
 
                               bool )
 
62
static void close_old_data_files(THD *thd, Table *table, bool morph_locks,
 
63
                                 bool send_refresh);
 
64
 
 
65
 
 
66
extern "C" unsigned char *table_cache_key(const unsigned char *record, size_t *length,
 
67
                                  bool not_used __attribute__((unused)))
210
68
{
211
69
  Table *entry=(Table*) record;
212
 
  *length= entry->getShare()->getCacheKey().size();
213
 
  return (unsigned char*) &entry->getShare()->getCacheKey()[0];
 
70
  *length= entry->s->table_cache_key.length;
 
71
  return (unsigned char*) entry->s->table_cache_key.str;
214
72
}
215
73
 
 
74
 
216
75
bool table_cache_init(void)
217
76
{
218
 
  return false;
 
77
  return hash_init(&open_cache, &my_charset_bin, table_cache_size+16,
 
78
                   0, 0, table_cache_key,
 
79
                   (hash_free_key) free_cache_entry, 0);
 
80
}
 
81
 
 
82
void table_cache_free(void)
 
83
{
 
84
  if (table_def_inited)
 
85
  {
 
86
    close_cached_tables(NULL, NULL, false, false, false);
 
87
    if (!open_cache.records)                    // Safety first
 
88
      hash_free(&open_cache);
 
89
  }
 
90
  return;
219
91
}
220
92
 
221
93
uint32_t cached_open_tables(void)
222
94
{
223
 
  return get_open_cache().size();
224
 
}
225
 
 
226
 
void table_cache_free(void)
227
 
{
228
 
  refresh_version++;                            // Force close of open tables
229
 
 
230
 
  unused_tables.clear();
231
 
  get_open_cache().clear();
232
 
}
233
 
 
234
 
/*
235
 
  Close cursor handle, but leave the table in the table cache
236
 
 
237
 
  SYNOPSIS
238
 
  close_handle_and_leave_table_as_lock()
239
 
  table         Table Cursor
240
 
 
241
 
  NOTES
242
 
  By leaving the table in the table cache, it disallows any other thread
243
 
  to open the table
244
 
 
245
 
  session->killed will be set if we run out of memory
246
 
 
247
 
  If closing a MERGE child, the calling function has to take care for
248
 
  closing the parent too, if necessary.
 
95
  return open_cache.records;
 
96
}
 
97
 
 
98
/*
 
99
  Create a table cache key
 
100
 
 
101
  SYNOPSIS
 
102
    create_table_def_key()
 
103
    thd                 Thread handler
 
104
    key                 Create key here (must be of size MAX_DBKEY_LENGTH)
 
105
    table_list          Table definition
 
106
    tmp_table           Set if table is a tmp table
 
107
 
 
108
 IMPLEMENTATION
 
109
    The table cache_key is created from:
 
110
    db_name + \0
 
111
    table_name + \0
 
112
 
 
113
    if the table is a tmp table, we add the following to make each tmp table
 
114
    unique on the slave:
 
115
 
 
116
    4 bytes for master thread id
 
117
    4 bytes pseudo thread id
 
118
 
 
119
  RETURN
 
120
    Length of key
 
121
*/
 
122
 
 
123
uint32_t create_table_def_key(THD *thd, char *key, TableList *table_list,
 
124
                          bool tmp_table)
 
125
{
 
126
  uint32_t key_length= (uint) (my_stpcpy(my_stpcpy(key, table_list->db)+1,
 
127
                                  table_list->table_name)-key)+1;
 
128
  if (tmp_table)
 
129
  {
 
130
    int4store(key + key_length, thd->server_id);
 
131
    int4store(key + key_length + 4, thd->variables.pseudo_thread_id);
 
132
    key_length+= TMP_TABLE_KEY_EXTRA;
 
133
  }
 
134
  return key_length;
 
135
}
 
136
 
 
137
 
 
138
 
 
139
/*****************************************************************************
 
140
  Functions to handle table definition cach (TABLE_SHARE)
 
141
*****************************************************************************/
 
142
 
 
143
extern "C" unsigned char *table_def_key(const unsigned char *record, size_t *length,
 
144
                                bool not_used __attribute__((unused)))
 
145
{
 
146
  TABLE_SHARE *entry=(TABLE_SHARE*) record;
 
147
  *length= entry->table_cache_key.length;
 
148
  return (unsigned char*) entry->table_cache_key.str;
 
149
}
 
150
 
 
151
 
 
152
static void table_def_free_entry(TABLE_SHARE *share)
 
153
{
 
154
  if (share->prev)
 
155
  {
 
156
    /* remove from old_unused_share list */
 
157
    pthread_mutex_lock(&LOCK_table_share);
 
158
    *share->prev= share->next;
 
159
    share->next->prev= share->prev;
 
160
    pthread_mutex_unlock(&LOCK_table_share);
 
161
  }
 
162
  free_table_share(share);
 
163
  return;
 
164
}
 
165
 
 
166
 
 
167
bool table_def_init(void)
 
168
{
 
169
  table_def_inited= 1;
 
170
  pthread_mutex_init(&LOCK_table_share, MY_MUTEX_INIT_FAST);
 
171
  oldest_unused_share= &end_of_unused_share;
 
172
  end_of_unused_share.prev= &oldest_unused_share;
 
173
 
 
174
  return hash_init(&table_def_cache, &my_charset_bin, table_def_size,
 
175
                   0, 0, table_def_key,
 
176
                   (hash_free_key) table_def_free_entry, 0);
 
177
}
 
178
 
 
179
 
 
180
void table_def_free(void)
 
181
{
 
182
  if (table_def_inited)
 
183
  {
 
184
    table_def_inited= 0;
 
185
    pthread_mutex_destroy(&LOCK_table_share);
 
186
    hash_free(&table_def_cache);
 
187
  }
 
188
  return;
 
189
}
 
190
 
 
191
 
 
192
uint32_t cached_table_definitions(void)
 
193
{
 
194
  return table_def_cache.records;
 
195
}
 
196
 
 
197
 
 
198
/*
 
199
  Get TABLE_SHARE for a table.
 
200
 
 
201
  get_table_share()
 
202
  thd                   Thread handle
 
203
  table_list            Table that should be opened
 
204
  key                   Table cache key
 
205
  key_length            Length of key
 
206
  db_flags              Flags to open_table_def():
 
207
                        OPEN_VIEW
 
208
  error                 out: Error code from open_table_def()
 
209
 
 
210
  IMPLEMENTATION
 
211
    Get a table definition from the table definition cache.
 
212
    If it doesn't exist, create a new from the table definition file.
 
213
 
 
214
  NOTES
 
215
    We must have wrlock on LOCK_open when we come here
 
216
    (To be changed later)
 
217
 
 
218
  RETURN
 
219
   0  Error
 
220
   #  Share for table
 
221
*/
 
222
 
 
223
TABLE_SHARE *get_table_share(THD *thd, TableList *table_list, char *key,
 
224
                             uint32_t key_length, uint32_t db_flags, int *error)
 
225
{
 
226
  TABLE_SHARE *share;
 
227
 
 
228
  *error= 0;
 
229
 
 
230
  /* Read table definition from cache */
 
231
  if ((share= (TABLE_SHARE*) hash_search(&table_def_cache,(unsigned char*) key,
 
232
                                         key_length)))
 
233
    goto found;
 
234
 
 
235
  if (!(share= alloc_table_share(table_list, key, key_length)))
 
236
  {
 
237
    return(0);
 
238
  }
 
239
 
 
240
  /*
 
241
    Lock mutex to be able to read table definition from file without
 
242
    conflicts
 
243
  */
 
244
  (void) pthread_mutex_lock(&share->mutex);
 
245
 
 
246
  /*
 
247
    We assign a new table id under the protection of the LOCK_open and
 
248
    the share's own mutex.  We do this insted of creating a new mutex
 
249
    and using it for the sole purpose of serializing accesses to a
 
250
    static variable, we assign the table id here.  We assign it to the
 
251
    share before inserting it into the table_def_cache to be really
 
252
    sure that it cannot be read from the cache without having a table
 
253
    id assigned.
 
254
 
 
255
    CAVEAT. This means that the table cannot be used for
 
256
    binlogging/replication purposes, unless get_table_share() has been
 
257
    called directly or indirectly.
 
258
   */
 
259
  assign_new_table_id(share);
 
260
 
 
261
  if (my_hash_insert(&table_def_cache, (unsigned char*) share))
 
262
  {
 
263
    free_table_share(share);
 
264
    return(0);                          // return error
 
265
  }
 
266
  if (open_table_def(thd, share, db_flags))
 
267
  {
 
268
    *error= share->error;
 
269
    (void) hash_delete(&table_def_cache, (unsigned char*) share);
 
270
    return(0);
 
271
  }
 
272
  share->ref_count++;                           // Mark in use
 
273
  (void) pthread_mutex_unlock(&share->mutex);
 
274
  return(share);
 
275
 
 
276
found:
 
277
  /* 
 
278
     We found an existing table definition. Return it if we didn't get
 
279
     an error when reading the table definition from file.
 
280
  */
 
281
 
 
282
  /* We must do a lock to ensure that the structure is initialized */
 
283
  (void) pthread_mutex_lock(&share->mutex);
 
284
  if (share->error)
 
285
  {
 
286
    /* Table definition contained an error */
 
287
    open_table_error(share, share->error, share->open_errno, share->errarg);
 
288
    (void) pthread_mutex_unlock(&share->mutex);
 
289
    return(0);
 
290
  }
 
291
 
 
292
  if (!share->ref_count++ && share->prev)
 
293
  {
 
294
    /*
 
295
      Share was not used before and it was in the old_unused_share list
 
296
      Unlink share from this list
 
297
    */
 
298
    pthread_mutex_lock(&LOCK_table_share);
 
299
    *share->prev= share->next;
 
300
    share->next->prev= share->prev;
 
301
    share->next= 0;
 
302
    share->prev= 0;
 
303
    pthread_mutex_unlock(&LOCK_table_share);
 
304
  }
 
305
  (void) pthread_mutex_unlock(&share->mutex);
 
306
 
 
307
   /* Free cache if too big */
 
308
  while (table_def_cache.records > table_def_size &&
 
309
         oldest_unused_share->next)
 
310
  {
 
311
    pthread_mutex_lock(&oldest_unused_share->mutex);
 
312
    hash_delete(&table_def_cache, (unsigned char*) oldest_unused_share);
 
313
  }
 
314
 
 
315
  return(share);
 
316
}
 
317
 
 
318
 
 
319
/*
 
320
  Get a table share. If it didn't exist, try creating it from engine
 
321
 
 
322
  For arguments and return values, see get_table_from_share()
 
323
*/
 
324
 
 
325
static TABLE_SHARE
 
326
*get_table_share_with_create(THD *thd, TableList *table_list,
 
327
                             char *key, uint32_t key_length,
 
328
                             uint32_t db_flags, int *error)
 
329
{
 
330
  TABLE_SHARE *share;
 
331
  int tmp;
 
332
 
 
333
  share= get_table_share(thd, table_list, key, key_length, db_flags, error);
 
334
  /*
 
335
    If share is not NULL, we found an existing share.
 
336
 
 
337
    If share is NULL, and there is no error, we're inside
 
338
    pre-locking, which silences 'ER_NO_SUCH_TABLE' errors
 
339
    with the intention to silently drop non-existing tables 
 
340
    from the pre-locking list. In this case we still need to try
 
341
    auto-discover before returning a NULL share.
 
342
 
 
343
    If share is NULL and the error is ER_NO_SUCH_TABLE, this is
 
344
    the same as above, only that the error was not silenced by 
 
345
    pre-locking. Once again, we need to try to auto-discover
 
346
    the share.
 
347
 
 
348
    Finally, if share is still NULL, it's a real error and we need
 
349
    to abort.
 
350
 
 
351
    @todo Rework alternative ways to deal with ER_NO_SUCH Table.
 
352
  */
 
353
  if (share || (thd->is_error() && (thd->main_da.sql_errno() != ER_NO_SUCH_TABLE)))
 
354
 
 
355
    return(share);
 
356
 
 
357
  /* Table didn't exist. Check if some engine can provide it */
 
358
  if ((tmp= ha_create_table_from_engine(thd, table_list->db,
 
359
                                        table_list->table_name)) < 0)
 
360
    return(0);
 
361
 
 
362
  if (tmp)
 
363
  {
 
364
    /* Give right error message */
 
365
    thd->clear_error();
 
366
    my_printf_error(ER_UNKNOWN_ERROR,
 
367
                    "Failed to open '%-.64s', error while "
 
368
                    "unpacking from engine",
 
369
                    MYF(0), table_list->table_name);
 
370
    return(0);
 
371
  }
 
372
  /* Table existed in engine. Let's open it */
 
373
  drizzle_reset_errors(thd, 1);                   // Clear warnings
 
374
  thd->clear_error();                           // Clear error message
 
375
  return(get_table_share(thd, table_list, key, key_length,
 
376
                              db_flags, error));
 
377
}
 
378
 
 
379
 
 
380
/* 
 
381
   Mark that we are not using table share anymore.
 
382
 
 
383
   SYNOPSIS
 
384
     release_table_share()
 
385
     share              Table share
 
386
     release_type       How the release should be done:
 
387
                        RELEASE_NORMAL
 
388
                         - Release without checking
 
389
                        RELEASE_WAIT_FOR_DROP
 
390
                         - Don't return until we get a signal that the
 
391
                           table is deleted or the thread is killed.
 
392
 
 
393
   IMPLEMENTATION
 
394
     If ref_count goes to zero and (we have done a refresh or if we have
 
395
     already too many open table shares) then delete the definition.
 
396
 
 
397
     If type == RELEASE_WAIT_FOR_DROP then don't return until we get a signal
 
398
     that the table is deleted or the thread is killed.
 
399
*/
 
400
 
 
401
void release_table_share(TABLE_SHARE *share,
 
402
                         enum release_type type __attribute__((unused)))
 
403
{
 
404
  bool to_be_deleted= 0;
 
405
 
 
406
  safe_mutex_assert_owner(&LOCK_open);
 
407
 
 
408
  pthread_mutex_lock(&share->mutex);
 
409
  if (!--share->ref_count)
 
410
  {
 
411
    if (share->version != refresh_version)
 
412
      to_be_deleted=1;
 
413
    else
 
414
    {
 
415
      /* Link share last in used_table_share list */
 
416
      assert(share->next == 0);
 
417
      pthread_mutex_lock(&LOCK_table_share);
 
418
      share->prev= end_of_unused_share.prev;
 
419
      *end_of_unused_share.prev= share;
 
420
      end_of_unused_share.prev= &share->next;
 
421
      share->next= &end_of_unused_share;
 
422
      pthread_mutex_unlock(&LOCK_table_share);
 
423
 
 
424
      to_be_deleted= (table_def_cache.records > table_def_size);
 
425
    }
 
426
  }
 
427
 
 
428
  if (to_be_deleted)
 
429
  {
 
430
    hash_delete(&table_def_cache, (unsigned char*) share);
 
431
    return;
 
432
  }
 
433
  pthread_mutex_unlock(&share->mutex);
 
434
  return;
 
435
}
 
436
 
 
437
 
 
438
/*
 
439
  Check if table definition exits in cache
 
440
 
 
441
  SYNOPSIS
 
442
    get_cached_table_share()
 
443
    db                  Database name
 
444
    table_name          Table name
 
445
 
 
446
  RETURN
 
447
    0  Not cached
 
448
    #  TABLE_SHARE for table
 
449
*/
 
450
 
 
451
TABLE_SHARE *get_cached_table_share(const char *db, const char *table_name)
 
452
{
 
453
  char key[NAME_LEN*2+2];
 
454
  TableList table_list;
 
455
  uint32_t key_length;
 
456
  safe_mutex_assert_owner(&LOCK_open);
 
457
 
 
458
  table_list.db= (char*) db;
 
459
  table_list.table_name= (char*) table_name;
 
460
  key_length= create_table_def_key((THD*) 0, key, &table_list, 0);
 
461
  return (TABLE_SHARE*) hash_search(&table_def_cache,(unsigned char*) key, key_length);
 
462
}  
 
463
 
 
464
 
 
465
/*
 
466
  Close file handle, but leave the table in the table cache
 
467
 
 
468
  SYNOPSIS
 
469
    close_handle_and_leave_table_as_lock()
 
470
    table               Table handler
 
471
 
 
472
  NOTES
 
473
    By leaving the table in the table cache, it disallows any other thread
 
474
    to open the table
 
475
 
 
476
    thd->killed will be set if we run out of memory
 
477
 
 
478
    If closing a MERGE child, the calling function has to take care for
 
479
    closing the parent too, if necessary.
249
480
*/
250
481
 
251
482
 
252
483
void close_handle_and_leave_table_as_lock(Table *table)
253
484
{
254
 
  TableShare *share, *old_share= table->getMutableShare();
 
485
  TABLE_SHARE *share, *old_share= table->s;
 
486
  char *key_buff;
 
487
  MEM_ROOT *mem_root= &table->mem_root;
 
488
 
255
489
  assert(table->db_stat);
256
 
  assert(table->getShare()->getType() == message::Table::STANDARD);
257
490
 
258
491
  /*
259
492
    Make a local copy of the table share and free the current one.
260
493
    This has to be done to ensure that the table share is removed from
261
494
    the table defintion cache as soon as the last instance is removed
262
495
  */
263
 
  TableIdentifier identifier(table->getShare()->getSchemaName(), table->getShare()->getTableName(), message::Table::INTERNAL);
264
 
  const TableIdentifier::Key &key(identifier.getKey());
265
 
  share= new TableShare(identifier.getType(),
266
 
                        identifier,
267
 
                        const_cast<char *>(&key[0]),  static_cast<uint32_t>(old_share->getCacheKeySize()));
268
 
 
269
 
  table->cursor->close();
270
 
  table->db_stat= 0;                            // Mark cursor closed
271
 
  TableShare::release(table->getMutableShare());
272
 
  table->setShare(share);
273
 
  table->cursor->change_table_ptr(table, table->getMutableShare());
274
 
}
275
 
 
 
496
  if (multi_alloc_root(mem_root,
 
497
                       &share, sizeof(*share),
 
498
                       &key_buff, old_share->table_cache_key.length,
 
499
                       NULL))
 
500
  {
 
501
    memset(share, 0, sizeof(*share));
 
502
    share->set_table_cache_key(key_buff, old_share->table_cache_key.str,
 
503
                               old_share->table_cache_key.length);
 
504
    share->tmp_table= INTERNAL_TMP_TABLE;       // for intern_close_table()
 
505
  }
 
506
 
 
507
  table->file->close();
 
508
  table->db_stat= 0;                            // Mark file closed
 
509
  release_table_share(table->s, RELEASE_NORMAL);
 
510
  table->s= share;
 
511
  table->file->change_table_ptr(table, table->s);
 
512
 
 
513
  return;
 
514
}
 
515
 
 
516
 
 
517
 
 
518
/*
 
519
  Create a list for all open tables matching SQL expression
 
520
 
 
521
  SYNOPSIS
 
522
    list_open_tables()
 
523
    thd                 Thread THD
 
524
    wild                SQL like expression
 
525
 
 
526
  NOTES
 
527
    One gets only a list of tables for which one has any kind of privilege.
 
528
    db and table names are allocated in result struct, so one doesn't need
 
529
    a lock on LOCK_open when traversing the return list.
 
530
 
 
531
  RETURN VALUES
 
532
    NULL        Error (Probably OOM)
 
533
    #           Pointer to list of names of open tables.
 
534
*/
 
535
 
 
536
OPEN_TableList *list_open_tables(THD *thd __attribute__((unused)),
 
537
                                  const char *db, const char *wild)
 
538
{
 
539
  int result = 0;
 
540
  OPEN_TableList **start_list, *open_list;
 
541
  TableList table_list;
 
542
 
 
543
  pthread_mutex_lock(&LOCK_open);
 
544
  memset(&table_list, 0, sizeof(table_list));
 
545
  start_list= &open_list;
 
546
  open_list=0;
 
547
 
 
548
  for (uint32_t idx=0 ; result == 0 && idx < open_cache.records; idx++)
 
549
  {
 
550
    OPEN_TableList *table;
 
551
    Table *entry=(Table*) hash_element(&open_cache,idx);
 
552
    TABLE_SHARE *share= entry->s;
 
553
 
 
554
    if (db && my_strcasecmp(system_charset_info, db, share->db.str))
 
555
      continue;
 
556
    if (wild && wild_compare(share->table_name.str, wild, 0))
 
557
      continue;
 
558
 
 
559
    /* Check if user has SELECT privilege for any column in the table */
 
560
    table_list.db=         share->db.str;
 
561
    table_list.table_name= share->table_name.str;
 
562
 
 
563
    /* need to check if we haven't already listed it */
 
564
    for (table= open_list  ; table ; table=table->next)
 
565
    {
 
566
      if (!strcmp(table->table, share->table_name.str) &&
 
567
          !strcmp(table->db,    share->db.str))
 
568
      {
 
569
        if (entry->in_use)
 
570
          table->in_use++;
 
571
        if (entry->locked_by_name)
 
572
          table->locked++;
 
573
        break;
 
574
      }
 
575
    }
 
576
    if (table)
 
577
      continue;
 
578
    if (!(*start_list = (OPEN_TableList *)
 
579
          sql_alloc(sizeof(**start_list)+share->table_cache_key.length)))
 
580
    {
 
581
      open_list=0;                              // Out of memory
 
582
      break;
 
583
    }
 
584
    my_stpcpy((*start_list)->table=
 
585
           my_stpcpy(((*start_list)->db= (char*) ((*start_list)+1)),
 
586
                  share->db.str)+1,
 
587
           share->table_name.str);
 
588
    (*start_list)->in_use= entry->in_use ? 1 : 0;
 
589
    (*start_list)->locked= entry->locked_by_name ? 1 : 0;
 
590
    start_list= &(*start_list)->next;
 
591
    *start_list=0;
 
592
  }
 
593
  pthread_mutex_unlock(&LOCK_open);
 
594
  return(open_list);
 
595
}
276
596
 
277
597
/*****************************************************************************
278
598
 *       Functions to free open table cache
279
599
 ****************************************************************************/
280
600
 
281
601
 
282
 
void Table::intern_close_table()
 
602
void intern_close_table(Table *table)
283
603
{                                               // Free all structures
284
 
  free_io_cache();
285
 
  if (cursor)                              // Not true if name lock
286
 
  {
287
 
    delete_table(true);                 // close cursor
288
 
  }
 
604
  free_io_cache(table);
 
605
  if (table->file)                              // Not true if name lock
 
606
    closefrm(table, 1);                 // close file
 
607
  return;
289
608
}
290
609
 
291
610
/*
292
611
  Remove table from the open table cache
293
612
 
294
613
  SYNOPSIS
295
 
  free_cache_entry()
296
 
  entry         Table to remove
 
614
    free_cache_entry()
 
615
    table               Table to remove
297
616
 
298
617
  NOTE
299
 
  We need to have a lock on LOCK_open when calling this
 
618
    We need to have a lock on LOCK_open when calling this
300
619
*/
301
620
 
302
 
void free_cache_entry(Table *table)
 
621
static void free_cache_entry(Table *table)
303
622
{
304
 
  table->intern_close_table();
305
 
  if (not table->in_use)
 
623
  intern_close_table(table);
 
624
  if (!table->in_use)
306
625
  {
307
 
    unused_tables.unlink(table);
 
626
    table->next->prev=table->prev;              /* remove from used chain */
 
627
    table->prev->next=table->next;
 
628
    if (table == unused_tables)
 
629
    {
 
630
      unused_tables=unused_tables->next;
 
631
      if (table == unused_tables)
 
632
        unused_tables=0;
 
633
    }
308
634
  }
309
 
 
310
 
  delete table;
 
635
  free((unsigned char*) table);
 
636
  return;
311
637
}
312
638
 
313
639
/* Free resources allocated by filesort() and read_record() */
314
640
 
315
 
void Table::free_io_cache()
 
641
void free_io_cache(Table *table)
316
642
{
317
 
  if (sort.io_cache)
 
643
  if (table->sort.io_cache)
318
644
  {
319
 
    close_cached_file(sort.io_cache);
320
 
    delete sort.io_cache;
321
 
    sort.io_cache= 0;
 
645
    close_cached_file(table->sort.io_cache);
 
646
    free((unsigned char*) table->sort.io_cache);
 
647
    table->sort.io_cache=0;
322
648
  }
 
649
  return;
323
650
}
324
651
 
325
652
 
326
653
/*
327
654
  Close all tables which aren't in use by any thread
328
655
 
329
 
  @param session Thread context (may be NULL)
 
656
  @param thd Thread context
330
657
  @param tables List of tables to remove from the cache
331
658
  @param have_lock If LOCK_open is locked
332
659
  @param wait_for_refresh Wait for a impending flush
333
660
  @param wait_for_placeholders Wait for tables being reopened so that the GRL
334
 
  won't proceed while write-locked tables are being reopened by other
335
 
  threads.
 
661
         won't proceed while write-locked tables are being reopened by other
 
662
         threads.
336
663
 
337
 
  @remark Session can be NULL, but then wait_for_refresh must be false
338
 
  and tables must be NULL.
 
664
  @remark THD can be NULL, but then wait_for_refresh must be false
 
665
          and tables must be NULL.
339
666
*/
340
667
 
341
 
bool Session::close_cached_tables(TableList *tables, bool wait_for_refresh, bool wait_for_placeholders)
 
668
bool close_cached_tables(THD *thd, TableList *tables, bool have_lock,
 
669
                         bool wait_for_refresh, bool wait_for_placeholders)
342
670
{
343
 
  bool result= false;
344
 
  Session *session= this;
345
 
 
346
 
  LOCK_open.lock(); /* Optionally lock for remove tables from open_cahe if not in use */
347
 
 
348
 
  if (tables == NULL)
 
671
  bool result=0;
 
672
  assert(thd || (!wait_for_refresh && !tables));
 
673
 
 
674
  if (!have_lock)
 
675
    pthread_mutex_lock(&LOCK_open);
 
676
  if (!tables)
349
677
  {
350
678
    refresh_version++;                          // Force close of open tables
351
 
 
352
 
    unused_tables.clear();
353
 
 
 
679
    while (unused_tables)
 
680
    {
 
681
#ifdef EXTRA_DEBUG
 
682
      if (hash_delete(&open_cache,(unsigned char*) unused_tables))
 
683
        printf("Warning: Couldn't delete open table from hash\n");
 
684
#else
 
685
      hash_delete(&open_cache,(unsigned char*) unused_tables);
 
686
#endif
 
687
    }
 
688
    /* Free table shares */
 
689
    while (oldest_unused_share->next)
 
690
    {
 
691
      pthread_mutex_lock(&oldest_unused_share->mutex);
 
692
      hash_delete(&table_def_cache, (unsigned char*) oldest_unused_share);
 
693
    }
354
694
    if (wait_for_refresh)
355
695
    {
356
696
      /*
361
701
        request is aborted. They loop in open_and_lock_tables() and
362
702
        enter open_table(). Here they notice the table is refreshed and
363
703
        wait for COND_refresh. Then they loop again in
364
 
        openTablesLock() and this time open_table() succeeds. At
 
704
        open_and_lock_tables() and this time open_table() succeeds. At
365
705
        this moment, if we (the FLUSH TABLES thread) are scheduled and
366
706
        on another FLUSH TABLES enter close_cached_tables(), they could
367
707
        awake while we sleep below, waiting for others threads (us) to
376
716
        The fix for this problem is to set some_tables_deleted for all
377
717
        threads with open tables. These threads can still get their
378
718
        locks, but will immediately release them again after checking
379
 
        this variable. They will then loop in openTablesLock()
 
719
        this variable. They will then loop in open_and_lock_tables()
380
720
        again. There they will wait until we update all tables version
381
721
        below.
382
722
 
387
727
        some_tables_deleted for the case when table was opened and all
388
728
        related checks were passed before incrementing refresh_version
389
729
        (which you already have) but attempt to lock the table happened
390
 
        after the call to Session::close_old_data_files() i.e. after removal of
 
730
        after the call to close_old_data_files() i.e. after removal of
391
731
        current thread locks.
392
732
      */
393
 
      for (TableOpenCache::const_iterator iter= get_open_cache().begin();
394
 
           iter != get_open_cache().end();
395
 
           iter++)
 
733
      for (uint32_t idx=0 ; idx < open_cache.records ; idx++)
396
734
      {
397
 
        Table *table= (*iter).second;
 
735
        Table *table=(Table*) hash_element(&open_cache,idx);
398
736
        if (table->in_use)
399
 
          table->in_use->some_tables_deleted= false;
 
737
          table->in_use->some_tables_deleted= 1;
400
738
      }
401
739
    }
402
740
  }
403
741
  else
404
742
  {
405
 
    bool found= false;
 
743
    bool found=0;
406
744
    for (TableList *table= tables; table; table= table->next_local)
407
745
    {
408
 
      TableIdentifier identifier(table->db, table->table_name);
409
 
      if (remove_table_from_cache(session, identifier,
410
 
                                  RTFC_OWNED_BY_Session_FLAG))
411
 
      {
412
 
        found= true;
413
 
      }
 
746
      if (remove_table_from_cache(thd, table->db, table->table_name,
 
747
                                  RTFC_OWNED_BY_THD_FLAG))
 
748
        found=1;
414
749
    }
415
750
    if (!found)
416
 
      wait_for_refresh= false;                  // Nothing to wait for
 
751
      wait_for_refresh=0;                       // Nothing to wait for
417
752
  }
418
753
 
419
754
  if (wait_for_refresh)
422
757
      If there is any table that has a lower refresh_version, wait until
423
758
      this is closed (or this thread is killed) before returning
424
759
    */
425
 
    session->mysys_var->current_mutex= &LOCK_open;
426
 
    session->mysys_var->current_cond= &COND_refresh;
427
 
    session->set_proc_info("Flushing tables");
428
 
 
429
 
    session->close_old_data_files();
430
 
 
431
 
    bool found= true;
 
760
    thd->mysys_var->current_mutex= &LOCK_open;
 
761
    thd->mysys_var->current_cond= &COND_refresh;
 
762
    thd->set_proc_info("Flushing tables");
 
763
 
 
764
    close_old_data_files(thd,thd->open_tables,1,1);
 
765
    mysql_ha_flush(thd);
 
766
 
 
767
    bool found=1;
432
768
    /* Wait until all threads has closed all the tables we had locked */
433
 
    while (found && ! session->killed)
 
769
    while (found && ! thd->killed)
434
770
    {
435
 
      found= false;
436
 
      for (TableOpenCache::const_iterator iter= get_open_cache().begin();
437
 
           iter != get_open_cache().end();
438
 
           iter++)
 
771
      found=0;
 
772
      for (uint32_t idx=0 ; idx < open_cache.records ; idx++)
439
773
      {
440
 
        Table *table= (*iter).second;
 
774
        Table *table=(Table*) hash_element(&open_cache,idx);
441
775
        /* Avoid a self-deadlock. */
442
 
        if (table->in_use == session)
 
776
        if (table->in_use == thd)
443
777
          continue;
444
778
        /*
445
779
          Note that we wait here only for tables which are actually open, and
446
780
          not for placeholders with Table::open_placeholder set. Waiting for
447
781
          latter will cause deadlock in the following scenario, for example:
448
782
 
449
 
          conn1-> lock table t1 write;
450
 
          conn2-> lock table t2 write;
451
 
          conn1-> flush tables;
452
 
          conn2-> flush tables;
 
783
          conn1: lock table t1 write;
 
784
          conn2: lock table t2 write;
 
785
          conn1: flush tables;
 
786
          conn2: flush tables;
453
787
 
454
788
          It also does not make sense to wait for those of placeholders that
455
789
          are employed by CREATE TABLE as in this case table simply does not
456
790
          exist yet.
457
791
        */
458
 
        if (table->needs_reopen_or_name_lock() && (table->db_stat ||
459
 
                                                   (table->open_placeholder && wait_for_placeholders)))
460
 
        {
461
 
          found= true;
462
 
          pthread_cond_wait(COND_refresh.native_handle(),LOCK_open.native_handle());
463
 
          break;
464
 
        }
 
792
        if (table->needs_reopen_or_name_lock() && (table->db_stat ||
 
793
            (table->open_placeholder && wait_for_placeholders)))
 
794
        {
 
795
          found=1;
 
796
          pthread_cond_wait(&COND_refresh,&LOCK_open);
 
797
          break;
 
798
        }
465
799
      }
466
800
    }
467
801
    /*
469
803
      old locks. This should always succeed (unless some external process
470
804
      has removed the tables)
471
805
    */
472
 
    result= session->reopen_tables(true, true);
473
 
 
 
806
    thd->in_lock_tables=1;
 
807
    result=reopen_tables(thd,1,1);
 
808
    thd->in_lock_tables=0;
474
809
    /* Set version for table */
475
 
    for (Table *table= session->open_tables; table ; table= table->getNext())
 
810
    for (Table *table=thd->open_tables; table ; table= table->next)
476
811
    {
477
812
      /*
478
813
        Preserve the version (0) of write locked tables so that a impending
479
814
        global read lock won't sneak in.
480
815
      */
481
816
      if (table->reginfo.lock_type < TL_WRITE_ALLOW_WRITE)
482
 
        table->getMutableShare()->refreshVersion();
 
817
        table->s->version= refresh_version;
483
818
    }
484
819
  }
485
 
 
486
 
  LOCK_open.unlock();
487
 
 
 
820
  if (!have_lock)
 
821
    pthread_mutex_unlock(&LOCK_open);
488
822
  if (wait_for_refresh)
489
823
  {
490
 
    boost::mutex::scoped_lock scopedLock(session->mysys_var->mutex);
491
 
    session->mysys_var->current_mutex= 0;
492
 
    session->mysys_var->current_cond= 0;
493
 
    session->set_proc_info(0);
494
 
  }
495
 
 
496
 
  return result;
497
 
}
498
 
 
499
 
 
500
 
/**
501
 
  move one table to free list 
502
 
*/
503
 
 
504
 
bool Session::free_cached_table()
505
 
{
506
 
  bool found_old_table= false;
507
 
  Table *table= open_tables;
508
 
 
509
 
  safe_mutex_assert_owner(LOCK_open.native_handle());
 
824
    pthread_mutex_lock(&thd->mysys_var->mutex);
 
825
    thd->mysys_var->current_mutex= 0;
 
826
    thd->mysys_var->current_cond= 0;
 
827
    thd->set_proc_info(0);
 
828
    pthread_mutex_unlock(&thd->mysys_var->mutex);
 
829
  }
 
830
  return(result);
 
831
}
 
832
 
 
833
 
 
834
/*
 
835
  Close all tables which match specified connection string or
 
836
  if specified string is NULL, then any table with a connection string.
 
837
*/
 
838
 
 
839
bool close_cached_connection_tables(THD *thd, bool if_wait_for_refresh,
 
840
                                    LEX_STRING *connection, bool have_lock)
 
841
{
 
842
  uint32_t idx;
 
843
  TableList tmp, *tables= NULL;
 
844
  bool result= false;
 
845
  assert(thd);
 
846
 
 
847
  memset(&tmp, 0, sizeof(TableList));
 
848
 
 
849
  if (!have_lock)
 
850
    pthread_mutex_lock(&LOCK_open);
 
851
 
 
852
  for (idx= 0; idx < table_def_cache.records; idx++)
 
853
  {
 
854
    TABLE_SHARE *share= (TABLE_SHARE *) hash_element(&table_def_cache, idx);
 
855
 
 
856
    /* Ignore if table is not open or does not have a connect_string */
 
857
    if (!share->connect_string.length || !share->ref_count)
 
858
      continue;
 
859
 
 
860
    /* Compare the connection string */
 
861
    if (connection &&
 
862
        (connection->length > share->connect_string.length ||
 
863
         (connection->length < share->connect_string.length &&
 
864
          (share->connect_string.str[connection->length] != '/' &&
 
865
           share->connect_string.str[connection->length] != '\\')) ||
 
866
         strncasecmp(connection->str, share->connect_string.str,
 
867
                     connection->length)))
 
868
      continue;
 
869
 
 
870
    /* close_cached_tables() only uses these elements */
 
871
    tmp.db= share->db.str;
 
872
    tmp.table_name= share->table_name.str;
 
873
    tmp.next_local= tables;
 
874
 
 
875
    tables= (TableList *) memdup_root(thd->mem_root, (char*)&tmp, 
 
876
                                       sizeof(TableList));
 
877
  }
 
878
 
 
879
  if (tables)
 
880
    result= close_cached_tables(thd, tables, true, false, false);
 
881
 
 
882
  if (!have_lock)
 
883
    pthread_mutex_unlock(&LOCK_open);
 
884
 
 
885
  if (if_wait_for_refresh)
 
886
  {
 
887
    pthread_mutex_lock(&thd->mysys_var->mutex);
 
888
    thd->mysys_var->current_mutex= 0;
 
889
    thd->mysys_var->current_cond= 0;
 
890
    thd->set_proc_info(0);
 
891
    pthread_mutex_unlock(&thd->mysys_var->mutex);
 
892
  }
 
893
 
 
894
  return(result);
 
895
}
 
896
 
 
897
 
 
898
/**
 
899
  Mark all temporary tables which were used by the current statement or
 
900
  substatement as free for reuse, but only if the query_id can be cleared.
 
901
 
 
902
  @param thd thread context
 
903
 
 
904
  @remark For temp tables associated with a open SQL HANDLER the query_id
 
905
          is not reset until the HANDLER is closed.
 
906
*/
 
907
 
 
908
static void mark_temp_tables_as_free_for_reuse(THD *thd)
 
909
{
 
910
  for (Table *table= thd->temporary_tables ; table ; table= table->next)
 
911
  {
 
912
    if ((table->query_id == thd->query_id) && ! table->open_by_handler)
 
913
    {
 
914
      table->query_id= 0;
 
915
      table->file->ha_reset();
 
916
    }
 
917
  }
 
918
}
 
919
 
 
920
 
 
921
/*
 
922
  Mark all tables in the list which were used by current substatement
 
923
  as free for reuse.
 
924
 
 
925
  SYNOPSIS
 
926
    mark_used_tables_as_free_for_reuse()
 
927
      thd   - thread context
 
928
      table - head of the list of tables
 
929
 
 
930
  DESCRIPTION
 
931
    Marks all tables in the list which were used by current substatement
 
932
    (they are marked by its query_id) as free for reuse.
 
933
 
 
934
  NOTE
 
935
    The reason we reset query_id is that it's not enough to just test
 
936
    if table->query_id != thd->query_id to know if a table is in use.
 
937
 
 
938
    For example
 
939
    SELECT f1_that_uses_t1() FROM t1;
 
940
    In f1_that_uses_t1() we will see one instance of t1 where query_id is
 
941
    set to query_id of original query.
 
942
*/
 
943
 
 
944
static void mark_used_tables_as_free_for_reuse(THD *thd, Table *table)
 
945
{
 
946
  for (; table ; table= table->next)
 
947
  {
 
948
    if (table->query_id == thd->query_id)
 
949
    {
 
950
      table->query_id= 0;
 
951
      table->file->ha_reset();
 
952
    }
 
953
  }
 
954
}
 
955
 
 
956
 
 
957
/**
 
958
  Auxiliary function to close all tables in the open_tables list.
 
959
 
 
960
  @param thd Thread context.
 
961
 
 
962
  @remark It should not ordinarily be called directly.
 
963
*/
 
964
 
 
965
static void close_open_tables(THD *thd)
 
966
{
 
967
  bool found_old_table= 0;
 
968
 
 
969
  safe_mutex_assert_not_owner(&LOCK_open);
 
970
 
 
971
  pthread_mutex_lock(&LOCK_open);
 
972
 
 
973
  while (thd->open_tables)
 
974
    found_old_table|= close_thread_table(thd, &thd->open_tables);
 
975
  thd->some_tables_deleted= 0;
 
976
 
 
977
  /* Free tables to hold down open files */
 
978
  while (open_cache.records > table_cache_size && unused_tables)
 
979
    hash_delete(&open_cache,(unsigned char*) unused_tables); /* purecov: tested */
 
980
  if (found_old_table)
 
981
  {
 
982
    /* Tell threads waiting for refresh that something has happened */
 
983
    broadcast_refresh();
 
984
  }
 
985
 
 
986
  pthread_mutex_unlock(&LOCK_open);
 
987
}
 
988
 
 
989
 
 
990
/*
 
991
  Close all tables used by the current substatement, or all tables
 
992
  used by this thread if we are on the upper level.
 
993
 
 
994
  SYNOPSIS
 
995
    close_thread_tables()
 
996
    thd                 Thread handler
 
997
 
 
998
  IMPLEMENTATION
 
999
    Unlocks tables and frees derived tables.
 
1000
    Put all normal tables used by thread in free list.
 
1001
 
 
1002
    It will only close/mark as free for reuse tables opened by this
 
1003
    substatement, it will also check if we are closing tables after
 
1004
    execution of complete query (i.e. we are on upper level) and will
 
1005
    leave prelocked mode if needed.
 
1006
*/
 
1007
 
 
1008
void close_thread_tables(THD *thd)
 
1009
{
 
1010
  Table *table;
 
1011
 
 
1012
  /*
 
1013
    We are assuming here that thd->derived_tables contains ONLY derived
 
1014
    tables for this substatement. i.e. instead of approach which uses
 
1015
    query_id matching for determining which of the derived tables belong
 
1016
    to this substatement we rely on the ability of substatements to
 
1017
    save/restore thd->derived_tables during their execution.
 
1018
 
 
1019
    TODO: Probably even better approach is to simply associate list of
 
1020
          derived tables with (sub-)statement instead of thread and destroy
 
1021
          them at the end of its execution.
 
1022
  */
 
1023
  if (thd->derived_tables)
 
1024
  {
 
1025
    Table *next;
 
1026
    /*
 
1027
      Close all derived tables generated in queries like
 
1028
      SELECT * FROM (SELECT * FROM t1)
 
1029
    */
 
1030
    for (table= thd->derived_tables ; table ; table= next)
 
1031
    {
 
1032
      next= table->next;
 
1033
      table->free_tmp_table(thd);
 
1034
    }
 
1035
    thd->derived_tables= 0;
 
1036
  }
 
1037
 
 
1038
  /*
 
1039
    Mark all temporary tables used by this statement as free for reuse.
 
1040
  */
 
1041
  mark_temp_tables_as_free_for_reuse(thd);
 
1042
  /*
 
1043
    Let us commit transaction for statement. Since in 5.0 we only have
 
1044
    one statement transaction and don't allow several nested statement
 
1045
    transactions this call will do nothing if we are inside of stored
 
1046
    function or trigger (i.e. statement transaction is already active and
 
1047
    does not belong to statement for which we do close_thread_tables()).
 
1048
    TODO: This should be fixed in later releases.
 
1049
   */
 
1050
  if (!(thd->state_flags & Open_tables_state::BACKUPS_AVAIL))
 
1051
  {
 
1052
    thd->main_da.can_overwrite_status= true;
 
1053
    ha_autocommit_or_rollback(thd, thd->is_error());
 
1054
    thd->main_da.can_overwrite_status= false;
 
1055
    thd->transaction.stmt.reset();
 
1056
  }
 
1057
 
 
1058
  if (thd->locked_tables)
 
1059
  {
 
1060
 
 
1061
    /* Ensure we are calling ha_reset() for all used tables */
 
1062
    mark_used_tables_as_free_for_reuse(thd, thd->open_tables);
 
1063
 
 
1064
    /*
 
1065
      We are under simple LOCK TABLES so should not do anything else.
 
1066
    */
 
1067
    return;
 
1068
  }
 
1069
 
 
1070
  if (thd->lock)
 
1071
  {
 
1072
    /*
 
1073
      For RBR we flush the pending event just before we unlock all the
 
1074
      tables.  This means that we are at the end of a topmost
 
1075
      statement, so we ensure that the STMT_END_F flag is set on the
 
1076
      pending event.  For statements that are *inside* stored
 
1077
      functions, the pending event will not be flushed: that will be
 
1078
      handled either before writing a query log event (inside
 
1079
      binlog_query()) or when preparing a pending event.
 
1080
     */
 
1081
    thd->binlog_flush_pending_rows_event(true);
 
1082
    mysql_unlock_tables(thd, thd->lock);
 
1083
    thd->lock=0;
 
1084
  }
 
1085
  /*
 
1086
    Note that we need to hold LOCK_open while changing the
 
1087
    open_tables list. Another thread may work on it.
 
1088
    (See: remove_table_from_cache(), mysql_wait_completed_table())
 
1089
    Closing a MERGE child before the parent would be fatal if the
 
1090
    other thread tries to abort the MERGE lock in between.
 
1091
  */
 
1092
  if (thd->open_tables)
 
1093
    close_open_tables(thd);
 
1094
 
 
1095
  return;
 
1096
}
 
1097
 
 
1098
 
 
1099
/* move one table to free list */
 
1100
 
 
1101
bool close_thread_table(THD *thd, Table **table_ptr)
 
1102
{
 
1103
  bool found_old_table= 0;
 
1104
  Table *table= *table_ptr;
 
1105
 
510
1106
  assert(table->key_read == 0);
511
 
  assert(!table->cursor || table->cursor->inited == Cursor::NONE);
 
1107
  assert(!table->file || table->file->inited == handler::NONE);
512
1108
 
513
 
  open_tables= table->getNext();
 
1109
  *table_ptr=table->next;
514
1110
 
515
1111
  if (table->needs_reopen_or_name_lock() ||
516
 
      version != refresh_version || !table->db_stat)
 
1112
      thd->version != refresh_version || !table->db_stat)
517
1113
  {
518
 
    remove_table(table);
519
 
    found_old_table= true;
 
1114
    hash_delete(&open_cache,(unsigned char*) table);
 
1115
    found_old_table=1;
520
1116
  }
521
1117
  else
522
1118
  {
524
1120
      Open placeholders have Table::db_stat set to 0, so they should be
525
1121
      handled by the first alternative.
526
1122
    */
527
 
    assert(not table->open_placeholder);
 
1123
    assert(!table->open_placeholder);
528
1124
 
529
1125
    /* Free memory and reset for next loop */
530
 
    table->cursor->ha_reset();
531
 
    table->in_use= false;
532
 
 
533
 
    unused_tables.link(table);
 
1126
    table->file->ha_reset();
 
1127
    table->in_use=0;
 
1128
    if (unused_tables)
 
1129
    {
 
1130
      table->next=unused_tables;                /* Link in last */
 
1131
      table->prev=unused_tables->prev;
 
1132
      unused_tables->prev=table;
 
1133
      table->prev->next=table;
 
1134
    }
 
1135
    else
 
1136
      unused_tables=table->next=table->prev=table;
534
1137
  }
535
 
 
536
 
  return found_old_table;
537
 
}
538
 
 
539
 
 
540
 
/**
541
 
  Auxiliary function to close all tables in the open_tables list.
542
 
 
543
 
  @param session Thread context.
544
 
 
545
 
  @remark It should not ordinarily be called directly.
 
1138
  return(found_old_table);
 
1139
}
 
1140
 
 
1141
 
 
1142
/* close_temporary_tables' internal, 4 is due to uint4korr definition */
 
1143
static inline uint32_t  tmpkeyval(THD *thd __attribute__((unused)),
 
1144
                              Table *table)
 
1145
{
 
1146
  return uint4korr(table->s->table_cache_key.str + table->s->table_cache_key.length - 4);
 
1147
}
 
1148
 
 
1149
 
 
1150
/*
 
1151
  Close all temporary tables created by 'CREATE TEMPORARY TABLE' for thread
 
1152
  creates one DROP TEMPORARY Table binlog event for each pseudo-thread 
546
1153
*/
547
1154
 
548
 
void Session::close_open_tables()
 
1155
void close_temporary_tables(THD *thd)
549
1156
{
550
 
  bool found_old_table= false;
551
 
 
552
 
  safe_mutex_assert_not_owner(LOCK_open.native_handle());
553
 
 
554
 
  boost::mutex::scoped_lock scoped_lock(LOCK_open); /* Close all open tables on Session */
555
 
 
556
 
  while (open_tables)
557
 
  {
558
 
    found_old_table|= free_cached_table();
559
 
  }
560
 
  some_tables_deleted= false;
561
 
 
562
 
  if (found_old_table)
563
 
  {
564
 
    /* Tell threads waiting for refresh that something has happened */
565
 
    broadcast_refresh();
566
 
  }
 
1157
  Table *table;
 
1158
  Table *next= NULL;
 
1159
  Table *prev_table;
 
1160
  /* Assume thd->options has OPTION_QUOTE_SHOW_CREATE */
 
1161
  bool was_quote_show= true;
 
1162
 
 
1163
  if (!thd->temporary_tables)
 
1164
    return;
 
1165
 
 
1166
  if (!mysql_bin_log.is_open() || thd->current_stmt_binlog_row_based)
 
1167
  {
 
1168
    Table *tmp_next;
 
1169
    for (table= thd->temporary_tables; table; table= tmp_next)
 
1170
    {
 
1171
      tmp_next= table->next;
 
1172
      close_temporary(table, 1, 1);
 
1173
    }
 
1174
    thd->temporary_tables= 0;
 
1175
    return;
 
1176
  }
 
1177
 
 
1178
  /* Better add "if exists", in case a RESET MASTER has been done */
 
1179
  const char stub[]= "DROP /*!40005 TEMPORARY */ Table IF EXISTS ";
 
1180
  uint32_t stub_len= sizeof(stub) - 1;
 
1181
  char buf[256];
 
1182
  String s_query= String(buf, sizeof(buf), system_charset_info);
 
1183
  bool found_user_tables= false;
 
1184
 
 
1185
  memcpy(buf, stub, stub_len);
 
1186
 
 
1187
  /*
 
1188
    Insertion sort of temp tables by pseudo_thread_id to build ordered list
 
1189
    of sublists of equal pseudo_thread_id
 
1190
  */
 
1191
 
 
1192
  for (prev_table= thd->temporary_tables, table= prev_table->next;
 
1193
       table;
 
1194
       prev_table= table, table= table->next)
 
1195
  {
 
1196
    Table *prev_sorted /* same as for prev_table */, *sorted;
 
1197
    if (is_user_table(table))
 
1198
    {
 
1199
      if (!found_user_tables)
 
1200
        found_user_tables= true;
 
1201
      for (prev_sorted= NULL, sorted= thd->temporary_tables; sorted != table;
 
1202
           prev_sorted= sorted, sorted= sorted->next)
 
1203
      {
 
1204
        if (!is_user_table(sorted) ||
 
1205
            tmpkeyval(thd, sorted) > tmpkeyval(thd, table))
 
1206
        {
 
1207
          /* move into the sorted part of the list from the unsorted */
 
1208
          prev_table->next= table->next;
 
1209
          table->next= sorted;
 
1210
          if (prev_sorted)
 
1211
          {
 
1212
            prev_sorted->next= table;
 
1213
          }
 
1214
          else
 
1215
          {
 
1216
            thd->temporary_tables= table;
 
1217
          }
 
1218
          table= prev_table;
 
1219
          break;
 
1220
        }
 
1221
      }
 
1222
    }
 
1223
  }
 
1224
 
 
1225
  /* We always quote db,table names though it is slight overkill */
 
1226
  if (found_user_tables &&
 
1227
      !(was_quote_show= test(thd->options & OPTION_QUOTE_SHOW_CREATE)))
 
1228
  {
 
1229
    thd->options |= OPTION_QUOTE_SHOW_CREATE;
 
1230
  }
 
1231
 
 
1232
  /* scan sorted tmps to generate sequence of DROP */
 
1233
  for (table= thd->temporary_tables; table; table= next)
 
1234
  {
 
1235
    if (is_user_table(table))
 
1236
    {
 
1237
      my_thread_id save_pseudo_thread_id= thd->variables.pseudo_thread_id;
 
1238
      /* Set pseudo_thread_id to be that of the processed table */
 
1239
      thd->variables.pseudo_thread_id= tmpkeyval(thd, table);
 
1240
      /*
 
1241
        Loop forward through all tables within the sublist of
 
1242
        common pseudo_thread_id to create single DROP query.
 
1243
      */
 
1244
      for (s_query.length(stub_len);
 
1245
           table && is_user_table(table) &&
 
1246
             tmpkeyval(thd, table) == thd->variables.pseudo_thread_id;
 
1247
           table= next)
 
1248
      {
 
1249
        /*
 
1250
          We are going to add 4 ` around the db/table names and possible more
 
1251
          due to special characters in the names
 
1252
        */
 
1253
        append_identifier(thd, &s_query, table->s->db.str, strlen(table->s->db.str));
 
1254
        s_query.append('.');
 
1255
        append_identifier(thd, &s_query, table->s->table_name.str,
 
1256
                          strlen(table->s->table_name.str));
 
1257
        s_query.append(',');
 
1258
        next= table->next;
 
1259
        close_temporary(table, 1, 1);
 
1260
      }
 
1261
      thd->clear_error();
 
1262
      const CHARSET_INFO * const cs_save= thd->variables.character_set_client;
 
1263
      thd->variables.character_set_client= system_charset_info;
 
1264
      Query_log_event qinfo(thd, s_query.ptr(),
 
1265
                            s_query.length() - 1 /* to remove trailing ',' */,
 
1266
                            0, false);
 
1267
      thd->variables.character_set_client= cs_save;
 
1268
      /*
 
1269
        Imagine the thread had created a temp table, then was doing a
 
1270
        SELECT, and the SELECT was killed. Then it's not clever to
 
1271
        mark the statement above as "killed", because it's not really
 
1272
        a statement updating data, and there are 99.99% chances it
 
1273
        will succeed on slave.  If a real update (one updating a
 
1274
        persistent table) was killed on the master, then this real
 
1275
        update will be logged with error_code=killed, rightfully
 
1276
        causing the slave to stop.
 
1277
      */
 
1278
      qinfo.error_code= 0;
 
1279
      mysql_bin_log.write(&qinfo);
 
1280
      thd->variables.pseudo_thread_id= save_pseudo_thread_id;
 
1281
    }
 
1282
    else
 
1283
    {
 
1284
      next= table->next;
 
1285
      close_temporary(table, 1, 1);
 
1286
    }
 
1287
  }
 
1288
  if (!was_quote_show)
 
1289
    thd->options&= ~OPTION_QUOTE_SHOW_CREATE; /* restore option */
 
1290
  thd->temporary_tables=0;
567
1291
}
568
1292
 
569
1293
/*
570
1294
  Find table in list.
571
1295
 
572
1296
  SYNOPSIS
573
 
  find_table_in_list()
574
 
  table         Pointer to table list
575
 
  offset                Offset to which list in table structure to use
576
 
  db_name               Data base name
577
 
  table_name            Table name
578
 
 
579
 
NOTES:
580
 
This is called by find_table_in_global_list().
581
 
 
582
 
RETURN VALUES
583
 
NULL    Table not found
584
 
#               Pointer to found table.
 
1297
    find_table_in_list()
 
1298
    table               Pointer to table list
 
1299
    offset              Offset to which list in table structure to use
 
1300
    db_name             Data base name
 
1301
    table_name          Table name
 
1302
 
 
1303
  NOTES:
 
1304
    This is called by find_table_in_local_list() and
 
1305
    find_table_in_global_list().
 
1306
 
 
1307
  RETURN VALUES
 
1308
    NULL        Table not found
 
1309
    #           Pointer to found table.
585
1310
*/
586
1311
 
587
1312
TableList *find_table_in_list(TableList *table,
588
 
                              TableList *TableList::*link,
589
 
                              const char *db_name,
590
 
                              const char *table_name)
 
1313
                               TableList *TableList::*link,
 
1314
                               const char *db_name,
 
1315
                               const char *table_name)
591
1316
{
592
1317
  for (; table; table= table->*link )
593
1318
  {
594
 
    if ((table->table == 0 || table->table->getShare()->getType() == message::Table::STANDARD) &&
595
 
        strcasecmp(table->db, db_name) == 0 &&
596
 
        strcasecmp(table->table_name, table_name) == 0)
 
1319
    if ((table->table == 0 || table->table->s->tmp_table == NO_TMP_TABLE) &&
 
1320
        strcmp(table->db, db_name) == 0 &&
 
1321
        strcmp(table->table_name, table_name) == 0)
597
1322
      break;
598
1323
  }
599
1324
  return table;
604
1329
  Test that table is unique (It's only exists once in the table list)
605
1330
 
606
1331
  SYNOPSIS
607
 
  unique_table()
608
 
  session                   thread handle
609
 
  table                 table which should be checked
610
 
  table_list            list of tables
611
 
  check_alias           whether to check tables' aliases
612
 
 
613
 
NOTE: to exclude derived tables from check we use following mechanism:
614
 
a) during derived table processing set Session::derived_tables_processing
615
 
b) JOIN::prepare set SELECT::exclude_from_table_unique_test if
616
 
Session::derived_tables_processing set. (we can't use JOIN::execute
617
 
because for PS we perform only JOIN::prepare, but we can't set this
618
 
flag in JOIN::prepare if we are not sure that we are in derived table
619
 
processing loop, because multi-update call fix_fields() for some its
620
 
items (which mean JOIN::prepare for subqueries) before unique_table
621
 
call to detect which tables should be locked for write).
622
 
c) unique_table skip all tables which belong to SELECT with
623
 
SELECT::exclude_from_table_unique_test set.
624
 
Also SELECT::exclude_from_table_unique_test used to exclude from check
625
 
tables of main SELECT of multi-delete and multi-update
626
 
 
627
 
We also skip tables with TableList::prelocking_placeholder set,
628
 
because we want to allow SELECTs from them, and their modification
629
 
will rise the error anyway.
630
 
 
631
 
TODO: when we will have table/view change detection we can do this check
632
 
only once for PS/SP
633
 
 
634
 
RETURN
635
 
found duplicate
636
 
0 if table is unique
 
1332
    unique_table()
 
1333
    thd                   thread handle
 
1334
    table                 table which should be checked
 
1335
    table_list            list of tables
 
1336
    check_alias           whether to check tables' aliases
 
1337
 
 
1338
  NOTE: to exclude derived tables from check we use following mechanism:
 
1339
    a) during derived table processing set THD::derived_tables_processing
 
1340
    b) JOIN::prepare set SELECT::exclude_from_table_unique_test if
 
1341
       THD::derived_tables_processing set. (we can't use JOIN::execute
 
1342
       because for PS we perform only JOIN::prepare, but we can't set this
 
1343
       flag in JOIN::prepare if we are not sure that we are in derived table
 
1344
       processing loop, because multi-update call fix_fields() for some its
 
1345
       items (which mean JOIN::prepare for subqueries) before unique_table
 
1346
       call to detect which tables should be locked for write).
 
1347
    c) unique_table skip all tables which belong to SELECT with
 
1348
       SELECT::exclude_from_table_unique_test set.
 
1349
    Also SELECT::exclude_from_table_unique_test used to exclude from check
 
1350
    tables of main SELECT of multi-delete and multi-update
 
1351
 
 
1352
    We also skip tables with TableList::prelocking_placeholder set,
 
1353
    because we want to allow SELECTs from them, and their modification
 
1354
    will rise the error anyway.
 
1355
 
 
1356
    TODO: when we will have table/view change detection we can do this check
 
1357
          only once for PS/SP
 
1358
 
 
1359
  RETURN
 
1360
    found duplicate
 
1361
    0 if table is unique
637
1362
*/
638
1363
 
639
 
TableList* unique_table(TableList *table, TableList *table_list,
640
 
                        bool check_alias)
 
1364
TableList* unique_table(THD *thd, TableList *table, TableList *table_list,
 
1365
                         bool check_alias)
641
1366
{
642
1367
  TableList *res;
643
1368
  const char *d_name, *t_name, *t_alias;
655
1380
  if (table->table)
656
1381
  {
657
1382
    /* temporary table is always unique */
658
 
    if (table->table && table->table->getShare()->getType() != message::Table::STANDARD)
659
 
      return 0;
 
1383
    if (table->table && table->table->s->tmp_table != NO_TMP_TABLE)
 
1384
      return(0);
660
1385
    table= table->find_underlying_table(table->table);
661
1386
    /*
662
1387
      as far as we have table->table we have to find real TableList of
670
1395
 
671
1396
  for (;;)
672
1397
  {
673
 
    if ((! (res= find_table_in_global_list(table_list, d_name, t_name))) ||
 
1398
    if (((! (res= find_table_in_global_list(table_list, d_name, t_name))) &&
 
1399
         (! (res= mysql_lock_have_duplicate(thd, table, table_list)))) ||
674
1400
        ((!res->table || res->table != table->table) &&
675
 
         (!check_alias || !(my_strcasecmp(files_charset_info, t_alias, res->alias))) &&
 
1401
         (!check_alias || !(lower_case_table_names ?
 
1402
          my_strcasecmp(files_charset_info, t_alias, res->alias) :
 
1403
          strcmp(t_alias, res->alias))) &&
676
1404
         res->select_lex && !res->select_lex->exclude_from_table_unique_test))
677
1405
      break;
678
1406
    /*
686
1414
}
687
1415
 
688
1416
 
689
 
void Session::doGetTableNames(const SchemaIdentifier &schema_identifier,
690
 
                              std::set<std::string>& set_of_names)
691
 
{
692
 
  for (Table *table= temporary_tables ; table ; table= table->getNext())
693
 
  {
694
 
    if (schema_identifier.compare(table->getShare()->getSchemaName()))
695
 
    {
696
 
      set_of_names.insert(table->getShare()->getTableName());
697
 
    }
698
 
  }
699
 
}
700
 
 
701
 
void Session::doGetTableNames(CachedDirectory &,
702
 
                              const SchemaIdentifier &schema_identifier,
703
 
                              std::set<std::string> &set_of_names)
704
 
{
705
 
  doGetTableNames(schema_identifier, set_of_names);
706
 
}
707
 
 
708
 
void Session::doGetTableIdentifiers(const SchemaIdentifier &schema_identifier,
709
 
                                    TableIdentifiers &set_of_identifiers)
710
 
{
711
 
  for (Table *table= temporary_tables ; table ; table= table->getNext())
712
 
  {
713
 
    if (schema_identifier.compare(table->getShare()->getSchemaName()))
714
 
    {
715
 
      set_of_identifiers.push_back(TableIdentifier(table->getShare()->getSchemaName(),
716
 
                                                   table->getShare()->getTableName(),
717
 
                                                   table->getShare()->getPath()));
718
 
    }
719
 
  }
720
 
}
721
 
 
722
 
void Session::doGetTableIdentifiers(CachedDirectory &,
723
 
                                    const SchemaIdentifier &schema_identifier,
724
 
                                    TableIdentifiers &set_of_identifiers)
725
 
{
726
 
  doGetTableIdentifiers(schema_identifier, set_of_identifiers);
727
 
}
728
 
 
729
 
bool Session::doDoesTableExist(const TableIdentifier &identifier)
730
 
{
731
 
  for (Table *table= temporary_tables ; table ; table= table->getNext())
732
 
  {
733
 
    if (table->getShare()->getType() == message::Table::TEMPORARY)
734
 
    {
735
 
      if (identifier.getKey() == table->getShare()->getCacheKey())
736
 
      {
737
 
        return true;
738
 
      }
739
 
    }
740
 
  }
741
 
 
742
 
  return false;
743
 
}
744
 
 
745
 
int Session::doGetTableDefinition(const TableIdentifier &identifier,
746
 
                                  message::Table &table_proto)
747
 
{
748
 
  for (Table *table= temporary_tables ; table ; table= table->getNext())
749
 
  {
750
 
    if (table->getShare()->getType() == message::Table::TEMPORARY)
751
 
    {
752
 
      if (identifier.getKey() == table->getShare()->getCacheKey())
753
 
      {
754
 
        table_proto.CopyFrom(*(table->getShare()->getTableProto()));
755
 
 
756
 
        return EEXIST;
757
 
      }
758
 
    }
759
 
  }
760
 
 
761
 
  return ENOENT;
762
 
}
763
 
 
764
 
Table *Session::find_temporary_table(const char *new_db, const char *table_name)
 
1417
/*
 
1418
  Issue correct error message in case we found 2 duplicate tables which
 
1419
  prevent some update operation
 
1420
 
 
1421
  SYNOPSIS
 
1422
    update_non_unique_table_error()
 
1423
    update      table which we try to update
 
1424
    operation   name of update operation
 
1425
    duplicate   duplicate table which we found
 
1426
 
 
1427
  NOTE:
 
1428
    here we hide view underlying tables if we have them
 
1429
*/
 
1430
 
 
1431
void update_non_unique_table_error(TableList *update,
 
1432
                                   const char *operation __attribute__((unused)),
 
1433
                                   TableList *duplicate __attribute__((unused)))
 
1434
{
 
1435
  my_error(ER_UPDATE_TABLE_USED, MYF(0), update->alias);
 
1436
}
 
1437
 
 
1438
 
 
1439
Table *find_temporary_table(THD *thd, const char *db, const char *table_name)
 
1440
{
 
1441
  TableList table_list;
 
1442
 
 
1443
  table_list.db= (char*) db;
 
1444
  table_list.table_name= (char*) table_name;
 
1445
  return find_temporary_table(thd, &table_list);
 
1446
}
 
1447
 
 
1448
 
 
1449
Table *find_temporary_table(THD *thd, TableList *table_list)
765
1450
{
766
1451
  char  key[MAX_DBKEY_LENGTH];
767
1452
  uint  key_length;
768
 
 
769
 
  key_length= TableIdentifier::createKey(key, new_db, table_name);
770
 
 
771
 
  for (Table *table= temporary_tables ; table ; table= table->getNext())
772
 
  {
773
 
    const TableIdentifier::Key &share_key(table->getShare()->getCacheKey());
774
 
    if (share_key.size() == key_length &&
775
 
        not memcmp(&share_key[0], key, key_length))
776
 
    {
777
 
      return table;
778
 
    }
779
 
  }
780
 
  return NULL;                               // Not a temporary table
781
 
}
782
 
 
783
 
Table *Session::find_temporary_table(TableList *table_list)
784
 
{
785
 
  return find_temporary_table(table_list->db, table_list->table_name);
786
 
}
787
 
 
788
 
Table *Session::find_temporary_table(TableIdentifier &identifier)
789
 
{
790
 
  for (Table *table= temporary_tables ; table ; table= table->getNext())
791
 
  {
792
 
    if (identifier.getKey() == table->getShare()->getCacheKey())
793
 
      return table;
794
 
  }
795
 
 
796
 
  return NULL;                               // Not a temporary table
 
1453
  Table *table;
 
1454
 
 
1455
  key_length= create_table_def_key(thd, key, table_list, 1);
 
1456
  for (table=thd->temporary_tables ; table ; table= table->next)
 
1457
  {
 
1458
    if (table->s->table_cache_key.length == key_length &&
 
1459
        !memcmp(table->s->table_cache_key.str, key, key_length))
 
1460
      return(table);
 
1461
  }
 
1462
  return(0);                               // Not a temporary table
797
1463
}
798
1464
 
799
1465
 
800
1466
/**
801
1467
  Drop a temporary table.
802
1468
 
803
 
  Try to locate the table in the list of session->temporary_tables.
 
1469
  Try to locate the table in the list of thd->temporary_tables.
804
1470
  If the table is found:
805
 
  - if the table is being used by some outer statement, fail.
806
 
  - if the table is in session->locked_tables, unlock it and
807
 
  remove it from the list of locked tables. Currently only transactional
808
 
  temporary tables are present in the locked_tables list.
809
 
  - Close the temporary table, remove its .FRM
810
 
  - remove the table from the list of temporary tables
 
1471
   - if the table is being used by some outer statement, fail.
 
1472
   - if the table is in thd->locked_tables, unlock it and
 
1473
     remove it from the list of locked tables. Currently only transactional
 
1474
     temporary tables are present in the locked_tables list.
 
1475
   - Close the temporary table, remove its .FRM
 
1476
   - remove the table from the list of temporary tables
811
1477
 
812
1478
  This function is used to drop user temporary tables, as well as
813
1479
  internal tables created in CREATE TEMPORARY TABLE ... SELECT
814
1480
  or ALTER Table. Even though part of the work done by this function
815
1481
  is redundant when the table is internal, as long as we
816
1482
  link both internal and user temporary tables into the same
817
 
  session->temporary_tables list, it's impossible to tell here whether
 
1483
  thd->temporary_tables list, it's impossible to tell here whether
818
1484
  we're dealing with an internal or a user temporary table.
819
1485
 
820
1486
  @retval  0  the table was found and dropped successfully.
821
1487
  @retval  1  the table was not found in the list of temporary tables
822
 
  of this thread
 
1488
              of this thread
823
1489
  @retval -1  the table is in use by a outer query
824
1490
*/
825
1491
 
826
 
int Session::drop_temporary_table(TableList *table_list)
 
1492
int drop_temporary_table(THD *thd, TableList *table_list)
827
1493
{
828
1494
  Table *table;
829
1495
 
830
 
  if (not (table= find_temporary_table(table_list)))
831
 
    return 1;
 
1496
  if (!(table= find_temporary_table(thd, table_list)))
 
1497
    return(1);
832
1498
 
833
1499
  /* Table might be in use by some outer statement. */
834
 
  if (table->query_id && table->query_id != query_id)
835
 
  {
836
 
    my_error(ER_CANT_REOPEN_TABLE, MYF(0), table->getAlias());
837
 
    return -1;
838
 
  }
839
 
 
840
 
  close_temporary_table(table);
841
 
 
842
 
  return 0;
 
1500
  if (table->query_id && table->query_id != thd->query_id)
 
1501
  {
 
1502
    my_error(ER_CANT_REOPEN_TABLE, MYF(0), table->alias);
 
1503
    return(-1);
 
1504
  }
 
1505
 
 
1506
  /*
 
1507
    If LOCK TABLES list is not empty and contains this table,
 
1508
    unlock the table and remove the table from this list.
 
1509
  */
 
1510
  mysql_lock_remove(thd, thd->locked_tables, table, false);
 
1511
  close_temporary_table(thd, table, 1, 1);
 
1512
  return(0);
 
1513
}
 
1514
 
 
1515
/*
 
1516
  unlink from thd->temporary tables and close temporary table
 
1517
*/
 
1518
 
 
1519
void close_temporary_table(THD *thd, Table *table,
 
1520
                           bool free_share, bool delete_table)
 
1521
{
 
1522
  if (table->prev)
 
1523
  {
 
1524
    table->prev->next= table->next;
 
1525
    if (table->prev->next)
 
1526
      table->next->prev= table->prev;
 
1527
  }
 
1528
  else
 
1529
  {
 
1530
    /* removing the item from the list */
 
1531
    assert(table == thd->temporary_tables);
 
1532
    /*
 
1533
      slave must reset its temporary list pointer to zero to exclude
 
1534
      passing non-zero value to end_slave via rli->save_temporary_tables
 
1535
      when no temp tables opened, see an invariant below.
 
1536
    */
 
1537
    thd->temporary_tables= table->next;
 
1538
    if (thd->temporary_tables)
 
1539
      table->next->prev= 0;
 
1540
  }
 
1541
  if (thd->slave_thread)
 
1542
  {
 
1543
    /* natural invariant of temporary_tables */
 
1544
    assert(slave_open_temp_tables || !thd->temporary_tables);
 
1545
    slave_open_temp_tables--;
 
1546
  }
 
1547
  close_temporary(table, free_share, delete_table);
 
1548
  return;
 
1549
}
 
1550
 
 
1551
 
 
1552
/*
 
1553
  Close and delete a temporary table
 
1554
 
 
1555
  NOTE
 
1556
    This dosn't unlink table from thd->temporary
 
1557
    If this is needed, use close_temporary_table()
 
1558
*/
 
1559
 
 
1560
void close_temporary(Table *table, bool free_share, bool delete_table)
 
1561
{
 
1562
  handlerton *table_type= table->s->db_type();
 
1563
 
 
1564
  free_io_cache(table);
 
1565
  closefrm(table, 0);
 
1566
  /*
 
1567
     Check that temporary table has not been created with
 
1568
     frm_only because it has then not been created in any storage engine
 
1569
   */
 
1570
  if (delete_table)
 
1571
    rm_temporary_table(table_type, table->s->path.str, 
 
1572
                       table->s->tmp_table == TMP_TABLE_FRM_FILE_ONLY);
 
1573
  if (free_share)
 
1574
  {
 
1575
    free_table_share(table->s);
 
1576
    free((char*) table);
 
1577
  }
 
1578
  return;
 
1579
}
 
1580
 
 
1581
 
 
1582
/*
 
1583
  Used by ALTER Table when the table is a temporary one. It changes something
 
1584
  only if the ALTER contained a RENAME clause (otherwise, table_name is the old
 
1585
  name).
 
1586
  Prepares a table cache key, which is the concatenation of db, table_name and
 
1587
  thd->slave_proxy_id, separated by '\0'.
 
1588
*/
 
1589
 
 
1590
bool rename_temporary_table(THD* thd, Table *table, const char *db,
 
1591
                            const char *table_name)
 
1592
{
 
1593
  char *key;
 
1594
  uint32_t key_length;
 
1595
  TABLE_SHARE *share= table->s;
 
1596
  TableList table_list;
 
1597
 
 
1598
  if (!(key=(char*) alloc_root(&share->mem_root, MAX_DBKEY_LENGTH)))
 
1599
    return(1);                          /* purecov: inspected */
 
1600
 
 
1601
  table_list.db= (char*) db;
 
1602
  table_list.table_name= (char*) table_name;
 
1603
  key_length= create_table_def_key(thd, key, &table_list, 1);
 
1604
  share->set_table_cache_key(key, key_length);
 
1605
  return(0);
 
1606
}
 
1607
 
 
1608
 
 
1609
        /* move table first in unused links */
 
1610
 
 
1611
static void relink_unused(Table *table)
 
1612
{
 
1613
  if (table != unused_tables)
 
1614
  {
 
1615
    table->prev->next=table->next;              /* Remove from unused list */
 
1616
    table->next->prev=table->prev;
 
1617
    table->next=unused_tables;                  /* Link in unused tables */
 
1618
    table->prev=unused_tables->prev;
 
1619
    unused_tables->prev->next=table;
 
1620
    unused_tables->prev=table;
 
1621
    unused_tables=table;
 
1622
  }
843
1623
}
844
1624
 
845
1625
 
846
1626
/**
847
 
  Remove all instances of table from thread's open list and
848
 
  table cache.
849
 
 
850
 
  @param  session     Thread context
851
 
  @param  find    Table to remove
 
1627
    Remove all instances of table from thread's open list and
 
1628
    table cache.
 
1629
 
 
1630
    @param  thd     Thread context
 
1631
    @param  find    Table to remove
 
1632
    @param  unlock  true  - free all locks on tables removed that are
 
1633
                            done with LOCK TABLES
 
1634
                    false - otherwise
 
1635
 
 
1636
    @note When unlock parameter is false or current thread doesn't have
 
1637
          any tables locked with LOCK TABLES, tables are assumed to be
 
1638
          not locked (for example already unlocked).
852
1639
*/
853
1640
 
854
 
void Session::unlink_open_table(Table *find)
 
1641
void unlink_open_table(THD *thd, Table *find, bool unlock)
855
1642
{
856
1643
  char key[MAX_DBKEY_LENGTH];
857
 
  uint32_t key_length= find->getShare()->getCacheKeySize();
 
1644
  uint32_t key_length= find->s->table_cache_key.length;
858
1645
  Table *list, **prev;
859
 
  safe_mutex_assert_owner(LOCK_open.native_handle());
860
 
 
861
 
  memcpy(key, &find->getMutableShare()->getCacheKey()[0], key_length);
 
1646
 
 
1647
  safe_mutex_assert_owner(&LOCK_open);
 
1648
 
 
1649
  memcpy(key, find->s->table_cache_key.str, key_length);
862
1650
  /*
863
1651
    Note that we need to hold LOCK_open while changing the
864
1652
    open_tables list. Another thread may work on it.
866
1654
    Closing a MERGE child before the parent would be fatal if the
867
1655
    other thread tries to abort the MERGE lock in between.
868
1656
  */
869
 
  for (prev= &open_tables; *prev; )
 
1657
  for (prev= &thd->open_tables; *prev; )
870
1658
  {
871
1659
    list= *prev;
872
1660
 
873
 
    if (list->getShare()->getCacheKeySize() == key_length &&
874
 
        not memcmp(&list->getShare()->getCacheKey()[0], key, key_length))
 
1661
    if (list->s->table_cache_key.length == key_length &&
 
1662
        !memcmp(list->s->table_cache_key.str, key, key_length))
875
1663
    {
 
1664
      if (unlock && thd->locked_tables)
 
1665
        mysql_lock_remove(thd, thd->locked_tables, list, true);
 
1666
 
876
1667
      /* Remove table from open_tables list. */
877
 
      *prev= list->getNext();
878
 
 
 
1668
      *prev= list->next;
879
1669
      /* Close table. */
880
 
      remove_table(list);
 
1670
      hash_delete(&open_cache,(unsigned char*) list); // Close table
881
1671
    }
882
1672
    else
883
1673
    {
884
1674
      /* Step to next entry in open_tables list. */
885
 
      prev= list->getNextPtr();
 
1675
      prev= &list->next;
886
1676
    }
887
1677
  }
888
1678
 
889
1679
  // Notify any 'refresh' threads
890
1680
  broadcast_refresh();
 
1681
  return;
891
1682
}
892
1683
 
893
1684
 
894
1685
/**
895
 
  Auxiliary routine which closes and drops open table.
896
 
 
897
 
  @param  session         Thread handle
898
 
  @param  table       Table object for table to be dropped
899
 
  @param  db_name     Name of database for this table
900
 
  @param  table_name  Name of this table
901
 
 
902
 
  @note This routine assumes that table to be closed is open only
903
 
  by calling thread so we needn't wait until other threads
904
 
  will close the table. Also unless called under implicit or
905
 
  explicit LOCK TABLES mode it assumes that table to be
906
 
  dropped is already unlocked. In the former case it will
907
 
  also remove lock on the table. But one should not rely on
908
 
  this behaviour as it may change in future.
909
 
  Currently, however, this function is never called for a
910
 
  table that was locked with LOCK TABLES.
 
1686
    Auxiliary routine which closes and drops open table.
 
1687
 
 
1688
    @param  thd         Thread handle
 
1689
    @param  table       Table object for table to be dropped
 
1690
    @param  db_name     Name of database for this table
 
1691
    @param  table_name  Name of this table
 
1692
 
 
1693
    @note This routine assumes that table to be closed is open only
 
1694
          by calling thread so we needn't wait until other threads
 
1695
          will close the table. Also unless called under implicit or
 
1696
          explicit LOCK TABLES mode it assumes that table to be
 
1697
          dropped is already unlocked. In the former case it will
 
1698
          also remove lock on the table. But one should not rely on
 
1699
          this behaviour as it may change in future.
 
1700
          Currently, however, this function is never called for a
 
1701
          table that was locked with LOCK TABLES.
911
1702
*/
912
1703
 
913
 
void Session::drop_open_table(Table *table, TableIdentifier &identifier)
 
1704
void drop_open_table(THD *thd, Table *table, const char *db_name,
 
1705
                     const char *table_name)
914
1706
{
915
 
  if (table->getShare()->getType())
916
 
  {
917
 
    close_temporary_table(table);
918
 
  }
 
1707
  if (table->s->tmp_table)
 
1708
    close_temporary_table(thd, table, 1, 1);
919
1709
  else
920
1710
  {
921
 
    boost::mutex::scoped_lock scoped_lock(LOCK_open); /* Close and drop a table (AUX routine) */
 
1711
    handlerton *table_type= table->s->db_type();
 
1712
    pthread_mutex_lock(&LOCK_open);
922
1713
    /*
923
1714
      unlink_open_table() also tells threads waiting for refresh or close
924
1715
      that something has happened.
925
1716
    */
926
 
    unlink_open_table(table);
927
 
    quick_rm_table(*this, identifier);
 
1717
    unlink_open_table(thd, table, false);
 
1718
    quick_rm_table(table_type, db_name, table_name, 0);
 
1719
    pthread_mutex_unlock(&LOCK_open);
928
1720
  }
929
1721
}
930
1722
 
931
1723
 
932
1724
/*
933
 
  Wait for condition but allow the user to send a kill to mysqld
 
1725
   Wait for condition but allow the user to send a kill to mysqld
934
1726
 
935
 
  SYNOPSIS
936
 
  wait_for_condition()
937
 
  session       Thread Cursor
938
 
  mutex mutex that is currently hold that is associated with condition
939
 
  Will be unlocked on return
940
 
  cond  Condition to wait for
 
1727
   SYNOPSIS
 
1728
     wait_for_condition()
 
1729
     thd        Thread handler
 
1730
     mutex      mutex that is currently hold that is associated with condition
 
1731
                Will be unlocked on return     
 
1732
     cond       Condition to wait for
941
1733
*/
942
1734
 
943
 
void Session::wait_for_condition(boost::mutex &mutex, boost::condition_variable &cond)
 
1735
void wait_for_condition(THD *thd, pthread_mutex_t *mutex, pthread_cond_t *cond)
944
1736
{
945
1737
  /* Wait until the current table is up to date */
946
 
  const char *saved_proc_info;
947
 
  mysys_var->current_mutex= &mutex;
948
 
  mysys_var->current_cond= &cond;
949
 
  saved_proc_info= get_proc_info();
950
 
  set_proc_info("Waiting for table");
951
 
  if (!killed)
952
 
    (void) pthread_cond_wait(cond.native_handle(), mutex.native_handle());
 
1738
  const char *proc_info;
 
1739
  thd->mysys_var->current_mutex= mutex;
 
1740
  thd->mysys_var->current_cond= cond;
 
1741
  proc_info=thd->get_proc_info();
 
1742
  thd->set_proc_info("Waiting for table");
 
1743
  if (!thd->killed)
 
1744
    (void) pthread_cond_wait(cond, mutex);
953
1745
 
954
1746
  /*
955
1747
    We must unlock mutex first to avoid deadlock becasue conditions are
961
1753
    condition variables that are guranteed to not disapper (freed) even if this
962
1754
    mutex is unlocked
963
1755
  */
964
 
 
965
 
  pthread_mutex_unlock(mutex.native_handle());
966
 
  boost::mutex::scoped_lock (mysys_var->mutex);
967
 
  mysys_var->current_mutex= 0;
968
 
  mysys_var->current_cond= 0;
969
 
  set_proc_info(saved_proc_info);
 
1756
    
 
1757
  pthread_mutex_unlock(mutex);
 
1758
  pthread_mutex_lock(&thd->mysys_var->mutex);
 
1759
  thd->mysys_var->current_mutex= 0;
 
1760
  thd->mysys_var->current_cond= 0;
 
1761
  thd->set_proc_info(proc_info);
 
1762
  pthread_mutex_unlock(&thd->mysys_var->mutex);
 
1763
  return;
 
1764
}
 
1765
 
 
1766
 
 
1767
/**
 
1768
  Exclusively name-lock a table that is already write-locked by the
 
1769
  current thread.
 
1770
 
 
1771
  @param thd current thread context
 
1772
  @param tables table list containing one table to open.
 
1773
 
 
1774
  @return false on success, true otherwise.
 
1775
*/
 
1776
 
 
1777
bool name_lock_locked_table(THD *thd, TableList *tables)
 
1778
{
 
1779
  /* Under LOCK TABLES we must only accept write locked tables. */
 
1780
  tables->table= find_locked_table(thd, tables->db, tables->table_name);
 
1781
 
 
1782
  if (!tables->table)
 
1783
    my_error(ER_TABLE_NOT_LOCKED, MYF(0), tables->alias);
 
1784
  else if (tables->table->reginfo.lock_type < TL_WRITE_LOW_PRIORITY)
 
1785
    my_error(ER_TABLE_NOT_LOCKED_FOR_WRITE, MYF(0), tables->alias);
 
1786
  else
 
1787
  {
 
1788
    /*
 
1789
      Ensures that table is opened only by this thread and that no
 
1790
      other statement will open this table.
 
1791
    */
 
1792
    wait_while_table_is_used(thd, tables->table, HA_EXTRA_FORCE_REOPEN);
 
1793
    return(false);
 
1794
  }
 
1795
 
 
1796
  return(true);
970
1797
}
971
1798
 
972
1799
 
974
1801
  Open table which is already name-locked by this thread.
975
1802
 
976
1803
  SYNOPSIS
977
 
  reopen_name_locked_table()
978
 
  session         Thread handle
979
 
  table_list  TableList object for table to be open, TableList::table
980
 
  member should point to Table object which was used for
981
 
  name-locking.
982
 
  link_in     true  - if Table object for table to be opened should be
983
 
  linked into Session::open_tables list.
984
 
  false - placeholder used for name-locking is already in
985
 
  this list so we only need to preserve Table::next
986
 
  pointer.
 
1804
    reopen_name_locked_table()
 
1805
      thd         Thread handle
 
1806
      table_list  TableList object for table to be open, TableList::table
 
1807
                  member should point to Table object which was used for
 
1808
                  name-locking.
 
1809
      link_in     true  - if Table object for table to be opened should be
 
1810
                          linked into THD::open_tables list.
 
1811
                  false - placeholder used for name-locking is already in
 
1812
                          this list so we only need to preserve Table::next
 
1813
                          pointer.
987
1814
 
988
1815
  NOTE
989
 
  This function assumes that its caller already acquired LOCK_open mutex.
 
1816
    This function assumes that its caller already acquired LOCK_open mutex.
990
1817
 
991
1818
  RETURN VALUE
992
 
  false - Success
993
 
  true  - Error
 
1819
    false - Success
 
1820
    true  - Error
994
1821
*/
995
1822
 
996
 
bool Session::reopen_name_locked_table(TableList* table_list, bool link_in)
 
1823
bool reopen_name_locked_table(THD* thd, TableList* table_list, bool link_in)
997
1824
{
998
1825
  Table *table= table_list->table;
999
 
  TableShare *share;
 
1826
  TABLE_SHARE *share;
1000
1827
  char *table_name= table_list->table_name;
1001
1828
  Table orig_table;
1002
1829
 
1003
 
  safe_mutex_assert_owner(LOCK_open.native_handle());
 
1830
  safe_mutex_assert_owner(&LOCK_open);
1004
1831
 
1005
 
  if (killed || !table)
1006
 
    return true;
 
1832
  if (thd->killed || !table)
 
1833
    return(true);
1007
1834
 
1008
1835
  orig_table= *table;
1009
1836
 
1010
 
  TableIdentifier identifier(table_list->db, table_list->table_name);
1011
 
  if (open_unireg_entry(this, table, table_name, identifier))
 
1837
  if (open_unireg_entry(thd, table, table_list, table_name,
 
1838
                        table->s->table_cache_key.str,
 
1839
                        table->s->table_cache_key.length))
1012
1840
  {
1013
 
    table->intern_close_table();
 
1841
    intern_close_table(table);
1014
1842
    /*
1015
1843
      If there was an error during opening of table (for example if it
1016
1844
      does not exist) '*table' object can be wiped out. To be able
1018
1846
      object to its original state.
1019
1847
    */
1020
1848
    *table= orig_table;
1021
 
    return true;
 
1849
    return(true);
1022
1850
  }
1023
1851
 
1024
 
  share= table->getMutableShare();
 
1852
  share= table->s;
1025
1853
  /*
1026
1854
    We want to prevent other connections from opening this table until end
1027
1855
    of statement as it is likely that modifications of table's metadata are
1028
 
    not yet finished (for example CREATE TRIGGER have to change .TRG cursor,
 
1856
    not yet finished (for example CREATE TRIGGER have to change .TRG file,
1029
1857
    or we might want to drop table if CREATE TABLE ... SELECT fails).
1030
1858
    This also allows us to assume that no other connection will sneak in
1031
1859
    before we will get table-level lock on this table.
1032
1860
  */
1033
 
  share->resetVersion();
1034
 
  table->in_use = this;
 
1861
  share->version=0;
 
1862
  table->in_use = thd;
1035
1863
 
1036
1864
  if (link_in)
1037
1865
  {
1038
 
    table->setNext(open_tables);
1039
 
    open_tables= table;
 
1866
    table->next= thd->open_tables;
 
1867
    thd->open_tables= table;
1040
1868
  }
1041
1869
  else
1042
1870
  {
1043
1871
    /*
1044
 
      Table object should be already in Session::open_tables list so we just
 
1872
      Table object should be already in THD::open_tables list so we just
1045
1873
      need to set Table::next correctly.
1046
1874
    */
1047
 
    table->setNext(orig_table.getNext());
 
1875
    table->next= orig_table.next;
1048
1876
  }
1049
1877
 
1050
 
  table->tablenr= current_tablenr++;
1051
 
  table->used_fields= 0;
1052
 
  table->const_table= 0;
 
1878
  table->tablenr=thd->current_tablenr++;
 
1879
  table->used_fields=0;
 
1880
  table->const_table=0;
1053
1881
  table->null_row= false;
1054
1882
  table->maybe_null= false;
1055
1883
  table->force_index= false;
1056
 
  table->status= STATUS_NO_RECORD;
1057
 
 
 
1884
  table->status=STATUS_NO_RECORD;
1058
1885
  return false;
1059
1886
}
1060
1887
 
1061
1888
 
1062
1889
/**
1063
 
  Create and insert into table cache placeholder for table
1064
 
  which will prevent its opening (or creation) (a.k.a lock
1065
 
  table name).
1066
 
 
1067
 
  @param session         Thread context
1068
 
  @param key         Table cache key for name to be locked
1069
 
  @param key_length  Table cache key length
1070
 
 
1071
 
  @return Pointer to Table object used for name locking or 0 in
1072
 
  case of failure.
 
1890
    Create and insert into table cache placeholder for table
 
1891
    which will prevent its opening (or creation) (a.k.a lock
 
1892
    table name).
 
1893
 
 
1894
    @param thd         Thread context
 
1895
    @param key         Table cache key for name to be locked
 
1896
    @param key_length  Table cache key length
 
1897
 
 
1898
    @return Pointer to Table object used for name locking or 0 in
 
1899
            case of failure.
1073
1900
*/
1074
1901
 
1075
 
Table *Session::table_cache_insert_placeholder(const char *db_name, const char *table_name)
 
1902
Table *table_cache_insert_placeholder(THD *thd, const char *key,
 
1903
                                      uint32_t key_length)
1076
1904
{
1077
 
  safe_mutex_assert_owner(LOCK_open.native_handle());
 
1905
  Table *table;
 
1906
  TABLE_SHARE *share;
 
1907
  char *key_buff;
 
1908
 
 
1909
  safe_mutex_assert_owner(&LOCK_open);
1078
1910
 
1079
1911
  /*
1080
1912
    Create a table entry with the right key and with an old refresh version
 
1913
    Note that we must use my_multi_malloc() here as this is freed by the
 
1914
    table cache
1081
1915
  */
1082
 
  TableIdentifier identifier(db_name, table_name, message::Table::INTERNAL);
1083
 
  TablePlaceholder *table= new TablePlaceholder(this, identifier);
1084
 
 
1085
 
  if (not add_table(table))
 
1916
  if (!my_multi_malloc(MYF(MY_WME | MY_ZEROFILL),
 
1917
                       &table, sizeof(*table),
 
1918
                       &share, sizeof(*share),
 
1919
                       &key_buff, key_length,
 
1920
                       NULL))
 
1921
    return(NULL);
 
1922
 
 
1923
  table->s= share;
 
1924
  share->set_table_cache_key(key_buff, key, key_length);
 
1925
  share->tmp_table= INTERNAL_TMP_TABLE;  // for intern_close_table
 
1926
  table->in_use= thd;
 
1927
  table->locked_by_name=1;
 
1928
 
 
1929
  if (my_hash_insert(&open_cache, (unsigned char*)table))
1086
1930
  {
1087
 
    delete table;
1088
 
 
1089
 
    return NULL;
 
1931
    free((unsigned char*) table);
 
1932
    return(NULL);
1090
1933
  }
1091
1934
 
1092
 
  return table;
 
1935
  return(table);
1093
1936
}
1094
1937
 
1095
1938
 
1096
1939
/**
1097
 
  Obtain an exclusive name lock on the table if it is not cached
1098
 
  in the table cache.
1099
 
 
1100
 
  @param      session         Thread context
1101
 
  @param      db          Name of database
1102
 
  @param      table_name  Name of table
1103
 
  @param[out] table       Out parameter which is either:
1104
 
  - set to NULL if table cache contains record for
1105
 
  the table or
1106
 
  - set to point to the Table instance used for
1107
 
  name-locking.
1108
 
 
1109
 
  @note This function takes into account all records for table in table
1110
 
  cache, even placeholders used for name-locking. This means that
1111
 
  'table' parameter can be set to NULL for some situations when
1112
 
  table does not really exist.
1113
 
 
1114
 
  @retval  true   Error occured (OOM)
1115
 
  @retval  false  Success. 'table' parameter set according to above rules.
 
1940
    Obtain an exclusive name lock on the table if it is not cached
 
1941
    in the table cache.
 
1942
 
 
1943
    @param      thd         Thread context
 
1944
    @param      db          Name of database
 
1945
    @param      table_name  Name of table
 
1946
    @param[out] table       Out parameter which is either:
 
1947
                            - set to NULL if table cache contains record for
 
1948
                              the table or
 
1949
                            - set to point to the Table instance used for
 
1950
                              name-locking.
 
1951
 
 
1952
    @note This function takes into account all records for table in table
 
1953
          cache, even placeholders used for name-locking. This means that
 
1954
          'table' parameter can be set to NULL for some situations when
 
1955
          table does not really exist.
 
1956
 
 
1957
    @retval  true   Error occured (OOM)
 
1958
    @retval  false  Success. 'table' parameter set according to above rules.
1116
1959
*/
1117
 
bool Session::lock_table_name_if_not_cached(TableIdentifier &identifier, Table **table)
 
1960
 
 
1961
bool lock_table_name_if_not_cached(THD *thd, const char *db,
 
1962
                                   const char *table_name, Table **table)
1118
1963
{
1119
 
  const TableIdentifier::Key &key(identifier.getKey());
1120
 
 
1121
 
  boost::mutex::scoped_lock scope_lock(LOCK_open); /* Obtain a name lock even though table is not in cache (like for create table)  */
1122
 
 
1123
 
  TableOpenCache::iterator iter;
1124
 
 
1125
 
  iter= get_open_cache().find(key);
1126
 
 
1127
 
  if (iter != get_open_cache().end())
 
1964
  char key[MAX_DBKEY_LENGTH];
 
1965
  uint32_t key_length;
 
1966
 
 
1967
  key_length= (uint)(my_stpcpy(my_stpcpy(key, db) + 1, table_name) - key) + 1;
 
1968
  pthread_mutex_lock(&LOCK_open);
 
1969
 
 
1970
  if (hash_search(&open_cache, (unsigned char *)key, key_length))
1128
1971
  {
 
1972
    pthread_mutex_unlock(&LOCK_open);
1129
1973
    *table= 0;
1130
 
    return false;
1131
 
  }
1132
 
 
1133
 
  if (not (*table= table_cache_insert_placeholder(identifier.getSchemaName().c_str(), identifier.getTableName().c_str())))
1134
 
  {
1135
 
    return true;
1136
 
  }
1137
 
  (*table)->open_placeholder= true;
1138
 
  (*table)->setNext(open_tables);
1139
 
  open_tables= *table;
1140
 
 
1141
 
  return false;
1142
 
}
 
1974
    return(false);
 
1975
  }
 
1976
  if (!(*table= table_cache_insert_placeholder(thd, key, key_length)))
 
1977
  {
 
1978
    pthread_mutex_unlock(&LOCK_open);
 
1979
    return(true);
 
1980
  }
 
1981
  (*table)->open_placeholder= 1;
 
1982
  (*table)->next= thd->open_tables;
 
1983
  thd->open_tables= *table;
 
1984
  pthread_mutex_unlock(&LOCK_open);
 
1985
  return(false);
 
1986
}
 
1987
 
 
1988
 
 
1989
/**
 
1990
    Check that table exists in table definition cache, on disk
 
1991
    or in some storage engine.
 
1992
 
 
1993
    @param       thd     Thread context
 
1994
    @param       table   Table list element
 
1995
    @param[out]  exists  Out parameter which is set to true if table
 
1996
                         exists and to false otherwise.
 
1997
 
 
1998
    @note This function assumes that caller owns LOCK_open mutex.
 
1999
          It also assumes that the fact that there are no name-locks
 
2000
          on the table was checked beforehand.
 
2001
 
 
2002
    @note If there is no .FRM file for the table but it exists in one
 
2003
          of engines (e.g. it was created on another node of NDB cluster)
 
2004
          this function will fetch and create proper .FRM file for it.
 
2005
 
 
2006
    @retval  true   Some error occured
 
2007
    @retval  false  No error. 'exists' out parameter set accordingly.
 
2008
*/
 
2009
 
 
2010
bool check_if_table_exists(THD *thd, TableList *table, bool *exists)
 
2011
{
 
2012
  char path[FN_REFLEN];
 
2013
  int rc;
 
2014
 
 
2015
  safe_mutex_assert_owner(&LOCK_open);
 
2016
 
 
2017
  *exists= true;
 
2018
 
 
2019
  if (get_cached_table_share(table->db, table->table_name))
 
2020
    return(false);
 
2021
 
 
2022
  build_table_filename(path, sizeof(path) - 1, table->db, table->table_name,
 
2023
                       reg_ext, 0);
 
2024
 
 
2025
  if (!access(path, F_OK))
 
2026
    return(false);
 
2027
 
 
2028
  /* .FRM file doesn't exist. Check if some engine can provide it. */
 
2029
 
 
2030
  rc= ha_create_table_from_engine(thd, table->db, table->table_name);
 
2031
 
 
2032
  if (rc < 0)
 
2033
  {
 
2034
    /* Table does not exists in engines as well. */
 
2035
    *exists= false;
 
2036
    return(false);
 
2037
  }
 
2038
  else if (!rc)
 
2039
  {
 
2040
    /* Table exists in some engine and .FRM for it was created. */
 
2041
    return(false);
 
2042
  }
 
2043
  else /* (rc > 0) */
 
2044
  {
 
2045
    my_printf_error(ER_UNKNOWN_ERROR, "Failed to open '%-.64s', error while "
 
2046
                    "unpacking from engine", MYF(0), table->table_name);
 
2047
    return(true);
 
2048
  }
 
2049
}
 
2050
 
1143
2051
 
1144
2052
/*
1145
2053
  Open a table.
1146
2054
 
1147
2055
  SYNOPSIS
1148
 
  open_table()
1149
 
  session                 Thread context.
1150
 
  table_list          Open first table in list.
1151
 
  refresh      INOUT  Pointer to memory that will be set to 1 if
1152
 
  we need to close all tables and reopen them.
1153
 
  If this is a NULL pointer, then the table is not
1154
 
  put in the thread-open-list.
1155
 
  flags               Bitmap of flags to modify how open works:
1156
 
  DRIZZLE_LOCK_IGNORE_FLUSH - Open table even if
1157
 
  someone has done a flush or namelock on it.
1158
 
  No version number checking is done.
1159
 
  DRIZZLE_OPEN_TEMPORARY_ONLY - Open only temporary
1160
 
  table not the base table or view.
 
2056
    open_table()
 
2057
    thd                 Thread context.
 
2058
    table_list          Open first table in list.
 
2059
    refresh      INOUT  Pointer to memory that will be set to 1 if
 
2060
                        we need to close all tables and reopen them.
 
2061
                        If this is a NULL pointer, then the table is not
 
2062
                        put in the thread-open-list.
 
2063
    flags               Bitmap of flags to modify how open works:
 
2064
                          DRIZZLE_LOCK_IGNORE_FLUSH - Open table even if
 
2065
                          someone has done a flush or namelock on it.
 
2066
                          No version number checking is done.
 
2067
                          DRIZZLE_OPEN_TEMPORARY_ONLY - Open only temporary
 
2068
                          table not the base table or view.
1161
2069
 
1162
2070
  IMPLEMENTATION
1163
 
  Uses a cache of open tables to find a table not in use.
 
2071
    Uses a cache of open tables to find a table not in use.
1164
2072
 
1165
 
  If table list element for the table to be opened has "create" flag
1166
 
  set and table does not exist, this function will automatically insert
1167
 
  a placeholder for exclusive name lock into the open tables cache and
1168
 
  will return the Table instance that corresponds to this placeholder.
 
2073
    If table list element for the table to be opened has "create" flag
 
2074
    set and table does not exist, this function will automatically insert
 
2075
    a placeholder for exclusive name lock into the open tables cache and
 
2076
    will return the Table instance that corresponds to this placeholder.
1169
2077
 
1170
2078
  RETURN
1171
 
  NULL  Open failed.  If refresh is set then one should close
1172
 
  all other tables and retry the open.
1173
 
#     Success. Pointer to Table object for open table.
 
2079
    NULL  Open failed.  If refresh is set then one should close
 
2080
          all other tables and retry the open.
 
2081
    #     Success. Pointer to Table object for open table.
1174
2082
*/
1175
2083
 
1176
2084
 
1177
 
Table *Session::openTable(TableList *table_list, bool *refresh, uint32_t flags)
 
2085
Table *open_table(THD *thd, TableList *table_list, bool *refresh, uint32_t flags)
1178
2086
{
1179
 
  Table *table;
1180
 
  const char *alias= table_list->alias;
 
2087
  register Table *table;
 
2088
  char key[MAX_DBKEY_LENGTH];
 
2089
  unsigned int key_length;
 
2090
  char *alias= table_list->alias;
 
2091
  HASH_SEARCH_STATE state;
1181
2092
 
1182
 
  /* Parsing of partitioning information from .frm needs session->lex set up. */
1183
 
  assert(lex->is_lex_started);
 
2093
  /* Parsing of partitioning information from .frm needs thd->lex set up. */
 
2094
  assert(thd->lex->is_lex_started);
1184
2095
 
1185
2096
  /* find a unused table in the open table cache */
1186
2097
  if (refresh)
1187
 
    *refresh= false;
 
2098
    *refresh=0;
1188
2099
 
1189
2100
  /* an open table operation needs a lot of the stack space */
1190
 
  if (check_stack_overrun(this, STACK_MIN_SIZE_FOR_OPEN, (unsigned char *)&alias))
1191
 
    return NULL;
1192
 
 
1193
 
  if (killed)
1194
 
    return NULL;
1195
 
 
1196
 
  TableIdentifier identifier(table_list->db, table_list->table_name);
1197
 
  const TableIdentifier::Key &key(identifier.getKey());
1198
 
  TableOpenCacheRange ppp;
 
2101
  if (check_stack_overrun(thd, STACK_MIN_SIZE_FOR_OPEN, (unsigned char *)&alias))
 
2102
    return(0);
 
2103
 
 
2104
  if (thd->killed)
 
2105
    return(0);
 
2106
 
 
2107
  key_length= (create_table_def_key(thd, key, table_list, 1) -
 
2108
               TMP_TABLE_KEY_EXTRA);
1199
2109
 
1200
2110
  /*
1201
2111
    Unless requested otherwise, try to resolve this table in the list
1202
2112
    of temporary tables of this thread. In MySQL temporary tables
1203
2113
    are always thread-local and "shadow" possible base tables with the
1204
2114
    same name. This block implements the behaviour.
1205
 
    TODO -> move this block into a separate function.
 
2115
    TODO: move this block into a separate function.
1206
2116
  */
1207
 
  for (table= temporary_tables; table ; table=table->getNext())
1208
2117
  {
1209
 
    if (table->getShare()->getCacheKey() == key)
 
2118
    for (table= thd->temporary_tables; table ; table=table->next)
1210
2119
    {
1211
 
      /*
1212
 
        We're trying to use the same temporary table twice in a query.
1213
 
        Right now we don't support this because a temporary table
1214
 
        is always represented by only one Table object in Session, and
1215
 
        it can not be cloned. Emit an error for an unsupported behaviour.
1216
 
      */
1217
 
      if (table->query_id)
 
2120
      if (table->s->table_cache_key.length == key_length +
 
2121
          TMP_TABLE_KEY_EXTRA &&
 
2122
          !memcmp(table->s->table_cache_key.str, key,
 
2123
                  key_length + TMP_TABLE_KEY_EXTRA))
1218
2124
      {
1219
 
        my_error(ER_CANT_REOPEN_TABLE, MYF(0), table->getAlias());
1220
 
        return NULL;
 
2125
        /*
 
2126
          We're trying to use the same temporary table twice in a query.
 
2127
          Right now we don't support this because a temporary table
 
2128
          is always represented by only one Table object in THD, and
 
2129
          it can not be cloned. Emit an error for an unsupported behaviour.
 
2130
        */
 
2131
        if (table->query_id)
 
2132
        {
 
2133
          my_error(ER_CANT_REOPEN_TABLE, MYF(0), table->alias);
 
2134
          return(0);
 
2135
        }
 
2136
        table->query_id= thd->query_id;
 
2137
        thd->thread_specific_used= true;
 
2138
        goto reset;
1221
2139
      }
1222
 
      table->query_id= getQueryId();
1223
 
      goto reset;
1224
2140
    }
1225
2141
  }
1226
2142
 
1227
2143
  if (flags & DRIZZLE_OPEN_TEMPORARY_ONLY)
1228
2144
  {
1229
2145
    my_error(ER_NO_SUCH_TABLE, MYF(0), table_list->db, table_list->table_name);
1230
 
    return NULL;
1231
 
  }
1232
 
 
1233
 
  /*
1234
 
    If it's the first table from a list of tables used in a query,
1235
 
    remember refresh_version (the version of open_cache state).
1236
 
    If the version changes while we're opening the remaining tables,
1237
 
    we will have to back off, close all the tables opened-so-far,
1238
 
    and try to reopen them.
1239
 
 
1240
 
    Note-> refresh_version is currently changed only during FLUSH TABLES.
1241
 
  */
1242
 
  if (!open_tables)
1243
 
  {
1244
 
    version= refresh_version;
1245
 
  }
1246
 
  else if ((version != refresh_version) &&
1247
 
           ! (flags & DRIZZLE_LOCK_IGNORE_FLUSH))
1248
 
  {
1249
 
    /* Someone did a refresh while thread was opening tables */
1250
 
    if (refresh)
1251
 
      *refresh= true;
1252
 
 
1253
 
    return NULL;
1254
 
  }
1255
 
 
1256
 
  /*
1257
 
    Before we test the global cache, we test our local session cache.
1258
 
  */
1259
 
  if (cached_table)
1260
 
  {
1261
 
    assert(false); /* Not implemented yet */
 
2146
    return(0);
 
2147
  }
 
2148
 
 
2149
  /*
 
2150
    The table is not temporary - if we're in pre-locked or LOCK TABLES
 
2151
    mode, let's try to find the requested table in the list of pre-opened
 
2152
    and locked tables. If the table is not there, return an error - we can't
 
2153
    open not pre-opened tables in pre-locked/LOCK TABLES mode.
 
2154
    TODO: move this block into a separate function.
 
2155
  */
 
2156
  if (thd->locked_tables)
 
2157
  {                                             // Using table locks
 
2158
    Table *best_table= 0;
 
2159
    int best_distance= INT_MIN;
 
2160
    bool check_if_used= false;
 
2161
    for (table=thd->open_tables; table ; table=table->next)
 
2162
    {
 
2163
      if (table->s->table_cache_key.length == key_length &&
 
2164
          !memcmp(table->s->table_cache_key.str, key, key_length))
 
2165
      {
 
2166
        if (check_if_used && table->query_id &&
 
2167
            table->query_id != thd->query_id)
 
2168
        {
 
2169
          /*
 
2170
            If we are in stored function or trigger we should ensure that
 
2171
            we won't change table that is already used by calling statement.
 
2172
            So if we are opening table for writing, we should check that it
 
2173
            is not already open by some calling stamement.
 
2174
          */
 
2175
          my_error(ER_CANT_UPDATE_USED_TABLE_IN_SF_OR_TRG, MYF(0),
 
2176
                   table->s->table_name.str);
 
2177
          return(0);
 
2178
        }
 
2179
        /*
 
2180
          When looking for a usable Table, ignore MERGE children, as they
 
2181
          belong to their parent and cannot be used explicitly.
 
2182
        */
 
2183
        if (!my_strcasecmp(system_charset_info, table->alias, alias) &&
 
2184
            table->query_id != thd->query_id)  /* skip tables already used */
 
2185
        {
 
2186
          int distance= ((int) table->reginfo.lock_type -
 
2187
                         (int) table_list->lock_type);
 
2188
          /*
 
2189
            Find a table that either has the exact lock type requested,
 
2190
            or has the best suitable lock. In case there is no locked
 
2191
            table that has an equal or higher lock than requested,
 
2192
            we us the closest matching lock to be able to produce an error
 
2193
            message about wrong lock mode on the table. The best_table
 
2194
            is changed if bd < 0 <= d or bd < d < 0 or 0 <= d < bd.
 
2195
 
 
2196
            distance <  0 - No suitable lock found
 
2197
            distance >  0 - we have lock mode higher then we require
 
2198
            distance == 0 - we have lock mode exactly which we need
 
2199
          */
 
2200
          if ((best_distance < 0 && distance > best_distance) || (distance >= 0 && distance < best_distance))
 
2201
          {
 
2202
            best_distance= distance;
 
2203
            best_table= table;
 
2204
            if (best_distance == 0 && !check_if_used)
 
2205
            {
 
2206
              /*
 
2207
                If we have found perfect match and we don't need to check that
 
2208
                table is not used by one of calling statements (assuming that
 
2209
                we are inside of function or trigger) we can finish iterating
 
2210
                through open tables list.
 
2211
              */
 
2212
              break;
 
2213
            }
 
2214
          }
 
2215
        }
 
2216
      }
 
2217
    }
 
2218
    if (best_table)
 
2219
    {
 
2220
      table= best_table;
 
2221
      table->query_id= thd->query_id;
 
2222
      goto reset;
 
2223
    }
 
2224
    /*
 
2225
      No table in the locked tables list. In case of explicit LOCK TABLES
 
2226
      this can happen if a user did not include the able into the list.
 
2227
      In case of pre-locked mode locked tables list is generated automatically,
 
2228
      so we may only end up here if the table did not exist when
 
2229
      locked tables list was created.
 
2230
    */
 
2231
    my_error(ER_TABLE_NOT_LOCKED, MYF(0), alias);
 
2232
    return(0);
1262
2233
  }
1263
2234
 
1264
2235
  /*
1267
2238
    Now we should:
1268
2239
    - try to find the table in the table cache.
1269
2240
    - if one of the discovered Table instances is name-locked
1270
 
    (table->getShare()->version == 0) back off -- we have to wait
1271
 
    until no one holds a name lock on the table.
 
2241
      (table->s->version == 0) or some thread has started FLUSH TABLES
 
2242
      (refresh_version > table->s->version), back off -- we have to wait
 
2243
      until no one holds a name lock on the table.
1272
2244
    - if there is no such Table in the name cache, read the table definition
1273
2245
    and insert it into the cache.
1274
2246
    We perform all of the above under LOCK_open which currently protects
1276
2248
    on disk.
1277
2249
  */
1278
2250
 
1279
 
  LOCK_open.lock(); /* Lock for FLUSH TABLES for open table */
 
2251
  pthread_mutex_lock(&LOCK_open);
 
2252
 
 
2253
  /*
 
2254
    If it's the first table from a list of tables used in a query,
 
2255
    remember refresh_version (the version of open_cache state).
 
2256
    If the version changes while we're opening the remaining tables,
 
2257
    we will have to back off, close all the tables opened-so-far,
 
2258
    and try to reopen them.
 
2259
    Note: refresh_version is currently changed only during FLUSH TABLES.
 
2260
  */
 
2261
  if (!thd->open_tables)
 
2262
    thd->version=refresh_version;
 
2263
  else if ((thd->version != refresh_version) &&
 
2264
           ! (flags & DRIZZLE_LOCK_IGNORE_FLUSH))
 
2265
  {
 
2266
    /* Someone did a refresh while thread was opening tables */
 
2267
    if (refresh)
 
2268
      *refresh=1;
 
2269
    pthread_mutex_unlock(&LOCK_open);
 
2270
    return(0);
 
2271
  }
 
2272
 
 
2273
  /*
 
2274
    In order for the back off and re-start process to work properly,
 
2275
    handler tables having old versions (due to FLUSH TABLES or pending
 
2276
    name-lock) MUST be closed. This is specially important if a name-lock
 
2277
    is pending for any table of the handler_tables list, otherwise a
 
2278
    deadlock may occur.
 
2279
  */
 
2280
  if (thd->handler_tables)
 
2281
    mysql_ha_flush(thd);
1280
2282
 
1281
2283
  /*
1282
2284
    Actually try to find the table in the open_cache.
1288
2290
    an implicit "pending locks queue" - see
1289
2291
    wait_for_locked_table_names for details.
1290
2292
  */
1291
 
  ppp= get_open_cache().equal_range(key);
1292
 
 
1293
 
  table= NULL;
1294
 
  for (TableOpenCache::const_iterator iter= ppp.first;
1295
 
       iter != ppp.second; ++iter, table= NULL)
 
2293
  for (table= (Table*) hash_first(&open_cache, (unsigned char*) key, key_length,
 
2294
                                  &state);
 
2295
       table && table->in_use ;
 
2296
       table= (Table*) hash_next(&open_cache, (unsigned char*) key, key_length,
 
2297
                                 &state))
1296
2298
  {
1297
 
    table= (*iter).second;
1298
 
 
1299
 
    if (not table->in_use)
1300
 
      break;
1301
2299
    /*
1302
2300
      Here we flush tables marked for flush.
1303
 
      Normally, table->getShare()->version contains the value of
 
2301
      Normally, table->s->version contains the value of
1304
2302
      refresh_version from the moment when this table was
1305
2303
      (re-)opened and added to the cache.
1306
2304
      If since then we did (or just started) FLUSH TABLES
1307
2305
      statement, refresh_version has been increased.
1308
 
      For "name-locked" Table instances, table->getShare()->version is set
 
2306
      For "name-locked" Table instances, table->s->version is set
1309
2307
      to 0 (see lock_table_name for details).
1310
2308
      In case there is a pending FLUSH TABLES or a name lock, we
1311
2309
      need to back off and re-start opening tables.
1312
2310
      If we do not back off now, we may dead lock in case of lock
1313
2311
      order mismatch with some other thread:
1314
 
      c1-> name lock t1; -- sort of exclusive lock
1315
 
      c2-> open t2;      -- sort of shared lock
1316
 
      c1-> name lock t2; -- blocks
1317
 
      c2-> open t1; -- blocks
 
2312
      c1: name lock t1; -- sort of exclusive lock 
 
2313
      c2: open t2;      -- sort of shared lock
 
2314
      c1: name lock t2; -- blocks
 
2315
      c2: open t1; -- blocks
1318
2316
    */
1319
2317
    if (table->needs_reopen_or_name_lock())
1320
2318
    {
1321
2319
      if (flags & DRIZZLE_LOCK_IGNORE_FLUSH)
1322
2320
      {
1323
2321
        /* Force close at once after usage */
1324
 
        version= table->getShare()->getVersion();
 
2322
        thd->version= table->s->version;
1325
2323
        continue;
1326
2324
      }
1327
2325
 
1328
2326
      /* Avoid self-deadlocks by detecting self-dependencies. */
1329
 
      if (table->open_placeholder && table->in_use == this)
 
2327
      if (table->open_placeholder && table->in_use == thd)
1330
2328
      {
1331
 
        LOCK_open.unlock();
1332
 
        my_error(ER_UPDATE_TABLE_USED, MYF(0), table->getMutableShare()->getTableName());
1333
 
        return NULL;
 
2329
        pthread_mutex_unlock(&LOCK_open);
 
2330
        my_error(ER_UPDATE_TABLE_USED, MYF(0), table->s->table_name.str);
 
2331
        return(0);
1334
2332
      }
1335
2333
 
1336
2334
      /*
1337
2335
        Back off, part 1: mark the table as "unused" for the
1338
2336
        purpose of name-locking by setting table->db_stat to 0. Do
1339
2337
        that only for the tables in this thread that have an old
1340
 
        table->getShare()->version (this is an optimization (?)).
 
2338
        table->s->version (this is an optimization (?)).
1341
2339
        table->db_stat == 0 signals wait_for_locked_table_names
1342
2340
        that the tables in question are not used any more. See
1343
2341
        table_is_used call for details.
 
2342
 
 
2343
        Notice that HANDLER tables were already taken care of by
 
2344
        the earlier call to mysql_ha_flush() in this same critical
 
2345
        section.
1344
2346
      */
1345
 
      close_old_data_files(false, false);
1346
 
 
 
2347
      close_old_data_files(thd,thd->open_tables,0,0);
1347
2348
      /*
1348
2349
        Back-off part 2: try to avoid "busy waiting" on the table:
1349
2350
        if the table is in use by some other thread, we suspend
1350
2351
        and wait till the operation is complete: when any
1351
 
        operation that juggles with table->getShare()->version completes,
 
2352
        operation that juggles with table->s->version completes,
1352
2353
        it broadcasts COND_refresh condition variable.
1353
2354
        If 'old' table we met is in use by current thread we return
1354
2355
        without waiting since in this situation it's this thread
1355
2356
        which is responsible for broadcasting on COND_refresh
1356
 
        (and this was done already in Session::close_old_data_files()).
 
2357
        (and this was done already in close_old_data_files()).
1357
2358
        Good example of such situation is when we have statement
1358
2359
        that needs two instances of table and FLUSH TABLES comes
1359
2360
        after we open first instance but before we open second
1360
2361
        instance.
1361
2362
      */
1362
 
      if (table->in_use != this)
 
2363
      if (table->in_use != thd)
1363
2364
      {
1364
2365
        /* wait_for_conditionwill unlock LOCK_open for us */
1365
 
        wait_for_condition(LOCK_open, COND_refresh);
 
2366
        wait_for_condition(thd, &LOCK_open, &COND_refresh);
1366
2367
      }
1367
2368
      else
1368
2369
      {
1369
 
        LOCK_open.unlock();
 
2370
        pthread_mutex_unlock(&LOCK_open);
1370
2371
      }
1371
2372
      /*
1372
2373
        There is a refresh in progress for this table.
1373
2374
        Signal the caller that it has to try again.
1374
2375
      */
1375
2376
      if (refresh)
1376
 
        *refresh= true;
1377
 
      return NULL;
 
2377
        *refresh=1;
 
2378
      return(0);
1378
2379
    }
1379
2380
  }
1380
2381
  if (table)
1381
2382
  {
1382
 
    unused_tables.unlink(table);
1383
 
    table->in_use= this;
 
2383
    /* Unlink the table from "unused_tables" list. */
 
2384
    if (table == unused_tables)
 
2385
    {                                           // First unused
 
2386
      unused_tables=unused_tables->next;        // Remove from link
 
2387
      if (table == unused_tables)
 
2388
        unused_tables=0;
 
2389
    }
 
2390
    table->prev->next=table->next;              /* Remove from unused list */
 
2391
    table->next->prev=table->prev;
 
2392
    table->in_use= thd;
1384
2393
  }
1385
2394
  else
1386
2395
  {
1387
2396
    /* Insert a new Table instance into the open cache */
1388
2397
    int error;
1389
2398
    /* Free cache if too big */
1390
 
    unused_tables.cull();
 
2399
    while (open_cache.records > table_cache_size && unused_tables)
 
2400
      hash_delete(&open_cache,(unsigned char*) unused_tables); /* purecov: tested */
1391
2401
 
1392
 
    if (table_list->isCreate())
 
2402
    if (table_list->create)
1393
2403
    {
1394
 
      TableIdentifier  lock_table_identifier(table_list->db, table_list->table_name, message::Table::STANDARD);
1395
 
 
1396
 
      if (not plugin::StorageEngine::doesTableExist(*this, lock_table_identifier))
 
2404
      bool exists;
 
2405
 
 
2406
      if (check_if_table_exists(thd, table_list, &exists))
 
2407
      {
 
2408
        pthread_mutex_unlock(&LOCK_open);
 
2409
        return(NULL);
 
2410
      }
 
2411
 
 
2412
      if (!exists)
1397
2413
      {
1398
2414
        /*
1399
2415
          Table to be created, so we need to create placeholder in table-cache.
1400
2416
        */
1401
 
        if (!(table= table_cache_insert_placeholder(table_list->db, table_list->table_name)))
 
2417
        if (!(table= table_cache_insert_placeholder(thd, key, key_length)))
1402
2418
        {
1403
 
          LOCK_open.unlock();
1404
 
          return NULL;
 
2419
          pthread_mutex_unlock(&LOCK_open);
 
2420
          return(NULL);
1405
2421
        }
1406
2422
        /*
1407
2423
          Link placeholder to the open tables list so it will be automatically
1408
2424
          removed once tables are closed. Also mark it so it won't be ignored
1409
2425
          by other trying to take name-lock.
1410
2426
        */
1411
 
        table->open_placeholder= true;
1412
 
        table->setNext(open_tables);
1413
 
        open_tables= table;
1414
 
        LOCK_open.unlock();
1415
 
 
1416
 
        return table ;
 
2427
        table->open_placeholder= 1;
 
2428
        table->next= thd->open_tables;
 
2429
        thd->open_tables= table;
 
2430
        pthread_mutex_unlock(&LOCK_open);
 
2431
        return(table);
1417
2432
      }
1418
2433
      /* Table exists. Let us try to open it. */
1419
2434
    }
1420
2435
 
1421
2436
    /* make a new table */
1422
 
    table= new Table;
1423
 
    if (table == NULL)
 
2437
    if (!(table=(Table*) my_malloc(sizeof(*table),MYF(MY_WME))))
1424
2438
    {
1425
 
      LOCK_open.unlock();
1426
 
      return NULL;
 
2439
      pthread_mutex_unlock(&LOCK_open);
 
2440
      return(NULL);
1427
2441
    }
1428
2442
 
1429
 
    error= open_unireg_entry(this, table, alias, identifier);
1430
 
    if (error != 0)
1431
 
    {
1432
 
      delete table;
1433
 
      LOCK_open.unlock();
1434
 
      return NULL;
1435
 
    }
1436
 
    (void)add_table(table);
 
2443
    error= open_unireg_entry(thd, table, table_list, alias, key, key_length);
 
2444
    /* Combine the follow two */
 
2445
    if (error > 0)
 
2446
    {
 
2447
      free((unsigned char*)table);
 
2448
      pthread_mutex_unlock(&LOCK_open);
 
2449
      return(NULL);
 
2450
    }
 
2451
    if (error < 0)
 
2452
    {
 
2453
      free((unsigned char*)table);
 
2454
      pthread_mutex_unlock(&LOCK_open);
 
2455
      return(0); // VIEW
 
2456
    }
 
2457
    my_hash_insert(&open_cache,(unsigned char*) table);
1437
2458
  }
1438
2459
 
1439
 
  LOCK_open.unlock();
 
2460
  pthread_mutex_unlock(&LOCK_open);
1440
2461
  if (refresh)
1441
2462
  {
1442
 
    table->setNext(open_tables); /* Link into simple list */
1443
 
    open_tables= table;
 
2463
    table->next=thd->open_tables;               /* Link into simple list */
 
2464
    thd->open_tables=table;
1444
2465
  }
1445
 
  table->reginfo.lock_type= TL_READ; /* Assume read */
1446
 
 
1447
 
reset:
1448
 
  assert(table->getShare()->getTableCount() > 0 || table->getShare()->getType() != message::Table::STANDARD);
1449
 
 
1450
 
  if (lex->need_correct_ident())
 
2466
  table->reginfo.lock_type=TL_READ;             /* Assume read */
 
2467
 
 
2468
 reset:
 
2469
  assert(table->s->ref_count > 0 || table->s->tmp_table != NO_TMP_TABLE);
 
2470
 
 
2471
  if (thd->lex->need_correct_ident())
1451
2472
    table->alias_name_used= my_strcasecmp(table_alias_charset,
1452
 
                                          table->getMutableShare()->getTableName(), alias);
 
2473
                                          table->s->table_name.str, alias);
1453
2474
  /* Fix alias if table name changes */
1454
 
  if (strcmp(table->getAlias(), alias))
 
2475
  if (strcmp(table->alias, alias))
1455
2476
  {
1456
 
    uint32_t length=(uint32_t) strlen(alias)+1;
1457
 
    table->alias= (char*) realloc((char*) table->alias, length);
 
2477
    uint32_t length=(uint) strlen(alias)+1;
 
2478
    table->alias= (char*) my_realloc((char*) table->alias, length,
 
2479
                                     MYF(MY_WME));
1458
2480
    memcpy((void*) table->alias, alias, length);
1459
2481
  }
1460
 
 
1461
2482
  /* These variables are also set in reopen_table() */
1462
 
  table->tablenr= current_tablenr++;
1463
 
  table->used_fields= 0;
1464
 
  table->const_table= 0;
 
2483
  table->tablenr=thd->current_tablenr++;
 
2484
  table->used_fields=0;
 
2485
  table->const_table=0;
1465
2486
  table->null_row= false;
1466
2487
  table->maybe_null= false;
1467
2488
  table->force_index= false;
1468
2489
  table->status=STATUS_NO_RECORD;
1469
 
  table->insert_values.clear();
 
2490
  table->insert_values= 0;
1470
2491
  /* Catch wrong handling of the auto_increment_field_not_null. */
1471
2492
  assert(!table->auto_increment_field_not_null);
1472
2493
  table->auto_increment_field_not_null= false;
1473
2494
  if (table->timestamp_field)
1474
 
  {
1475
2495
    table->timestamp_field_type= table->timestamp_field->get_auto_set_type();
1476
 
  }
1477
2496
  table->pos_in_table_list= table_list;
1478
2497
  table->clear_column_bitmaps();
1479
2498
  assert(table->key_read == 0);
1480
 
 
1481
 
  return table;
1482
 
}
1483
 
 
1484
 
 
1485
 
#if 0
 
2499
  return(table);
 
2500
}
 
2501
 
 
2502
 
 
2503
Table *find_locked_table(THD *thd, const char *db,const char *table_name)
 
2504
{
 
2505
  char  key[MAX_DBKEY_LENGTH];
 
2506
  uint32_t key_length=(uint) (my_stpcpy(my_stpcpy(key,db)+1,table_name)-key)+1;
 
2507
 
 
2508
  for (Table *table=thd->open_tables; table ; table=table->next)
 
2509
  {
 
2510
    if (table->s->table_cache_key.length == key_length &&
 
2511
        !memcmp(table->s->table_cache_key.str, key, key_length))
 
2512
      return table;
 
2513
  }
 
2514
  return(0);
 
2515
}
 
2516
 
 
2517
 
1486
2518
/*
1487
2519
  Reopen an table because the definition has changed.
1488
2520
 
1489
2521
  SYNOPSIS
1490
 
  reopen_table()
1491
 
  table Table object
 
2522
    reopen_table()
 
2523
    table       Table object
1492
2524
 
1493
2525
  NOTES
1494
 
  The data cursor for the table is already closed and the share is released
1495
 
  The table has a 'dummy' share that mainly contains database and table name.
 
2526
   The data file for the table is already closed and the share is released
 
2527
   The table has a 'dummy' share that mainly contains database and table name.
1496
2528
 
1497
 
  RETURN
1498
 
  0  ok
1499
 
  1  error. The old table object is not changed.
 
2529
 RETURN
 
2530
   0  ok
 
2531
   1  error. The old table object is not changed.
1500
2532
*/
1501
2533
 
1502
2534
bool reopen_table(Table *table)
1506
2538
  Field **field;
1507
2539
  uint32_t key,part;
1508
2540
  TableList table_list;
1509
 
  Session *session= table->in_use;
 
2541
  THD *thd= table->in_use;
1510
2542
 
1511
 
  assert(table->getShare()->ref_count == 0);
 
2543
  assert(table->s->ref_count == 0);
1512
2544
  assert(!table->sort.io_cache);
1513
2545
 
1514
2546
#ifdef EXTRA_DEBUG
1515
2547
  if (table->db_stat)
1516
 
    errmsg_printf(ERRMSG_LVL_ERROR, _("Table %s had a open data Cursor in reopen_table"),
1517
 
                  table->alias);
 
2548
    sql_print_error(_("Table %s had a open data handler in reopen_table"),
 
2549
                    table->alias);
1518
2550
#endif
1519
 
  table_list.db=         const_cast<char *>(table->getShare()->getSchemaName());
1520
 
  table_list.table_name= table->getShare()->getTableName();
 
2551
  memset(&table_list, 0, sizeof(TableList));
 
2552
  table_list.db=         table->s->db.str;
 
2553
  table_list.table_name= table->s->table_name.str;
1521
2554
  table_list.table=      table;
1522
2555
 
1523
 
  if (wait_for_locked_table_names(session, &table_list))
1524
 
    return true;                             // Thread was killed
 
2556
  if (wait_for_locked_table_names(thd, &table_list))
 
2557
    return(1);                             // Thread was killed
1525
2558
 
1526
 
  if (open_unireg_entry(session, &tmp, &table_list,
1527
 
                        table->alias,
1528
 
                        table->getShare()->getCacheKey(),
1529
 
                        table->getShare()->getCacheKeySize()))
 
2559
  if (open_unireg_entry(thd, &tmp, &table_list,
 
2560
                        table->alias,
 
2561
                        table->s->table_cache_key.str,
 
2562
                        table->s->table_cache_key.length))
1530
2563
    goto end;
1531
2564
 
1532
2565
  /* This list copies variables set by open_table */
1537
2570
  tmp.maybe_null=       table->maybe_null;
1538
2571
  tmp.status=           table->status;
1539
2572
 
 
2573
  tmp.s->table_map_id=  table->s->table_map_id;
 
2574
 
1540
2575
  /* Get state */
1541
 
  tmp.in_use=           session;
 
2576
  tmp.in_use=           thd;
1542
2577
  tmp.reginfo.lock_type=table->reginfo.lock_type;
1543
2578
 
1544
2579
  /* Replace table in open list */
1545
2580
  tmp.next=             table->next;
1546
2581
  tmp.prev=             table->prev;
1547
2582
 
1548
 
  if (table->cursor)
1549
 
    table->delete_table(true);          // close cursor, free everything
 
2583
  if (table->file)
 
2584
    closefrm(table, 1);         // close file, free everything
1550
2585
 
1551
2586
  *table= tmp;
1552
2587
  table->default_column_bitmaps();
1553
 
  table->cursor->change_table_ptr(table, table->s);
 
2588
  table->file->change_table_ptr(table, table->s);
1554
2589
 
1555
2590
  assert(table->alias != 0);
1556
2591
  for (field=table->field ; *field ; field++)
1558
2593
    (*field)->table= (*field)->orig_table= table;
1559
2594
    (*field)->table_name= &table->alias;
1560
2595
  }
1561
 
  for (key=0 ; key < table->getShare()->keys ; key++)
 
2596
  for (key=0 ; key < table->s->keys ; key++)
1562
2597
  {
1563
2598
    for (part=0 ; part < table->key_info[key].usable_key_parts ; part++)
1564
2599
      table->key_info[key].key_part[part].field->table= table;
1565
2600
  }
 
2601
  /*
 
2602
    Do not attach MERGE children here. The children might be reopened
 
2603
    after the parent. Attach children after reopening all tables that
 
2604
    require reopen. See for example reopen_tables().
 
2605
  */
1566
2606
 
1567
2607
  broadcast_refresh();
1568
 
  error= false;
 
2608
  error=0;
1569
2609
 
1570
 
end:
 
2610
 end:
1571
2611
  return(error);
1572
2612
}
1573
 
#endif
1574
2613
 
1575
2614
 
1576
2615
/**
1577
 
  Close all instances of a table open by this thread and replace
1578
 
  them with exclusive name-locks.
1579
 
 
1580
 
  @param session        Thread context
1581
 
  @param db         Database name for the table to be closed
1582
 
  @param table_name Name of the table to be closed
1583
 
 
1584
 
  @note This function assumes that if we are not under LOCK TABLES,
1585
 
  then there is only one table open and locked. This means that
1586
 
  the function probably has to be adjusted before it can be used
1587
 
  anywhere outside ALTER Table.
1588
 
 
1589
 
  @note Must not use TableShare::table_name/db of the table being closed,
1590
 
  the strings are used in a loop even after the share may be freed.
 
2616
    Close all instances of a table open by this thread and replace
 
2617
    them with exclusive name-locks.
 
2618
 
 
2619
    @param thd        Thread context
 
2620
    @param db         Database name for the table to be closed
 
2621
    @param table_name Name of the table to be closed
 
2622
 
 
2623
    @note This function assumes that if we are not under LOCK TABLES,
 
2624
          then there is only one table open and locked. This means that
 
2625
          the function probably has to be adjusted before it can be used
 
2626
          anywhere outside ALTER Table.
 
2627
 
 
2628
    @note Must not use TABLE_SHARE::table_name/db of the table being closed,
 
2629
          the strings are used in a loop even after the share may be freed.
1591
2630
*/
1592
2631
 
1593
 
void Session::close_data_files_and_morph_locks(TableIdentifier &identifier)
 
2632
void close_data_files_and_morph_locks(THD *thd, const char *db,
 
2633
                                      const char *table_name)
1594
2634
{
1595
 
  safe_mutex_assert_owner(LOCK_open.native_handle()); /* Adjust locks at the end of ALTER TABLEL */
1596
 
 
1597
 
  if (lock)
 
2635
  Table *table;
 
2636
 
 
2637
  safe_mutex_assert_owner(&LOCK_open);
 
2638
 
 
2639
  if (thd->lock)
1598
2640
  {
1599
2641
    /*
1600
2642
      If we are not under LOCK TABLES we should have only one table
1601
2643
      open and locked so it makes sense to remove the lock at once.
1602
2644
    */
1603
 
    mysql_unlock_tables(this, lock);
1604
 
    lock= 0;
 
2645
    mysql_unlock_tables(thd, thd->lock);
 
2646
    thd->lock= 0;
1605
2647
  }
1606
2648
 
1607
2649
  /*
1609
2651
    for target table name if we process ALTER Table ... RENAME.
1610
2652
    So loop below makes sense even if we are not under LOCK TABLES.
1611
2653
  */
1612
 
  for (Table *table= open_tables; table ; table=table->getNext())
 
2654
  for (table=thd->open_tables; table ; table=table->next)
1613
2655
  {
1614
 
    if (table->getShare()->getCacheKey() == identifier.getKey())
 
2656
    if (!strcmp(table->s->table_name.str, table_name) &&
 
2657
        !strcmp(table->s->db.str, db))
1615
2658
    {
1616
 
      table->open_placeholder= true;
 
2659
      if (thd->locked_tables)
 
2660
      {
 
2661
        mysql_lock_remove(thd, thd->locked_tables, table, true);
 
2662
      }
 
2663
      table->open_placeholder= 1;
1617
2664
      close_handle_and_leave_table_as_lock(table);
1618
2665
    }
1619
2666
  }
 
2667
  return;
1620
2668
}
1621
2669
 
1622
2670
 
1623
2671
/**
1624
 
  Reopen all tables with closed data files.
1625
 
 
1626
 
  @param session         Thread context
1627
 
  @param get_locks   Should we get locks after reopening tables ?
1628
 
  @param mark_share_as_old  Mark share as old to protect from a impending
1629
 
  global read lock.
1630
 
 
1631
 
  @note Since this function can't properly handle prelocking and
1632
 
  create placeholders it should be used in very special
1633
 
  situations like FLUSH TABLES or ALTER Table. In general
1634
 
  case one should just repeat open_tables()/lock_tables()
1635
 
  combination when one needs tables to be reopened (for
1636
 
  example see openTablesLock()).
1637
 
 
1638
 
  @note One should have lock on LOCK_open when calling this.
1639
 
 
1640
 
  @return false in case of success, true - otherwise.
 
2672
    Reopen all tables with closed data files.
 
2673
 
 
2674
    @param thd         Thread context
 
2675
    @param get_locks   Should we get locks after reopening tables ?
 
2676
    @param mark_share_as_old  Mark share as old to protect from a impending
 
2677
                              global read lock.
 
2678
 
 
2679
    @note Since this function can't properly handle prelocking and
 
2680
          create placeholders it should be used in very special
 
2681
          situations like FLUSH TABLES or ALTER Table. In general
 
2682
          case one should just repeat open_tables()/lock_tables()
 
2683
          combination when one needs tables to be reopened (for
 
2684
          example see open_and_lock_tables()).
 
2685
 
 
2686
    @note One should have lock on LOCK_open when calling this.
 
2687
 
 
2688
    @return false in case of success, true - otherwise.
1641
2689
*/
1642
2690
 
1643
 
bool Session::reopen_tables(bool get_locks, bool)
 
2691
bool reopen_tables(THD *thd, bool get_locks, bool mark_share_as_old)
1644
2692
{
1645
2693
  Table *table,*next,**prev;
1646
2694
  Table **tables,**tables_ptr;                  // For locks
1647
2695
  bool error=0, not_used;
1648
2696
  const uint32_t flags= DRIZZLE_LOCK_NOTIFY_IF_NEED_REOPEN |
1649
 
    DRIZZLE_LOCK_IGNORE_GLOBAL_READ_LOCK |
1650
 
    DRIZZLE_LOCK_IGNORE_FLUSH;
1651
 
 
1652
 
  if (open_tables == NULL)
1653
 
    return false;
1654
 
 
1655
 
  safe_mutex_assert_owner(LOCK_open.native_handle());
 
2697
                    DRIZZLE_LOCK_IGNORE_GLOBAL_READ_LOCK |
 
2698
                    DRIZZLE_LOCK_IGNORE_FLUSH;
 
2699
 
 
2700
  if (!thd->open_tables)
 
2701
    return(0);
 
2702
 
 
2703
  safe_mutex_assert_owner(&LOCK_open);
1656
2704
  if (get_locks)
1657
2705
  {
1658
2706
    /*
1659
2707
      The ptr is checked later
1660
2708
      Do not handle locks of MERGE children.
1661
2709
    */
1662
 
    uint32_t opens= 0;
1663
 
 
1664
 
    for (table= open_tables; table ; table=table->getNext())
1665
 
    {
 
2710
    uint32_t opens=0;
 
2711
    for (table= thd->open_tables; table ; table=table->next)
1666
2712
      opens++;
1667
 
    }
1668
 
    tables= new Table *[opens];
 
2713
    tables= (Table**) my_alloca(sizeof(Table*)*opens);
1669
2714
  }
1670
2715
  else
1671
 
  {
1672
 
    tables= &open_tables;
1673
 
  }
 
2716
    tables= &thd->open_tables;
1674
2717
  tables_ptr =tables;
1675
2718
 
1676
 
  prev= &open_tables;
1677
 
  for (table= open_tables; table ; table=next)
 
2719
  prev= &thd->open_tables;
 
2720
  for (table=thd->open_tables; table ; table=next)
1678
2721
  {
1679
 
    next= table->getNext();
1680
 
 
1681
 
    my_error(ER_CANT_REOPEN_TABLE, MYF(0), table->getAlias());
1682
 
    remove_table(table);
1683
 
    error= 1;
 
2722
    uint32_t db_stat=table->db_stat;
 
2723
    next=table->next;
 
2724
    if (!tables || (!db_stat && reopen_table(table)))
 
2725
    {
 
2726
      my_error(ER_CANT_REOPEN_TABLE, MYF(0), table->alias);
 
2727
      hash_delete(&open_cache,(unsigned char*) table);
 
2728
      error=1;
 
2729
    }
 
2730
    else
 
2731
    {
 
2732
      *prev= table;
 
2733
      prev= &table->next;
 
2734
      /* Do not handle locks of MERGE children. */
 
2735
      if (get_locks && !db_stat)
 
2736
        *tables_ptr++= table;                   // need new lock on this
 
2737
      if (mark_share_as_old)
 
2738
      {
 
2739
        table->s->version=0;
 
2740
        table->open_placeholder= 0;
 
2741
      }
 
2742
    }
1684
2743
  }
1685
2744
  *prev=0;
1686
2745
  if (tables != tables_ptr)                     // Should we get back old locks
1687
2746
  {
1688
 
    DrizzleLock *local_lock;
 
2747
    DRIZZLE_LOCK *lock;
1689
2748
    /*
1690
2749
      We should always get these locks. Anyway, we must not go into
1691
2750
      wait_for_tables() as it tries to acquire LOCK_open, which is
1692
2751
      already locked.
1693
2752
    */
1694
 
    some_tables_deleted= false;
1695
 
 
1696
 
    if ((local_lock= mysql_lock_tables(this, tables, (uint32_t) (tables_ptr - tables),
 
2753
    thd->some_tables_deleted=0;
 
2754
    if ((lock= mysql_lock_tables(thd, tables, (uint) (tables_ptr - tables),
1697
2755
                                 flags, &not_used)))
1698
2756
    {
1699
 
      /* unused */
 
2757
      thd->locked_tables=mysql_lock_merge(thd->locked_tables,lock);
1700
2758
    }
1701
2759
    else
1702
2760
    {
1709
2767
      error=1;
1710
2768
    }
1711
2769
  }
1712
 
 
1713
2770
  if (get_locks && tables)
1714
 
    delete [] tables;
1715
 
 
 
2771
  {
 
2772
    my_afree((unsigned char*) tables);
 
2773
  }
1716
2774
  broadcast_refresh();
1717
 
 
1718
2775
  return(error);
1719
2776
}
1720
2777
 
1721
2778
 
1722
2779
/**
1723
 
  Close handlers for tables in list, but leave the Table structure
1724
 
  intact so that we can re-open these quickly.
 
2780
    Close handlers for tables in list, but leave the Table structure
 
2781
    intact so that we can re-open these quickly.
1725
2782
 
1726
 
  @param session           Thread context
1727
 
  @param table         Head of the list of Table objects
1728
 
  @param morph_locks   true  - remove locks which we have on tables being closed
1729
 
  but ensure that no DML or DDL will sneak in before
1730
 
  we will re-open the table (i.e. temporarily morph
1731
 
  our table-level locks into name-locks).
1732
 
  false - otherwise
1733
 
  @param send_refresh  Should we awake waiters even if we didn't close any tables?
 
2783
    @param thd           Thread context
 
2784
    @param table         Head of the list of Table objects
 
2785
    @param morph_locks   true  - remove locks which we have on tables being closed
 
2786
                                 but ensure that no DML or DDL will sneak in before
 
2787
                                 we will re-open the table (i.e. temporarily morph
 
2788
                                 our table-level locks into name-locks).
 
2789
                         false - otherwise
 
2790
    @param send_refresh  Should we awake waiters even if we didn't close any tables?
1734
2791
*/
1735
2792
 
1736
 
void Session::close_old_data_files(bool morph_locks, bool send_refresh)
 
2793
static void close_old_data_files(THD *thd, Table *table, bool morph_locks,
 
2794
                                 bool send_refresh)
1737
2795
{
1738
2796
  bool found= send_refresh;
1739
2797
 
1740
 
  Table *table= open_tables;
1741
 
 
1742
 
  for (; table ; table=table->getNext())
 
2798
  for (; table ; table=table->next)
1743
2799
  {
1744
2800
    /*
1745
2801
      Reopen marked for flush.
1749
2805
      found=1;
1750
2806
      if (table->db_stat)
1751
2807
      {
1752
 
        if (morph_locks)
1753
 
        {
 
2808
        if (morph_locks)
 
2809
        {
1754
2810
          Table *ulcktbl= table;
1755
2811
          if (ulcktbl->lock_count)
1756
2812
          {
1760
2816
              lock on it. This will also give them a chance to close their
1761
2817
              instances of this table.
1762
2818
            */
1763
 
            mysql_lock_abort(this, ulcktbl);
1764
 
            mysql_lock_remove(this, ulcktbl);
 
2819
            mysql_lock_abort(thd, ulcktbl, true);
 
2820
            mysql_lock_remove(thd, thd->locked_tables, ulcktbl, true);
1765
2821
            ulcktbl->lock_count= 0;
1766
2822
          }
1767
2823
          if ((ulcktbl != table) && ulcktbl->db_stat)
1772
2828
              as a placeholder. When this happens, do not clear the
1773
2829
              placeholder flag. See the branch below ("***").
1774
2830
            */
1775
 
            ulcktbl->open_placeholder= true;
 
2831
            ulcktbl->open_placeholder= 1;
1776
2832
            close_handle_and_leave_table_as_lock(ulcktbl);
1777
2833
          }
1778
2834
          /*
1779
2835
            We want to protect the table from concurrent DDL operations
1780
2836
            (like RENAME Table) until we will re-open and re-lock it.
1781
2837
          */
1782
 
          table->open_placeholder= true;
1783
 
        }
 
2838
          table->open_placeholder= 1;
 
2839
        }
1784
2840
        close_handle_and_leave_table_as_lock(table);
1785
2841
      }
1786
2842
      else if (table->open_placeholder && !morph_locks)
1796
2852
          flag has been set because of a former close through a child.
1797
2853
          See above the comment that refers to this note.
1798
2854
        */
1799
 
        table->open_placeholder= false;
 
2855
        table->open_placeholder= 0;
1800
2856
      }
1801
2857
    }
1802
2858
  }
1803
2859
  if (found)
1804
2860
    broadcast_refresh();
 
2861
  return;
1805
2862
}
1806
2863
 
1807
2864
 
1815
2872
{
1816
2873
  do
1817
2874
  {
1818
 
    const TableIdentifier::Key &key(table->getShare()->getCacheKey());
1819
 
 
1820
 
    TableOpenCacheRange ppp;
1821
 
    ppp= get_open_cache().equal_range(key);
1822
 
 
1823
 
    for (TableOpenCache::const_iterator iter= ppp.first;
1824
 
         iter != ppp.second; ++iter)
 
2875
    char *key= table->s->table_cache_key.str;
 
2876
    uint32_t key_length= table->s->table_cache_key.length;
 
2877
 
 
2878
    HASH_SEARCH_STATE state;
 
2879
    for (Table *search= (Table*) hash_first(&open_cache, (unsigned char*) key,
 
2880
                                             key_length, &state);
 
2881
         search ;
 
2882
         search= (Table*) hash_next(&open_cache, (unsigned char*) key,
 
2883
                                    key_length, &state))
1825
2884
    {
1826
 
      Table *search= (*iter).second;
1827
2885
      if (search->in_use == table->in_use)
1828
2886
        continue;                               // Name locked by this thread
1829
2887
      /*
1835
2893
      */
1836
2894
      if ( (search->locked_by_name && wait_for_name_lock) ||
1837
2895
           (search->is_name_opened() && search->needs_reopen_or_name_lock()))
1838
 
        return 1;
 
2896
        return(1);
1839
2897
    }
1840
 
  } while ((table=table->getNext()));
1841
 
  return 0;
 
2898
  } while ((table=table->next));
 
2899
  return(0);
1842
2900
}
1843
2901
 
1844
2902
 
1845
2903
/* Wait until all used tables are refreshed */
1846
2904
 
1847
 
bool wait_for_tables(Session *session)
 
2905
bool wait_for_tables(THD *thd)
1848
2906
{
1849
2907
  bool result;
1850
2908
 
1851
 
  session->set_proc_info("Waiting for tables");
1852
 
  {
1853
 
    boost::mutex::scoped_lock lock(LOCK_open);
1854
 
    while (!session->killed)
1855
 
    {
1856
 
      session->some_tables_deleted= false;
1857
 
      session->close_old_data_files(false, dropping_tables != 0);
1858
 
      if (!table_is_used(session->open_tables, 1))
1859
 
        break;
1860
 
      COND_refresh.wait(lock);
1861
 
    }
1862
 
    if (session->killed)
1863
 
      result= true;                                     // aborted
1864
 
    else
1865
 
    {
1866
 
      /* Now we can open all tables without any interference */
1867
 
      session->set_proc_info("Reopen tables");
1868
 
      session->version= refresh_version;
1869
 
      result= session->reopen_tables(false, false);
1870
 
    }
1871
 
  }
1872
 
  session->set_proc_info(0);
1873
 
 
1874
 
  return result;
 
2909
  thd->set_proc_info("Waiting for tables");
 
2910
  pthread_mutex_lock(&LOCK_open);
 
2911
  while (!thd->killed)
 
2912
  {
 
2913
    thd->some_tables_deleted=0;
 
2914
    close_old_data_files(thd,thd->open_tables,0,dropping_tables != 0);
 
2915
    mysql_ha_flush(thd);
 
2916
    if (!table_is_used(thd->open_tables,1))
 
2917
      break;
 
2918
    (void) pthread_cond_wait(&COND_refresh,&LOCK_open);
 
2919
  }
 
2920
  if (thd->killed)
 
2921
    result= 1;                                  // aborted
 
2922
  else
 
2923
  {
 
2924
    /* Now we can open all tables without any interference */
 
2925
    thd->set_proc_info("Reopen tables");
 
2926
    thd->version= refresh_version;
 
2927
    result=reopen_tables(thd,0,0);
 
2928
  }
 
2929
  pthread_mutex_unlock(&LOCK_open);
 
2930
  thd->set_proc_info(0);
 
2931
  return(result);
1875
2932
}
1876
2933
 
1877
2934
 
1879
2936
  drop tables from locked list
1880
2937
 
1881
2938
  SYNOPSIS
1882
 
  drop_locked_tables()
1883
 
  session                       Thread thandler
1884
 
  db                    Database
1885
 
  table_name            Table name
 
2939
    drop_locked_tables()
 
2940
    thd                 Thread thandler
 
2941
    db                  Database
 
2942
    table_name          Table name
1886
2943
 
1887
2944
  INFORMATION
1888
 
  This is only called on drop tables
 
2945
    This is only called on drop tables
1889
2946
 
1890
 
  The Table object for the dropped table is unlocked but still kept around
1891
 
  as a name lock, which means that the table will be available for other
1892
 
  thread as soon as we call unlock_table_names().
1893
 
  If there is multiple copies of the table locked, all copies except
1894
 
  the first, which acts as a name lock, is removed.
 
2947
    The Table object for the dropped table is unlocked but still kept around
 
2948
    as a name lock, which means that the table will be available for other
 
2949
    thread as soon as we call unlock_table_names().
 
2950
    If there is multiple copies of the table locked, all copies except
 
2951
    the first, which acts as a name lock, is removed.
1895
2952
 
1896
2953
  RETURN
1897
 
#    If table existed, return table
1898
 
0        Table was not locked
 
2954
    #    If table existed, return table
 
2955
    0    Table was not locked
1899
2956
*/
1900
2957
 
1901
2958
 
1902
 
Table *drop_locked_tables(Session *session, const drizzled::TableIdentifier &identifier)
 
2959
Table *drop_locked_tables(THD *thd,const char *db, const char *table_name)
1903
2960
{
1904
2961
  Table *table,*next,**prev, *found= 0;
1905
 
  prev= &session->open_tables;
 
2962
  prev= &thd->open_tables;
1906
2963
 
1907
2964
  /*
1908
2965
    Note that we need to hold LOCK_open while changing the
1911
2968
    Closing a MERGE child before the parent would be fatal if the
1912
2969
    other thread tries to abort the MERGE lock in between.
1913
2970
  */
1914
 
  for (table= session->open_tables; table ; table=next)
 
2971
  for (table= thd->open_tables; table ; table=next)
1915
2972
  {
1916
 
    next=table->getNext();
1917
 
    if (table->getShare()->getCacheKey() == identifier.getKey())
 
2973
    next=table->next;
 
2974
    if (!strcmp(table->s->table_name.str, table_name) &&
 
2975
        !strcmp(table->s->db.str, db))
1918
2976
    {
1919
 
      mysql_lock_remove(session, table);
 
2977
      mysql_lock_remove(thd, thd->locked_tables, table, true);
1920
2978
 
1921
2979
      if (!found)
1922
2980
      {
1925
2983
        if (table->db_stat)
1926
2984
        {
1927
2985
          table->db_stat= 0;
1928
 
          table->cursor->close();
 
2986
          table->file->close();
1929
2987
        }
1930
2988
      }
1931
2989
      else
1932
2990
      {
1933
2991
        /* We already have a name lock, remove copy */
1934
 
        remove_table(table);
 
2992
        hash_delete(&open_cache,(unsigned char*) table);
1935
2993
      }
1936
2994
    }
1937
2995
    else
1938
2996
    {
1939
2997
      *prev=table;
1940
 
      prev= table->getNextPtr();
 
2998
      prev= &table->next;
1941
2999
    }
1942
3000
  }
1943
3001
  *prev=0;
1944
3002
  if (found)
1945
3003
    broadcast_refresh();
1946
 
 
 
3004
  if (thd->locked_tables && thd->locked_tables->table_count == 0)
 
3005
  {
 
3006
    free((unsigned char*) thd->locked_tables);
 
3007
    thd->locked_tables=0;
 
3008
  }
1947
3009
  return(found);
1948
3010
}
1949
3011
 
1954
3016
  other threads trying to get the lock.
1955
3017
*/
1956
3018
 
1957
 
void abort_locked_tables(Session *session, const drizzled::TableIdentifier &identifier)
 
3019
void abort_locked_tables(THD *thd,const char *db, const char *table_name)
1958
3020
{
1959
3021
  Table *table;
1960
 
  for (table= session->open_tables; table ; table= table->getNext())
 
3022
  for (table= thd->open_tables; table ; table= table->next)
1961
3023
  {
1962
 
    if (table->getShare()->getCacheKey() == identifier.getKey())
 
3024
    if (!strcmp(table->s->table_name.str, table_name) &&
 
3025
        !strcmp(table->s->db.str, db))
1963
3026
    {
1964
3027
      /* If MERGE child, forward lock handling to parent. */
1965
 
      mysql_lock_abort(session, table);
 
3028
      mysql_lock_abort(thd, table, true);
1966
3029
      break;
1967
3030
    }
1968
3031
  }
1969
3032
}
1970
3033
 
1971
 
/*
1972
 
  Load a table definition from cursor and open unireg table
 
3034
 
 
3035
/*
 
3036
  Function to assign a new table map id to a table share.
 
3037
 
 
3038
  PARAMETERS
 
3039
 
 
3040
    share - Pointer to table share structure
 
3041
 
 
3042
  DESCRIPTION
 
3043
 
 
3044
    We are intentionally not checking that share->mutex is locked
 
3045
    since this function should only be called when opening a table
 
3046
    share and before it is entered into the table_def_cache (meaning
 
3047
    that it cannot be fetched by another thread, even accidentally).
 
3048
 
 
3049
  PRE-CONDITION(S)
 
3050
 
 
3051
    share is non-NULL
 
3052
    The LOCK_open mutex is locked
 
3053
 
 
3054
  POST-CONDITION(S)
 
3055
 
 
3056
    share->table_map_id is given a value that with a high certainty is
 
3057
    not used by any other table (the only case where a table id can be
 
3058
    reused is on wrap-around, which means more than 4 billion table
 
3059
    share opens have been executed while one table was open all the
 
3060
    time).
 
3061
 
 
3062
    share->table_map_id is not UINT32_MAX.
 
3063
 */
 
3064
void assign_new_table_id(TABLE_SHARE *share)
 
3065
{
 
3066
  static uint32_t last_table_id= UINT32_MAX;
 
3067
 
 
3068
  /* Preconditions */
 
3069
  assert(share != NULL);
 
3070
  safe_mutex_assert_owner(&LOCK_open);
 
3071
 
 
3072
  ulong tid= ++last_table_id;                   /* get next id */
 
3073
  /*
 
3074
    There is one reserved number that cannot be used.  Remember to
 
3075
    change this when 6-byte global table id's are introduced.
 
3076
  */
 
3077
  if (unlikely(tid == UINT32_MAX))
 
3078
    tid= ++last_table_id;
 
3079
  share->table_map_id= tid;
 
3080
 
 
3081
  /* Post conditions */
 
3082
  assert(share->table_map_id != UINT32_MAX);
 
3083
 
 
3084
  return;
 
3085
}
 
3086
 
 
3087
/*
 
3088
  Load a table definition from file and open unireg table
1973
3089
 
1974
3090
  SYNOPSIS
1975
 
  open_unireg_entry()
1976
 
  session                       Thread handle
1977
 
  entry         Store open table definition here
1978
 
  table_list            TableList with db, table_name
1979
 
  alias         Alias name
1980
 
  cache_key             Key for share_cache
1981
 
  cache_key_length      length of cache_key
 
3091
    open_unireg_entry()
 
3092
    thd                 Thread handle
 
3093
    entry               Store open table definition here
 
3094
    table_list          TableList with db, table_name
 
3095
    alias               Alias name
 
3096
    cache_key           Key for share_cache
 
3097
    cache_key_length    length of cache_key
1982
3098
 
1983
3099
  NOTES
1984
 
  Extra argument for open is taken from session->open_options
1985
 
  One must have a lock on LOCK_open when calling this function
 
3100
   Extra argument for open is taken from thd->open_options
 
3101
   One must have a lock on LOCK_open when calling this function
1986
3102
 
1987
3103
  RETURN
1988
 
  0     ok
1989
 
#       Error
 
3104
    0   ok
 
3105
    #   Error
1990
3106
*/
1991
3107
 
1992
 
static int open_unireg_entry(Session *session,
1993
 
                             Table *entry,
 
3108
static int open_unireg_entry(THD *thd, Table *entry, TableList *table_list,
1994
3109
                             const char *alias,
1995
 
                             TableIdentifier &identifier)
 
3110
                             char *cache_key, uint32_t cache_key_length)
1996
3111
{
1997
3112
  int error;
1998
 
  TableShare *share;
 
3113
  TABLE_SHARE *share;
1999
3114
  uint32_t discover_retry_count= 0;
2000
3115
 
2001
 
  safe_mutex_assert_owner(LOCK_open.native_handle());
 
3116
  safe_mutex_assert_owner(&LOCK_open);
2002
3117
retry:
2003
 
  if (not (share= TableShare::getShareCreate(session,
2004
 
                                             identifier,
2005
 
                                             &error)))
2006
 
    return 1;
 
3118
  if (!(share= get_table_share_with_create(thd, table_list, cache_key,
 
3119
                                           cache_key_length, 
 
3120
                                           table_list->i_s_requested_object,
 
3121
                                           &error)))
 
3122
    return(1);
2007
3123
 
2008
 
  while ((error= share->open_table_from_share(session,
2009
 
                                              identifier,
2010
 
                                              alias,
2011
 
                                              (uint32_t) (HA_OPEN_KEYFILE |
2012
 
                                                          HA_OPEN_RNDFILE |
2013
 
                                                          HA_GET_INDEX |
2014
 
                                                          HA_TRY_READ_ONLY),
2015
 
                                              session->open_options, *entry)))
 
3124
  while ((error= open_table_from_share(thd, share, alias,
 
3125
                                       (uint) (HA_OPEN_KEYFILE |
 
3126
                                               HA_OPEN_RNDFILE |
 
3127
                                               HA_GET_INDEX |
 
3128
                                               HA_TRY_READ_ONLY),
 
3129
                                       (EXTRA_RECORD),
 
3130
                                       thd->open_options, entry, OTM_OPEN)))
2016
3131
  {
2017
3132
    if (error == 7)                             // Table def changed
2018
3133
    {
2019
 
      share->resetVersion();                        // Mark share as old
 
3134
      share->version= 0;                        // Mark share as old
2020
3135
      if (discover_retry_count++)               // Retry once
2021
3136
        goto err;
2022
3137
 
2023
3138
      /*
2024
 
        TODO->
 
3139
        TODO:
2025
3140
        Here we should wait until all threads has released the table.
2026
3141
        For now we do one retry. This may cause a deadlock if there
2027
3142
        is other threads waiting for other tables used by this thread.
2028
 
 
 
3143
        
2029
3144
        Proper fix would be to if the second retry failed:
2030
3145
        - Mark that table def changed
2031
3146
        - Return from open table
2033
3148
        - Start waiting that the share is released
2034
3149
        - Retry by opening all tables again
2035
3150
      */
2036
 
 
 
3151
      if (ha_create_table_from_engine(thd, table_list->db,
 
3152
                                      table_list->table_name))
 
3153
        goto err;
2037
3154
      /*
2038
3155
        TO BE FIXED
2039
3156
        To avoid deadlock, only wait for release if no one else is
2040
3157
        using the share.
2041
3158
      */
2042
 
      if (share->getTableCount() != 1)
 
3159
      if (share->ref_count != 1)
2043
3160
        goto err;
2044
3161
      /* Free share and wait until it's released by all threads */
2045
 
      TableShare::release(share);
2046
 
 
2047
 
      if (!session->killed)
 
3162
      release_table_share(share, RELEASE_WAIT_FOR_DROP);
 
3163
      if (!thd->killed)
2048
3164
      {
2049
 
        drizzle_reset_errors(session, 1);         // Clear warnings
2050
 
        session->clear_error();                 // Clear error message
 
3165
        drizzle_reset_errors(thd, 1);         // Clear warnings
 
3166
        thd->clear_error();                 // Clear error message
2051
3167
        goto retry;
2052
3168
      }
2053
 
      return 1;
 
3169
      return(1);
2054
3170
    }
 
3171
    if (!entry->s || !entry->s->crashed)
 
3172
      goto err;
 
3173
     // Code below is for repairing a crashed file
 
3174
     if ((error= lock_table_name(thd, table_list, true)))
 
3175
     {
 
3176
       if (error < 0)
 
3177
        goto err;
 
3178
       if (wait_for_locked_table_names(thd, table_list))
 
3179
       {
 
3180
        unlock_table_name(thd, table_list);
 
3181
        goto err;
 
3182
       }
 
3183
     }
 
3184
     pthread_mutex_unlock(&LOCK_open);
 
3185
     thd->clear_error();                                // Clear error message
 
3186
     error= 0;
 
3187
     if (open_table_from_share(thd, share, alias,
 
3188
                               (uint) (HA_OPEN_KEYFILE | HA_OPEN_RNDFILE |
 
3189
                                       HA_GET_INDEX |
 
3190
                                       HA_TRY_READ_ONLY),
 
3191
                               EXTRA_RECORD,
 
3192
                               ha_open_options | HA_OPEN_FOR_REPAIR,
 
3193
                               entry, OTM_OPEN) || ! entry->file ||
 
3194
        (entry->file->is_crashed() && entry->file->ha_check_and_repair(thd)))
 
3195
     {
 
3196
       /* Give right error message */
 
3197
       thd->clear_error();
 
3198
       my_error(ER_NOT_KEYFILE, MYF(0), share->table_name.str, my_errno);
 
3199
       sql_print_error(_("Couldn't repair table: %s.%s"), share->db.str,
 
3200
                       share->table_name.str);
 
3201
       if (entry->file)
 
3202
        closefrm(entry, 0);
 
3203
       error=1;
 
3204
     }
 
3205
     else
 
3206
       thd->clear_error();                      // Clear error message
 
3207
     pthread_mutex_lock(&LOCK_open);
 
3208
     unlock_table_name(thd, table_list);
 
3209
 
 
3210
     if (error)
 
3211
       goto err;
 
3212
     break;
 
3213
   }
2055
3214
 
2056
 
    goto err;
 
3215
  /*
 
3216
    If we are here, there was no fatal error (but error may be still
 
3217
    unitialized).
 
3218
  */
 
3219
  if (unlikely(entry->file->implicit_emptied))
 
3220
  {
 
3221
    entry->file->implicit_emptied= 0;
 
3222
    if (mysql_bin_log.is_open())
 
3223
    {
 
3224
      char *query, *end;
 
3225
      uint32_t query_buf_size= 20 + share->db.length + share->table_name.length +1;
 
3226
      if ((query= (char*) my_malloc(query_buf_size,MYF(MY_WME))))
 
3227
      {
 
3228
        /* this DELETE FROM is needed even with row-based binlogging */
 
3229
        end = strxmov(my_stpcpy(query, "DELETE FROM `"),
 
3230
                      share->db.str,"`.`",share->table_name.str,"`", NULL);
 
3231
        thd->binlog_query(THD::STMT_QUERY_TYPE,
 
3232
                          query, (ulong)(end-query), false, false);
 
3233
        free(query);
 
3234
      }
 
3235
      else
 
3236
      {
 
3237
        /*
 
3238
          As replication is maybe going to be corrupted, we need to warn the
 
3239
          DBA on top of warning the client (which will automatically be done
 
3240
          because of MYF(MY_WME) in my_malloc() above).
 
3241
        */
 
3242
        sql_print_error(_("When opening HEAP table, could not allocate memory "
 
3243
                          "to write 'DELETE FROM `%s`.`%s`' to the binary log"),
 
3244
                        table_list->db, table_list->table_name);
 
3245
        closefrm(entry, 0);
 
3246
        goto err;
 
3247
      }
 
3248
    }
2057
3249
  }
2058
 
 
2059
 
  return 0;
 
3250
  return(0);
2060
3251
 
2061
3252
err:
2062
 
  TableShare::release(share);
2063
 
 
2064
 
  return 1;
 
3253
  release_table_share(share, RELEASE_NORMAL);
 
3254
  return(1);
2065
3255
}
2066
3256
 
2067
3257
 
2069
3259
  Open all tables in list
2070
3260
 
2071
3261
  SYNOPSIS
2072
 
  open_tables()
2073
 
  session - thread Cursor
2074
 
  start - list of tables in/out
2075
 
  counter - number of opened tables will be return using this parameter
2076
 
  flags   - bitmap of flags to modify how the tables will be open:
2077
 
  DRIZZLE_LOCK_IGNORE_FLUSH - open table even if someone has
2078
 
  done a flush or namelock on it.
 
3262
    open_tables()
 
3263
    thd - thread handler
 
3264
    start - list of tables in/out
 
3265
    counter - number of opened tables will be return using this parameter
 
3266
    flags   - bitmap of flags to modify how the tables will be open:
 
3267
              DRIZZLE_LOCK_IGNORE_FLUSH - open table even if someone has
 
3268
              done a flush or namelock on it.
2079
3269
 
2080
3270
  NOTE
2081
 
  Unless we are already in prelocked mode, this function will also precache
2082
 
  all SP/SFs explicitly or implicitly (via views and triggers) used by the
2083
 
  query and add tables needed for their execution to table list. If resulting
2084
 
  tables list will be non empty it will mark query as requiring precaching.
2085
 
  Prelocked mode will be enabled for such query during lock_tables() call.
 
3271
    Unless we are already in prelocked mode, this function will also precache
 
3272
    all SP/SFs explicitly or implicitly (via views and triggers) used by the
 
3273
    query and add tables needed for their execution to table list. If resulting
 
3274
    tables list will be non empty it will mark query as requiring precaching.
 
3275
    Prelocked mode will be enabled for such query during lock_tables() call.
2086
3276
 
2087
 
  If query for which we are opening tables is already marked as requiring
2088
 
  prelocking it won't do such precaching and will simply reuse table list
2089
 
  which is already built.
 
3277
    If query for which we are opening tables is already marked as requiring
 
3278
    prelocking it won't do such precaching and will simply reuse table list
 
3279
    which is already built.
2090
3280
 
2091
3281
  RETURN
2092
 
  0  - OK
2093
 
  -1 - error
 
3282
    0  - OK
 
3283
    -1 - error
2094
3284
*/
2095
3285
 
2096
 
int Session::open_tables_from_list(TableList **start, uint32_t *counter, uint32_t flags)
 
3286
int open_tables(THD *thd, TableList **start, uint32_t *counter, uint32_t flags)
2097
3287
{
2098
3288
  TableList *tables= NULL;
2099
3289
  bool refresh;
2100
 
  int result= 0;
 
3290
  int result=0;
 
3291
  MEM_ROOT new_frm_mem;
2101
3292
  /* Also used for indicating that prelocking is need */
2102
3293
  bool safe_to_ignore_table;
2103
3294
 
2104
 
  current_tablenr= 0;
2105
 
restart:
 
3295
  /*
 
3296
    temporary mem_root for new .frm parsing.
 
3297
    TODO: variables for size
 
3298
  */
 
3299
  init_sql_alloc(&new_frm_mem, 8024, 8024);
 
3300
 
 
3301
  thd->current_tablenr= 0;
 
3302
 restart:
2106
3303
  *counter= 0;
2107
 
  set_proc_info("Opening tables");
 
3304
  thd->set_proc_info("Opening tables");
2108
3305
 
2109
3306
  /*
2110
3307
    For every table in the list of tables to open, try to find or open
2119
3316
      processing, link to created temporary table will be put here.
2120
3317
      If this is derived table for view then we still want to process
2121
3318
      routines used by this view.
2122
 
    */
 
3319
     */
2123
3320
    if (tables->derived)
2124
3321
    {
2125
3322
      continue;
2126
3323
    }
 
3324
    /*
 
3325
      If this TableList object is a placeholder for an information_schema
 
3326
      table, create a temporary table to represent the information_schema
 
3327
      table in the query. Do not fill it yet - will be filled during
 
3328
      execution.
 
3329
    */
 
3330
    if (tables->schema_table)
 
3331
    {
 
3332
      if (!mysql_schema_table(thd, thd->lex, tables))
 
3333
        continue;
 
3334
      return(-1);
 
3335
    }
2127
3336
    (*counter)++;
2128
3337
 
2129
3338
    /*
2130
 
     * Is the user authorized to see this table? Do this before we check
2131
 
     * to see if it exists so that an unauthorized user cannot phish for
2132
 
     * table/schema information via error messages
2133
 
     */
2134
 
    TableIdentifier the_table(tables->db, tables->table_name);
2135
 
    if (not plugin::Authorization::isAuthorized(getSecurityContext(),
2136
 
                                                the_table))
2137
 
    {
2138
 
      result= -1;                               // Fatal error
2139
 
      break;
2140
 
    }
2141
 
 
2142
 
 
2143
 
    /*
2144
3339
      Not a placeholder: must be a base table or a view, and the table is
2145
3340
      not opened yet. Try to open the table.
2146
3341
    */
2147
 
    if (tables->table == NULL)
2148
 
      tables->table= openTable(tables, &refresh, flags);
 
3342
    if (!tables->table)
 
3343
      tables->table= open_table(thd, tables, &refresh, flags);
2149
3344
 
2150
 
    if (tables->table == NULL)
 
3345
    if (!tables->table)
2151
3346
    {
 
3347
      free_root(&new_frm_mem, MYF(MY_KEEP_PREALLOC));
 
3348
 
2152
3349
      if (refresh)                              // Refresh in progress
2153
3350
      {
2154
3351
        /*
2165
3362
          we pretend that we have finished calculation which we were doing
2166
3363
          currently.
2167
3364
        */
2168
 
        close_tables_for_reopen(start);
2169
 
        goto restart;
 
3365
        close_tables_for_reopen(thd, start);
 
3366
        goto restart;
2170
3367
      }
2171
3368
 
2172
3369
      if (safe_to_ignore_table)
2175
3372
      result= -1;                               // Fatal error
2176
3373
      break;
2177
3374
    }
2178
 
    if (tables->lock_type != TL_UNLOCK)
 
3375
    if (tables->lock_type != TL_UNLOCK && ! thd->locked_tables)
2179
3376
    {
2180
3377
      if (tables->lock_type == TL_WRITE_DEFAULT)
2181
 
        tables->table->reginfo.lock_type= update_lock_default;
2182
 
      else if (tables->table->getShare()->getType() == message::Table::STANDARD)
 
3378
        tables->table->reginfo.lock_type= thd->update_lock_default;
 
3379
      else if (tables->table->s->tmp_table == NO_TMP_TABLE)
2183
3380
        tables->table->reginfo.lock_type= tables->lock_type;
2184
3381
    }
2185
3382
  }
2186
3383
 
2187
 
  set_proc_info(0);
 
3384
  thd->set_proc_info(0);
 
3385
  free_root(&new_frm_mem, MYF(0));              // Free pre-alloced block
2188
3386
 
2189
3387
  if (result && tables)
2190
3388
  {
2191
3389
    /*
2192
3390
      Some functions determine success as (tables->table != NULL).
2193
 
      tables->table is in session->open_tables.
 
3391
      tables->table is in thd->open_tables.
2194
3392
    */
2195
3393
    tables->table= NULL;
2196
3394
  }
2197
 
 
2198
3395
  return(result);
2199
3396
}
2200
3397
 
2201
3398
 
2202
3399
/*
 
3400
  Check that lock is ok for tables; Call start stmt if ok
 
3401
 
 
3402
  SYNOPSIS
 
3403
    check_lock_and_start_stmt()
 
3404
    thd                 Thread handle
 
3405
    table_list          Table to check
 
3406
    lock_type           Lock used for table
 
3407
 
 
3408
  RETURN VALUES
 
3409
  0     ok
 
3410
  1     error
 
3411
*/
 
3412
 
 
3413
static bool check_lock_and_start_stmt(THD *thd, Table *table,
 
3414
                                      thr_lock_type lock_type)
 
3415
{
 
3416
  int error;
 
3417
 
 
3418
  if ((int) lock_type >= (int) TL_WRITE_ALLOW_READ &&
 
3419
      (int) table->reginfo.lock_type < (int) TL_WRITE_ALLOW_READ)
 
3420
  {
 
3421
    my_error(ER_TABLE_NOT_LOCKED_FOR_WRITE, MYF(0),table->alias);
 
3422
    return(1);
 
3423
  }
 
3424
  if ((error=table->file->start_stmt(thd, lock_type)))
 
3425
  {
 
3426
    table->file->print_error(error,MYF(0));
 
3427
    return(1);
 
3428
  }
 
3429
  return(0);
 
3430
}
 
3431
 
 
3432
 
 
3433
/**
 
3434
  @brief Open and lock one table
 
3435
 
 
3436
  @param[in]    thd             thread handle
 
3437
  @param[in]    table_l         table to open is first table in this list
 
3438
  @param[in]    lock_type       lock to use for table
 
3439
 
 
3440
  @return       table
 
3441
    @retval     != NULL         OK, opened table returned
 
3442
    @retval     NULL            Error
 
3443
 
 
3444
  @note
 
3445
    If ok, the following are also set:
 
3446
      table_list->lock_type     lock_type
 
3447
      table_list->table         table
 
3448
 
 
3449
  @note
 
3450
    If table_l is a list, not a single table, the list is temporarily
 
3451
    broken.
 
3452
 
 
3453
  @detail
 
3454
    This function is meant as a replacement for open_ltable() when
 
3455
    MERGE tables can be opened. open_ltable() cannot open MERGE tables.
 
3456
 
 
3457
    There may be more differences between open_n_lock_single_table() and
 
3458
    open_ltable(). One known difference is that open_ltable() does
 
3459
    neither call decide_logging_format() nor handle some other logging
 
3460
    and locking issues because it does not call lock_tables().
 
3461
*/
 
3462
 
 
3463
Table *open_n_lock_single_table(THD *thd, TableList *table_l,
 
3464
                                thr_lock_type lock_type)
 
3465
{
 
3466
  TableList *save_next_global;
 
3467
 
 
3468
  /* Remember old 'next' pointer. */
 
3469
  save_next_global= table_l->next_global;
 
3470
  /* Break list. */
 
3471
  table_l->next_global= NULL;
 
3472
 
 
3473
  /* Set requested lock type. */
 
3474
  table_l->lock_type= lock_type;
 
3475
 
 
3476
  /* Open the table. */
 
3477
  if (simple_open_n_lock_tables(thd, table_l))
 
3478
    table_l->table= NULL; /* Just to be sure. */
 
3479
 
 
3480
  /* Restore list. */
 
3481
  table_l->next_global= save_next_global;
 
3482
 
 
3483
  return(table_l->table);
 
3484
}
 
3485
 
 
3486
 
 
3487
/*
2203
3488
  Open and lock one table
2204
3489
 
2205
3490
  SYNOPSIS
2206
 
  openTableLock()
2207
 
  session                       Thread Cursor
2208
 
  table_list            Table to open is first table in this list
2209
 
  lock_type             Lock to use for open
2210
 
  lock_flags          Flags passed to mysql_lock_table
 
3491
    open_ltable()
 
3492
    thd                 Thread handler
 
3493
    table_list          Table to open is first table in this list
 
3494
    lock_type           Lock to use for open
 
3495
    lock_flags          Flags passed to mysql_lock_table
2211
3496
 
2212
3497
  NOTE
2213
 
  This function don't do anything like SP/SF/views/triggers analysis done
2214
 
  in open_tables(). It is intended for opening of only one concrete table.
2215
 
  And used only in special contexts.
 
3498
    This function don't do anything like SP/SF/views/triggers analysis done
 
3499
    in open_tables(). It is intended for opening of only one concrete table.
 
3500
    And used only in special contexts.
2216
3501
 
2217
3502
  RETURN VALUES
2218
 
  table         Opened table
2219
 
  0                     Error
2220
 
 
2221
 
  If ok, the following are also set:
2222
 
  table_list->lock_type         lock_type
2223
 
  table_list->table             table
 
3503
    table               Opened table
 
3504
    0                   Error
 
3505
  
 
3506
    If ok, the following are also set:
 
3507
      table_list->lock_type     lock_type
 
3508
      table_list->table         table
2224
3509
*/
2225
3510
 
2226
 
Table *Session::openTableLock(TableList *table_list, thr_lock_type lock_type)
 
3511
Table *open_ltable(THD *thd, TableList *table_list, thr_lock_type lock_type,
 
3512
                   uint32_t lock_flags)
2227
3513
{
2228
3514
  Table *table;
2229
3515
  bool refresh;
2230
3516
 
2231
 
  set_proc_info("Opening table");
2232
 
  current_tablenr= 0;
2233
 
  while (!(table= openTable(table_list, &refresh)) &&
 
3517
  thd->set_proc_info("Opening table");
 
3518
  thd->current_tablenr= 0;
 
3519
  while (!(table= open_table(thd, table_list, &refresh, 0)) &&
2234
3520
         refresh)
2235
3521
    ;
2236
3522
 
2238
3524
  {
2239
3525
    table_list->lock_type= lock_type;
2240
3526
    table_list->table=     table;
2241
 
 
2242
 
    assert(lock == 0);  // You must lock everything at once
2243
 
    if ((table->reginfo.lock_type= lock_type) != TL_UNLOCK)
2244
 
      if (! (lock= mysql_lock_tables(this, &table_list->table, 1, 0, &refresh)))
2245
 
        table= 0;
2246
 
  }
2247
 
 
2248
 
  set_proc_info(0);
2249
 
 
2250
 
  return table;
 
3527
    if (thd->locked_tables)
 
3528
    {
 
3529
      if (check_lock_and_start_stmt(thd, table, lock_type))
 
3530
        table= 0;
 
3531
    }
 
3532
    else
 
3533
    {
 
3534
      assert(thd->lock == 0);   // You must lock everything at once
 
3535
      if ((table->reginfo.lock_type= lock_type) != TL_UNLOCK)
 
3536
        if (! (thd->lock= mysql_lock_tables(thd, &table_list->table, 1,
 
3537
                                            lock_flags, &refresh)))
 
3538
          table= 0;
 
3539
    }
 
3540
  }
 
3541
 
 
3542
  thd->set_proc_info(0);
 
3543
  return(table);
 
3544
}
 
3545
 
 
3546
 
 
3547
/*
 
3548
  Open all tables in list, locks them and optionally process derived tables.
 
3549
 
 
3550
  SYNOPSIS
 
3551
    open_and_lock_tables_derived()
 
3552
    thd         - thread handler
 
3553
    tables      - list of tables for open&locking
 
3554
    derived     - if to handle derived tables
 
3555
 
 
3556
  RETURN
 
3557
    false - ok
 
3558
    true  - error
 
3559
 
 
3560
  NOTE
 
3561
    The lock will automaticaly be freed by close_thread_tables()
 
3562
 
 
3563
  NOTE
 
3564
    There are two convenience functions:
 
3565
    - simple_open_n_lock_tables(thd, tables)  without derived handling
 
3566
    - open_and_lock_tables(thd, tables)       with derived handling
 
3567
    Both inline functions call open_and_lock_tables_derived() with
 
3568
    the third argument set appropriately.
 
3569
*/
 
3570
 
 
3571
int open_and_lock_tables_derived(THD *thd, TableList *tables, bool derived)
 
3572
{
 
3573
  uint32_t counter;
 
3574
  bool need_reopen;
 
3575
 
 
3576
  for ( ; ; ) 
 
3577
  {
 
3578
    if (open_tables(thd, &tables, &counter, 0))
 
3579
      return(-1);
 
3580
 
 
3581
    if (!lock_tables(thd, tables, counter, &need_reopen))
 
3582
      break;
 
3583
    if (!need_reopen)
 
3584
      return(-1);
 
3585
    close_tables_for_reopen(thd, &tables);
 
3586
  }
 
3587
  if (derived &&
 
3588
      (mysql_handle_derived(thd->lex, &mysql_derived_prepare) ||
 
3589
       (thd->fill_derived_tables() &&
 
3590
        mysql_handle_derived(thd->lex, &mysql_derived_filling))))
 
3591
    return(true); /* purecov: inspected */
 
3592
  return(0);
 
3593
}
 
3594
 
 
3595
 
 
3596
/*
 
3597
  Open all tables in list and process derived tables
 
3598
 
 
3599
  SYNOPSIS
 
3600
    open_normal_and_derived_tables
 
3601
    thd         - thread handler
 
3602
    tables      - list of tables for open
 
3603
    flags       - bitmap of flags to modify how the tables will be open:
 
3604
                  DRIZZLE_LOCK_IGNORE_FLUSH - open table even if someone has
 
3605
                  done a flush or namelock on it.
 
3606
 
 
3607
  RETURN
 
3608
    false - ok
 
3609
    true  - error
 
3610
 
 
3611
  NOTE 
 
3612
    This is to be used on prepare stage when you don't read any
 
3613
    data from the tables.
 
3614
*/
 
3615
 
 
3616
bool open_normal_and_derived_tables(THD *thd, TableList *tables, uint32_t flags)
 
3617
{
 
3618
  uint32_t counter;
 
3619
  assert(!thd->fill_derived_tables());
 
3620
  if (open_tables(thd, &tables, &counter, flags) ||
 
3621
      mysql_handle_derived(thd->lex, &mysql_derived_prepare))
 
3622
    return(true); /* purecov: inspected */
 
3623
  return(0);
 
3624
}
 
3625
 
 
3626
 
 
3627
/**
 
3628
   Decide on logging format to use for the statement.
 
3629
 
 
3630
   Compute the capabilities vector for the involved storage engines
 
3631
   and mask out the flags for the binary log. Right now, the binlog
 
3632
   flags only include the capabilities of the storage engines, so this
 
3633
   is safe.
 
3634
 
 
3635
   We now have three alternatives that prevent the statement from
 
3636
   being loggable:
 
3637
 
 
3638
   1. If there are no capabilities left (all flags are clear) it is
 
3639
      not possible to log the statement at all, so we roll back the
 
3640
      statement and report an error.
 
3641
 
 
3642
   2. Statement mode is set, but the capabilities indicate that
 
3643
      statement format is not possible.
 
3644
 
 
3645
   3. Row mode is set, but the capabilities indicate that row
 
3646
      format is not possible.
 
3647
 
 
3648
   4. Statement is unsafe, but the capabilities indicate that row
 
3649
      format is not possible.
 
3650
 
 
3651
   If we are in MIXED mode, we then decide what logging format to use:
 
3652
 
 
3653
   1. If the statement is unsafe, row-based logging is used.
 
3654
 
 
3655
   2. If statement-based logging is not possible, row-based logging is
 
3656
      used.
 
3657
 
 
3658
   3. Otherwise, statement-based logging is used.
 
3659
 
 
3660
   @param thd    Client thread
 
3661
   @param tables Tables involved in the query
 
3662
 */
 
3663
 
 
3664
int decide_logging_format(THD *thd, TableList *tables)
 
3665
{
 
3666
  if (mysql_bin_log.is_open() && (thd->options & OPTION_BIN_LOG))
 
3667
  {
 
3668
    handler::Table_flags flags_some_set= handler::Table_flags();
 
3669
    handler::Table_flags flags_all_set= ~handler::Table_flags();
 
3670
    bool multi_engine= false;
 
3671
    void* prev_ht= NULL;
 
3672
    for (TableList *table= tables; table; table= table->next_global)
 
3673
    {
 
3674
      if (!table->placeholder() && table->lock_type >= TL_WRITE_ALLOW_WRITE)
 
3675
      {
 
3676
        uint64_t const flags= table->table->file->ha_table_flags();
 
3677
        if (prev_ht && prev_ht != table->table->file->ht)
 
3678
          multi_engine= true;
 
3679
        prev_ht= table->table->file->ht;
 
3680
        flags_all_set &= flags;
 
3681
        flags_some_set |= flags;
 
3682
      }
 
3683
    }
 
3684
 
 
3685
    int error= 0;
 
3686
    if (flags_all_set == 0)
 
3687
    {
 
3688
      my_error((error= ER_BINLOG_LOGGING_IMPOSSIBLE), MYF(0),
 
3689
               "Statement cannot be logged to the binary log in"
 
3690
               " row-based nor statement-based format");
 
3691
    }
 
3692
    else if (thd->variables.binlog_format == BINLOG_FORMAT_STMT &&
 
3693
             (flags_all_set & HA_BINLOG_STMT_CAPABLE) == 0)
 
3694
    {
 
3695
      my_error((error= ER_BINLOG_LOGGING_IMPOSSIBLE), MYF(0),
 
3696
                "Statement-based format required for this statement,"
 
3697
                " but not allowed by this combination of engines");
 
3698
    }
 
3699
    else if ((thd->variables.binlog_format == BINLOG_FORMAT_ROW ||
 
3700
              thd->lex->is_stmt_unsafe()) &&
 
3701
             (flags_all_set & HA_BINLOG_ROW_CAPABLE) == 0)
 
3702
    {
 
3703
      my_error((error= ER_BINLOG_LOGGING_IMPOSSIBLE), MYF(0),
 
3704
                "Row-based format required for this statement,"
 
3705
                " but not allowed by this combination of engines");
 
3706
    }
 
3707
 
 
3708
    if (error)
 
3709
      return -1;
 
3710
 
 
3711
    /*
 
3712
      We switch to row-based format if we are in mixed mode and one of
 
3713
      the following are true:
 
3714
 
 
3715
      1. If the statement is unsafe
 
3716
      2. If statement format cannot be used
 
3717
 
 
3718
      Observe that point to cannot be decided before the tables
 
3719
      involved in a statement has been checked, i.e., we cannot put
 
3720
      this code in reset_current_stmt_binlog_row_based(), it has to be
 
3721
      here.
 
3722
    */
 
3723
    if (thd->lex->is_stmt_unsafe() ||
 
3724
        (flags_all_set & HA_BINLOG_STMT_CAPABLE) == 0)
 
3725
    {
 
3726
      thd->set_current_stmt_binlog_row_based_if_mixed();
 
3727
    }
 
3728
  }
 
3729
 
 
3730
  return 0;
2251
3731
}
2252
3732
 
2253
3733
/*
2254
3734
  Lock all tables in list
2255
3735
 
2256
3736
  SYNOPSIS
2257
 
  lock_tables()
2258
 
  session                       Thread Cursor
2259
 
  tables                Tables to lock
2260
 
  count         Number of opened tables
2261
 
  need_reopen         Out parameter which if true indicates that some
2262
 
  tables were dropped or altered during this call
2263
 
  and therefore invoker should reopen tables and
2264
 
  try to lock them once again (in this case
2265
 
  lock_tables() will also return error).
 
3737
    lock_tables()
 
3738
    thd                 Thread handler
 
3739
    tables              Tables to lock
 
3740
    count               Number of opened tables
 
3741
    need_reopen         Out parameter which if true indicates that some
 
3742
                        tables were dropped or altered during this call
 
3743
                        and therefore invoker should reopen tables and
 
3744
                        try to lock them once again (in this case
 
3745
                        lock_tables() will also return error).
2266
3746
 
2267
3747
  NOTES
2268
 
  You can't call lock_tables twice, as this would break the dead-lock-free
2269
 
  handling thr_lock gives us.  You most always get all needed locks at
2270
 
  once.
 
3748
    You can't call lock_tables twice, as this would break the dead-lock-free
 
3749
    handling thr_lock gives us.  You most always get all needed locks at
 
3750
    once.
2271
3751
 
2272
 
  If query for which we are calling this function marked as requring
2273
 
  prelocking, this function will do implicit LOCK TABLES and change
2274
 
  session::prelocked_mode accordingly.
 
3752
    If query for which we are calling this function marked as requring
 
3753
    prelocking, this function will do implicit LOCK TABLES and change
 
3754
    thd::prelocked_mode accordingly.
2275
3755
 
2276
3756
  RETURN VALUES
2277
 
  0     ok
2278
 
  -1    Error
 
3757
   0    ok
 
3758
   -1   Error
2279
3759
*/
2280
3760
 
2281
 
int Session::lock_tables(TableList *tables, uint32_t count, bool *need_reopen)
 
3761
int lock_tables(THD *thd, TableList *tables, uint32_t count, bool *need_reopen)
2282
3762
{
2283
3763
  TableList *table;
2284
 
  Session *session= this;
2285
3764
 
2286
3765
  /*
2287
3766
    We can't meet statement requiring prelocking if we already
2289
3768
  */
2290
3769
  *need_reopen= false;
2291
3770
 
2292
 
  if (tables == NULL)
2293
 
    return 0;
2294
 
 
2295
 
  assert(session->lock == 0);   // You must lock everything at once
2296
 
  Table **start,**ptr;
2297
 
  uint32_t lock_flag= DRIZZLE_LOCK_NOTIFY_IF_NEED_REOPEN;
2298
 
 
2299
 
  if (!(ptr=start=(Table**) session->alloc(sizeof(Table*)*count)))
2300
 
    return -1;
2301
 
  for (table= tables; table; table= table->next_global)
2302
 
  {
2303
 
    if (!table->placeholder())
2304
 
      *(ptr++)= table->table;
2305
 
  }
2306
 
 
2307
 
  if (!(session->lock= mysql_lock_tables(session, start, (uint32_t) (ptr - start),
2308
 
                                         lock_flag, need_reopen)))
2309
 
  {
2310
 
    return -1;
2311
 
  }
2312
 
 
2313
 
  return 0;
 
3771
  if (!tables)
 
3772
    return(decide_logging_format(thd, tables));
 
3773
 
 
3774
  if (!thd->locked_tables)
 
3775
  {
 
3776
    assert(thd->lock == 0);     // You must lock everything at once
 
3777
    Table **start,**ptr;
 
3778
    uint32_t lock_flag= DRIZZLE_LOCK_NOTIFY_IF_NEED_REOPEN;
 
3779
 
 
3780
    if (!(ptr=start=(Table**) thd->alloc(sizeof(Table*)*count)))
 
3781
      return(-1);
 
3782
    for (table= tables; table; table= table->next_global)
 
3783
    {
 
3784
      if (!table->placeholder())
 
3785
        *(ptr++)= table->table;
 
3786
    }
 
3787
 
 
3788
    if (!(thd->lock= mysql_lock_tables(thd, start, (uint) (ptr - start),
 
3789
                                       lock_flag, need_reopen)))
 
3790
    {
 
3791
      return(-1);
 
3792
    }
 
3793
  }
 
3794
  else
 
3795
  {
 
3796
    TableList *first_not_own= thd->lex->first_not_own_table();
 
3797
    /*
 
3798
      When open_and_lock_tables() is called for a single table out of
 
3799
      a table list, the 'next_global' chain is temporarily broken. We
 
3800
      may not find 'first_not_own' before the end of the "list".
 
3801
      Look for example at those places where open_n_lock_single_table()
 
3802
      is called. That function implements the temporary breaking of
 
3803
      a table list for opening a single table.
 
3804
    */
 
3805
    for (table= tables;
 
3806
         table && table != first_not_own;
 
3807
         table= table->next_global)
 
3808
    {
 
3809
      if (!table->placeholder() &&
 
3810
          check_lock_and_start_stmt(thd, table->table, table->lock_type))
 
3811
      {
 
3812
        return(-1);
 
3813
      }
 
3814
    }
 
3815
  }
 
3816
 
 
3817
  return(decide_logging_format(thd, tables));
 
3818
}
 
3819
 
 
3820
 
 
3821
/*
 
3822
  Prepare statement for reopening of tables and recalculation of set of
 
3823
  prelocked tables.
 
3824
 
 
3825
  SYNOPSIS
 
3826
    close_tables_for_reopen()
 
3827
      thd    in     Thread context
 
3828
      tables in/out List of tables which we were trying to open and lock
 
3829
 
 
3830
*/
 
3831
 
 
3832
void close_tables_for_reopen(THD *thd, TableList **tables)
 
3833
{
 
3834
  /*
 
3835
    If table list consists only from tables from prelocking set, table list
 
3836
    for new attempt should be empty, so we have to update list's root pointer.
 
3837
  */
 
3838
  if (thd->lex->first_not_own_table() == *tables)
 
3839
    *tables= 0;
 
3840
  thd->lex->chop_off_not_own_tables();
 
3841
  for (TableList *tmp= *tables; tmp; tmp= tmp->next_global)
 
3842
    tmp->table= 0;
 
3843
  close_thread_tables(thd);
2314
3844
}
2315
3845
 
2316
3846
 
2318
3848
  Open a single table without table caching and don't set it in open_list
2319
3849
 
2320
3850
  SYNPOSIS
2321
 
  open_temporary_table()
2322
 
  session                 Thread object
2323
 
  path    Path (without .frm)
2324
 
  db              database
2325
 
  table_name      Table name
2326
 
  link_in_list  1 if table should be linked into session->temporary_tables
2327
 
 
2328
 
NOTES:
2329
 
Used by alter_table to open a temporary table and when creating
2330
 
a temporary table with CREATE TEMPORARY ...
2331
 
 
2332
 
RETURN
2333
 
0  Error
2334
 
#  Table object
 
3851
    open_temporary_table()
 
3852
    thd           Thread object
 
3853
    path          Path (without .frm)
 
3854
    db            database
 
3855
    table_name    Table name
 
3856
    link_in_list  1 if table should be linked into thd->temporary_tables
 
3857
 
 
3858
 NOTES:
 
3859
    Used by alter_table to open a temporary table and when creating
 
3860
    a temporary table with CREATE TEMPORARY ...
 
3861
 
 
3862
 RETURN
 
3863
   0  Error
 
3864
   #  Table object
2335
3865
*/
2336
3866
 
2337
 
Table *Session::open_temporary_table(TableIdentifier &identifier,
2338
 
                                     bool link_in_list)
 
3867
Table *open_temporary_table(THD *thd, const char *path, const char *db,
 
3868
                            const char *table_name, bool link_in_list,
 
3869
                            open_table_mode open_mode)
2339
3870
{
2340
 
  TableShare *share;
2341
 
 
2342
 
  assert(identifier.isTmp());
2343
 
  share= new TableShare(identifier.getType(),
2344
 
                        identifier,
2345
 
                        const_cast<char *>(identifier.getPath().c_str()), static_cast<uint32_t>(identifier.getPath().length()));
2346
 
 
2347
 
 
2348
 
  Table *new_tmp_table= new Table;
2349
 
  if (not new_tmp_table)
2350
 
    return NULL;
2351
 
 
2352
 
  /*
2353
 
    First open the share, and then open the table from the share we just opened.
2354
 
  */
2355
 
  if (share->open_table_def(*this, identifier) ||
2356
 
      share->open_table_from_share(this, identifier, identifier.getTableName().c_str(),
2357
 
                            (uint32_t) (HA_OPEN_KEYFILE | HA_OPEN_RNDFILE |
2358
 
                                        HA_GET_INDEX),
 
3871
  Table *tmp_table;
 
3872
  TABLE_SHARE *share;
 
3873
  char cache_key[MAX_DBKEY_LENGTH], *saved_cache_key, *tmp_path;
 
3874
  uint32_t key_length;
 
3875
  TableList table_list;
 
3876
 
 
3877
  table_list.db=         (char*) db;
 
3878
  table_list.table_name= (char*) table_name;
 
3879
  /* Create the cache_key for temporary tables */
 
3880
  key_length= create_table_def_key(thd, cache_key, &table_list, 1);
 
3881
 
 
3882
  if (!(tmp_table= (Table*) my_malloc(sizeof(*tmp_table) + sizeof(*share) +
 
3883
                                      strlen(path)+1 + key_length,
 
3884
                                      MYF(MY_WME))))
 
3885
    return(0);                          /* purecov: inspected */
 
3886
 
 
3887
  share= (TABLE_SHARE*) (tmp_table+1);
 
3888
  tmp_path= (char*) (share+1);
 
3889
  saved_cache_key= my_stpcpy(tmp_path, path)+1;
 
3890
  memcpy(saved_cache_key, cache_key, key_length);
 
3891
 
 
3892
  init_tmp_table_share(thd, share, saved_cache_key, key_length,
 
3893
                       strchr(saved_cache_key, '\0')+1, tmp_path);
 
3894
 
 
3895
  if (open_table_def(thd, share, 0) ||
 
3896
      open_table_from_share(thd, share, table_name,
 
3897
                            (open_mode == OTM_ALTER) ? 0 :
 
3898
                            (uint) (HA_OPEN_KEYFILE | HA_OPEN_RNDFILE |
 
3899
                                    HA_GET_INDEX),
 
3900
                            (open_mode == OTM_ALTER) ?
 
3901
                              (EXTRA_RECORD | OPEN_FRM_FILE_ONLY)
 
3902
                            : (EXTRA_RECORD),
2359
3903
                            ha_open_options,
2360
 
                            *new_tmp_table))
 
3904
                            tmp_table, open_mode))
2361
3905
  {
2362
3906
    /* No need to lock share->mutex as this is not needed for tmp tables */
2363
 
    delete share;
2364
 
    delete new_tmp_table;
2365
 
 
2366
 
    return 0;
2367
 
  }
2368
 
 
2369
 
  new_tmp_table->reginfo.lock_type= TL_WRITE;    // Simulate locked
 
3907
    free_table_share(share);
 
3908
    free((char*) tmp_table);
 
3909
    return(0);
 
3910
  }
 
3911
 
 
3912
  tmp_table->reginfo.lock_type= TL_WRITE;        // Simulate locked
 
3913
  if (open_mode == OTM_ALTER)
 
3914
  {
 
3915
    /*
 
3916
       Temporary table has been created with frm_only
 
3917
       and has not been created in any storage engine
 
3918
    */
 
3919
    share->tmp_table= TMP_TABLE_FRM_FILE_ONLY;
 
3920
  }
 
3921
  else
 
3922
    share->tmp_table= (tmp_table->file->has_transactions() ?
 
3923
                       TRANSACTIONAL_TMP_TABLE : NON_TRANSACTIONAL_TMP_TABLE);
2370
3924
 
2371
3925
  if (link_in_list)
2372
3926
  {
2373
3927
    /* growing temp list at the head */
2374
 
    new_tmp_table->setNext(this->temporary_tables);
2375
 
    if (new_tmp_table->getNext())
2376
 
    {
2377
 
      new_tmp_table->getNext()->setPrev(new_tmp_table);
2378
 
    }
2379
 
    this->temporary_tables= new_tmp_table;
2380
 
    this->temporary_tables->setPrev(0);
2381
 
  }
2382
 
  new_tmp_table->pos_in_table_list= 0;
2383
 
 
2384
 
  return new_tmp_table;
 
3928
    tmp_table->next= thd->temporary_tables;
 
3929
    if (tmp_table->next)
 
3930
      tmp_table->next->prev= tmp_table;
 
3931
    thd->temporary_tables= tmp_table;
 
3932
    thd->temporary_tables->prev= 0;
 
3933
    if (thd->slave_thread)
 
3934
      slave_open_temp_tables++;
 
3935
  }
 
3936
  tmp_table->pos_in_table_list= 0;
 
3937
  return(tmp_table);
 
3938
}
 
3939
 
 
3940
 
 
3941
bool rm_temporary_table(handlerton *base, char *path, bool frm_only)
 
3942
{
 
3943
  bool error=0;
 
3944
  handler *file;
 
3945
  char *ext;
 
3946
 
 
3947
  my_stpcpy(ext= strchr(path, '\0'), reg_ext);
 
3948
  if (my_delete(path,MYF(0)))
 
3949
    error=1; /* purecov: inspected */
 
3950
  *ext= 0;                              // remove extension
 
3951
  file= get_new_handler((TABLE_SHARE*) 0, current_thd->mem_root, base);
 
3952
  if (!frm_only && file && file->ha_delete_table(path))
 
3953
  {
 
3954
    error=1;
 
3955
    sql_print_warning(_("Could not remove temporary table: '%s', error: %d"),
 
3956
                      path, my_errno);
 
3957
  }
 
3958
  delete file;
 
3959
  return(error);
2385
3960
}
2386
3961
 
2387
3962
 
2388
3963
/*****************************************************************************
2389
 
 * The following find_field_in_XXX procedures implement the core of the
2390
 
 * name resolution functionality. The entry point to resolve a column name in a
2391
 
 * list of tables is 'find_field_in_tables'. It calls 'find_field_in_table_ref'
2392
 
 * for each table reference. In turn, depending on the type of table reference,
2393
 
 * 'find_field_in_table_ref' calls one of the 'find_field_in_XXX' procedures
2394
 
 * below specific for the type of table reference.
2395
 
 ******************************************************************************/
 
3964
* The following find_field_in_XXX procedures implement the core of the
 
3965
* name resolution functionality. The entry point to resolve a column name in a
 
3966
* list of tables is 'find_field_in_tables'. It calls 'find_field_in_table_ref'
 
3967
* for each table reference. In turn, depending on the type of table reference,
 
3968
* 'find_field_in_table_ref' calls one of the 'find_field_in_XXX' procedures
 
3969
* below specific for the type of table reference.
 
3970
******************************************************************************/
2396
3971
 
2397
3972
/* Special Field pointers as return values of find_field_in_XXX functions. */
2398
3973
Field *not_found_field= (Field*) 0x1;
2399
 
Field *view_ref_found= (Field*) 0x2;
2400
 
 
2401
 
static void update_field_dependencies(Session *session, Field *field, Table *table)
 
3974
Field *view_ref_found= (Field*) 0x2; 
 
3975
 
 
3976
#define WRONG_GRANT (Field*) -1
 
3977
 
 
3978
static void update_field_dependencies(THD *thd, Field *field, Table *table)
2402
3979
{
2403
 
  if (session->mark_used_columns != MARK_COLUMNS_NONE)
 
3980
  if (thd->mark_used_columns != MARK_COLUMNS_NONE)
2404
3981
  {
2405
 
    MyBitmap *current_bitmap, *other_bitmap;
 
3982
    MY_BITMAP *current_bitmap, *other_bitmap;
2406
3983
 
2407
3984
    /*
2408
3985
      We always want to register the used keys, as the column bitmap may have
2409
3986
      been set for all fields (for example for view).
2410
3987
    */
2411
 
 
2412
 
    table->covering_keys&= field->part_of_key;
2413
 
    table->merge_keys|= field->part_of_key;
2414
 
 
2415
 
    if (session->mark_used_columns == MARK_COLUMNS_READ)
 
3988
      
 
3989
    table->covering_keys.intersect(field->part_of_key);
 
3990
    table->merge_keys.merge(field->part_of_key);
 
3991
 
 
3992
    if (thd->mark_used_columns == MARK_COLUMNS_READ)
2416
3993
    {
2417
3994
      current_bitmap= table->read_set;
2418
3995
      other_bitmap=   table->write_set;
2423
4000
      other_bitmap=   table->read_set;
2424
4001
    }
2425
4002
 
2426
 
    if (current_bitmap->testAndSet(field->field_index))
 
4003
    if (bitmap_fast_test_and_set(current_bitmap, field->field_index))
2427
4004
    {
2428
 
      if (session->mark_used_columns == MARK_COLUMNS_WRITE)
2429
 
        session->dup_field= field;
 
4005
      if (thd->mark_used_columns == MARK_COLUMNS_WRITE)
 
4006
        thd->dup_field= field;
2430
4007
      return;
2431
4008
    }
 
4009
    if (table->get_fields_in_item_tree)
 
4010
      field->flags|= GET_FIXED_FIELDS_FLAG;
2432
4011
    table->used_fields++;
2433
4012
  }
 
4013
  else if (table->get_fields_in_item_tree)
 
4014
    field->flags|= GET_FIXED_FIELDS_FLAG;
 
4015
  return;
2434
4016
}
2435
4017
 
2436
4018
 
2438
4020
  Find field by name in a NATURAL/USING join table reference.
2439
4021
 
2440
4022
  SYNOPSIS
2441
 
  find_field_in_natural_join()
2442
 
  session                        [in]  thread Cursor
2443
 
  table_ref            [in]  table reference to search
2444
 
  name           [in]  name of field
2445
 
  length                 [in]  length of name
2446
 
  ref                  [in/out] if 'name' is resolved to a view field, ref is
2447
 
  set to point to the found view field
2448
 
  register_tree_change [in]  true if ref is not stack variable and we
2449
 
  need register changes in item tree
2450
 
  actual_table         [out] the original table reference where the field
2451
 
  belongs - differs from 'table_list' only for
2452
 
  NATURAL/USING joins
 
4023
    find_field_in_natural_join()
 
4024
    thd                  [in]  thread handler
 
4025
    table_ref            [in]  table reference to search
 
4026
    name                 [in]  name of field
 
4027
    length               [in]  length of name
 
4028
    ref                  [in/out] if 'name' is resolved to a view field, ref is
 
4029
                               set to point to the found view field
 
4030
    register_tree_change [in]  true if ref is not stack variable and we
 
4031
                               need register changes in item tree
 
4032
    actual_table         [out] the original table reference where the field
 
4033
                               belongs - differs from 'table_list' only for
 
4034
                               NATURAL/USING joins
2453
4035
 
2454
4036
  DESCRIPTION
2455
 
  Search for a field among the result fields of a NATURAL/USING join.
2456
 
  Notice that this procedure is called only for non-qualified field
2457
 
  names. In the case of qualified fields, we search directly the base
2458
 
  tables of a natural join.
 
4037
    Search for a field among the result fields of a NATURAL/USING join.
 
4038
    Notice that this procedure is called only for non-qualified field
 
4039
    names. In the case of qualified fields, we search directly the base
 
4040
    tables of a natural join.
2459
4041
 
2460
4042
  RETURN
2461
 
  NULL        if the field was not found
2462
 
  PTR         Pointer to the found Field
 
4043
    NULL        if the field was not found
 
4044
    WRONG_GRANT if no access rights to the found field
 
4045
    #           Pointer to the found Field
2463
4046
*/
2464
4047
 
2465
4048
static Field *
2466
 
find_field_in_natural_join(Session *session, TableList *table_ref,
2467
 
                           const char *name, uint32_t , Item **,
2468
 
                           bool, TableList **actual_table)
 
4049
find_field_in_natural_join(THD *thd, TableList *table_ref, const char *name,
 
4050
                           uint32_t length __attribute__((unused)),
 
4051
                           Item **ref __attribute__((unused)), bool register_tree_change __attribute__((unused)),
 
4052
                           TableList **actual_table)
2469
4053
{
2470
4054
  List_iterator_fast<Natural_join_column>
2471
4055
    field_it(*(table_ref->join_columns));
2475
4059
  assert(table_ref->is_natural_join && table_ref->join_columns);
2476
4060
  assert(*actual_table == NULL);
2477
4061
 
2478
 
  for (nj_col= NULL, curr_nj_col= field_it++; curr_nj_col;
 
4062
  for (nj_col= NULL, curr_nj_col= field_it++; curr_nj_col; 
2479
4063
       curr_nj_col= field_it++)
2480
4064
  {
2481
4065
    if (!my_strcasecmp(system_charset_info, curr_nj_col->name(), name))
2482
4066
    {
2483
4067
      if (nj_col)
2484
4068
      {
2485
 
        my_error(ER_NON_UNIQ_ERROR, MYF(0), name, session->where);
2486
 
        return NULL;
 
4069
        my_error(ER_NON_UNIQ_ERROR, MYF(0), name, thd->where);
 
4070
        return(NULL);
2487
4071
      }
2488
4072
      nj_col= curr_nj_col;
2489
4073
    }
2490
4074
  }
2491
4075
  if (!nj_col)
2492
 
    return NULL;
 
4076
    return(NULL);
2493
4077
  {
2494
4078
    /* This is a base table. */
2495
 
    assert(nj_col->table_ref->table == nj_col->table_field->getTable());
 
4079
    assert(nj_col->table_ref->table == nj_col->table_field->table);
2496
4080
    found_field= nj_col->table_field;
2497
 
    update_field_dependencies(session, found_field, nj_col->table_ref->table);
 
4081
    update_field_dependencies(thd, found_field, nj_col->table_ref->table);
2498
4082
  }
2499
4083
 
2500
4084
  *actual_table= nj_col->table_ref;
2501
 
 
 
4085
  
2502
4086
  return(found_field);
2503
4087
}
2504
4088
 
2507
4091
  Find field by name in a base table or a view with temp table algorithm.
2508
4092
 
2509
4093
  SYNOPSIS
2510
 
  find_field_in_table()
2511
 
  session                               thread Cursor
2512
 
  table                 table where to search for the field
2513
 
  name                  name of field
2514
 
  length                        length of name
2515
 
  allow_rowid                   do allow finding of "_rowid" field?
2516
 
  cached_field_index_ptr        cached position in field list (used to speedup
2517
 
  lookup for fields in prepared tables)
 
4094
    find_field_in_table()
 
4095
    thd                         thread handler
 
4096
    table                       table where to search for the field
 
4097
    name                        name of field
 
4098
    length                      length of name
 
4099
    allow_rowid                 do allow finding of "_rowid" field?
 
4100
    cached_field_index_ptr      cached position in field list (used to speedup
 
4101
                                lookup for fields in prepared tables)
2518
4102
 
2519
4103
  RETURN
2520
 
  0     field is not found
2521
 
#       pointer to field
 
4104
    0   field is not found
 
4105
    #   pointer to field
2522
4106
*/
2523
4107
 
2524
4108
Field *
2525
 
find_field_in_table(Session *session, Table *table, const char *name, uint32_t length,
 
4109
find_field_in_table(THD *thd, Table *table, const char *name, uint32_t length,
2526
4110
                    bool allow_rowid, uint32_t *cached_field_index_ptr)
2527
4111
{
2528
4112
  Field **field_ptr, *field;
2529
4113
  uint32_t cached_field_index= *cached_field_index_ptr;
2530
4114
 
2531
4115
  /* We assume here that table->field < NO_CACHED_FIELD_INDEX = UINT_MAX */
2532
 
  if (cached_field_index < table->getShare()->sizeFields() &&
 
4116
  if (cached_field_index < table->s->fields &&
2533
4117
      !my_strcasecmp(system_charset_info,
2534
 
                     table->getField(cached_field_index)->field_name, name))
2535
 
  {
2536
 
    field_ptr= table->getFields() + cached_field_index;
2537
 
  }
2538
 
  else if (table->getShare()->getNamedFieldSize())
2539
 
  {
2540
 
    field_ptr= table->getMutableShare()->getNamedField(std::string(name, length));
 
4118
                     table->field[cached_field_index]->field_name, name))
 
4119
    field_ptr= table->field + cached_field_index;
 
4120
  else if (table->s->name_hash.records)
 
4121
  {
 
4122
    field_ptr= (Field**) hash_search(&table->s->name_hash, (unsigned char*) name,
 
4123
                                     length);
2541
4124
    if (field_ptr)
2542
4125
    {
2543
4126
      /*
2544
 
        field_ptr points to field in TableShare. Convert it to the matching
 
4127
        field_ptr points to field in TABLE_SHARE. Convert it to the matching
2545
4128
        field in table
2546
4129
      */
2547
 
      field_ptr= (table->getFields() + table->getShare()->positionFields(field_ptr));
 
4130
      field_ptr= (table->field + (field_ptr - table->s->field));
2548
4131
    }
2549
4132
  }
2550
4133
  else
2551
4134
  {
2552
 
    if (!(field_ptr= table->getFields()))
 
4135
    if (!(field_ptr= table->field))
2553
4136
      return((Field *)0);
2554
4137
    for (; *field_ptr; ++field_ptr)
2555
4138
      if (!my_strcasecmp(system_charset_info, (*field_ptr)->field_name, name))
2558
4141
 
2559
4142
  if (field_ptr && *field_ptr)
2560
4143
  {
2561
 
    *cached_field_index_ptr= field_ptr - table->getFields();
 
4144
    *cached_field_index_ptr= field_ptr - table->field;
2562
4145
    field= *field_ptr;
2563
4146
  }
2564
4147
  else
2565
4148
  {
2566
4149
    if (!allow_rowid ||
2567
4150
        my_strcasecmp(system_charset_info, name, "_rowid") ||
2568
 
        table->getShare()->rowid_field_offset == 0)
 
4151
        table->s->rowid_field_offset == 0)
2569
4152
      return((Field*) 0);
2570
 
    field= table->getField(table->getShare()->rowid_field_offset-1);
 
4153
    field= table->field[table->s->rowid_field_offset-1];
2571
4154
  }
2572
4155
 
2573
 
  update_field_dependencies(session, field, table);
 
4156
  update_field_dependencies(thd, field, table);
2574
4157
 
2575
 
  return field;
 
4158
  return(field);
2576
4159
}
2577
4160
 
2578
4161
 
2580
4163
  Find field in a table reference.
2581
4164
 
2582
4165
  SYNOPSIS
2583
 
  find_field_in_table_ref()
2584
 
  session                          [in]  thread Cursor
2585
 
  table_list               [in]  table reference to search
2586
 
  name             [in]  name of field
2587
 
  length                   [in]  field length of name
2588
 
  item_name              [in]  name of item if it will be created (VIEW)
2589
 
  db_name                [in]  optional database name that qualifies the
2590
 
  table_name             [in]  optional table name that qualifies the field
2591
 
  ref                  [in/out] if 'name' is resolved to a view field, ref
2592
 
  is set to point to the found view field
2593
 
  allow_rowid              [in]  do allow finding of "_rowid" field?
2594
 
  cached_field_index_ptr [in]  cached position in field list (used to
2595
 
  speedup lookup for fields in prepared tables)
2596
 
  register_tree_change   [in]  true if ref is not stack variable and we
2597
 
  need register changes in item tree
2598
 
  actual_table           [out] the original table reference where the field
2599
 
  belongs - differs from 'table_list' only for
2600
 
  NATURAL_USING joins.
 
4166
    find_field_in_table_ref()
 
4167
    thd                    [in]  thread handler
 
4168
    table_list             [in]  table reference to search
 
4169
    name                   [in]  name of field
 
4170
    length                 [in]  field length of name
 
4171
    item_name              [in]  name of item if it will be created (VIEW)
 
4172
    db_name                [in]  optional database name that qualifies the
 
4173
    table_name             [in]  optional table name that qualifies the field
 
4174
    ref                [in/out] if 'name' is resolved to a view field, ref
 
4175
                                 is set to point to the found view field
 
4176
    check_privileges       [in]  check privileges
 
4177
    allow_rowid            [in]  do allow finding of "_rowid" field?
 
4178
    cached_field_index_ptr [in]  cached position in field list (used to
 
4179
                                 speedup lookup for fields in prepared tables)
 
4180
    register_tree_change   [in]  true if ref is not stack variable and we
 
4181
                                 need register changes in item tree
 
4182
    actual_table           [out] the original table reference where the field
 
4183
                                 belongs - differs from 'table_list' only for
 
4184
                                 NATURAL_USING joins.
2601
4185
 
2602
4186
  DESCRIPTION
2603
 
  Find a field in a table reference depending on the type of table
2604
 
  reference. There are three types of table references with respect
2605
 
  to the representation of their result columns:
2606
 
  - an array of Field_translator objects for MERGE views and some
2607
 
  information_schema tables,
2608
 
  - an array of Field objects (and possibly a name hash) for stored
2609
 
  tables,
2610
 
  - a list of Natural_join_column objects for NATURAL/USING joins.
2611
 
  This procedure detects the type of the table reference 'table_list'
2612
 
  and calls the corresponding search routine.
 
4187
    Find a field in a table reference depending on the type of table
 
4188
    reference. There are three types of table references with respect
 
4189
    to the representation of their result columns:
 
4190
    - an array of Field_translator objects for MERGE views and some
 
4191
      information_schema tables,
 
4192
    - an array of Field objects (and possibly a name hash) for stored
 
4193
      tables,
 
4194
    - a list of Natural_join_column objects for NATURAL/USING joins.
 
4195
    This procedure detects the type of the table reference 'table_list'
 
4196
    and calls the corresponding search routine.
2613
4197
 
2614
4198
  RETURN
2615
 
  0                     field is not found
2616
 
  view_ref_found        found value in VIEW (real result is in *ref)
2617
 
#                       pointer to field
 
4199
    0                   field is not found
 
4200
    view_ref_found      found value in VIEW (real result is in *ref)
 
4201
    #                   pointer to field
2618
4202
*/
2619
4203
 
2620
4204
Field *
2621
 
find_field_in_table_ref(Session *session, TableList *table_list,
 
4205
find_field_in_table_ref(THD *thd, TableList *table_list,
2622
4206
                        const char *name, uint32_t length,
2623
4207
                        const char *item_name, const char *db_name,
2624
4208
                        const char *table_name, Item **ref,
2625
 
                        bool allow_rowid,
 
4209
                        bool check_privileges, bool allow_rowid,
2626
4210
                        uint32_t *cached_field_index_ptr,
2627
4211
                        bool register_tree_change, TableList **actual_table)
2628
4212
{
2646
4230
    inside the view, but we want to search directly in the view columns
2647
4231
    which are represented as a 'field_translation'.
2648
4232
 
2649
 
    TODO-> Ensure that table_name, db_name and tables->db always points to something !
 
4233
    TODO: Ensure that table_name, db_name and tables->db always points to
 
4234
          something !
2650
4235
  */
2651
4236
  if (/* Exclude nested joins. */
2652
 
      (!table_list->getNestedJoin()) &&
2653
 
      /* Include merge views and information schema tables. */
 
4237
      (!table_list->nested_join ||
 
4238
       /* Include merge views and information schema tables. */
 
4239
       table_list->field_translation) &&
2654
4240
      /*
2655
4241
        Test if the field qualifiers match the table reference we plan
2656
4242
        to search.
2659
4245
      (my_strcasecmp(table_alias_charset, table_list->alias, table_name) ||
2660
4246
       (db_name && db_name[0] && table_list->db && table_list->db[0] &&
2661
4247
        strcmp(db_name, table_list->db))))
2662
 
    return 0;
 
4248
    return(0);
2663
4249
 
2664
4250
  *actual_table= NULL;
2665
4251
 
2666
 
  if (!table_list->getNestedJoin())
 
4252
  if (table_list->field_translation)
 
4253
  {
 
4254
  }
 
4255
  else if (!table_list->nested_join)
2667
4256
  {
2668
4257
    /* 'table_list' is a stored table. */
2669
4258
    assert(table_list->table);
2670
 
    if ((fld= find_field_in_table(session, table_list->table, name, length,
 
4259
    if ((fld= find_field_in_table(thd, table_list->table, name, length,
2671
4260
                                  allow_rowid,
2672
4261
                                  cached_field_index_ptr)))
2673
4262
      *actual_table= table_list;
2683
4272
    */
2684
4273
    if (table_name && table_name[0])
2685
4274
    {
2686
 
      List_iterator<TableList> it(table_list->getNestedJoin()->join_list);
 
4275
      List_iterator<TableList> it(table_list->nested_join->join_list);
2687
4276
      TableList *table;
2688
4277
      while ((table= it++))
2689
4278
      {
2690
 
        if ((fld= find_field_in_table_ref(session, table, name, length, item_name,
 
4279
        if ((fld= find_field_in_table_ref(thd, table, name, length, item_name,
2691
4280
                                          db_name, table_name, ref,
2692
 
                                          allow_rowid,
 
4281
                                          check_privileges, allow_rowid,
2693
4282
                                          cached_field_index_ptr,
2694
4283
                                          register_tree_change, actual_table)))
2695
 
          return fld;
 
4284
          return(fld);
2696
4285
      }
2697
 
      return NULL;
 
4286
      return(0);
2698
4287
    }
2699
4288
    /*
2700
4289
      Non-qualified field, search directly in the result columns of the
2702
4291
      natural join, thus if the field is not qualified, we will search
2703
4292
      directly the top-most NATURAL/USING join.
2704
4293
    */
2705
 
    fld= find_field_in_natural_join(session, table_list, name, length, ref,
 
4294
    fld= find_field_in_natural_join(thd, table_list, name, length, ref,
2706
4295
                                    register_tree_change, actual_table);
2707
4296
  }
2708
4297
 
2709
4298
  if (fld)
2710
4299
  {
2711
 
    if (session->mark_used_columns != MARK_COLUMNS_NONE)
2712
 
    {
2713
 
      /*
2714
 
        Get rw_set correct for this field so that the Cursor
2715
 
        knows that this field is involved in the query and gets
2716
 
        retrieved/updated
2717
 
      */
2718
 
      Field *field_to_set= NULL;
2719
 
      if (fld == view_ref_found)
2720
 
      {
2721
 
        Item *it= (*ref)->real_item();
2722
 
        if (it->type() == Item::FIELD_ITEM)
2723
 
          field_to_set= ((Item_field*)it)->field;
2724
 
        else
2725
 
        {
2726
 
          if (session->mark_used_columns == MARK_COLUMNS_READ)
2727
 
            it->walk(&Item::register_field_in_read_map, 1, (unsigned char *) 0);
2728
 
        }
2729
 
      }
2730
 
      else
2731
 
        field_to_set= fld;
2732
 
      if (field_to_set)
2733
 
      {
2734
 
        Table *table= field_to_set->getTable();
2735
 
        if (session->mark_used_columns == MARK_COLUMNS_READ)
2736
 
          table->setReadSet(field_to_set->field_index);
2737
 
        else
2738
 
          table->setWriteSet(field_to_set->field_index);
2739
 
      }
2740
 
    }
 
4300
      if (thd->mark_used_columns != MARK_COLUMNS_NONE)
 
4301
      {
 
4302
        /*
 
4303
          Get rw_set correct for this field so that the handler
 
4304
          knows that this field is involved in the query and gets
 
4305
          retrieved/updated
 
4306
         */
 
4307
        Field *field_to_set= NULL;
 
4308
        if (fld == view_ref_found)
 
4309
        {
 
4310
          Item *it= (*ref)->real_item();
 
4311
          if (it->type() == Item::FIELD_ITEM)
 
4312
            field_to_set= ((Item_field*)it)->field;
 
4313
          else
 
4314
          {
 
4315
            if (thd->mark_used_columns == MARK_COLUMNS_READ)
 
4316
              it->walk(&Item::register_field_in_read_map, 1, (unsigned char *) 0);
 
4317
          }
 
4318
        }
 
4319
        else
 
4320
          field_to_set= fld;
 
4321
        if (field_to_set)
 
4322
        {
 
4323
          Table *table= field_to_set->table;
 
4324
          if (thd->mark_used_columns == MARK_COLUMNS_READ)
 
4325
            bitmap_set_bit(table->read_set, field_to_set->field_index);
 
4326
          else
 
4327
            bitmap_set_bit(table->write_set, field_to_set->field_index);
 
4328
        }
 
4329
      }
2741
4330
  }
2742
4331
  return(fld);
2743
4332
}
2744
4333
 
2745
4334
 
2746
4335
/*
 
4336
  Find field in table, no side effects, only purpose is to check for field
 
4337
  in table object and get reference to the field if found.
 
4338
 
 
4339
  SYNOPSIS
 
4340
  find_field_in_table_sef()
 
4341
 
 
4342
  table                         table where to find
 
4343
  name                          Name of field searched for
 
4344
 
 
4345
  RETURN
 
4346
    0                   field is not found
 
4347
    #                   pointer to field
 
4348
*/
 
4349
 
 
4350
Field *find_field_in_table_sef(Table *table, const char *name)
 
4351
{
 
4352
  Field **field_ptr;
 
4353
  if (table->s->name_hash.records)
 
4354
  {
 
4355
    field_ptr= (Field**)hash_search(&table->s->name_hash,(unsigned char*) name,
 
4356
                                    strlen(name));
 
4357
    if (field_ptr)
 
4358
    {
 
4359
      /*
 
4360
        field_ptr points to field in TABLE_SHARE. Convert it to the matching
 
4361
        field in table
 
4362
      */
 
4363
      field_ptr= (table->field + (field_ptr - table->s->field));
 
4364
    }
 
4365
  }
 
4366
  else
 
4367
  {
 
4368
    if (!(field_ptr= table->field))
 
4369
      return (Field *)0;
 
4370
    for (; *field_ptr; ++field_ptr)
 
4371
      if (!my_strcasecmp(system_charset_info, (*field_ptr)->field_name, name))
 
4372
        break;
 
4373
  }
 
4374
  if (field_ptr)
 
4375
    return *field_ptr;
 
4376
  else
 
4377
    return (Field *)0;
 
4378
}
 
4379
 
 
4380
 
 
4381
/*
2747
4382
  Find field in table list.
2748
4383
 
2749
4384
  SYNOPSIS
2750
 
  find_field_in_tables()
2751
 
  session                         pointer to current thread structure
2752
 
  item            field item that should be found
2753
 
  first_table           list of tables to be searched for item
2754
 
  last_table            end of the list of tables to search for item. If NULL
2755
 
  then search to the end of the list 'first_table'.
2756
 
  ref                     if 'item' is resolved to a view field, ref is set to
2757
 
  point to the found view field
2758
 
  report_error    Degree of error reporting:
2759
 
  - IGNORE_ERRORS then do not report any error
2760
 
  - IGNORE_EXCEPT_NON_UNIQUE report only non-unique
2761
 
  fields, suppress all other errors
2762
 
  - REPORT_EXCEPT_NON_UNIQUE report all other errors
2763
 
  except when non-unique fields were found
2764
 
  - REPORT_ALL_ERRORS
2765
 
  register_tree_change  true if ref is not a stack variable and we
2766
 
  to need register changes in item tree
 
4385
    find_field_in_tables()
 
4386
    thd                   pointer to current thread structure
 
4387
    item                  field item that should be found
 
4388
    first_table           list of tables to be searched for item
 
4389
    last_table            end of the list of tables to search for item. If NULL
 
4390
                          then search to the end of the list 'first_table'.
 
4391
    ref                   if 'item' is resolved to a view field, ref is set to
 
4392
                          point to the found view field
 
4393
    report_error          Degree of error reporting:
 
4394
                          - IGNORE_ERRORS then do not report any error
 
4395
                          - IGNORE_EXCEPT_NON_UNIQUE report only non-unique
 
4396
                            fields, suppress all other errors
 
4397
                          - REPORT_EXCEPT_NON_UNIQUE report all other errors
 
4398
                            except when non-unique fields were found
 
4399
                          - REPORT_ALL_ERRORS
 
4400
    check_privileges      need to check privileges
 
4401
    register_tree_change  true if ref is not a stack variable and we
 
4402
                          to need register changes in item tree
2767
4403
 
2768
4404
  RETURN VALUES
2769
 
  0                     If error: the found field is not unique, or there are
2770
 
  no sufficient access priviliges for the found field,
2771
 
  or the field is qualified with non-existing table.
2772
 
  not_found_field       The function was called with report_error ==
2773
 
  (IGNORE_ERRORS || IGNORE_EXCEPT_NON_UNIQUE) and a
2774
 
  field was not found.
2775
 
  view_ref_found        View field is found, item passed through ref parameter
2776
 
  found field         If a item was resolved to some field
 
4405
    0                   If error: the found field is not unique, or there are
 
4406
                        no sufficient access priviliges for the found field,
 
4407
                        or the field is qualified with non-existing table.
 
4408
    not_found_field     The function was called with report_error ==
 
4409
                        (IGNORE_ERRORS || IGNORE_EXCEPT_NON_UNIQUE) and a
 
4410
                        field was not found.
 
4411
    view_ref_found      View field is found, item passed through ref parameter
 
4412
    found field         If a item was resolved to some field
2777
4413
*/
2778
4414
 
2779
4415
Field *
2780
 
find_field_in_tables(Session *session, Item_ident *item,
 
4416
find_field_in_tables(THD *thd, Item_ident *item,
2781
4417
                     TableList *first_table, TableList *last_table,
2782
 
                     Item **ref, find_item_error_report_type report_error,
2783
 
                     bool register_tree_change)
 
4418
                     Item **ref, find_item_error_report_type report_error,
 
4419
                     bool check_privileges, bool register_tree_change)
2784
4420
{
2785
4421
  Field *found=0;
2786
4422
  const char *db= item->db_name;
2787
4423
  const char *table_name= item->table_name;
2788
4424
  const char *name= item->field_name;
2789
 
  uint32_t length=(uint32_t) strlen(name);
 
4425
  uint32_t length=(uint) strlen(name);
2790
4426
  char name_buff[NAME_LEN+1];
2791
4427
  TableList *cur_table= first_table;
2792
4428
  TableList *actual_table;
2816
4452
      The condition (table_ref->view == NULL) ensures that we will call
2817
4453
      find_field_in_table even in the case of information schema tables
2818
4454
      when table_ref->field_translation != NULL.
2819
 
    */
 
4455
      */
2820
4456
    if (table_ref->table)
2821
 
      found= find_field_in_table(session, table_ref->table, name, length,
 
4457
      found= find_field_in_table(thd, table_ref->table, name, length,
2822
4458
                                 true, &(item->cached_field_index));
2823
4459
    else
2824
 
      found= find_field_in_table_ref(session, table_ref, name, length, item->name,
2825
 
                                     NULL, NULL, ref,
 
4460
      found= find_field_in_table_ref(thd, table_ref, name, length, item->name,
 
4461
                                     NULL, NULL, ref, check_privileges,
2826
4462
                                     true, &(item->cached_field_index),
2827
4463
                                     register_tree_change,
2828
4464
                                     &actual_table);
2829
4465
    if (found)
2830
4466
    {
 
4467
      if (found == WRONG_GRANT)
 
4468
        return (Field*) 0;
 
4469
 
2831
4470
      /*
2832
4471
        Only views fields should be marked as dependent, not an underlying
2833
4472
        fields.
2834
4473
      */
2835
4474
      {
2836
 
        Select_Lex *current_sel= session->lex->current_select;
2837
 
        Select_Lex *last_select= table_ref->select_lex;
 
4475
        SELECT_LEX *current_sel= thd->lex->current_select;
 
4476
        SELECT_LEX *last_select= table_ref->select_lex;
2838
4477
        /*
2839
4478
          If the field was an outer referencee, mark all selects using this
2840
4479
          sub query as dependent on the outer query
2841
4480
        */
2842
4481
        if (current_sel != last_select)
2843
 
          mark_select_range_as_dependent(session, last_select, current_sel,
 
4482
          mark_select_range_as_dependent(thd, last_select, current_sel,
2844
4483
                                         found, *ref, item);
2845
4484
      }
2846
4485
      return found;
2847
4486
    }
2848
4487
  }
2849
4488
 
2850
 
  if (db)
 
4489
  if (db && lower_case_table_names)
2851
4490
  {
2852
4491
    /*
2853
4492
      convert database to lower case for comparison.
2854
4493
      We can't do this in Item_field as this would change the
2855
4494
      'name' of the item which may be used in the select list
2856
4495
    */
2857
 
    strncpy(name_buff, db, sizeof(name_buff)-1);
 
4496
    strmake(name_buff, db, sizeof(name_buff)-1);
2858
4497
    my_casedn_str(files_charset_info, name_buff);
2859
4498
    db= name_buff;
2860
4499
  }
2865
4504
  for (; cur_table != last_table ;
2866
4505
       cur_table= cur_table->next_name_resolution_table)
2867
4506
  {
2868
 
    Field *cur_field= find_field_in_table_ref(session, cur_table, name, length,
 
4507
    Field *cur_field= find_field_in_table_ref(thd, cur_table, name, length,
2869
4508
                                              item->name, db, table_name, ref,
 
4509
                                              (thd->lex->sql_command ==
 
4510
                                               SQLCOM_SHOW_FIELDS)
 
4511
                                              ? false : check_privileges,
2870
4512
                                              allow_rowid,
2871
4513
                                              &(item->cached_field_index),
2872
4514
                                              register_tree_change,
2873
4515
                                              &actual_table);
2874
4516
    if (cur_field)
2875
4517
    {
 
4518
      if (cur_field == WRONG_GRANT)
 
4519
      {
 
4520
        if (thd->lex->sql_command != SQLCOM_SHOW_FIELDS)
 
4521
          return (Field*) 0;
 
4522
 
 
4523
        thd->clear_error();
 
4524
        cur_field= find_field_in_table_ref(thd, cur_table, name, length,
 
4525
                                           item->name, db, table_name, ref,
 
4526
                                           false,
 
4527
                                           allow_rowid,
 
4528
                                           &(item->cached_field_index),
 
4529
                                           register_tree_change,
 
4530
                                           &actual_table);
 
4531
        if (cur_field)
 
4532
        {
 
4533
          Field *nf=new Field_null(NULL,0,Field::NONE,
 
4534
                                   cur_field->field_name,
 
4535
                                   &my_charset_bin);
 
4536
          nf->init(cur_table->table);
 
4537
          cur_field= nf;
 
4538
        }
 
4539
      }
 
4540
 
2876
4541
      /*
2877
4542
        Store the original table of the field, which may be different from
2878
4543
        cur_table in the case of NATURAL/USING join.
2879
4544
      */
2880
 
      item->cached_table= found ?  0 : actual_table;
 
4545
      item->cached_table= (!actual_table->cacheable_table || found) ?
 
4546
                          0 : actual_table;
2881
4547
 
2882
 
      assert(session->where);
 
4548
      assert(thd->where);
2883
4549
      /*
2884
4550
        If we found a fully qualified field we return it directly as it can't
2885
4551
        have duplicates.
2886
 
      */
 
4552
       */
2887
4553
      if (db)
2888
4554
        return cur_field;
2889
4555
 
2892
4558
        if (report_error == REPORT_ALL_ERRORS ||
2893
4559
            report_error == IGNORE_EXCEPT_NON_UNIQUE)
2894
4560
          my_error(ER_NON_UNIQ_ERROR, MYF(0),
2895
 
                   table_name ? item->full_name() : name, session->where);
 
4561
                   table_name ? item->full_name() : name, thd->where);
2896
4562
        return (Field*) 0;
2897
4563
      }
2898
4564
      found= cur_field;
2916
4582
    char buff[NAME_LEN*2+1];
2917
4583
    if (db && db[0])
2918
4584
    {
2919
 
      /* We're in an error condition, two extra strlen's aren't going
2920
 
       * to kill us */
2921
 
      assert(strlen(db) <= NAME_LEN);
2922
 
      assert(strlen(table_name) <= NAME_LEN);
2923
 
      strcpy(buff, db);
2924
 
      strcat(buff,".");
2925
 
      strcat(buff, table_name);
 
4585
      strxnmov(buff,sizeof(buff)-1,db,".",table_name,NULL);
2926
4586
      table_name=buff;
2927
4587
    }
2928
 
    my_error(ER_UNKNOWN_TABLE, MYF(0), table_name, session->where);
 
4588
    my_error(ER_UNKNOWN_TABLE, MYF(0), table_name, thd->where);
2929
4589
  }
2930
4590
  else
2931
4591
  {
2932
4592
    if (report_error == REPORT_ALL_ERRORS ||
2933
4593
        report_error == REPORT_EXCEPT_NON_UNIQUE)
2934
 
      my_error(ER_BAD_FIELD_ERROR, MYF(0), item->full_name(), session->where);
 
4594
      my_error(ER_BAD_FIELD_ERROR, MYF(0), item->full_name(), thd->where);
2935
4595
    else
2936
4596
      found= not_found_field;
2937
4597
  }
2943
4603
  Find Item in list of items (find_field_in_tables analog)
2944
4604
 
2945
4605
  TODO
2946
 
  is it better return only counter?
 
4606
    is it better return only counter?
2947
4607
 
2948
4608
  SYNOPSIS
2949
 
  find_item_in_list()
2950
 
  find                  Item to find
2951
 
  items                 List of items
2952
 
  counter                       To return number of found item
2953
 
  report_error
2954
 
  REPORT_ALL_ERRORS             report errors, return 0 if error
2955
 
  REPORT_EXCEPT_NOT_FOUND       Do not report 'not found' error and
2956
 
  return not_found_item, report other errors,
2957
 
  return 0
2958
 
  IGNORE_ERRORS         Do not report errors, return 0 if error
2959
 
  resolution                  Set to the resolution type if the item is found
2960
 
  (it says whether the item is resolved
2961
 
  against an alias name,
2962
 
  or as a field name without alias,
2963
 
  or as a field hidden by alias,
2964
 
  or ignoring alias)
2965
 
 
 
4609
    find_item_in_list()
 
4610
    find                        Item to find
 
4611
    items                       List of items
 
4612
    counter                     To return number of found item
 
4613
    report_error
 
4614
      REPORT_ALL_ERRORS         report errors, return 0 if error
 
4615
      REPORT_EXCEPT_NOT_FOUND   Do not report 'not found' error and
 
4616
                                return not_found_item, report other errors,
 
4617
                                return 0
 
4618
      IGNORE_ERRORS             Do not report errors, return 0 if error
 
4619
    resolution                  Set to the resolution type if the item is found 
 
4620
                                (it says whether the item is resolved 
 
4621
                                 against an alias name,
 
4622
                                 or as a field name without alias,
 
4623
                                 or as a field hidden by alias,
 
4624
                                 or ignoring alias)
 
4625
                                
2966
4626
  RETURN VALUES
2967
 
  0                     Item is not found or item is not unique,
2968
 
  error message is reported
2969
 
  not_found_item        Function was called with
2970
 
  report_error == REPORT_EXCEPT_NOT_FOUND and
2971
 
  item was not found. No error message was reported
2972
 
  found field
 
4627
    0                   Item is not found or item is not unique,
 
4628
                        error message is reported
 
4629
    not_found_item      Function was called with
 
4630
                        report_error == REPORT_EXCEPT_NOT_FOUND and
 
4631
                        item was not found. No error message was reported
 
4632
                        found field
2973
4633
*/
2974
4634
 
2975
4635
/* Special Item pointer to serve as a return value from find_item_in_list(). */
2977
4637
 
2978
4638
 
2979
4639
Item **
2980
 
find_item_in_list(Session *session,
2981
 
                  Item *find, List<Item> &items, uint32_t *counter,
 
4640
find_item_in_list(Item *find, List<Item> &items, uint32_t *counter,
2982
4641
                  find_item_error_report_type report_error,
2983
4642
                  enum_resolution_type *resolution)
2984
4643
{
2997
4656
 
2998
4657
  *resolution= NOT_RESOLVED;
2999
4658
 
3000
 
  is_ref_by_name= (find->type() == Item::FIELD_ITEM  ||
 
4659
  is_ref_by_name= (find->type() == Item::FIELD_ITEM  || 
3001
4660
                   find->type() == Item::REF_ITEM);
3002
4661
  if (is_ref_by_name)
3003
4662
  {
3013
4672
      Item_ident *item_field= (Item_ident*) item;
3014
4673
 
3015
4674
      /*
3016
 
        In case of group_concat() with ORDER BY condition in the QUERY
3017
 
        item_field can be field of temporary table without item name
3018
 
        (if this field created from expression argument of group_concat()),
3019
 
        => we have to check presence of name before compare
3020
 
      */
 
4675
        In case of group_concat() with ORDER BY condition in the QUERY
 
4676
        item_field can be field of temporary table without item name 
 
4677
        (if this field created from expression argument of group_concat()),
 
4678
        => we have to check presence of name before compare
 
4679
      */ 
3021
4680
      if (!item_field->name)
3022
4681
        continue;
3023
4682
 
3036
4695
          case sensitive. In cases where they are not case sensitive, they
3037
4696
          are always in lower case.
3038
4697
 
3039
 
          item_field->field_name and item_field->table_name can be 0x0 if
3040
 
          item is not fix_field()'ed yet.
 
4698
          item_field->field_name and item_field->table_name can be 0x0 if
 
4699
          item is not fix_field()'ed yet.
3041
4700
        */
3042
4701
        if (item_field->field_name && item_field->table_name &&
3043
 
            !my_strcasecmp(system_charset_info, item_field->field_name,
 
4702
            !my_strcasecmp(system_charset_info, item_field->field_name,
3044
4703
                           field_name) &&
3045
 
            !my_strcasecmp(table_alias_charset, item_field->table_name,
 
4704
            !my_strcasecmp(table_alias_charset, item_field->table_name, 
3046
4705
                           table_name) &&
3047
4706
            (!db_name || (item_field->db_name &&
3048
4707
                          !strcmp(item_field->db_name, db_name))))
3058
4717
            */
3059
4718
            if (report_error != IGNORE_ERRORS)
3060
4719
              my_error(ER_NON_UNIQ_ERROR, MYF(0),
3061
 
                       find->full_name(), session->where);
 
4720
                       find->full_name(), current_thd->where);
3062
4721
            return (Item**) 0;
3063
4722
          }
3064
4723
          found_unaliased= li.ref();
3089
4748
              continue;                           // Same field twice
3090
4749
            if (report_error != IGNORE_ERRORS)
3091
4750
              my_error(ER_NON_UNIQ_ERROR, MYF(0),
3092
 
                       find->full_name(), session->where);
 
4751
                       find->full_name(), current_thd->where);
3093
4752
            return (Item**) 0;
3094
4753
          }
3095
4754
          found= li.ref();
3096
4755
          *counter= i;
3097
4756
          *resolution= fname_cmp ? RESOLVED_AGAINST_ALIAS:
3098
 
            RESOLVED_WITH_NO_ALIAS;
 
4757
                                   RESOLVED_WITH_NO_ALIAS;
3099
4758
        }
3100
4759
        else if (!fname_cmp)
3101
4760
        {
3117
4776
      }
3118
4777
    }
3119
4778
    else if (!table_name)
3120
 
    {
 
4779
    { 
3121
4780
      if (is_ref_by_name && find->name && item->name &&
3122
 
          !my_strcasecmp(system_charset_info,item->name,find->name))
 
4781
          !my_strcasecmp(system_charset_info,item->name,find->name))
3123
4782
      {
3124
4783
        found= li.ref();
3125
4784
        *counter= i;
3134
4793
        break;
3135
4794
      }
3136
4795
    }
 
4796
    else if (table_name && item->type() == Item::REF_ITEM &&
 
4797
             ((Item_ref *)item)->ref_type() == Item_ref::VIEW_REF)
 
4798
    {
 
4799
      /*
 
4800
        TODO:Here we process prefixed view references only. What we should 
 
4801
        really do is process all types of Item_refs. But this will currently 
 
4802
        lead to a clash with the way references to outer SELECTs (from the 
 
4803
        HAVING clause) are handled in e.g. :
 
4804
        SELECT 1 FROM t1 AS t1_o GROUP BY a
 
4805
          HAVING (SELECT t1_o.a FROM t1 AS t1_i GROUP BY t1_i.a LIMIT 1).
 
4806
        Processing all Item_refs here will cause t1_o.a to resolve to itself.
 
4807
        We still need to process the special case of Item_direct_view_ref 
 
4808
        because in the context of views they have the same meaning as 
 
4809
        Item_field for tables.
 
4810
      */
 
4811
      Item_ident *item_ref= (Item_ident *) item;
 
4812
      if (item_ref->name && item_ref->table_name &&
 
4813
          !my_strcasecmp(system_charset_info, item_ref->name, field_name) &&
 
4814
          !my_strcasecmp(table_alias_charset, item_ref->table_name,
 
4815
                         table_name) &&
 
4816
          (!db_name || (item_ref->db_name && 
 
4817
                        !strcmp (item_ref->db_name, db_name))))
 
4818
      {
 
4819
        found= li.ref();
 
4820
        *counter= i;
 
4821
        *resolution= RESOLVED_IGNORING_ALIAS;
 
4822
        break;
 
4823
      }
 
4824
    }
3137
4825
  }
3138
4826
  if (!found)
3139
4827
  {
3141
4829
    {
3142
4830
      if (report_error != IGNORE_ERRORS)
3143
4831
        my_error(ER_NON_UNIQ_ERROR, MYF(0),
3144
 
                 find->full_name(), session->where);
 
4832
                 find->full_name(), current_thd->where);
3145
4833
      return (Item **) 0;
3146
4834
    }
3147
4835
    if (found_unaliased)
3157
4845
  {
3158
4846
    if (report_error == REPORT_ALL_ERRORS)
3159
4847
      my_error(ER_BAD_FIELD_ERROR, MYF(0),
3160
 
               find->full_name(), session->where);
 
4848
               find->full_name(), current_thd->where);
3161
4849
    return (Item **) 0;
3162
4850
  }
3163
4851
  else
3169
4857
  Test if a string is a member of a list of strings.
3170
4858
 
3171
4859
  SYNOPSIS
3172
 
  test_if_string_in_list()
3173
 
  find      the string to look for
3174
 
  str_list  a list of strings to be searched
 
4860
    test_if_string_in_list()
 
4861
    find      the string to look for
 
4862
    str_list  a list of strings to be searched
3175
4863
 
3176
4864
  DESCRIPTION
3177
 
  Sequentially search a list of strings for a string, and test whether
3178
 
  the list contains the same string.
 
4865
    Sequentially search a list of strings for a string, and test whether
 
4866
    the list contains the same string.
3179
4867
 
3180
4868
  RETURN
3181
 
  true  if find is in str_list
3182
 
  false otherwise
 
4869
    true  if find is in str_list
 
4870
    false otherwise
3183
4871
*/
3184
4872
 
3185
4873
static bool
3204
4892
  being resolved in a specific table reference.
3205
4893
 
3206
4894
  SYNOPSIS
3207
 
  set_new_item_local_context()
3208
 
  session        pointer to current thread
3209
 
  item       item for which new context is created and set
3210
 
  table_ref  table ref where an item showld be resolved
 
4895
    set_new_item_local_context()
 
4896
    thd        pointer to current thread
 
4897
    item       item for which new context is created and set
 
4898
    table_ref  table ref where an item showld be resolved
3211
4899
 
3212
4900
  DESCRIPTION
3213
 
  Create a new name resolution context for an item, so that the item
3214
 
  is resolved only the supplied 'table_ref'.
 
4901
    Create a new name resolution context for an item, so that the item
 
4902
    is resolved only the supplied 'table_ref'.
3215
4903
 
3216
4904
  RETURN
3217
 
  false  if all OK
3218
 
  true   otherwise
 
4905
    false  if all OK
 
4906
    true   otherwise
3219
4907
*/
3220
4908
 
3221
4909
static bool
3222
 
set_new_item_local_context(Session *session, Item_ident *item, TableList *table_ref)
 
4910
set_new_item_local_context(THD *thd, Item_ident *item, TableList *table_ref)
3223
4911
{
3224
4912
  Name_resolution_context *context;
3225
 
  if (!(context= new (session->mem_root) Name_resolution_context))
 
4913
  if (!(context= new (thd->mem_root) Name_resolution_context))
3226
4914
    return true;
3227
4915
  context->init();
3228
4916
  context->first_name_resolution_table=
3236
4924
  Find and mark the common columns of two table references.
3237
4925
 
3238
4926
  SYNOPSIS
3239
 
  mark_common_columns()
3240
 
  session                [in] current thread
3241
 
  table_ref_1        [in] the first (left) join operand
3242
 
  table_ref_2        [in] the second (right) join operand
3243
 
  using_fields       [in] if the join is JOIN...USING - the join columns,
3244
 
  if NATURAL join, then NULL
3245
 
  found_using_fields [out] number of fields from the USING clause that were
3246
 
  found among the common fields
 
4927
    mark_common_columns()
 
4928
    thd                [in] current thread
 
4929
    table_ref_1        [in] the first (left) join operand
 
4930
    table_ref_2        [in] the second (right) join operand
 
4931
    using_fields       [in] if the join is JOIN...USING - the join columns,
 
4932
                            if NATURAL join, then NULL
 
4933
    found_using_fields [out] number of fields from the USING clause that were
 
4934
                             found among the common fields
3247
4935
 
3248
4936
  DESCRIPTION
3249
 
  The procedure finds the common columns of two relations (either
3250
 
  tables or intermediate join results), and adds an equi-join condition
3251
 
  to the ON clause of 'table_ref_2' for each pair of matching columns.
3252
 
  If some of table_ref_XXX represents a base table or view, then we
3253
 
  create new 'Natural_join_column' instances for each column
3254
 
  reference and store them in the 'join_columns' of the table
3255
 
  reference.
 
4937
    The procedure finds the common columns of two relations (either
 
4938
    tables or intermediate join results), and adds an equi-join condition
 
4939
    to the ON clause of 'table_ref_2' for each pair of matching columns.
 
4940
    If some of table_ref_XXX represents a base table or view, then we
 
4941
    create new 'Natural_join_column' instances for each column
 
4942
    reference and store them in the 'join_columns' of the table
 
4943
    reference.
3256
4944
 
3257
4945
  IMPLEMENTATION
3258
 
  The procedure assumes that store_natural_using_join_columns() was
3259
 
  called for the previous level of NATURAL/USING joins.
 
4946
    The procedure assumes that store_natural_using_join_columns() was
 
4947
    called for the previous level of NATURAL/USING joins.
3260
4948
 
3261
4949
  RETURN
3262
 
  true   error when some common column is non-unique, or out of memory
3263
 
  false  OK
 
4950
    true   error when some common column is non-unique, or out of memory
 
4951
    false  OK
3264
4952
*/
3265
4953
 
3266
4954
static bool
3267
 
mark_common_columns(Session *session, TableList *table_ref_1, TableList *table_ref_2,
 
4955
mark_common_columns(THD *thd, TableList *table_ref_1, TableList *table_ref_2,
3268
4956
                    List<String> *using_fields, uint32_t *found_using_fields)
3269
4957
{
3270
4958
  Field_iterator_table_ref it_1, it_2;
3275
4963
    Leaf table references to which new natural join columns are added
3276
4964
    if the leaves are != NULL.
3277
4965
  */
3278
 
  TableList *leaf_1= (table_ref_1->getNestedJoin() &&
3279
 
                      ! table_ref_1->is_natural_join) ?
3280
 
    NULL : table_ref_1;
3281
 
  TableList *leaf_2= (table_ref_2->getNestedJoin() &&
3282
 
                      ! table_ref_2->is_natural_join) ?
3283
 
    NULL : table_ref_2;
 
4966
  TableList *leaf_1= (table_ref_1->nested_join &&
 
4967
                       !table_ref_1->is_natural_join) ?
 
4968
                      NULL : table_ref_1;
 
4969
  TableList *leaf_2= (table_ref_2->nested_join &&
 
4970
                       !table_ref_2->is_natural_join) ?
 
4971
                      NULL : table_ref_2;
3284
4972
 
3285
4973
  *found_using_fields= 0;
3286
4974
 
3293
4981
    if (!(nj_col_1= it_1.get_or_create_column_ref(leaf_1)))
3294
4982
      goto err;
3295
4983
    field_name_1= nj_col_1->name();
3296
 
    is_using_column_1= using_fields &&
 
4984
    is_using_column_1= using_fields && 
3297
4985
      test_if_string_in_list(field_name_1, using_fields);
3298
4986
 
3299
4987
    /*
3320
5008
        (then cur_nj_col_2->is_common == true).
3321
5009
        Note that it is too early to check the columns outside of the
3322
5010
        USING list for ambiguity because they are not actually "referenced"
3323
 
        here. These columns must be checked only on unqualified reference
 
5011
        here. These columns must be checked only on unqualified reference 
3324
5012
        by name (e.g. in SELECT list).
3325
5013
      */
3326
5014
      if (!my_strcasecmp(system_charset_info, field_name_1, cur_field_name_2))
3328
5016
        if (cur_nj_col_2->is_common ||
3329
5017
            (found && (!using_fields || is_using_column_1)))
3330
5018
        {
3331
 
          my_error(ER_NON_UNIQ_ERROR, MYF(0), field_name_1, session->where);
 
5019
          my_error(ER_NON_UNIQ_ERROR, MYF(0), field_name_1, thd->where);
3332
5020
          goto err;
3333
5021
        }
3334
5022
        nj_col_2= cur_nj_col_2;
3354
5042
    */
3355
5043
    if (nj_col_2 && (!using_fields ||is_using_column_1))
3356
5044
    {
3357
 
      Item *item_1=   nj_col_1->create_item(session);
3358
 
      Item *item_2=   nj_col_2->create_item(session);
 
5045
      Item *item_1=   nj_col_1->create_item(thd);
 
5046
      Item *item_2=   nj_col_2->create_item(thd);
3359
5047
      Field *field_1= nj_col_1->field();
3360
5048
      Field *field_2= nj_col_2->field();
3361
5049
      Item_ident *item_ident_1, *item_ident_2;
3369
5057
        of sub-classes of Item_ident.
3370
5058
      */
3371
5059
      assert(item_1->type() == Item::FIELD_ITEM ||
3372
 
             item_1->type() == Item::REF_ITEM);
 
5060
                  item_1->type() == Item::REF_ITEM);
3373
5061
      assert(item_2->type() == Item::FIELD_ITEM ||
3374
 
             item_2->type() == Item::REF_ITEM);
 
5062
                  item_2->type() == Item::REF_ITEM);
3375
5063
 
3376
5064
      /*
3377
5065
        We need to cast item_1,2 to Item_ident, because we need to hook name
3385
5073
        resolution of these items, and to enable proper name resolution of
3386
5074
        the items during the execute phase of PS.
3387
5075
      */
3388
 
      if (set_new_item_local_context(session, item_ident_1, nj_col_1->table_ref) ||
3389
 
          set_new_item_local_context(session, item_ident_2, nj_col_2->table_ref))
 
5076
      if (set_new_item_local_context(thd, item_ident_1, nj_col_1->table_ref) ||
 
5077
          set_new_item_local_context(thd, item_ident_2, nj_col_2->table_ref))
3390
5078
        goto err;
3391
5079
 
3392
5080
      if (!(eq_cond= new Item_func_eq(item_ident_1, item_ident_2)))
3396
5084
        Add the new equi-join condition to the ON clause. Notice that
3397
5085
        fix_fields() is applied to all ON conditions in setup_conds()
3398
5086
        so we don't do it here.
3399
 
      */
 
5087
       */
3400
5088
      add_join_on((table_ref_1->outer_join & JOIN_TYPE_RIGHT ?
3401
5089
                   table_ref_1 : table_ref_2),
3402
5090
                  eq_cond);
3407
5095
      {
3408
5096
        Table *table_1= nj_col_1->table_ref->table;
3409
5097
        /* Mark field_1 used for table cache. */
3410
 
        table_1->setReadSet(field_1->field_index);
3411
 
        table_1->covering_keys&= field_1->part_of_key;
3412
 
        table_1->merge_keys|= field_1->part_of_key;
 
5098
        bitmap_set_bit(table_1->read_set, field_1->field_index);
 
5099
        table_1->covering_keys.intersect(field_1->part_of_key);
 
5100
        table_1->merge_keys.merge(field_1->part_of_key);
3413
5101
      }
3414
5102
      if (field_2)
3415
5103
      {
3416
5104
        Table *table_2= nj_col_2->table_ref->table;
3417
5105
        /* Mark field_2 used for table cache. */
3418
 
        table_2->setReadSet(field_2->field_index);
3419
 
        table_2->covering_keys&= field_2->part_of_key;
3420
 
        table_2->merge_keys|= field_2->part_of_key;
 
5106
        bitmap_set_bit(table_2->read_set, field_2->field_index);
 
5107
        table_2->covering_keys.intersect(field_2->part_of_key);
 
5108
        table_2->merge_keys.merge(field_2->part_of_key);
3421
5109
      }
3422
5110
 
3423
5111
      if (using_fields != NULL)
3446
5134
  Materialize and store the row type of NATURAL/USING join.
3447
5135
 
3448
5136
  SYNOPSIS
3449
 
  store_natural_using_join_columns()
3450
 
  session                current thread
3451
 
  natural_using_join the table reference of the NATURAL/USING join
3452
 
  table_ref_1        the first (left) operand (of a NATURAL/USING join).
3453
 
  table_ref_2        the second (right) operand (of a NATURAL/USING join).
3454
 
  using_fields       if the join is JOIN...USING - the join columns,
3455
 
  if NATURAL join, then NULL
3456
 
  found_using_fields number of fields from the USING clause that were
3457
 
  found among the common fields
 
5137
    store_natural_using_join_columns()
 
5138
    thd                current thread
 
5139
    natural_using_join the table reference of the NATURAL/USING join
 
5140
    table_ref_1        the first (left) operand (of a NATURAL/USING join).
 
5141
    table_ref_2        the second (right) operand (of a NATURAL/USING join).
 
5142
    using_fields       if the join is JOIN...USING - the join columns,
 
5143
                       if NATURAL join, then NULL
 
5144
    found_using_fields number of fields from the USING clause that were
 
5145
                       found among the common fields
3458
5146
 
3459
5147
  DESCRIPTION
3460
 
  Iterate over the columns of both join operands and sort and store
3461
 
  all columns into the 'join_columns' list of natural_using_join
3462
 
  where the list is formed by three parts:
3463
 
part1: The coalesced columns of table_ref_1 and table_ref_2,
3464
 
sorted according to the column order of the first table.
3465
 
part2: The other columns of the first table, in the order in
3466
 
which they were defined in CREATE TABLE.
3467
 
part3: The other columns of the second table, in the order in
3468
 
which they were defined in CREATE TABLE.
3469
 
Time complexity - O(N1+N2), where Ni = length(table_ref_i).
3470
 
 
3471
 
IMPLEMENTATION
3472
 
The procedure assumes that mark_common_columns() has been called
3473
 
for the join that is being processed.
3474
 
 
3475
 
RETURN
3476
 
true    error: Some common column is ambiguous
3477
 
false   OK
 
5148
    Iterate over the columns of both join operands and sort and store
 
5149
    all columns into the 'join_columns' list of natural_using_join
 
5150
    where the list is formed by three parts:
 
5151
      part1: The coalesced columns of table_ref_1 and table_ref_2,
 
5152
             sorted according to the column order of the first table.
 
5153
      part2: The other columns of the first table, in the order in
 
5154
             which they were defined in CREATE TABLE.
 
5155
      part3: The other columns of the second table, in the order in
 
5156
             which they were defined in CREATE TABLE.
 
5157
    Time complexity - O(N1+N2), where Ni = length(table_ref_i).
 
5158
 
 
5159
  IMPLEMENTATION
 
5160
    The procedure assumes that mark_common_columns() has been called
 
5161
    for the join that is being processed.
 
5162
 
 
5163
  RETURN
 
5164
    true    error: Some common column is ambiguous
 
5165
    false   OK
3478
5166
*/
3479
5167
 
3480
5168
static bool
3481
 
store_natural_using_join_columns(Session *session,
 
5169
store_natural_using_join_columns(THD *thd __attribute__((unused)),
3482
5170
                                 TableList *natural_using_join,
3483
5171
                                 TableList *table_ref_1,
3484
5172
                                 TableList *table_ref_2,
3532
5220
        if (!(common_field= it++))
3533
5221
        {
3534
5222
          my_error(ER_BAD_FIELD_ERROR, MYF(0), using_field_name_ptr,
3535
 
                   session->where);
 
5223
                   current_thd->where);
3536
5224
          goto err;
3537
5225
        }
3538
5226
        if (!my_strcasecmp(system_charset_info,
3570
5258
  Precompute and store the row types of the top-most NATURAL/USING joins.
3571
5259
 
3572
5260
  SYNOPSIS
3573
 
  store_top_level_join_columns()
3574
 
  session            current thread
3575
 
  table_ref      nested join or table in a FROM clause
3576
 
  left_neighbor  neighbor table reference to the left of table_ref at the
3577
 
  same level in the join tree
3578
 
  right_neighbor neighbor table reference to the right of table_ref at the
3579
 
  same level in the join tree
 
5261
    store_top_level_join_columns()
 
5262
    thd            current thread
 
5263
    table_ref      nested join or table in a FROM clause
 
5264
    left_neighbor  neighbor table reference to the left of table_ref at the
 
5265
                   same level in the join tree
 
5266
    right_neighbor neighbor table reference to the right of table_ref at the
 
5267
                   same level in the join tree
3580
5268
 
3581
5269
  DESCRIPTION
3582
 
  The procedure performs a post-order traversal of a nested join tree
3583
 
  and materializes the row types of NATURAL/USING joins in a
3584
 
  bottom-up manner until it reaches the TableList elements that
3585
 
  represent the top-most NATURAL/USING joins. The procedure should be
3586
 
  applied to each element of Select_Lex::top_join_list (i.e. to each
3587
 
  top-level element of the FROM clause).
 
5270
    The procedure performs a post-order traversal of a nested join tree
 
5271
    and materializes the row types of NATURAL/USING joins in a
 
5272
    bottom-up manner until it reaches the TableList elements that
 
5273
    represent the top-most NATURAL/USING joins. The procedure should be
 
5274
    applied to each element of SELECT_LEX::top_join_list (i.e. to each
 
5275
    top-level element of the FROM clause).
3588
5276
 
3589
5277
  IMPLEMENTATION
3590
 
  Notice that the table references in the list nested_join->join_list
3591
 
  are in reverse order, thus when we iterate over it, we are moving
3592
 
  from the right to the left in the FROM clause.
 
5278
    Notice that the table references in the list nested_join->join_list
 
5279
    are in reverse order, thus when we iterate over it, we are moving
 
5280
    from the right to the left in the FROM clause.
3593
5281
 
3594
5282
  RETURN
3595
 
  true   Error
3596
 
  false  OK
 
5283
    true   Error
 
5284
    false  OK
3597
5285
*/
3598
5286
 
3599
5287
static bool
3600
 
store_top_level_join_columns(Session *session, TableList *table_ref,
 
5288
store_top_level_join_columns(THD *thd, TableList *table_ref,
3601
5289
                             TableList *left_neighbor,
3602
5290
                             TableList *right_neighbor)
3603
5291
{
3604
5292
  bool result= true;
3605
5293
 
3606
5294
  /* Call the procedure recursively for each nested table reference. */
3607
 
  if (table_ref->getNestedJoin())
 
5295
  if (table_ref->nested_join)
3608
5296
  {
3609
 
    List_iterator_fast<TableList> nested_it(table_ref->getNestedJoin()->join_list);
 
5297
    List_iterator_fast<TableList> nested_it(table_ref->nested_join->join_list);
3610
5298
    TableList *same_level_left_neighbor= nested_it++;
3611
5299
    TableList *same_level_right_neighbor= NULL;
3612
5300
    /* Left/right-most neighbors, possibly at higher levels in the join tree. */
3631
5319
          cur_table_ref->outer_join & JOIN_TYPE_RIGHT)
3632
5320
      {
3633
5321
        /* This can happen only for JOIN ... ON. */
3634
 
        assert(table_ref->getNestedJoin()->join_list.elements == 2);
 
5322
        assert(table_ref->nested_join->join_list.elements == 2);
3635
5323
        std::swap(same_level_left_neighbor, cur_table_ref);
3636
5324
      }
3637
5325
 
3640
5328
        neighbors at the same level.
3641
5329
      */
3642
5330
      real_left_neighbor=  (same_level_left_neighbor) ?
3643
 
        same_level_left_neighbor : left_neighbor;
 
5331
                           same_level_left_neighbor : left_neighbor;
3644
5332
      real_right_neighbor= (same_level_right_neighbor) ?
3645
 
        same_level_right_neighbor : right_neighbor;
 
5333
                           same_level_right_neighbor : right_neighbor;
3646
5334
 
3647
 
      if (cur_table_ref->getNestedJoin() &&
3648
 
          store_top_level_join_columns(session, cur_table_ref,
 
5335
      if (cur_table_ref->nested_join &&
 
5336
          store_top_level_join_columns(thd, cur_table_ref,
3649
5337
                                       real_left_neighbor, real_right_neighbor))
3650
5338
        goto err;
3651
5339
      same_level_right_neighbor= cur_table_ref;
3658
5346
  */
3659
5347
  if (table_ref->is_natural_join)
3660
5348
  {
3661
 
    assert(table_ref->getNestedJoin() &&
3662
 
           table_ref->getNestedJoin()->join_list.elements == 2);
3663
 
    List_iterator_fast<TableList> operand_it(table_ref->getNestedJoin()->join_list);
 
5349
    assert(table_ref->nested_join &&
 
5350
                table_ref->nested_join->join_list.elements == 2);
 
5351
    List_iterator_fast<TableList> operand_it(table_ref->nested_join->join_list);
3664
5352
    /*
3665
5353
      Notice that the order of join operands depends on whether table_ref
3666
5354
      represents a LEFT or a RIGHT join. In a RIGHT join, the operands are
3667
5355
      in inverted order.
3668
 
    */
 
5356
     */
3669
5357
    TableList *table_ref_2= operand_it++; /* Second NATURAL join operand.*/
3670
5358
    TableList *table_ref_1= operand_it++; /* First NATURAL join operand. */
3671
5359
    List<String> *using_fields= table_ref->join_using_fields;
3677
5365
    */
3678
5366
    if (table_ref_2->outer_join & JOIN_TYPE_RIGHT)
3679
5367
      std::swap(table_ref_1, table_ref_2);
3680
 
    if (mark_common_columns(session, table_ref_1, table_ref_2,
 
5368
    if (mark_common_columns(thd, table_ref_1, table_ref_2,
3681
5369
                            using_fields, &found_using_fields))
3682
5370
      goto err;
3683
5371
 
3688
5376
    */
3689
5377
    if (table_ref_1->outer_join & JOIN_TYPE_RIGHT)
3690
5378
      std::swap(table_ref_1, table_ref_2);
3691
 
    if (store_natural_using_join_columns(session, table_ref, table_ref_1,
 
5379
    if (store_natural_using_join_columns(thd, table_ref, table_ref_1,
3692
5380
                                         table_ref_2, using_fields,
3693
5381
                                         found_using_fields))
3694
5382
      goto err;
3734
5422
  in a FROM clause.
3735
5423
 
3736
5424
  SYNOPSIS
3737
 
  setup_natural_join_row_types()
3738
 
  session          current thread
3739
 
  from_clause  list of top-level table references in a FROM clause
 
5425
    setup_natural_join_row_types()
 
5426
    thd          current thread
 
5427
    from_clause  list of top-level table references in a FROM clause
3740
5428
 
3741
5429
  DESCRIPTION
3742
 
  Apply the procedure 'store_top_level_join_columns' to each of the
3743
 
  top-level table referencs of the FROM clause. Adjust the list of tables
3744
 
  for name resolution - context->first_name_resolution_table to the
3745
 
  top-most, lef-most NATURAL/USING join.
 
5430
    Apply the procedure 'store_top_level_join_columns' to each of the
 
5431
    top-level table referencs of the FROM clause. Adjust the list of tables
 
5432
    for name resolution - context->first_name_resolution_table to the
 
5433
    top-most, lef-most NATURAL/USING join.
3746
5434
 
3747
5435
  IMPLEMENTATION
3748
 
  Notice that the table references in 'from_clause' are in reverse
3749
 
  order, thus when we iterate over it, we are moving from the right
3750
 
  to the left in the FROM clause.
 
5436
    Notice that the table references in 'from_clause' are in reverse
 
5437
    order, thus when we iterate over it, we are moving from the right
 
5438
    to the left in the FROM clause.
3751
5439
 
3752
5440
  RETURN
3753
 
  true   Error
3754
 
  false  OK
 
5441
    true   Error
 
5442
    false  OK
3755
5443
*/
3756
 
static bool setup_natural_join_row_types(Session *session,
 
5444
static bool setup_natural_join_row_types(THD *thd,
3757
5445
                                         List<TableList> *from_clause,
3758
5446
                                         Name_resolution_context *context)
3759
5447
{
3760
 
  session->where= "from clause";
 
5448
  thd->where= "from clause";
3761
5449
  if (from_clause->elements == 0)
3762
5450
    return false; /* We come here in the case of UNIONs. */
3763
5451
 
3773
5461
  {
3774
5462
    table_ref= left_neighbor;
3775
5463
    left_neighbor= table_ref_it++;
3776
 
    if (store_top_level_join_columns(session, table_ref,
 
5464
    if (store_top_level_join_columns(thd, table_ref,
3777
5465
                                     left_neighbor, right_neighbor))
3778
5466
      return true;
3779
5467
    if (left_neighbor)
3800
5488
 
3801
5489
 
3802
5490
/****************************************************************************
3803
 
 ** Expand all '*' in given fields
3804
 
 ****************************************************************************/
 
5491
** Expand all '*' in given fields
 
5492
****************************************************************************/
3805
5493
 
3806
 
int setup_wild(Session *session, List<Item> &fields,
 
5494
int setup_wild(THD *thd,
 
5495
               TableList *tables __attribute__((unused)),
 
5496
               List<Item> &fields,
3807
5497
               List<Item> *sum_func_list,
3808
5498
               uint32_t wild_num)
3809
5499
{
3810
5500
  if (!wild_num)
3811
 
    return 0;
 
5501
    return(0);
3812
5502
 
3813
5503
  Item *item;
3814
5504
  List_iterator<Item> it(fields);
3815
5505
 
3816
 
  session->lex->current_select->cur_pos_in_select_list= 0;
 
5506
  thd->lex->current_select->cur_pos_in_select_list= 0;
3817
5507
  while (wild_num && (item= it++))
3818
5508
  {
3819
5509
    if (item->type() == Item::FIELD_ITEM &&
3820
5510
        ((Item_field*) item)->field_name &&
3821
 
        ((Item_field*) item)->field_name[0] == '*' &&
3822
 
        !((Item_field*) item)->field)
 
5511
        ((Item_field*) item)->field_name[0] == '*' &&
 
5512
        !((Item_field*) item)->field)
3823
5513
    {
3824
5514
      uint32_t elem= fields.elements;
3825
5515
      bool any_privileges= ((Item_field *) item)->any_privileges;
3826
 
      Item_subselect *subsel= session->lex->current_select->master_unit()->item;
 
5516
      Item_subselect *subsel= thd->lex->current_select->master_unit()->item;
3827
5517
      if (subsel &&
3828
5518
          subsel->substype() == Item_subselect::EXISTS_SUBS)
3829
5519
      {
3835
5525
        it.replace(new Item_int("Not_used", (int64_t) 1,
3836
5526
                                MY_INT64_NUM_DECIMAL_DIGITS));
3837
5527
      }
3838
 
      else if (insert_fields(session, ((Item_field*) item)->context,
 
5528
      else if (insert_fields(thd, ((Item_field*) item)->context,
3839
5529
                             ((Item_field*) item)->db_name,
3840
5530
                             ((Item_field*) item)->table_name, &it,
3841
5531
                             any_privileges))
3842
5532
      {
3843
 
        return -1;
 
5533
        return(-1);
3844
5534
      }
3845
5535
      if (sum_func_list)
3846
5536
      {
3847
 
        /*
3848
 
          sum_func_list is a list that has the fields list as a tail.
3849
 
          Because of this we have to update the element count also for this
3850
 
          list after expanding the '*' entry.
3851
 
        */
3852
 
        sum_func_list->elements+= fields.elements - elem;
 
5537
        /*
 
5538
          sum_func_list is a list that has the fields list as a tail.
 
5539
          Because of this we have to update the element count also for this
 
5540
          list after expanding the '*' entry.
 
5541
        */
 
5542
        sum_func_list->elements+= fields.elements - elem;
3853
5543
      }
3854
5544
      wild_num--;
3855
5545
    }
3856
5546
    else
3857
 
      session->lex->current_select->cur_pos_in_select_list++;
 
5547
      thd->lex->current_select->cur_pos_in_select_list++;
3858
5548
  }
3859
 
  session->lex->current_select->cur_pos_in_select_list= UNDEF_POS;
3860
 
 
3861
 
  return 0;
 
5549
  thd->lex->current_select->cur_pos_in_select_list= UNDEF_POS;
 
5550
  return(0);
3862
5551
}
3863
5552
 
3864
5553
/****************************************************************************
3865
 
 ** Check that all given fields exists and fill struct with current data
3866
 
 ****************************************************************************/
 
5554
** Check that all given fields exists and fill struct with current data
 
5555
****************************************************************************/
3867
5556
 
3868
 
bool setup_fields(Session *session, Item **ref_pointer_array,
 
5557
bool setup_fields(THD *thd, Item **ref_pointer_array,
3869
5558
                  List<Item> &fields, enum_mark_columns mark_used_columns,
3870
5559
                  List<Item> *sum_func_list, bool allow_sum_func)
3871
5560
{
3872
5561
  register Item *item;
3873
 
  enum_mark_columns save_mark_used_columns= session->mark_used_columns;
3874
 
  nesting_map save_allow_sum_func= session->lex->allow_sum_func;
 
5562
  enum_mark_columns save_mark_used_columns= thd->mark_used_columns;
 
5563
  nesting_map save_allow_sum_func= thd->lex->allow_sum_func;
3875
5564
  List_iterator<Item> it(fields);
3876
5565
  bool save_is_item_list_lookup;
3877
5566
 
3878
 
  session->mark_used_columns= mark_used_columns;
 
5567
  thd->mark_used_columns= mark_used_columns;
3879
5568
  if (allow_sum_func)
3880
 
    session->lex->allow_sum_func|= 1 << session->lex->current_select->nest_level;
3881
 
  session->where= Session::DEFAULT_WHERE;
3882
 
  save_is_item_list_lookup= session->lex->current_select->is_item_list_lookup;
3883
 
  session->lex->current_select->is_item_list_lookup= 0;
 
5569
    thd->lex->allow_sum_func|= 1 << thd->lex->current_select->nest_level;
 
5570
  thd->where= THD::DEFAULT_WHERE;
 
5571
  save_is_item_list_lookup= thd->lex->current_select->is_item_list_lookup;
 
5572
  thd->lex->current_select->is_item_list_lookup= 0;
3884
5573
 
3885
5574
  /*
3886
5575
    To prevent fail on forward lookup we fill it with zerows,
3890
5579
    There is other way to solve problem: fill array with pointers to list,
3891
5580
    but it will be slower.
3892
5581
 
3893
 
TODO: remove it when (if) we made one list for allfields and
3894
 
ref_pointer_array
 
5582
    TODO: remove it when (if) we made one list for allfields and
 
5583
    ref_pointer_array
3895
5584
  */
3896
5585
  if (ref_pointer_array)
3897
5586
    memset(ref_pointer_array, 0, sizeof(Item *) * fields.elements);
3898
5587
 
3899
5588
  Item **ref= ref_pointer_array;
3900
 
  session->lex->current_select->cur_pos_in_select_list= 0;
 
5589
  thd->lex->current_select->cur_pos_in_select_list= 0;
3901
5590
  while ((item= it++))
3902
5591
  {
3903
 
    if ((!item->fixed && item->fix_fields(session, it.ref())) || (item= *(it.ref()))->check_cols(1))
 
5592
    if ((!item->fixed && item->fix_fields(thd, it.ref())) || (item= *(it.ref()))->check_cols(1))
3904
5593
    {
3905
 
      session->lex->current_select->is_item_list_lookup= save_is_item_list_lookup;
3906
 
      session->lex->allow_sum_func= save_allow_sum_func;
3907
 
      session->mark_used_columns= save_mark_used_columns;
3908
 
      return true;
 
5594
      thd->lex->current_select->is_item_list_lookup= save_is_item_list_lookup;
 
5595
      thd->lex->allow_sum_func= save_allow_sum_func;
 
5596
      thd->mark_used_columns= save_mark_used_columns;
 
5597
      return(true); /* purecov: inspected */
3909
5598
    }
3910
5599
    if (ref)
3911
5600
      *(ref++)= item;
3912
5601
    if (item->with_sum_func && item->type() != Item::SUM_FUNC_ITEM &&
3913
 
        sum_func_list)
3914
 
      item->split_sum_func(session, ref_pointer_array, *sum_func_list);
3915
 
    session->used_tables|= item->used_tables();
3916
 
    session->lex->current_select->cur_pos_in_select_list++;
 
5602
        sum_func_list)
 
5603
      item->split_sum_func(thd, ref_pointer_array, *sum_func_list);
 
5604
    thd->used_tables|= item->used_tables();
 
5605
    thd->lex->current_select->cur_pos_in_select_list++;
3917
5606
  }
3918
 
  session->lex->current_select->is_item_list_lookup= save_is_item_list_lookup;
3919
 
  session->lex->current_select->cur_pos_in_select_list= UNDEF_POS;
 
5607
  thd->lex->current_select->is_item_list_lookup= save_is_item_list_lookup;
 
5608
  thd->lex->current_select->cur_pos_in_select_list= UNDEF_POS;
3920
5609
 
3921
 
  session->lex->allow_sum_func= save_allow_sum_func;
3922
 
  session->mark_used_columns= save_mark_used_columns;
3923
 
  return(test(session->is_error()));
 
5610
  thd->lex->allow_sum_func= save_allow_sum_func;
 
5611
  thd->mark_used_columns= save_mark_used_columns;
 
5612
  return(test(thd->is_error()));
3924
5613
}
3925
5614
 
3926
5615
 
3928
5617
  make list of leaves of join table tree
3929
5618
 
3930
5619
  SYNOPSIS
3931
 
  make_leaves_list()
3932
 
  list    pointer to pointer on list first element
3933
 
  tables  table list
 
5620
    make_leaves_list()
 
5621
    list    pointer to pointer on list first element
 
5622
    tables  table list
3934
5623
 
3935
5624
  RETURN pointer on pointer to next_leaf of last element
3936
5625
*/
3937
5626
 
3938
 
static TableList **make_leaves_list(TableList **list, TableList *tables)
 
5627
TableList **make_leaves_list(TableList **list, TableList *tables)
3939
5628
{
3940
5629
  for (TableList *table= tables; table; table= table->next_local)
3941
5630
  {
3951
5640
  prepare tables
3952
5641
 
3953
5642
  SYNOPSIS
3954
 
  setup_tables()
3955
 
  session                 Thread Cursor
3956
 
  context       name resolution contest to setup table list there
3957
 
  from_clause   Top-level list of table references in the FROM clause
3958
 
  tables          Table list (select_lex->table_list)
3959
 
  leaves        List of join table leaves list (select_lex->leaf_tables)
3960
 
  refresh       It is onle refresh for subquery
3961
 
  select_insert It is SELECT ... INSERT command
 
5643
    setup_tables()
 
5644
    thd           Thread handler
 
5645
    context       name resolution contest to setup table list there
 
5646
    from_clause   Top-level list of table references in the FROM clause
 
5647
    tables        Table list (select_lex->table_list)
 
5648
    leaves        List of join table leaves list (select_lex->leaf_tables)
 
5649
    refresh       It is onle refresh for subquery
 
5650
    select_insert It is SELECT ... INSERT command
3962
5651
 
3963
5652
  NOTE
3964
 
  Check also that the 'used keys' and 'ignored keys' exists and set up the
3965
 
  table structure accordingly.
3966
 
  Create a list of leaf tables. For queries with NATURAL/USING JOINs,
3967
 
  compute the row types of the top most natural/using join table references
3968
 
  and link these into a list of table references for name resolution.
 
5653
    Check also that the 'used keys' and 'ignored keys' exists and set up the
 
5654
    table structure accordingly.
 
5655
    Create a list of leaf tables. For queries with NATURAL/USING JOINs,
 
5656
    compute the row types of the top most natural/using join table references
 
5657
    and link these into a list of table references for name resolution.
3969
5658
 
3970
 
  This has to be called for all tables that are used by items, as otherwise
3971
 
  table->map is not set and all Item_field will be regarded as const items.
 
5659
    This has to be called for all tables that are used by items, as otherwise
 
5660
    table->map is not set and all Item_field will be regarded as const items.
3972
5661
 
3973
5662
  RETURN
3974
 
  false ok;  In this case *map will includes the chosen index
3975
 
  true  error
 
5663
    false ok;  In this case *map will includes the chosen index
 
5664
    true  error
3976
5665
*/
3977
5666
 
3978
 
bool setup_tables(Session *session, Name_resolution_context *context,
 
5667
bool setup_tables(THD *thd, Name_resolution_context *context,
3979
5668
                  List<TableList> *from_clause, TableList *tables,
3980
5669
                  TableList **leaves, bool select_insert)
3981
5670
{
3982
5671
  uint32_t tablenr= 0;
3983
5672
 
3984
 
  assert ((select_insert && !tables->next_name_resolution_table) || !tables ||
3985
 
          (context->table_list && context->first_name_resolution_table));
 
5673
  assert ((select_insert && !tables->next_name_resolution_table) || !tables || 
 
5674
               (context->table_list && context->first_name_resolution_table));
3986
5675
  /*
3987
5676
    this is used for INSERT ... SELECT.
3988
5677
    For select we setup tables except first (and its underlying tables)
3989
5678
  */
3990
 
  TableList *first_select_table= (select_insert ?  tables->next_local: NULL);
3991
 
 
 
5679
  TableList *first_select_table= (select_insert ?
 
5680
                                   tables->next_local:
 
5681
                                   0);
3992
5682
  if (!(*leaves))
3993
5683
    make_leaves_list(leaves, tables);
3994
5684
 
4006
5696
      first_select_table= 0;
4007
5697
      tablenr= 0;
4008
5698
    }
4009
 
    table->setup_table_map(table_list, tablenr);
 
5699
    setup_table_map(table, table_list, tablenr);
4010
5700
    if (table_list->process_index_hints(table))
4011
 
      return 1;
 
5701
      return(1);
4012
5702
  }
4013
5703
  if (tablenr > MAX_TABLES)
4014
5704
  {
4015
5705
    my_error(ER_TOO_MANY_TABLES,MYF(0),MAX_TABLES);
4016
 
    return 1;
 
5706
    return(1);
4017
5707
  }
4018
5708
 
4019
5709
  /* Precompute and store the row types of NATURAL/USING joins. */
4020
 
  if (setup_natural_join_row_types(session, from_clause, context))
4021
 
    return 1;
 
5710
  if (setup_natural_join_row_types(thd, from_clause, context))
 
5711
    return(1);
4022
5712
 
4023
 
  return 0;
 
5713
  return(0);
4024
5714
}
4025
5715
 
4026
5716
 
4028
5718
  prepare tables and check access for the view tables
4029
5719
 
4030
5720
  SYNOPSIS
4031
 
  setup_tables_and_check_view_access()
4032
 
  session                 Thread Cursor
4033
 
  context       name resolution contest to setup table list there
4034
 
  from_clause   Top-level list of table references in the FROM clause
4035
 
  tables          Table list (select_lex->table_list)
4036
 
  conds   Condition of current SELECT (can be changed by VIEW)
4037
 
  leaves        List of join table leaves list (select_lex->leaf_tables)
4038
 
  refresh       It is onle refresh for subquery
4039
 
  select_insert It is SELECT ... INSERT command
4040
 
  want_access   what access is needed
 
5721
    setup_tables_and_check_view_access()
 
5722
    thd           Thread handler
 
5723
    context       name resolution contest to setup table list there
 
5724
    from_clause   Top-level list of table references in the FROM clause
 
5725
    tables        Table list (select_lex->table_list)
 
5726
    conds         Condition of current SELECT (can be changed by VIEW)
 
5727
    leaves        List of join table leaves list (select_lex->leaf_tables)
 
5728
    refresh       It is onle refresh for subquery
 
5729
    select_insert It is SELECT ... INSERT command
 
5730
    want_access   what access is needed
4041
5731
 
4042
5732
  NOTE
4043
 
  a wrapper for check_tables that will also check the resulting
4044
 
  table leaves list for access to all the tables that belong to a view
 
5733
    a wrapper for check_tables that will also check the resulting
 
5734
    table leaves list for access to all the tables that belong to a view
4045
5735
 
4046
5736
  RETURN
4047
 
  false ok;  In this case *map will include the chosen index
4048
 
  true  error
 
5737
    false ok;  In this case *map will include the chosen index
 
5738
    true  error
4049
5739
*/
4050
 
bool setup_tables_and_check_access(Session *session,
 
5740
bool setup_tables_and_check_access(THD *thd, 
4051
5741
                                   Name_resolution_context *context,
4052
5742
                                   List<TableList> *from_clause,
4053
5743
                                   TableList *tables,
4055
5745
                                   bool select_insert)
4056
5746
{
4057
5747
  TableList *leaves_tmp= NULL;
 
5748
  bool first_table= true;
4058
5749
 
4059
 
  if (setup_tables(session, context, from_clause, tables,
 
5750
  if (setup_tables(thd, context, from_clause, tables,
4060
5751
                   &leaves_tmp, select_insert))
4061
5752
    return true;
4062
5753
 
4063
5754
  if (leaves)
4064
5755
    *leaves= leaves_tmp;
4065
5756
 
 
5757
  for (; leaves_tmp; leaves_tmp= leaves_tmp->next_leaf)
 
5758
  {
 
5759
    first_table= 0;
 
5760
  }
4066
5761
  return false;
4067
5762
}
4068
5763
 
4069
5764
 
4070
5765
/*
 
5766
   Create a key_map from a list of index names
 
5767
 
 
5768
   SYNOPSIS
 
5769
     get_key_map_from_key_list()
 
5770
     map                key_map to fill in
 
5771
     table              Table
 
5772
     index_list         List of index names
 
5773
 
 
5774
   RETURN
 
5775
     0  ok;  In this case *map will includes the choosed index
 
5776
     1  error
 
5777
*/
 
5778
 
 
5779
bool get_key_map_from_key_list(key_map *map, Table *table,
 
5780
                               List<String> *index_list)
 
5781
{
 
5782
  List_iterator_fast<String> it(*index_list);
 
5783
  String *name;
 
5784
  uint32_t pos;
 
5785
 
 
5786
  map->clear_all();
 
5787
  while ((name=it++))
 
5788
  {
 
5789
    if (table->s->keynames.type_names == 0 ||
 
5790
        (pos= find_type(&table->s->keynames, name->ptr(),
 
5791
                        name->length(), 1)) <=
 
5792
        0)
 
5793
    {
 
5794
      my_error(ER_KEY_DOES_NOT_EXITS, MYF(0), name->c_ptr(),
 
5795
               table->pos_in_table_list->alias);
 
5796
      map->set_all();
 
5797
      return 1;
 
5798
    }
 
5799
    map->set_bit(pos-1);
 
5800
  }
 
5801
  return 0;
 
5802
}
 
5803
 
 
5804
 
 
5805
/*
4071
5806
  Drops in all fields instead of current '*' field
4072
5807
 
4073
5808
  SYNOPSIS
4074
 
  insert_fields()
4075
 
  session                       Thread Cursor
4076
 
  context             Context for name resolution
4077
 
  db_name               Database name in case of 'database_name.table_name.*'
4078
 
  table_name            Table name in case of 'table_name.*'
4079
 
  it                    Pointer to '*'
4080
 
  any_privileges        0 If we should ensure that we have SELECT privileges
4081
 
  for all columns
4082
 
  1 If any privilege is ok
 
5809
    insert_fields()
 
5810
    thd                 Thread handler
 
5811
    context             Context for name resolution
 
5812
    db_name             Database name in case of 'database_name.table_name.*'
 
5813
    table_name          Table name in case of 'table_name.*'
 
5814
    it                  Pointer to '*'
 
5815
    any_privileges      0 If we should ensure that we have SELECT privileges
 
5816
                          for all columns
 
5817
                        1 If any privilege is ok
4083
5818
  RETURN
4084
 
  0     ok     'it' is updated to point at last inserted
4085
 
  1     error.  Error message is generated but not sent to client
 
5819
    0   ok     'it' is updated to point at last inserted
 
5820
    1   error.  Error message is generated but not sent to client
4086
5821
*/
4087
5822
 
4088
5823
bool
4089
 
insert_fields(Session *session, Name_resolution_context *context, const char *db_name,
 
5824
insert_fields(THD *thd, Name_resolution_context *context, const char *db_name,
4090
5825
              const char *table_name, List_iterator<Item> *it,
4091
 
              bool )
 
5826
              bool any_privileges __attribute__((unused)))
4092
5827
{
4093
5828
  Field_iterator_table_ref field_iterator;
4094
5829
  bool found;
4095
5830
  char name_buff[NAME_LEN+1];
4096
5831
 
4097
 
  if (db_name)
 
5832
  if (db_name && lower_case_table_names)
4098
5833
  {
4099
5834
    /*
4100
5835
      convert database to lower case for comparison
4101
5836
      We can't do this in Item_field as this would change the
4102
5837
      'name' of the item which may be used in the select list
4103
5838
    */
4104
 
    strncpy(name_buff, db_name, sizeof(name_buff)-1);
 
5839
    strmake(name_buff, db_name, sizeof(name_buff)-1);
4105
5840
    my_casedn_str(files_charset_info, name_buff);
4106
5841
    db_name= name_buff;
4107
5842
  }
4114
5849
    tables.
4115
5850
  */
4116
5851
  for (TableList *tables= (table_name ? context->table_list :
4117
 
                           context->first_name_resolution_table);
 
5852
                            context->first_name_resolution_table);
4118
5853
       tables;
4119
5854
       tables= (table_name ? tables->next_local :
4120
5855
                tables->next_name_resolution_table)
4121
 
      )
 
5856
       )
4122
5857
  {
4123
5858
    Field *field;
4124
5859
    Table *table= tables->table;
4125
5860
 
4126
5861
    assert(tables->is_leaf_for_name_resolution());
4127
5862
 
4128
 
    if ((table_name && my_strcasecmp(table_alias_charset, table_name, tables->alias)) ||
4129
 
        (db_name && strcasecmp(tables->db,db_name)))
 
5863
    if ((table_name && my_strcasecmp(table_alias_charset, table_name, tables->alias)) || 
 
5864
        (db_name && strcmp(tables->db,db_name)))
4130
5865
      continue;
4131
5866
 
4132
5867
    /*
4134
5869
      views and natural joins this update is performed inside the loop below.
4135
5870
    */
4136
5871
    if (table)
4137
 
      session->used_tables|= table->map;
 
5872
      thd->used_tables|= table->map;
4138
5873
 
4139
5874
    /*
4140
5875
      Initialize a generic field iterator for the current table reference.
4148
5883
    {
4149
5884
      Item *item;
4150
5885
 
4151
 
      if (!(item= field_iterator.create_item(session)))
4152
 
        return true;
 
5886
      if (!(item= field_iterator.create_item(thd)))
 
5887
        return(true);
4153
5888
 
4154
5889
      if (!found)
4155
5890
      {
4162
5897
      if ((field= field_iterator.field()))
4163
5898
      {
4164
5899
        /* Mark fields as used to allow storage engine to optimze access */
4165
 
        field->getTable()->setReadSet(field->field_index);
 
5900
        bitmap_set_bit(field->table->read_set, field->field_index);
4166
5901
        if (table)
4167
5902
        {
4168
 
          table->covering_keys&= field->part_of_key;
4169
 
          table->merge_keys|= field->part_of_key;
 
5903
          table->covering_keys.intersect(field->part_of_key);
 
5904
          table->merge_keys.merge(field->part_of_key);
4170
5905
        }
4171
5906
        if (tables->is_natural_join)
4172
5907
        {
4177
5912
          */
4178
5913
          Natural_join_column *nj_col;
4179
5914
          if (!(nj_col= field_iterator.get_natural_column_ref()))
4180
 
            return true;
 
5915
            return(true);
4181
5916
          assert(nj_col->table_field);
4182
5917
          field_table= nj_col->table_ref->table;
4183
5918
          if (field_table)
4184
5919
          {
4185
 
            session->used_tables|= field_table->map;
4186
 
            field_table->covering_keys&= field->part_of_key;
4187
 
            field_table->merge_keys|= field->part_of_key;
 
5920
            thd->used_tables|= field_table->map;
 
5921
            field_table->covering_keys.intersect(field->part_of_key);
 
5922
            field_table->merge_keys.merge(field->part_of_key);
4188
5923
            field_table->used_fields++;
4189
5924
          }
4190
5925
        }
4191
5926
      }
4192
5927
      else
4193
 
        session->used_tables|= item->used_tables();
4194
 
      session->lex->current_select->cur_pos_in_select_list++;
 
5928
        thd->used_tables|= item->used_tables();
 
5929
      thd->lex->current_select->cur_pos_in_select_list++;
4195
5930
    }
4196
5931
    /*
4197
5932
      In case of stored tables, all fields are considered as used,
4200
5935
      For NATURAL joins, used_tables is updated in the IF above.
4201
5936
    */
4202
5937
    if (table)
4203
 
      table->used_fields= table->getShare()->sizeFields();
 
5938
      table->used_fields= table->s->fields;
4204
5939
  }
4205
5940
  if (found)
4206
 
    return false;
 
5941
    return(false);
4207
5942
 
4208
5943
  /*
4209
 
    @TODO in the case when we skipped all columns because there was a
 
5944
    TODO: in the case when we skipped all columns because there was a
4210
5945
    qualified '*', and all columns were coalesced, we have to give a more
4211
5946
    meaningful message than ER_BAD_TABLE_ERROR.
4212
5947
  */
4215
5950
  else
4216
5951
    my_error(ER_BAD_TABLE_ERROR, MYF(0), table_name);
4217
5952
 
4218
 
  return true;
 
5953
  return(true);
4219
5954
}
4220
5955
 
4221
5956
 
4223
5958
  Fix all conditions and outer join expressions.
4224
5959
 
4225
5960
  SYNOPSIS
4226
 
  setup_conds()
4227
 
  session     thread Cursor
4228
 
  tables  list of tables for name resolving (select_lex->table_list)
4229
 
  leaves  list of leaves of join table tree (select_lex->leaf_tables)
4230
 
  conds   WHERE clause
 
5961
    setup_conds()
 
5962
    thd     thread handler
 
5963
    tables  list of tables for name resolving (select_lex->table_list)
 
5964
    leaves  list of leaves of join table tree (select_lex->leaf_tables)
 
5965
    conds   WHERE clause
4231
5966
 
4232
5967
  DESCRIPTION
4233
 
  TODO
 
5968
    TODO
4234
5969
 
4235
5970
  RETURN
4236
 
  true  if some error occured (e.g. out of memory)
4237
 
  false if all is OK
 
5971
    true  if some error occured (e.g. out of memory)
 
5972
    false if all is OK
4238
5973
*/
4239
5974
 
4240
 
int Session::setup_conds(TableList *leaves, COND **conds)
 
5975
int setup_conds(THD *thd, TableList *tables __attribute__((unused)),
 
5976
                TableList *leaves,
 
5977
                COND **conds)
4241
5978
{
4242
 
  Session *session= this;
4243
 
  Select_Lex *select_lex= session->lex->current_select;
 
5979
  SELECT_LEX *select_lex= thd->lex->current_select;
4244
5980
  TableList *table= NULL;       // For HP compilers
4245
 
  void *save_session_marker= session->session_marker;
 
5981
  void *save_thd_marker= thd->thd_marker;
4246
5982
  /*
4247
 
    it_is_update set to true when tables of primary Select_Lex (Select_Lex
 
5983
    it_is_update set to true when tables of primary SELECT_LEX (SELECT_LEX
4248
5984
    which belong to LEX, i.e. most up SELECT) will be updated by
4249
5985
    INSERT/UPDATE/LOAD
4250
 
    NOTE-> using this condition helps to prevent call of prepare_check_option()
 
5986
    NOTE: using this condition helps to prevent call of prepare_check_option()
4251
5987
    from subquery of VIEW, because tables of subquery belongs to VIEW
4252
5988
    (see condition before prepare_check_option() call)
4253
5989
  */
4254
5990
  bool save_is_item_list_lookup= select_lex->is_item_list_lookup;
4255
5991
  select_lex->is_item_list_lookup= 0;
4256
5992
 
4257
 
  session->mark_used_columns= MARK_COLUMNS_READ;
 
5993
  thd->mark_used_columns= MARK_COLUMNS_READ;
4258
5994
  select_lex->cond_count= 0;
4259
5995
  select_lex->between_count= 0;
4260
5996
  select_lex->max_equal_elems= 0;
4261
5997
 
4262
 
  session->session_marker= (void*)1;
 
5998
  thd->thd_marker= (void*)1;
4263
5999
  if (*conds)
4264
6000
  {
4265
 
    session->where="where clause";
4266
 
    if ((!(*conds)->fixed && (*conds)->fix_fields(session, conds)) ||
4267
 
        (*conds)->check_cols(1))
 
6001
    thd->where="where clause";
 
6002
    if ((!(*conds)->fixed && (*conds)->fix_fields(thd, conds)) ||
 
6003
        (*conds)->check_cols(1))
4268
6004
      goto err_no_arena;
4269
6005
  }
4270
 
  session->session_marker= save_session_marker;
 
6006
  thd->thd_marker= save_thd_marker;
4271
6007
 
4272
6008
  /*
4273
6009
    Apply fix_fields() to all ON clauses at all levels of nesting,
4283
6019
      if (embedded->on_expr)
4284
6020
      {
4285
6021
        /* Make a join an a expression */
4286
 
        session->session_marker= (void*)embedded;
4287
 
        session->where="on clause";
4288
 
        if ((!embedded->on_expr->fixed && embedded->on_expr->fix_fields(session, &embedded->on_expr)) ||
4289
 
            embedded->on_expr->check_cols(1))
4290
 
          goto err_no_arena;
 
6022
        thd->thd_marker= (void*)embedded;
 
6023
        thd->where="on clause";
 
6024
        if ((!embedded->on_expr->fixed && embedded->on_expr->fix_fields(thd, &embedded->on_expr)) ||
 
6025
            embedded->on_expr->check_cols(1))
 
6026
          goto err_no_arena;
4291
6027
        select_lex->cond_count++;
4292
6028
      }
4293
 
      embedding= embedded->getEmbedding();
 
6029
      embedding= embedded->embedding;
4294
6030
    }
4295
6031
    while (embedding &&
4296
 
           embedding->getNestedJoin()->join_list.head() == embedded);
 
6032
           embedding->nested_join->join_list.head() == embedded);
4297
6033
 
4298
6034
  }
4299
 
  session->session_marker= save_session_marker;
 
6035
  thd->thd_marker= save_thd_marker;
4300
6036
 
4301
 
  session->lex->current_select->is_item_list_lookup= save_is_item_list_lookup;
4302
 
  return(test(session->is_error()));
 
6037
  thd->lex->current_select->is_item_list_lookup= save_is_item_list_lookup;
 
6038
  return(test(thd->is_error()));
4303
6039
 
4304
6040
err_no_arena:
4305
6041
  select_lex->is_item_list_lookup= save_is_item_list_lookup;
4306
 
 
4307
 
  return 1;
 
6042
  return(1);
4308
6043
}
4309
6044
 
4310
6045
 
4311
6046
/******************************************************************************
4312
 
 ** Fill a record with data (for INSERT or UPDATE)
4313
 
 ** Returns : 1 if some field has wrong type
4314
 
 ******************************************************************************/
 
6047
** Fill a record with data (for INSERT or UPDATE)
 
6048
** Returns : 1 if some field has wrong type
 
6049
******************************************************************************/
4315
6050
 
4316
6051
 
4317
6052
/*
4318
6053
  Fill fields with given items.
4319
6054
 
4320
6055
  SYNOPSIS
4321
 
  fill_record()
4322
 
  fields        Item_fields list to be filled
4323
 
  values        values to fill with
4324
 
  ignore_errors true if we should ignore errors
 
6056
    fill_record()
 
6057
    thd           thread handler
 
6058
    fields        Item_fields list to be filled
 
6059
    values        values to fill with
 
6060
    ignore_errors true if we should ignore errors
4325
6061
 
4326
6062
  NOTE
4327
 
  fill_record() may set table->auto_increment_field_not_null and a
4328
 
  caller should make sure that it is reset after their last call to this
4329
 
  function.
 
6063
    fill_record() may set table->auto_increment_field_not_null and a
 
6064
    caller should make sure that it is reset after their last call to this
 
6065
    function.
4330
6066
 
4331
6067
  RETURN
4332
 
  false   OK
4333
 
  true    error occured
 
6068
    false   OK
 
6069
    true    error occured
4334
6070
*/
4335
6071
 
4336
6072
bool
4337
 
fill_record(Session *session, List<Item> &fields, List<Item> &values, bool ignore_errors)
 
6073
fill_record(THD * thd, List<Item> &fields, List<Item> &values, bool ignore_errors)
4338
6074
{
4339
6075
  List_iterator_fast<Item> f(fields),v(values);
4340
 
  Item *value;
 
6076
  Item *value, *fld;
4341
6077
  Item_field *field;
4342
 
  Table *table;
 
6078
  Table *table= 0;
4343
6079
 
4344
6080
  /*
4345
6081
    Reset the table->auto_increment_field_not_null as it is valid for
4351
6087
      On INSERT or UPDATE fields are checked to be from the same table,
4352
6088
      thus we safely can take table from the first field.
4353
6089
    */
4354
 
    field= static_cast<Item_field *>(f++);
4355
 
    table= field->field->getTable();
 
6090
    fld= (Item_field*)f++;
 
6091
    if (!(field= fld->filed_for_view_update()))
 
6092
    {
 
6093
      my_error(ER_NONUPDATEABLE_COLUMN, MYF(0), fld->name);
 
6094
      goto err;
 
6095
    }
 
6096
    table= field->field->table;
4356
6097
    table->auto_increment_field_not_null= false;
4357
6098
    f.rewind();
4358
6099
  }
4359
 
 
4360
 
  while ((field= static_cast<Item_field *>(f++)))
 
6100
  while ((fld= f++))
4361
6101
  {
4362
 
    value= v++;
4363
 
 
 
6102
    if (!(field= fld->filed_for_view_update()))
 
6103
    {
 
6104
      my_error(ER_NONUPDATEABLE_COLUMN, MYF(0), fld->name);
 
6105
      goto err;
 
6106
    }
 
6107
    value=v++;
4364
6108
    Field *rfield= field->field;
4365
 
    table= rfield->getTable();
4366
 
 
 
6109
    table= rfield->table;
4367
6110
    if (rfield == table->next_number_field)
4368
6111
      table->auto_increment_field_not_null= true;
4369
6112
    if ((value->save_in_field(rfield, 0) < 0) && !ignore_errors)
4372
6115
      goto err;
4373
6116
    }
4374
6117
  }
4375
 
 
4376
 
  return session->is_error();
4377
 
 
 
6118
  return(thd->is_error());
4378
6119
err:
4379
6120
  if (table)
4380
6121
    table->auto_increment_field_not_null= false;
4381
 
 
4382
 
  return true;
 
6122
  return(true);
4383
6123
}
4384
6124
 
4385
6125
 
4387
6127
  Fill field buffer with values from Field list
4388
6128
 
4389
6129
  SYNOPSIS
4390
 
  fill_record()
4391
 
  ptr           pointer on pointer to record
4392
 
  values        list of fields
4393
 
  ignore_errors true if we should ignore errors
 
6130
    fill_record()
 
6131
    thd           thread handler
 
6132
    ptr           pointer on pointer to record
 
6133
    values        list of fields
 
6134
    ignore_errors true if we should ignore errors
4394
6135
 
4395
6136
  NOTE
4396
 
  fill_record() may set table->auto_increment_field_not_null and a
4397
 
  caller should make sure that it is reset after their last call to this
4398
 
  function.
 
6137
    fill_record() may set table->auto_increment_field_not_null and a
 
6138
    caller should make sure that it is reset after their last call to this
 
6139
    function.
4399
6140
 
4400
6141
  RETURN
4401
 
  false   OK
4402
 
  true    error occured
 
6142
    false   OK
 
6143
    true    error occured
4403
6144
*/
4404
6145
 
4405
 
bool fill_record(Session *session, Field **ptr, List<Item> &values, bool)
 
6146
bool
 
6147
fill_record(THD *thd, Field **ptr, List<Item> &values,
 
6148
            bool ignore_errors __attribute__((unused)))
4406
6149
{
4407
6150
  List_iterator_fast<Item> v(values);
4408
6151
  Item *value;
4409
6152
  Table *table= 0;
 
6153
 
4410
6154
  Field *field;
4411
 
 
4412
6155
  /*
4413
6156
    Reset the table->auto_increment_field_not_null as it is valid for
4414
6157
    only one row.
4419
6162
      On INSERT or UPDATE fields are checked to be from the same table,
4420
6163
      thus we safely can take table from the first field.
4421
6164
    */
4422
 
    table= (*ptr)->getTable();
 
6165
    table= (*ptr)->table;
4423
6166
    table->auto_increment_field_not_null= false;
4424
6167
  }
4425
 
  while ((field = *ptr++) && ! session->is_error())
 
6168
  while ((field = *ptr++) && ! thd->is_error())
4426
6169
  {
4427
6170
    value=v++;
4428
 
    table= field->getTable();
 
6171
    table= field->table;
4429
6172
    if (field == table->next_number_field)
4430
6173
      table->auto_increment_field_not_null= true;
4431
6174
    if (value->save_in_field(field, 0) < 0)
4432
6175
      goto err;
4433
6176
  }
4434
 
 
4435
 
  return(session->is_error());
 
6177
  return(thd->is_error());
4436
6178
 
4437
6179
err:
4438
6180
  if (table)
4439
6181
    table->auto_increment_field_not_null= false;
4440
 
 
4441
 
  return true;
 
6182
  return(true);
4442
6183
}
4443
6184
 
4444
6185
 
4445
 
bool drizzle_rm_tmp_tables()
 
6186
bool mysql_rm_tmp_tables(void)
4446
6187
{
4447
 
  Session *session;
4448
 
 
4449
 
  assert(drizzle_tmpdir.size());
4450
 
 
4451
 
  if (!(session= new Session(plugin::Listen::getNullClient())))
4452
 
    return true;
4453
 
  session->thread_stack= (char*) &session;
4454
 
  session->storeGlobals();
4455
 
 
4456
 
  plugin::StorageEngine::removeLostTemporaryTables(*session, drizzle_tmpdir.c_str());
4457
 
 
4458
 
  session->lockForDelete();
4459
 
  delete session;
4460
 
 
4461
 
  return false;
 
6188
  uint32_t i, idx;
 
6189
  char  filePath[FN_REFLEN], *tmpdir, filePathCopy[FN_REFLEN];
 
6190
  MY_DIR *dirp;
 
6191
  FILEINFO *file;
 
6192
  TABLE_SHARE share;
 
6193
  THD *thd;
 
6194
 
 
6195
  if (!(thd= new THD))
 
6196
    return(1);
 
6197
  thd->thread_stack= (char*) &thd;
 
6198
  thd->store_globals();
 
6199
 
 
6200
  for (i=0; i<=mysql_tmpdir_list.max; i++)
 
6201
  {
 
6202
    tmpdir=mysql_tmpdir_list.list[i];
 
6203
    /* See if the directory exists */
 
6204
    if (!(dirp = my_dir(tmpdir,MYF(MY_WME | MY_DONT_SORT))))
 
6205
      continue;
 
6206
 
 
6207
    /* Remove all SQLxxx tables from directory */
 
6208
 
 
6209
    for (idx=0 ; idx < (uint) dirp->number_off_files ; idx++)
 
6210
    {
 
6211
      file=dirp->dir_entry+idx;
 
6212
 
 
6213
      /* skiping . and .. */
 
6214
      if (file->name[0] == '.' && (!file->name[1] ||
 
6215
                                   (file->name[1] == '.' &&  !file->name[2])))
 
6216
        continue;
 
6217
 
 
6218
      if (!memcmp(file->name, tmp_file_prefix, tmp_file_prefix_length))
 
6219
      {
 
6220
        char *ext= fn_ext(file->name);
 
6221
        uint32_t ext_len= strlen(ext);
 
6222
        uint32_t filePath_len= snprintf(filePath, sizeof(filePath),
 
6223
                                    "%s%c%s", tmpdir, FN_LIBCHAR,
 
6224
                                    file->name);
 
6225
        if (!memcmp(reg_ext, ext, ext_len))
 
6226
        {
 
6227
          handler *handler_file= 0;
 
6228
          /* We should cut file extention before deleting of table */
 
6229
          memcpy(filePathCopy, filePath, filePath_len - ext_len);
 
6230
          filePathCopy[filePath_len - ext_len]= 0;
 
6231
          init_tmp_table_share(thd, &share, "", 0, "", filePathCopy);
 
6232
          if (!open_table_def(thd, &share, 0) &&
 
6233
              ((handler_file= get_new_handler(&share, thd->mem_root,
 
6234
                                              share.db_type()))))
 
6235
          {
 
6236
            handler_file->ha_delete_table(filePathCopy);
 
6237
            delete handler_file;
 
6238
          }
 
6239
          free_table_share(&share);
 
6240
        }
 
6241
        /*
 
6242
          File can be already deleted by tmp_table.file->delete_table().
 
6243
          So we hide error messages which happnes during deleting of these
 
6244
          files(MYF(0)).
 
6245
        */
 
6246
        my_delete(filePath, MYF(0)); 
 
6247
      }
 
6248
    }
 
6249
    my_dirend(dirp);
 
6250
  }
 
6251
  delete thd;
 
6252
  my_pthread_setspecific_ptr(THR_THD,  0);
 
6253
  return(0);
4462
6254
}
4463
6255
 
4464
6256
 
4465
6257
 
4466
6258
/*****************************************************************************
4467
 
  unireg support functions
4468
 
 *****************************************************************************/
 
6259
        unireg support functions
 
6260
*****************************************************************************/
4469
6261
 
4470
6262
/*
4471
6263
  Invalidate any cache entries that are for some DB
4472
6264
 
4473
6265
  SYNOPSIS
4474
 
  remove_db_from_cache()
4475
 
  db            Database name. This will be in lower case if
4476
 
  lower_case_table_name is set
 
6266
    remove_db_from_cache()
 
6267
    db          Database name. This will be in lower case if
 
6268
                lower_case_table_name is set
4477
6269
 
4478
 
NOTE:
4479
 
We can't use hash_delete when looping hash_elements. We mark them first
4480
 
and afterwards delete those marked unused.
 
6270
  NOTE:
 
6271
  We can't use hash_delete when looping hash_elements. We mark them first
 
6272
  and afterwards delete those marked unused.
4481
6273
*/
4482
6274
 
4483
 
void remove_db_from_cache(const SchemaIdentifier &schema_identifier)
 
6275
void remove_db_from_cache(const char *db)
4484
6276
{
4485
 
  safe_mutex_assert_owner(LOCK_open.native_handle());
4486
 
 
4487
 
  for (TableOpenCache::const_iterator iter= get_open_cache().begin();
4488
 
       iter != get_open_cache().end();
4489
 
       iter++)
 
6277
  for (uint32_t idx=0 ; idx < open_cache.records ; idx++)
4490
6278
  {
4491
 
    Table *table= (*iter).second;
4492
 
 
4493
 
    if (not schema_identifier.getPath().compare(table->getMutableShare()->getSchemaName()))
 
6279
    Table *table=(Table*) hash_element(&open_cache,idx);
 
6280
    if (!strcmp(table->s->db.str, db))
4494
6281
    {
4495
 
      table->getMutableShare()->resetVersion();                 /* Free when thread is ready */
4496
 
      if (not table->in_use)
4497
 
        unused_tables.relink(table);
 
6282
      table->s->version= 0L;                    /* Free when thread is ready */
 
6283
      if (!table->in_use)
 
6284
        relink_unused(table);
4498
6285
    }
4499
6286
  }
4500
 
 
4501
 
  unused_tables.cullByVersion();
 
6287
  while (unused_tables && !unused_tables->s->version)
 
6288
    hash_delete(&open_cache,(unsigned char*) unused_tables);
 
6289
}
 
6290
 
 
6291
 
 
6292
/*
 
6293
  free all unused tables
 
6294
 
 
6295
  NOTE
 
6296
    This is called by 'handle_manager' when one wants to periodicly flush
 
6297
    all not used tables.
 
6298
*/
 
6299
 
 
6300
void flush_tables()
 
6301
{
 
6302
  (void) pthread_mutex_lock(&LOCK_open);
 
6303
  while (unused_tables)
 
6304
    hash_delete(&open_cache,(unsigned char*) unused_tables);
 
6305
  (void) pthread_mutex_unlock(&LOCK_open);
4502
6306
}
4503
6307
 
4504
6308
 
4509
6313
  close_thread_tables() is called.
4510
6314
 
4511
6315
  PREREQUISITES
4512
 
  Lock on LOCK_open()
 
6316
    Lock on LOCK_open()
4513
6317
 
4514
6318
  RETURN
4515
 
  0  This thread now have exclusive access to this table and no other thread
4516
 
  can access the table until close_thread_tables() is called.
4517
 
  1  Table is in use by another thread
 
6319
    0  This thread now have exclusive access to this table and no other thread
 
6320
       can access the table until close_thread_tables() is called.
 
6321
    1  Table is in use by another thread
4518
6322
*/
4519
6323
 
4520
 
bool remove_table_from_cache(Session *session, TableIdentifier &identifier, uint32_t flags)
 
6324
bool remove_table_from_cache(THD *thd, const char *db, const char *table_name,
 
6325
                             uint32_t flags)
4521
6326
{
4522
 
  const TableIdentifier::Key &key(identifier.getKey());
4523
 
  bool result= false; 
4524
 
  bool signalled= false;
 
6327
  char key[MAX_DBKEY_LENGTH];
 
6328
  uint32_t key_length;
 
6329
  Table *table;
 
6330
  TABLE_SHARE *share;
 
6331
  bool result= 0, signalled= 0;
4525
6332
 
 
6333
  key_length=(uint) (my_stpcpy(my_stpcpy(key,db)+1,table_name)-key)+1;
4526
6334
  for (;;)
4527
6335
  {
4528
 
    result= signalled= false;
4529
 
 
4530
 
    TableOpenCacheRange ppp;
4531
 
    ppp= get_open_cache().equal_range(key);
4532
 
 
4533
 
    for (TableOpenCache::const_iterator iter= ppp.first;
4534
 
         iter != ppp.second; ++iter)
 
6336
    HASH_SEARCH_STATE state;
 
6337
    result= signalled= 0;
 
6338
 
 
6339
    for (table= (Table*) hash_first(&open_cache, (unsigned char*) key, key_length,
 
6340
                                    &state);
 
6341
         table;
 
6342
         table= (Table*) hash_next(&open_cache, (unsigned char*) key, key_length,
 
6343
                                   &state))
4535
6344
    {
4536
 
      Table *table= (*iter).second;
4537
 
      Session *in_use;
 
6345
      THD *in_use;
4538
6346
 
4539
 
      table->getMutableShare()->resetVersion();         /* Free when thread is ready */
 
6347
      table->s->version=0L;             /* Free when thread is ready */
4540
6348
      if (!(in_use=table->in_use))
4541
6349
      {
4542
 
        unused_tables.relink(table);
 
6350
        relink_unused(table);
4543
6351
      }
4544
 
      else if (in_use != session)
 
6352
      else if (in_use != thd)
4545
6353
      {
4546
6354
        /*
4547
6355
          Mark that table is going to be deleted from cache. This will
4548
6356
          force threads that are in mysql_lock_tables() (but not yet
4549
6357
          in thr_multi_lock()) to abort it's locks, close all tables and retry
4550
6358
        */
4551
 
        in_use->some_tables_deleted= true;
 
6359
        in_use->some_tables_deleted= 1;
4552
6360
        if (table->is_name_opened())
4553
6361
        {
4554
 
          result= true;
 
6362
          result=1;
4555
6363
        }
4556
6364
        /*
4557
 
          Now we must abort all tables locks used by this thread
4558
 
          as the thread may be waiting to get a lock for another table.
 
6365
          Now we must abort all tables locks used by this thread
 
6366
          as the thread may be waiting to get a lock for another table.
4559
6367
          Note that we need to hold LOCK_open while going through the
4560
6368
          list. So that the other thread cannot change it. The other
4561
6369
          thread must also hold LOCK_open whenever changing the
4562
6370
          open_tables list. Aborting the MERGE lock after a child was
4563
6371
          closed and before the parent is closed would be fatal.
4564
6372
        */
4565
 
        for (Table *session_table= in_use->open_tables;
4566
 
             session_table ;
4567
 
             session_table= session_table->getNext())
 
6373
        for (Table *thd_table= in_use->open_tables;
 
6374
             thd_table ;
 
6375
             thd_table= thd_table->next)
4568
6376
        {
4569
6377
          /* Do not handle locks of MERGE children. */
4570
 
          if (session_table->db_stat)   // If table is open
4571
 
            signalled|= mysql_lock_abort_for_thread(session, session_table);
 
6378
          if (thd_table->db_stat)       // If table is open
 
6379
            signalled|= mysql_lock_abort_for_thread(thd, thd_table);
4572
6380
        }
4573
6381
      }
4574
6382
      else
4575
 
        result= result || (flags & RTFC_OWNED_BY_Session_FLAG);
 
6383
        result= result || (flags & RTFC_OWNED_BY_THD_FLAG);
4576
6384
    }
4577
 
 
4578
 
    unused_tables.cullByVersion();
 
6385
    while (unused_tables && !unused_tables->s->version)
 
6386
      hash_delete(&open_cache,(unsigned char*) unused_tables);
4579
6387
 
4580
6388
    /* Remove table from table definition cache if it's not in use */
4581
 
    TableShare::release(identifier);
 
6389
    if ((share= (TABLE_SHARE*) hash_search(&table_def_cache,(unsigned char*) key,
 
6390
                                           key_length)))
 
6391
    {
 
6392
      share->version= 0;                          // Mark for delete
 
6393
      if (share->ref_count == 0)
 
6394
      {
 
6395
        pthread_mutex_lock(&share->mutex);
 
6396
        hash_delete(&table_def_cache, (unsigned char*) share);
 
6397
      }
 
6398
    }
4582
6399
 
4583
6400
    if (result && (flags & RTFC_WAIT_OTHER_THREAD_FLAG))
4584
6401
    {
4587
6404
        reopen their tables
4588
6405
      */
4589
6406
      broadcast_refresh();
4590
 
      if (!(flags & RTFC_CHECK_KILLED_FLAG) || !session->killed)
 
6407
      if (!(flags & RTFC_CHECK_KILLED_FLAG) || !thd->killed)
4591
6408
      {
4592
6409
        dropping_tables++;
4593
6410
        if (likely(signalled))
4594
 
          (void) pthread_cond_wait(COND_refresh.native_handle(), LOCK_open.native_handle());
 
6411
          (void) pthread_cond_wait(&COND_refresh, &LOCK_open);
4595
6412
        else
4596
6413
        {
4597
6414
          struct timespec abstime;
4606
6423
            remove_table_from_cache routine.
4607
6424
          */
4608
6425
          set_timespec(abstime, 10);
4609
 
          pthread_cond_timedwait(COND_refresh.native_handle(), LOCK_open.native_handle(), &abstime);
 
6426
          pthread_cond_timedwait(&COND_refresh, &LOCK_open, &abstime);
4610
6427
        }
4611
6428
        dropping_tables--;
4612
6429
        continue;
4614
6431
    }
4615
6432
    break;
4616
6433
  }
4617
 
 
4618
 
  return result;
4619
 
}
4620
 
 
4621
 
 
 
6434
  return(result);
 
6435
}
 
6436
 
 
6437
 
 
6438
bool is_equal(const LEX_STRING *a, const LEX_STRING *b)
 
6439
{
 
6440
  return a->length == b->length && !strncmp(a->str, b->str, a->length);
 
6441
}
4622
6442
/**
4623
6443
  @} (end of group Data_Dictionary)
4624
6444
*/
4625
 
 
4626
 
void kill_drizzle(void)
4627
 
{
4628
 
  pthread_kill(signal_thread, SIGTERM);
4629
 
  shutdown_in_progress= 1;                      // Safety if kill didn't work
4630
 
}
4631
 
 
4632
 
} /* namespace drizzled */