~stewart/drizzle/embedded-innodb-create-select-transaction-arrgh

« back to all changes in this revision

Viewing changes to sql/sql_base.cc

  • Committer: brian
  • Date: 2008-06-25 05:29:13 UTC
  • Revision ID: brian@localhost.localdomain-20080625052913-6upwo0jsrl4lnapl
clean slate

Show diffs side-by-side

added added

removed removed

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