~drizzle-trunk/drizzle/development

« back to all changes in this revision

Viewing changes to server/sql_base.cc

Removed/replaced DBUG symbols and TRUE/FALSE

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