~drizzle-trunk/drizzle/development

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