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