~drizzle-trunk/drizzle/development

« back to all changes in this revision

Viewing changes to server/sql_base.cc

  • Committer: Jim Winstead
  • Date: 2008-07-19 02:56:45 UTC
  • mto: (202.1.8 codestyle)
  • mto: This revision was merged to the branch mainline in revision 207.
  • Revision ID: jimw@mysql.com-20080719025645-w2pwytebgzusjzjb
Various fixes to enable compilation on Mac OS X, and remove the glib dependency.
Temporarily disables tab-completion in the drizzle client until an appropriate
autoconf check can be added/enabled.

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