~drizzle-trunk/drizzle/development

« back to all changes in this revision

Viewing changes to sql/sql_base.cc

  • Committer: Brian Aker
  • Date: 2008-07-08 16:17:31 UTC
  • Revision ID: brian@tangent.org-20080708161731-io36j7igglok79py
DATE cleanup.

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