~drizzle-trunk/drizzle/development

« back to all changes in this revision

Viewing changes to server/sql_base.cc

Removed/replaced DBUG symbols and TRUE/FALSE

Show diffs side-by-side

added added

removed removed

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