1
/* Copyright (C) 2000-2006 MySQL AB
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.
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.
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 */
17
/* Basic functions needed by many modules */
19
#include "mysql_priv.h"
20
#include "sql_select.h"
25
#define FLAGSTR(S,F) ((S) & (F) ? #F " " : "")
28
@defgroup Data_Dictionary Data Dictionary
31
TABLE *unused_tables; /* Used by mysql_test */
32
HASH open_cache; /* Used by mysql_test */
33
static HASH table_def_cache;
34
static TABLE_SHARE *oldest_unused_share, end_of_unused_share;
35
static pthread_mutex_t LOCK_table_share;
36
static bool table_def_inited= 0;
38
static int open_unireg_entry(THD *thd, TABLE *entry, TABLE_LIST *table_list,
40
char *cache_key, uint cache_key_length,
41
MEM_ROOT *mem_root, uint flags);
42
static void free_cache_entry(TABLE *entry);
43
static void close_old_data_files(THD *thd, TABLE *table, bool morph_locks,
47
extern "C" uchar *table_cache_key(const uchar *record, size_t *length,
48
my_bool not_used __attribute__((unused)))
50
TABLE *entry=(TABLE*) record;
51
*length= entry->s->table_cache_key.length;
52
return (uchar*) entry->s->table_cache_key.str;
56
bool table_cache_init(void)
58
return hash_init(&open_cache, &my_charset_bin, table_cache_size+16,
59
0, 0, table_cache_key,
60
(hash_free_key) free_cache_entry, 0) != 0;
63
void table_cache_free(void)
65
DBUG_ENTER("table_cache_free");
68
close_cached_tables(NULL, NULL, FALSE, FALSE, FALSE);
69
if (!open_cache.records) // Safety first
70
hash_free(&open_cache);
75
uint cached_open_tables(void)
77
return open_cache.records;
82
static void check_unused(void)
84
uint count= 0, open_files= 0, idx= 0;
85
TABLE *cur_link,*start_link;
87
if ((start_link=cur_link=unused_tables))
91
if (cur_link != cur_link->next->prev || cur_link != cur_link->prev->next)
93
DBUG_PRINT("error",("Unused_links aren't linked properly")); /* purecov: inspected */
94
return; /* purecov: inspected */
96
} while (count++ < open_cache.records &&
97
(cur_link=cur_link->next) != start_link);
98
if (cur_link != start_link)
100
DBUG_PRINT("error",("Unused_links aren't connected")); /* purecov: inspected */
103
for (idx=0 ; idx < open_cache.records ; idx++)
105
TABLE *entry=(TABLE*) hash_element(&open_cache,idx);
113
DBUG_PRINT("error",("Unused_links doesn't match open_cache: diff: %d", /* purecov: inspected */
114
count)); /* purecov: inspected */
117
#ifdef NOT_SAFE_FOR_REPAIR
119
check that open cache and table definition cache has same number of
123
for (idx=0 ; idx < table_def_cache.records ; idx++)
125
TABLE_SHARE *entry= (TABLE_SHARE*) hash_element(&table_def_cache,idx);
126
count+= entry->ref_count;
128
if (count != open_files)
130
DBUG_PRINT("error", ("table_def ref_count: %u open_cache: %u",
132
DBUG_ASSERT(count == open_files);
137
#define check_unused()
142
Create a table cache key
145
create_table_def_key()
147
key Create key here (must be of size MAX_DBKEY_LENGTH)
148
table_list Table definition
149
tmp_table Set if table is a tmp table
152
The table cache_key is created from:
156
if the table is a tmp table, we add the following to make each tmp table
159
4 bytes for master thread id
160
4 bytes pseudo thread id
166
uint create_table_def_key(THD *thd, char *key, TABLE_LIST *table_list,
169
uint key_length= (uint) (strmov(strmov(key, table_list->db)+1,
170
table_list->table_name)-key)+1;
173
int4store(key + key_length, thd->server_id);
174
int4store(key + key_length + 4, thd->variables.pseudo_thread_id);
175
key_length+= TMP_TABLE_KEY_EXTRA;
182
/*****************************************************************************
183
Functions to handle table definition cach (TABLE_SHARE)
184
*****************************************************************************/
186
extern "C" uchar *table_def_key(const uchar *record, size_t *length,
187
my_bool not_used __attribute__((unused)))
189
TABLE_SHARE *entry=(TABLE_SHARE*) record;
190
*length= entry->table_cache_key.length;
191
return (uchar*) entry->table_cache_key.str;
195
static void table_def_free_entry(TABLE_SHARE *share)
197
DBUG_ENTER("table_def_free_entry");
200
/* remove from old_unused_share list */
201
pthread_mutex_lock(&LOCK_table_share);
202
*share->prev= share->next;
203
share->next->prev= share->prev;
204
pthread_mutex_unlock(&LOCK_table_share);
206
free_table_share(share);
211
bool table_def_init(void)
214
pthread_mutex_init(&LOCK_table_share, MY_MUTEX_INIT_FAST);
215
oldest_unused_share= &end_of_unused_share;
216
end_of_unused_share.prev= &oldest_unused_share;
218
return hash_init(&table_def_cache, &my_charset_bin, table_def_size,
220
(hash_free_key) table_def_free_entry, 0) != 0;
224
void table_def_free(void)
226
DBUG_ENTER("table_def_free");
227
if (table_def_inited)
230
pthread_mutex_destroy(&LOCK_table_share);
231
hash_free(&table_def_cache);
237
uint cached_table_definitions(void)
239
return table_def_cache.records;
244
Get TABLE_SHARE for a table.
248
table_list Table that should be opened
250
key_length Length of key
251
db_flags Flags to open_table_def():
253
error out: Error code from open_table_def()
256
Get a table definition from the table definition cache.
257
If it doesn't exist, create a new from the table definition file.
260
We must have wrlock on LOCK_open when we come here
261
(To be changed later)
268
TABLE_SHARE *get_table_share(THD *thd, TABLE_LIST *table_list, char *key,
269
uint key_length, uint db_flags, int *error)
272
DBUG_ENTER("get_table_share");
276
/* Read table definition from cache */
277
if ((share= (TABLE_SHARE*) hash_search(&table_def_cache,(uchar*) key,
281
if (!(share= alloc_table_share(table_list, key, key_length)))
287
Lock mutex to be able to read table definition from file without
290
(void) pthread_mutex_lock(&share->mutex);
293
We assign a new table id under the protection of the LOCK_open and
294
the share's own mutex. We do this insted of creating a new mutex
295
and using it for the sole purpose of serializing accesses to a
296
static variable, we assign the table id here. We assign it to the
297
share before inserting it into the table_def_cache to be really
298
sure that it cannot be read from the cache without having a table
301
CAVEAT. This means that the table cannot be used for
302
binlogging/replication purposes, unless get_table_share() has been
303
called directly or indirectly.
305
assign_new_table_id(share);
307
if (my_hash_insert(&table_def_cache, (uchar*) share))
309
free_table_share(share);
310
DBUG_RETURN(0); // return error
312
if (open_table_def(thd, share, db_flags))
314
*error= share->error;
315
(void) hash_delete(&table_def_cache, (uchar*) share);
318
share->ref_count++; // Mark in use
319
DBUG_PRINT("exit", ("share: 0x%lx ref_count: %u",
320
(ulong) share, share->ref_count));
321
(void) pthread_mutex_unlock(&share->mutex);
326
We found an existing table definition. Return it if we didn't get
327
an error when reading the table definition from file.
330
/* We must do a lock to ensure that the structure is initialized */
331
(void) pthread_mutex_lock(&share->mutex);
334
/* Table definition contained an error */
335
open_table_error(share, share->error, share->open_errno, share->errarg);
336
(void) pthread_mutex_unlock(&share->mutex);
340
if (!share->ref_count++ && share->prev)
343
Share was not used before and it was in the old_unused_share list
344
Unlink share from this list
346
DBUG_PRINT("info", ("Unlinking from not used list"));
347
pthread_mutex_lock(&LOCK_table_share);
348
*share->prev= share->next;
349
share->next->prev= share->prev;
352
pthread_mutex_unlock(&LOCK_table_share);
354
(void) pthread_mutex_unlock(&share->mutex);
356
/* Free cache if too big */
357
while (table_def_cache.records > table_def_size &&
358
oldest_unused_share->next)
360
pthread_mutex_lock(&oldest_unused_share->mutex);
361
VOID(hash_delete(&table_def_cache, (uchar*) oldest_unused_share));
364
DBUG_PRINT("exit", ("share: 0x%lx ref_count: %u",
365
(ulong) share, share->ref_count));
371
Get a table share. If it didn't exist, try creating it from engine
373
For arguments and return values, see get_table_from_share()
377
*get_table_share_with_create(THD *thd, TABLE_LIST *table_list,
378
char *key, uint key_length,
379
uint db_flags, int *error)
383
DBUG_ENTER("get_table_share_with_create");
385
share= get_table_share(thd, table_list, key, key_length, db_flags, error);
387
If share is not NULL, we found an existing share.
389
If share is NULL, and there is no error, we're inside
390
pre-locking, which silences 'ER_NO_SUCH_TABLE' errors
391
with the intention to silently drop non-existing tables
392
from the pre-locking list. In this case we still need to try
393
auto-discover before returning a NULL share.
395
If share is NULL and the error is ER_NO_SUCH_TABLE, this is
396
the same as above, only that the error was not silenced by
397
pre-locking. Once again, we need to try to auto-discover
400
Finally, if share is still NULL, it's a real error and we need
403
@todo Rework alternative ways to deal with ER_NO_SUCH TABLE.
405
if (share || (thd->is_error() && (thd->main_da.sql_errno() != ER_NO_SUCH_TABLE)))
409
/* Table didn't exist. Check if some engine can provide it */
410
if ((tmp= ha_create_table_from_engine(thd, table_list->db,
411
table_list->table_name)) < 0)
414
No such table in any engine.
415
Hide "Table doesn't exist" errors if the table belongs to a view.
416
The check for thd->is_error() is necessary to not push an
417
unwanted error in case of pre-locking, which silences
418
"no such table" errors.
419
@todo Rework the alternative ways to deal with ER_NO_SUCH TABLE.
421
if (thd->is_error() && table_list->belong_to_view)
424
my_error(ER_VIEW_INVALID, MYF(0), "", "");
430
/* Give right error message */
432
DBUG_PRINT("error", ("Discovery of %s/%s failed", table_list->db,
433
table_list->table_name));
434
my_printf_error(ER_UNKNOWN_ERROR,
435
"Failed to open '%-.64s', error while "
436
"unpacking from engine",
437
MYF(0), table_list->table_name);
440
/* Table existed in engine. Let's open it */
441
mysql_reset_errors(thd, 1); // Clear warnings
442
thd->clear_error(); // Clear error message
443
DBUG_RETURN(get_table_share(thd, table_list, key, key_length,
449
Mark that we are not using table share anymore.
452
release_table_share()
454
release_type How the release should be done:
456
- Release without checking
457
RELEASE_WAIT_FOR_DROP
458
- Don't return until we get a signal that the
459
table is deleted or the thread is killed.
462
If ref_count goes to zero and (we have done a refresh or if we have
463
already too many open table shares) then delete the definition.
465
If type == RELEASE_WAIT_FOR_DROP then don't return until we get a signal
466
that the table is deleted or the thread is killed.
469
void release_table_share(TABLE_SHARE *share, enum release_type type)
471
bool to_be_deleted= 0;
472
DBUG_ENTER("release_table_share");
474
("share: 0x%lx table: %s.%s ref_count: %u version: %lu",
475
(ulong) share, share->db.str, share->table_name.str,
476
share->ref_count, share->version));
478
safe_mutex_assert_owner(&LOCK_open);
480
pthread_mutex_lock(&share->mutex);
481
if (!--share->ref_count)
483
if (share->version != refresh_version)
487
/* Link share last in used_table_share list */
488
DBUG_PRINT("info",("moving share to unused list"));
490
DBUG_ASSERT(share->next == 0);
491
pthread_mutex_lock(&LOCK_table_share);
492
share->prev= end_of_unused_share.prev;
493
*end_of_unused_share.prev= share;
494
end_of_unused_share.prev= &share->next;
495
share->next= &end_of_unused_share;
496
pthread_mutex_unlock(&LOCK_table_share);
498
to_be_deleted= (table_def_cache.records > table_def_size);
504
DBUG_PRINT("info", ("Deleting share"));
505
hash_delete(&table_def_cache, (uchar*) share);
508
pthread_mutex_unlock(&share->mutex);
514
Check if table definition exits in cache
517
get_cached_table_share()
519
table_name Table name
523
# TABLE_SHARE for table
526
TABLE_SHARE *get_cached_table_share(const char *db, const char *table_name)
528
char key[NAME_LEN*2+2];
529
TABLE_LIST table_list;
531
safe_mutex_assert_owner(&LOCK_open);
533
table_list.db= (char*) db;
534
table_list.table_name= (char*) table_name;
535
key_length= create_table_def_key((THD*) 0, key, &table_list, 0);
536
return (TABLE_SHARE*) hash_search(&table_def_cache,(uchar*) key, key_length);
541
Close file handle, but leave the table in the table cache
544
close_handle_and_leave_table_as_lock()
548
By leaving the table in the table cache, it disallows any other thread
551
thd->killed will be set if we run out of memory
553
If closing a MERGE child, the calling function has to take care for
554
closing the parent too, if necessary.
558
void close_handle_and_leave_table_as_lock(TABLE *table)
560
TABLE_SHARE *share, *old_share= table->s;
562
MEM_ROOT *mem_root= &table->mem_root;
563
DBUG_ENTER("close_handle_and_leave_table_as_lock");
565
DBUG_ASSERT(table->db_stat);
568
Make a local copy of the table share and free the current one.
569
This has to be done to ensure that the table share is removed from
570
the table defintion cache as soon as the last instance is removed
572
if (multi_alloc_root(mem_root,
573
&share, sizeof(*share),
574
&key_buff, old_share->table_cache_key.length,
577
bzero((char*) share, sizeof(*share));
578
share->set_table_cache_key(key_buff, old_share->table_cache_key.str,
579
old_share->table_cache_key.length);
580
share->tmp_table= INTERNAL_TMP_TABLE; // for intern_close_table()
583
table->file->close();
584
table->db_stat= 0; // Mark file closed
585
release_table_share(table->s, RELEASE_NORMAL);
587
table->file->change_table_ptr(table, table->s);
595
Create a list for all open tables matching SQL expression
600
wild SQL like expression
603
One gets only a list of tables for which one has any kind of privilege.
604
db and table names are allocated in result struct, so one doesn't need
605
a lock on LOCK_open when traversing the return list.
608
NULL Error (Probably OOM)
609
# Pointer to list of names of open tables.
612
OPEN_TABLE_LIST *list_open_tables(THD *thd, const char *db, const char *wild)
615
OPEN_TABLE_LIST **start_list, *open_list;
616
TABLE_LIST table_list;
617
DBUG_ENTER("list_open_tables");
619
VOID(pthread_mutex_lock(&LOCK_open));
620
bzero((char*) &table_list,sizeof(table_list));
621
start_list= &open_list;
624
for (uint idx=0 ; result == 0 && idx < open_cache.records; idx++)
626
OPEN_TABLE_LIST *table;
627
TABLE *entry=(TABLE*) hash_element(&open_cache,idx);
628
TABLE_SHARE *share= entry->s;
630
if (db && my_strcasecmp(system_charset_info, db, share->db.str))
632
if (wild && wild_compare(share->table_name.str, wild, 0))
635
/* Check if user has SELECT privilege for any column in the table */
636
table_list.db= share->db.str;
637
table_list.table_name= share->table_name.str;
639
/* need to check if we haven't already listed it */
640
for (table= open_list ; table ; table=table->next)
642
if (!strcmp(table->table, share->table_name.str) &&
643
!strcmp(table->db, share->db.str))
647
if (entry->locked_by_name)
654
if (!(*start_list = (OPEN_TABLE_LIST *)
655
sql_alloc(sizeof(**start_list)+share->table_cache_key.length)))
657
open_list=0; // Out of memory
660
strmov((*start_list)->table=
661
strmov(((*start_list)->db= (char*) ((*start_list)+1)),
663
share->table_name.str);
664
(*start_list)->in_use= entry->in_use ? 1 : 0;
665
(*start_list)->locked= entry->locked_by_name ? 1 : 0;
666
start_list= &(*start_list)->next;
669
VOID(pthread_mutex_unlock(&LOCK_open));
670
DBUG_RETURN(open_list);
673
/*****************************************************************************
674
* Functions to free open table cache
675
****************************************************************************/
678
void intern_close_table(TABLE *table)
679
{ // Free all structures
680
DBUG_ENTER("intern_close_table");
681
DBUG_PRINT("tcache", ("table: '%s'.'%s' 0x%lx",
682
table->s ? table->s->db.str : "?",
683
table->s ? table->s->table_name.str : "?",
686
free_io_cache(table);
687
if (table->file) // Not true if name lock
688
VOID(closefrm(table, 1)); // close file
693
Remove table from the open table cache
697
table Table to remove
700
We need to have a lock on LOCK_open when calling this
703
static void free_cache_entry(TABLE *table)
705
DBUG_ENTER("free_cache_entry");
707
intern_close_table(table);
710
table->next->prev=table->prev; /* remove from used chain */
711
table->prev->next=table->next;
712
if (table == unused_tables)
714
unused_tables=unused_tables->next;
715
if (table == unused_tables)
718
check_unused(); // consisty check
720
my_free((uchar*) table,MYF(0));
724
/* Free resources allocated by filesort() and read_record() */
726
void free_io_cache(TABLE *table)
728
DBUG_ENTER("free_io_cache");
729
if (table->sort.io_cache)
731
close_cached_file(table->sort.io_cache);
732
my_free((uchar*) table->sort.io_cache,MYF(0));
733
table->sort.io_cache=0;
740
Close all tables which aren't in use by any thread
742
@param thd Thread context
743
@param tables List of tables to remove from the cache
744
@param have_lock If LOCK_open is locked
745
@param wait_for_refresh Wait for a impending flush
746
@param wait_for_placeholders Wait for tables being reopened so that the GRL
747
won't proceed while write-locked tables are being reopened by other
750
@remark THD can be NULL, but then wait_for_refresh must be FALSE
751
and tables must be NULL.
754
bool close_cached_tables(THD *thd, TABLE_LIST *tables, bool have_lock,
755
bool wait_for_refresh, bool wait_for_placeholders)
758
DBUG_ENTER("close_cached_tables");
759
DBUG_ASSERT(thd || (!wait_for_refresh && !tables));
762
VOID(pthread_mutex_lock(&LOCK_open));
765
refresh_version++; // Force close of open tables
766
while (unused_tables)
769
if (hash_delete(&open_cache,(uchar*) unused_tables))
770
printf("Warning: Couldn't delete open table from hash\n");
772
VOID(hash_delete(&open_cache,(uchar*) unused_tables));
775
/* Free table shares */
776
while (oldest_unused_share->next)
778
pthread_mutex_lock(&oldest_unused_share->mutex);
779
VOID(hash_delete(&table_def_cache, (uchar*) oldest_unused_share));
781
DBUG_PRINT("tcache", ("incremented global refresh_version to: %lu",
783
if (wait_for_refresh)
786
Other threads could wait in a loop in open_and_lock_tables(),
787
trying to lock one or more of our tables.
789
If they wait for the locks in thr_multi_lock(), their lock
790
request is aborted. They loop in open_and_lock_tables() and
791
enter open_table(). Here they notice the table is refreshed and
792
wait for COND_refresh. Then they loop again in
793
open_and_lock_tables() and this time open_table() succeeds. At
794
this moment, if we (the FLUSH TABLES thread) are scheduled and
795
on another FLUSH TABLES enter close_cached_tables(), they could
796
awake while we sleep below, waiting for others threads (us) to
797
close their open tables. If this happens, the other threads
798
would find the tables unlocked. They would get the locks, one
799
after the other, and could do their destructive work. This is an
800
issue if we have LOCK TABLES in effect.
802
The problem is that the other threads passed all checks in
803
open_table() before we refresh the table.
805
The fix for this problem is to set some_tables_deleted for all
806
threads with open tables. These threads can still get their
807
locks, but will immediately release them again after checking
808
this variable. They will then loop in open_and_lock_tables()
809
again. There they will wait until we update all tables version
812
Setting some_tables_deleted is done by remove_table_from_cache()
815
In other words (reviewer suggestion): You need this setting of
816
some_tables_deleted for the case when table was opened and all
817
related checks were passed before incrementing refresh_version
818
(which you already have) but attempt to lock the table happened
819
after the call to close_old_data_files() i.e. after removal of
820
current thread locks.
822
for (uint idx=0 ; idx < open_cache.records ; idx++)
824
TABLE *table=(TABLE*) hash_element(&open_cache,idx);
826
table->in_use->some_tables_deleted= 1;
833
for (TABLE_LIST *table= tables; table; table= table->next_local)
835
if (remove_table_from_cache(thd, table->db, table->table_name,
836
RTFC_OWNED_BY_THD_FLAG))
840
wait_for_refresh=0; // Nothing to wait for
843
if (wait_for_refresh)
846
If there is any table that has a lower refresh_version, wait until
847
this is closed (or this thread is killed) before returning
849
thd->mysys_var->current_mutex= &LOCK_open;
850
thd->mysys_var->current_cond= &COND_refresh;
851
thd_proc_info(thd, "Flushing tables");
853
close_old_data_files(thd,thd->open_tables,1,1);
857
/* Wait until all threads has closed all the tables we had locked */
859
("Waiting for other threads to close their open tables"));
860
while (found && ! thd->killed)
863
for (uint idx=0 ; idx < open_cache.records ; idx++)
865
TABLE *table=(TABLE*) hash_element(&open_cache,idx);
866
/* Avoid a self-deadlock. */
867
if (table->in_use == thd)
870
Note that we wait here only for tables which are actually open, and
871
not for placeholders with TABLE::open_placeholder set. Waiting for
872
latter will cause deadlock in the following scenario, for example:
874
conn1: lock table t1 write;
875
conn2: lock table t2 write;
879
It also does not make sense to wait for those of placeholders that
880
are employed by CREATE TABLE as in this case table simply does not
883
if (table->needs_reopen_or_name_lock() && (table->db_stat ||
884
(table->open_placeholder && wait_for_placeholders)))
887
DBUG_PRINT("signal", ("Waiting for COND_refresh"));
888
pthread_cond_wait(&COND_refresh,&LOCK_open);
894
No other thread has the locked tables open; reopen them and get the
895
old locks. This should always succeed (unless some external process
896
has removed the tables)
898
thd->in_lock_tables=1;
899
result=reopen_tables(thd,1,1);
900
thd->in_lock_tables=0;
901
/* Set version for table */
902
for (TABLE *table=thd->open_tables; table ; table= table->next)
905
Preserve the version (0) of write locked tables so that a impending
906
global read lock won't sneak in.
908
if (table->reginfo.lock_type < TL_WRITE_ALLOW_WRITE)
909
table->s->version= refresh_version;
913
VOID(pthread_mutex_unlock(&LOCK_open));
914
if (wait_for_refresh)
916
pthread_mutex_lock(&thd->mysys_var->mutex);
917
thd->mysys_var->current_mutex= 0;
918
thd->mysys_var->current_cond= 0;
919
thd_proc_info(thd, 0);
920
pthread_mutex_unlock(&thd->mysys_var->mutex);
927
Close all tables which match specified connection string or
928
if specified string is NULL, then any table with a connection string.
931
bool close_cached_connection_tables(THD *thd, bool if_wait_for_refresh,
932
LEX_STRING *connection, bool have_lock)
935
TABLE_LIST tmp, *tables= NULL;
937
DBUG_ENTER("close_cached_connections");
940
bzero(&tmp, sizeof(TABLE_LIST));
943
VOID(pthread_mutex_lock(&LOCK_open));
945
for (idx= 0; idx < table_def_cache.records; idx++)
947
TABLE_SHARE *share= (TABLE_SHARE *) hash_element(&table_def_cache, idx);
949
/* Ignore if table is not open or does not have a connect_string */
950
if (!share->connect_string.length || !share->ref_count)
953
/* Compare the connection string */
955
(connection->length > share->connect_string.length ||
956
(connection->length < share->connect_string.length &&
957
(share->connect_string.str[connection->length] != '/' &&
958
share->connect_string.str[connection->length] != '\\')) ||
959
strncasecmp(connection->str, share->connect_string.str,
960
connection->length)))
963
/* close_cached_tables() only uses these elements */
964
tmp.db= share->db.str;
965
tmp.table_name= share->table_name.str;
966
tmp.next_local= tables;
968
tables= (TABLE_LIST *) memdup_root(thd->mem_root, (char*)&tmp,
973
result= close_cached_tables(thd, tables, TRUE, FALSE, FALSE);
976
VOID(pthread_mutex_unlock(&LOCK_open));
978
if (if_wait_for_refresh)
980
pthread_mutex_lock(&thd->mysys_var->mutex);
981
thd->mysys_var->current_mutex= 0;
982
thd->mysys_var->current_cond= 0;
984
pthread_mutex_unlock(&thd->mysys_var->mutex);
992
Mark all temporary tables which were used by the current statement or
993
substatement as free for reuse, but only if the query_id can be cleared.
995
@param thd thread context
997
@remark For temp tables associated with a open SQL HANDLER the query_id
998
is not reset until the HANDLER is closed.
1001
static void mark_temp_tables_as_free_for_reuse(THD *thd)
1003
for (TABLE *table= thd->temporary_tables ; table ; table= table->next)
1005
if ((table->query_id == thd->query_id) && ! table->open_by_handler)
1008
table->file->ha_reset();
1015
Mark all tables in the list which were used by current substatement
1019
mark_used_tables_as_free_for_reuse()
1020
thd - thread context
1021
table - head of the list of tables
1024
Marks all tables in the list which were used by current substatement
1025
(they are marked by its query_id) as free for reuse.
1028
The reason we reset query_id is that it's not enough to just test
1029
if table->query_id != thd->query_id to know if a table is in use.
1032
SELECT f1_that_uses_t1() FROM t1;
1033
In f1_that_uses_t1() we will see one instance of t1 where query_id is
1034
set to query_id of original query.
1037
static void mark_used_tables_as_free_for_reuse(THD *thd, TABLE *table)
1039
for (; table ; table= table->next)
1041
if (table->query_id == thd->query_id)
1044
table->file->ha_reset();
1051
Auxiliary function to close all tables in the open_tables list.
1053
@param thd Thread context.
1055
@remark It should not ordinarily be called directly.
1058
static void close_open_tables(THD *thd)
1060
bool found_old_table= 0;
1062
safe_mutex_assert_not_owner(&LOCK_open);
1064
VOID(pthread_mutex_lock(&LOCK_open));
1066
DBUG_PRINT("info", ("thd->open_tables: 0x%lx", (long) thd->open_tables));
1068
while (thd->open_tables)
1069
found_old_table|= close_thread_table(thd, &thd->open_tables);
1070
thd->some_tables_deleted= 0;
1072
/* Free tables to hold down open files */
1073
while (open_cache.records > table_cache_size && unused_tables)
1074
VOID(hash_delete(&open_cache,(uchar*) unused_tables)); /* purecov: tested */
1076
if (found_old_table)
1078
/* Tell threads waiting for refresh that something has happened */
1079
broadcast_refresh();
1082
VOID(pthread_mutex_unlock(&LOCK_open));
1087
Close all tables used by the current substatement, or all tables
1088
used by this thread if we are on the upper level.
1091
close_thread_tables()
1095
Unlocks tables and frees derived tables.
1096
Put all normal tables used by thread in free list.
1098
It will only close/mark as free for reuse tables opened by this
1099
substatement, it will also check if we are closing tables after
1100
execution of complete query (i.e. we are on upper level) and will
1101
leave prelocked mode if needed.
1104
void close_thread_tables(THD *thd)
1107
DBUG_ENTER("close_thread_tables");
1110
We are assuming here that thd->derived_tables contains ONLY derived
1111
tables for this substatement. i.e. instead of approach which uses
1112
query_id matching for determining which of the derived tables belong
1113
to this substatement we rely on the ability of substatements to
1114
save/restore thd->derived_tables during their execution.
1116
TODO: Probably even better approach is to simply associate list of
1117
derived tables with (sub-)statement instead of thread and destroy
1118
them at the end of its execution.
1120
if (thd->derived_tables)
1124
Close all derived tables generated in queries like
1125
SELECT * FROM (SELECT * FROM t1)
1127
for (table= thd->derived_tables ; table ; table= next)
1130
free_tmp_table(thd, table);
1132
thd->derived_tables= 0;
1136
Mark all temporary tables used by this statement as free for reuse.
1138
mark_temp_tables_as_free_for_reuse(thd);
1140
Let us commit transaction for statement. Since in 5.0 we only have
1141
one statement transaction and don't allow several nested statement
1142
transactions this call will do nothing if we are inside of stored
1143
function or trigger (i.e. statement transaction is already active and
1144
does not belong to statement for which we do close_thread_tables()).
1145
TODO: This should be fixed in later releases.
1147
if (!(thd->state_flags & Open_tables_state::BACKUPS_AVAIL))
1149
thd->main_da.can_overwrite_status= TRUE;
1150
ha_autocommit_or_rollback(thd, thd->is_error());
1151
thd->main_da.can_overwrite_status= FALSE;
1152
thd->transaction.stmt.reset();
1155
if (thd->locked_tables)
1158
/* Ensure we are calling ha_reset() for all used tables */
1159
mark_used_tables_as_free_for_reuse(thd, thd->open_tables);
1162
We are under simple LOCK TABLES so should not do anything else.
1170
For RBR we flush the pending event just before we unlock all the
1171
tables. This means that we are at the end of a topmost
1172
statement, so we ensure that the STMT_END_F flag is set on the
1173
pending event. For statements that are *inside* stored
1174
functions, the pending event will not be flushed: that will be
1175
handled either before writing a query log event (inside
1176
binlog_query()) or when preparing a pending event.
1178
thd->binlog_flush_pending_rows_event(TRUE);
1179
mysql_unlock_tables(thd, thd->lock);
1183
Note that we need to hold LOCK_open while changing the
1184
open_tables list. Another thread may work on it.
1185
(See: remove_table_from_cache(), mysql_wait_completed_table())
1186
Closing a MERGE child before the parent would be fatal if the
1187
other thread tries to abort the MERGE lock in between.
1189
if (thd->open_tables)
1190
close_open_tables(thd);
1196
/* move one table to free list */
1198
bool close_thread_table(THD *thd, TABLE **table_ptr)
1200
bool found_old_table= 0;
1201
TABLE *table= *table_ptr;
1202
DBUG_ENTER("close_thread_table");
1203
DBUG_ASSERT(table->key_read == 0);
1204
DBUG_ASSERT(!table->file || table->file->inited == handler::NONE);
1205
DBUG_PRINT("tcache", ("table: '%s'.'%s' 0x%lx", table->s->db.str,
1206
table->s->table_name.str, (long) table));
1208
*table_ptr=table->next;
1210
if (table->needs_reopen_or_name_lock() ||
1211
thd->version != refresh_version || !table->db_stat)
1213
VOID(hash_delete(&open_cache,(uchar*) table));
1219
Open placeholders have TABLE::db_stat set to 0, so they should be
1220
handled by the first alternative.
1222
DBUG_ASSERT(!table->open_placeholder);
1224
/* Free memory and reset for next loop */
1225
table->file->ha_reset();
1229
table->next=unused_tables; /* Link in last */
1230
table->prev=unused_tables->prev;
1231
unused_tables->prev=table;
1232
table->prev->next=table;
1235
unused_tables=table->next=table->prev=table;
1237
DBUG_RETURN(found_old_table);
1241
/* close_temporary_tables' internal, 4 is due to uint4korr definition */
1242
static inline uint tmpkeyval(THD *thd, TABLE *table)
1244
return uint4korr(table->s->table_cache_key.str + table->s->table_cache_key.length - 4);
1249
Close all temporary tables created by 'CREATE TEMPORARY TABLE' for thread
1250
creates one DROP TEMPORARY TABLE binlog event for each pseudo-thread
1253
void close_temporary_tables(THD *thd)
1258
/* Assume thd->options has OPTION_QUOTE_SHOW_CREATE */
1259
bool was_quote_show= TRUE;
1261
if (!thd->temporary_tables)
1264
if (!mysql_bin_log.is_open() || thd->current_stmt_binlog_row_based)
1267
for (table= thd->temporary_tables; table; table= tmp_next)
1269
tmp_next= table->next;
1270
close_temporary(table, 1, 1);
1272
thd->temporary_tables= 0;
1276
/* Better add "if exists", in case a RESET MASTER has been done */
1277
const char stub[]= "DROP /*!40005 TEMPORARY */ TABLE IF EXISTS ";
1278
uint stub_len= sizeof(stub) - 1;
1280
String s_query= String(buf, sizeof(buf), system_charset_info);
1281
bool found_user_tables= FALSE;
1283
memcpy(buf, stub, stub_len);
1286
Insertion sort of temp tables by pseudo_thread_id to build ordered list
1287
of sublists of equal pseudo_thread_id
1290
for (prev_table= thd->temporary_tables, table= prev_table->next;
1292
prev_table= table, table= table->next)
1294
TABLE *prev_sorted /* same as for prev_table */, *sorted;
1295
if (is_user_table(table))
1297
if (!found_user_tables)
1298
found_user_tables= true;
1299
for (prev_sorted= NULL, sorted= thd->temporary_tables; sorted != table;
1300
prev_sorted= sorted, sorted= sorted->next)
1302
if (!is_user_table(sorted) ||
1303
tmpkeyval(thd, sorted) > tmpkeyval(thd, table))
1305
/* move into the sorted part of the list from the unsorted */
1306
prev_table->next= table->next;
1307
table->next= sorted;
1310
prev_sorted->next= table;
1314
thd->temporary_tables= table;
1323
/* We always quote db,table names though it is slight overkill */
1324
if (found_user_tables &&
1325
!(was_quote_show= test(thd->options & OPTION_QUOTE_SHOW_CREATE)))
1327
thd->options |= OPTION_QUOTE_SHOW_CREATE;
1330
/* scan sorted tmps to generate sequence of DROP */
1331
for (table= thd->temporary_tables; table; table= next)
1333
if (is_user_table(table))
1335
my_thread_id save_pseudo_thread_id= thd->variables.pseudo_thread_id;
1336
/* Set pseudo_thread_id to be that of the processed table */
1337
thd->variables.pseudo_thread_id= tmpkeyval(thd, table);
1339
Loop forward through all tables within the sublist of
1340
common pseudo_thread_id to create single DROP query.
1342
for (s_query.length(stub_len);
1343
table && is_user_table(table) &&
1344
tmpkeyval(thd, table) == thd->variables.pseudo_thread_id;
1348
We are going to add 4 ` around the db/table names and possible more
1349
due to special characters in the names
1351
append_identifier(thd, &s_query, table->s->db.str, strlen(table->s->db.str));
1352
s_query.append('.');
1353
append_identifier(thd, &s_query, table->s->table_name.str,
1354
strlen(table->s->table_name.str));
1355
s_query.append(',');
1357
close_temporary(table, 1, 1);
1360
CHARSET_INFO *cs_save= thd->variables.character_set_client;
1361
thd->variables.character_set_client= system_charset_info;
1362
Query_log_event qinfo(thd, s_query.ptr(),
1363
s_query.length() - 1 /* to remove trailing ',' */,
1365
thd->variables.character_set_client= cs_save;
1367
Imagine the thread had created a temp table, then was doing a
1368
SELECT, and the SELECT was killed. Then it's not clever to
1369
mark the statement above as "killed", because it's not really
1370
a statement updating data, and there are 99.99% chances it
1371
will succeed on slave. If a real update (one updating a
1372
persistent table) was killed on the master, then this real
1373
update will be logged with error_code=killed, rightfully
1374
causing the slave to stop.
1376
qinfo.error_code= 0;
1377
mysql_bin_log.write(&qinfo);
1378
thd->variables.pseudo_thread_id= save_pseudo_thread_id;
1383
close_temporary(table, 1, 1);
1386
if (!was_quote_show)
1387
thd->options&= ~OPTION_QUOTE_SHOW_CREATE; /* restore option */
1388
thd->temporary_tables=0;
1395
find_table_in_list()
1396
table Pointer to table list
1397
offset Offset to which list in table structure to use
1398
db_name Data base name
1399
table_name Table name
1402
This is called by find_table_in_local_list() and
1403
find_table_in_global_list().
1406
NULL Table not found
1407
# Pointer to found table.
1410
TABLE_LIST *find_table_in_list(TABLE_LIST *table,
1411
TABLE_LIST *TABLE_LIST::*link,
1412
const char *db_name,
1413
const char *table_name)
1415
for (; table; table= table->*link )
1417
if ((table->table == 0 || table->table->s->tmp_table == NO_TMP_TABLE) &&
1418
strcmp(table->db, db_name) == 0 &&
1419
strcmp(table->table_name, table_name) == 0)
1427
Test that table is unique (It's only exists once in the table list)
1432
table table which should be checked
1433
table_list list of tables
1434
check_alias whether to check tables' aliases
1436
NOTE: to exclude derived tables from check we use following mechanism:
1437
a) during derived table processing set THD::derived_tables_processing
1438
b) JOIN::prepare set SELECT::exclude_from_table_unique_test if
1439
THD::derived_tables_processing set. (we can't use JOIN::execute
1440
because for PS we perform only JOIN::prepare, but we can't set this
1441
flag in JOIN::prepare if we are not sure that we are in derived table
1442
processing loop, because multi-update call fix_fields() for some its
1443
items (which mean JOIN::prepare for subqueries) before unique_table
1444
call to detect which tables should be locked for write).
1445
c) unique_table skip all tables which belong to SELECT with
1446
SELECT::exclude_from_table_unique_test set.
1447
Also SELECT::exclude_from_table_unique_test used to exclude from check
1448
tables of main SELECT of multi-delete and multi-update
1450
We also skip tables with TABLE_LIST::prelocking_placeholder set,
1451
because we want to allow SELECTs from them, and their modification
1452
will rise the error anyway.
1454
TODO: when we will have table/view change detection we can do this check
1459
0 if table is unique
1462
TABLE_LIST* unique_table(THD *thd, TABLE_LIST *table, TABLE_LIST *table_list,
1466
const char *d_name, *t_name, *t_alias;
1467
DBUG_ENTER("unique_table");
1468
DBUG_PRINT("enter", ("table alias: %s", table->alias));
1471
If this function called for query which update table (INSERT/UPDATE/...)
1472
then we have in table->table pointer to TABLE object which we are
1473
updating even if it is VIEW so we need TABLE_LIST of this TABLE object
1474
to get right names (even if lower_case_table_names used).
1476
If this function called for CREATE command that we have not opened table
1477
(table->table equal to 0) and right names is in current TABLE_LIST
1482
/* temporary table is always unique */
1483
if (table->table && table->table->s->tmp_table != NO_TMP_TABLE)
1485
table= table->find_underlying_table(table->table);
1487
as far as we have table->table we have to find real TABLE_LIST of
1488
it in underlying tables
1493
t_name= table->table_name;
1494
t_alias= table->alias;
1496
DBUG_PRINT("info", ("real table: %s.%s", d_name, t_name));
1499
if (((! (res= find_table_in_global_list(table_list, d_name, t_name))) &&
1500
(! (res= mysql_lock_have_duplicate(thd, table, table_list)))) ||
1501
((!res->table || res->table != table->table) &&
1502
(!check_alias || !(lower_case_table_names ?
1503
my_strcasecmp(files_charset_info, t_alias, res->alias) :
1504
strcmp(t_alias, res->alias))) &&
1505
res->select_lex && !res->select_lex->exclude_from_table_unique_test))
1508
If we found entry of this table or table of SELECT which already
1509
processed in derived table or top select of multi-update/multi-delete
1510
(exclude_from_table_unique_test) or prelocking placeholder.
1512
table_list= res->next_global;
1514
("found same copy of table or table which we should skip"));
1521
Issue correct error message in case we found 2 duplicate tables which
1522
prevent some update operation
1525
update_non_unique_table_error()
1526
update table which we try to update
1527
operation name of update operation
1528
duplicate duplicate table which we found
1531
here we hide view underlying tables if we have them
1534
void update_non_unique_table_error(TABLE_LIST *update,
1535
const char *operation,
1536
TABLE_LIST *duplicate)
1538
my_error(ER_UPDATE_TABLE_USED, MYF(0), update->alias);
1542
TABLE *find_temporary_table(THD *thd, const char *db, const char *table_name)
1544
TABLE_LIST table_list;
1546
table_list.db= (char*) db;
1547
table_list.table_name= (char*) table_name;
1548
return find_temporary_table(thd, &table_list);
1552
TABLE *find_temporary_table(THD *thd, TABLE_LIST *table_list)
1554
char key[MAX_DBKEY_LENGTH];
1557
DBUG_ENTER("find_temporary_table");
1558
DBUG_PRINT("enter", ("table: '%s'.'%s'",
1559
table_list->db, table_list->table_name));
1561
key_length= create_table_def_key(thd, key, table_list, 1);
1562
for (table=thd->temporary_tables ; table ; table= table->next)
1564
if (table->s->table_cache_key.length == key_length &&
1565
!memcmp(table->s->table_cache_key.str, key, key_length))
1568
("Found table. server_id: %u pseudo_thread_id: %lu",
1569
(uint) thd->server_id,
1570
(ulong) thd->variables.pseudo_thread_id));
1574
DBUG_RETURN(0); // Not a temporary table
1579
Drop a temporary table.
1581
Try to locate the table in the list of thd->temporary_tables.
1582
If the table is found:
1583
- if the table is being used by some outer statement, fail.
1584
- if the table is in thd->locked_tables, unlock it and
1585
remove it from the list of locked tables. Currently only transactional
1586
temporary tables are present in the locked_tables list.
1587
- Close the temporary table, remove its .FRM
1588
- remove the table from the list of temporary tables
1590
This function is used to drop user temporary tables, as well as
1591
internal tables created in CREATE TEMPORARY TABLE ... SELECT
1592
or ALTER TABLE. Even though part of the work done by this function
1593
is redundant when the table is internal, as long as we
1594
link both internal and user temporary tables into the same
1595
thd->temporary_tables list, it's impossible to tell here whether
1596
we're dealing with an internal or a user temporary table.
1598
@retval 0 the table was found and dropped successfully.
1599
@retval 1 the table was not found in the list of temporary tables
1601
@retval -1 the table is in use by a outer query
1604
int drop_temporary_table(THD *thd, TABLE_LIST *table_list)
1607
DBUG_ENTER("drop_temporary_table");
1608
DBUG_PRINT("tmptable", ("closing table: '%s'.'%s'",
1609
table_list->db, table_list->table_name));
1611
if (!(table= find_temporary_table(thd, table_list)))
1614
/* Table might be in use by some outer statement. */
1615
if (table->query_id && table->query_id != thd->query_id)
1617
my_error(ER_CANT_REOPEN_TABLE, MYF(0), table->alias);
1622
If LOCK TABLES list is not empty and contains this table,
1623
unlock the table and remove the table from this list.
1625
mysql_lock_remove(thd, thd->locked_tables, table, FALSE);
1626
close_temporary_table(thd, table, 1, 1);
1631
unlink from thd->temporary tables and close temporary table
1634
void close_temporary_table(THD *thd, TABLE *table,
1635
bool free_share, bool delete_table)
1637
DBUG_ENTER("close_temporary_table");
1638
DBUG_PRINT("tmptable", ("closing table: '%s'.'%s' 0x%lx alias: '%s'",
1639
table->s->db.str, table->s->table_name.str,
1640
(long) table, table->alias));
1644
table->prev->next= table->next;
1645
if (table->prev->next)
1646
table->next->prev= table->prev;
1650
/* removing the item from the list */
1651
DBUG_ASSERT(table == thd->temporary_tables);
1653
slave must reset its temporary list pointer to zero to exclude
1654
passing non-zero value to end_slave via rli->save_temporary_tables
1655
when no temp tables opened, see an invariant below.
1657
thd->temporary_tables= table->next;
1658
if (thd->temporary_tables)
1659
table->next->prev= 0;
1661
if (thd->slave_thread)
1663
/* natural invariant of temporary_tables */
1664
DBUG_ASSERT(slave_open_temp_tables || !thd->temporary_tables);
1665
slave_open_temp_tables--;
1667
close_temporary(table, free_share, delete_table);
1673
Close and delete a temporary table
1676
This dosn't unlink table from thd->temporary
1677
If this is needed, use close_temporary_table()
1680
void close_temporary(TABLE *table, bool free_share, bool delete_table)
1682
handlerton *table_type= table->s->db_type();
1683
DBUG_ENTER("close_temporary");
1684
DBUG_PRINT("tmptable", ("closing table: '%s'.'%s'",
1685
table->s->db.str, table->s->table_name.str));
1687
free_io_cache(table);
1690
Check that temporary table has not been created with
1691
frm_only because it has then not been created in any storage engine
1694
rm_temporary_table(table_type, table->s->path.str,
1695
table->s->tmp_table == TMP_TABLE_FRM_FILE_ONLY);
1698
free_table_share(table->s);
1699
my_free((char*) table,MYF(0));
1706
Used by ALTER TABLE when the table is a temporary one. It changes something
1707
only if the ALTER contained a RENAME clause (otherwise, table_name is the old
1709
Prepares a table cache key, which is the concatenation of db, table_name and
1710
thd->slave_proxy_id, separated by '\0'.
1713
bool rename_temporary_table(THD* thd, TABLE *table, const char *db,
1714
const char *table_name)
1718
TABLE_SHARE *share= table->s;
1719
TABLE_LIST table_list;
1720
DBUG_ENTER("rename_temporary_table");
1722
if (!(key=(char*) alloc_root(&share->mem_root, MAX_DBKEY_LENGTH)))
1723
DBUG_RETURN(1); /* purecov: inspected */
1725
table_list.db= (char*) db;
1726
table_list.table_name= (char*) table_name;
1727
key_length= create_table_def_key(thd, key, &table_list, 1);
1728
share->set_table_cache_key(key, key_length);
1733
/* move table first in unused links */
1735
static void relink_unused(TABLE *table)
1737
if (table != unused_tables)
1739
table->prev->next=table->next; /* Remove from unused list */
1740
table->next->prev=table->prev;
1741
table->next=unused_tables; /* Link in unused tables */
1742
table->prev=unused_tables->prev;
1743
unused_tables->prev->next=table;
1744
unused_tables->prev=table;
1745
unused_tables=table;
1752
Remove all instances of table from thread's open list and
1755
@param thd Thread context
1756
@param find Table to remove
1757
@param unlock TRUE - free all locks on tables removed that are
1758
done with LOCK TABLES
1761
@note When unlock parameter is FALSE or current thread doesn't have
1762
any tables locked with LOCK TABLES, tables are assumed to be
1763
not locked (for example already unlocked).
1766
void unlink_open_table(THD *thd, TABLE *find, bool unlock)
1768
char key[MAX_DBKEY_LENGTH];
1769
uint key_length= find->s->table_cache_key.length;
1770
TABLE *list, **prev;
1771
DBUG_ENTER("unlink_open_table");
1773
safe_mutex_assert_owner(&LOCK_open);
1775
memcpy(key, find->s->table_cache_key.str, key_length);
1777
Note that we need to hold LOCK_open while changing the
1778
open_tables list. Another thread may work on it.
1779
(See: remove_table_from_cache(), mysql_wait_completed_table())
1780
Closing a MERGE child before the parent would be fatal if the
1781
other thread tries to abort the MERGE lock in between.
1783
for (prev= &thd->open_tables; *prev; )
1787
if (list->s->table_cache_key.length == key_length &&
1788
!memcmp(list->s->table_cache_key.str, key, key_length))
1790
if (unlock && thd->locked_tables)
1791
mysql_lock_remove(thd, thd->locked_tables, list, TRUE);
1793
/* Remove table from open_tables list. */
1796
VOID(hash_delete(&open_cache,(uchar*) list)); // Close table
1800
/* Step to next entry in open_tables list. */
1805
// Notify any 'refresh' threads
1806
broadcast_refresh();
1812
Auxiliary routine which closes and drops open table.
1814
@param thd Thread handle
1815
@param table TABLE object for table to be dropped
1816
@param db_name Name of database for this table
1817
@param table_name Name of this table
1819
@note This routine assumes that table to be closed is open only
1820
by calling thread so we needn't wait until other threads
1821
will close the table. Also unless called under implicit or
1822
explicit LOCK TABLES mode it assumes that table to be
1823
dropped is already unlocked. In the former case it will
1824
also remove lock on the table. But one should not rely on
1825
this behaviour as it may change in future.
1826
Currently, however, this function is never called for a
1827
table that was locked with LOCK TABLES.
1830
void drop_open_table(THD *thd, TABLE *table, const char *db_name,
1831
const char *table_name)
1833
if (table->s->tmp_table)
1834
close_temporary_table(thd, table, 1, 1);
1837
handlerton *table_type= table->s->db_type();
1838
VOID(pthread_mutex_lock(&LOCK_open));
1840
unlink_open_table() also tells threads waiting for refresh or close
1841
that something has happened.
1843
unlink_open_table(thd, table, FALSE);
1844
quick_rm_table(table_type, db_name, table_name, 0);
1845
VOID(pthread_mutex_unlock(&LOCK_open));
1851
Wait for condition but allow the user to send a kill to mysqld
1854
wait_for_condition()
1856
mutex mutex that is currently hold that is associated with condition
1857
Will be unlocked on return
1858
cond Condition to wait for
1861
void wait_for_condition(THD *thd, pthread_mutex_t *mutex, pthread_cond_t *cond)
1863
/* Wait until the current table is up to date */
1864
const char *proc_info;
1865
thd->mysys_var->current_mutex= mutex;
1866
thd->mysys_var->current_cond= cond;
1867
proc_info=thd->proc_info;
1868
thd_proc_info(thd, "Waiting for table");
1869
DBUG_ENTER("wait_for_condition");
1871
(void) pthread_cond_wait(cond, mutex);
1874
We must unlock mutex first to avoid deadlock becasue conditions are
1875
sent to this thread by doing locks in the following order:
1876
lock(mysys_var->mutex)
1877
lock(mysys_var->current_mutex)
1879
One by effect of this that one can only use wait_for_condition with
1880
condition variables that are guranteed to not disapper (freed) even if this
1884
pthread_mutex_unlock(mutex);
1885
pthread_mutex_lock(&thd->mysys_var->mutex);
1886
thd->mysys_var->current_mutex= 0;
1887
thd->mysys_var->current_cond= 0;
1888
thd_proc_info(thd, proc_info);
1889
pthread_mutex_unlock(&thd->mysys_var->mutex);
1895
Exclusively name-lock a table that is already write-locked by the
1898
@param thd current thread context
1899
@param tables table list containing one table to open.
1901
@return FALSE on success, TRUE otherwise.
1904
bool name_lock_locked_table(THD *thd, TABLE_LIST *tables)
1906
DBUG_ENTER("name_lock_locked_table");
1908
/* Under LOCK TABLES we must only accept write locked tables. */
1909
tables->table= find_locked_table(thd, tables->db, tables->table_name);
1912
my_error(ER_TABLE_NOT_LOCKED, MYF(0), tables->alias);
1913
else if (tables->table->reginfo.lock_type < TL_WRITE_LOW_PRIORITY)
1914
my_error(ER_TABLE_NOT_LOCKED_FOR_WRITE, MYF(0), tables->alias);
1918
Ensures that table is opened only by this thread and that no
1919
other statement will open this table.
1921
wait_while_table_is_used(thd, tables->table, HA_EXTRA_FORCE_REOPEN);
1930
Open table which is already name-locked by this thread.
1933
reopen_name_locked_table()
1935
table_list TABLE_LIST object for table to be open, TABLE_LIST::table
1936
member should point to TABLE object which was used for
1938
link_in TRUE - if TABLE object for table to be opened should be
1939
linked into THD::open_tables list.
1940
FALSE - placeholder used for name-locking is already in
1941
this list so we only need to preserve TABLE::next
1945
This function assumes that its caller already acquired LOCK_open mutex.
1952
bool reopen_name_locked_table(THD* thd, TABLE_LIST* table_list, bool link_in)
1954
TABLE *table= table_list->table;
1956
char *table_name= table_list->table_name;
1958
DBUG_ENTER("reopen_name_locked_table");
1960
safe_mutex_assert_owner(&LOCK_open);
1962
if (thd->killed || !table)
1967
if (open_unireg_entry(thd, table, table_list, table_name,
1968
table->s->table_cache_key.str,
1969
table->s->table_cache_key.length, thd->mem_root, 0))
1971
intern_close_table(table);
1973
If there was an error during opening of table (for example if it
1974
does not exist) '*table' object can be wiped out. To be able
1975
properly release name-lock in this case we should restore this
1976
object to its original state.
1984
We want to prevent other connections from opening this table until end
1985
of statement as it is likely that modifications of table's metadata are
1986
not yet finished (for example CREATE TRIGGER have to change .TRG file,
1987
or we might want to drop table if CREATE TABLE ... SELECT fails).
1988
This also allows us to assume that no other connection will sneak in
1989
before we will get table-level lock on this table.
1992
table->in_use = thd;
1997
table->next= thd->open_tables;
1998
thd->open_tables= table;
2003
TABLE object should be already in THD::open_tables list so we just
2004
need to set TABLE::next correctly.
2006
table->next= orig_table.next;
2009
table->tablenr=thd->current_tablenr++;
2010
table->used_fields=0;
2011
table->const_table=0;
2012
table->null_row= table->maybe_null= table->force_index= 0;
2013
table->status=STATUS_NO_RECORD;
2019
Create and insert into table cache placeholder for table
2020
which will prevent its opening (or creation) (a.k.a lock
2023
@param thd Thread context
2024
@param key Table cache key for name to be locked
2025
@param key_length Table cache key length
2027
@return Pointer to TABLE object used for name locking or 0 in
2031
TABLE *table_cache_insert_placeholder(THD *thd, const char *key,
2037
DBUG_ENTER("table_cache_insert_placeholder");
2039
safe_mutex_assert_owner(&LOCK_open);
2042
Create a table entry with the right key and with an old refresh version
2043
Note that we must use my_multi_malloc() here as this is freed by the
2046
if (!my_multi_malloc(MYF(MY_WME | MY_ZEROFILL),
2047
&table, sizeof(*table),
2048
&share, sizeof(*share),
2049
&key_buff, key_length,
2054
share->set_table_cache_key(key_buff, key, key_length);
2055
share->tmp_table= INTERNAL_TMP_TABLE; // for intern_close_table
2057
table->locked_by_name=1;
2059
if (my_hash_insert(&open_cache, (uchar*)table))
2061
my_free((uchar*) table, MYF(0));
2070
Obtain an exclusive name lock on the table if it is not cached
2073
@param thd Thread context
2074
@param db Name of database
2075
@param table_name Name of table
2076
@param[out] table Out parameter which is either:
2077
- set to NULL if table cache contains record for
2079
- set to point to the TABLE instance used for
2082
@note This function takes into account all records for table in table
2083
cache, even placeholders used for name-locking. This means that
2084
'table' parameter can be set to NULL for some situations when
2085
table does not really exist.
2087
@retval TRUE Error occured (OOM)
2088
@retval FALSE Success. 'table' parameter set according to above rules.
2091
bool lock_table_name_if_not_cached(THD *thd, const char *db,
2092
const char *table_name, TABLE **table)
2094
char key[MAX_DBKEY_LENGTH];
2096
DBUG_ENTER("lock_table_name_if_not_cached");
2098
key_length= (uint)(strmov(strmov(key, db) + 1, table_name) - key) + 1;
2099
VOID(pthread_mutex_lock(&LOCK_open));
2101
if (hash_search(&open_cache, (uchar *)key, key_length))
2103
VOID(pthread_mutex_unlock(&LOCK_open));
2104
DBUG_PRINT("info", ("Table is cached, name-lock is not obtained"));
2108
if (!(*table= table_cache_insert_placeholder(thd, key, key_length)))
2110
VOID(pthread_mutex_unlock(&LOCK_open));
2113
(*table)->open_placeholder= 1;
2114
(*table)->next= thd->open_tables;
2115
thd->open_tables= *table;
2116
VOID(pthread_mutex_unlock(&LOCK_open));
2122
Check that table exists in table definition cache, on disk
2123
or in some storage engine.
2125
@param thd Thread context
2126
@param table Table list element
2127
@param[out] exists Out parameter which is set to TRUE if table
2128
exists and to FALSE otherwise.
2130
@note This function assumes that caller owns LOCK_open mutex.
2131
It also assumes that the fact that there are no name-locks
2132
on the table was checked beforehand.
2134
@note If there is no .FRM file for the table but it exists in one
2135
of engines (e.g. it was created on another node of NDB cluster)
2136
this function will fetch and create proper .FRM file for it.
2138
@retval TRUE Some error occured
2139
@retval FALSE No error. 'exists' out parameter set accordingly.
2142
bool check_if_table_exists(THD *thd, TABLE_LIST *table, bool *exists)
2144
char path[FN_REFLEN];
2146
DBUG_ENTER("check_if_table_exists");
2148
safe_mutex_assert_owner(&LOCK_open);
2152
if (get_cached_table_share(table->db, table->table_name))
2155
build_table_filename(path, sizeof(path) - 1, table->db, table->table_name,
2158
if (!access(path, F_OK))
2161
/* .FRM file doesn't exist. Check if some engine can provide it. */
2163
rc= ha_create_table_from_engine(thd, table->db, table->table_name);
2167
/* Table does not exists in engines as well. */
2173
/* Table exists in some engine and .FRM for it was created. */
2178
my_printf_error(ER_UNKNOWN_ERROR, "Failed to open '%-.64s', error while "
2179
"unpacking from engine", MYF(0), table->table_name);
2191
table_list Open first table in list.
2192
refresh INOUT Pointer to memory that will be set to 1 if
2193
we need to close all tables and reopen them.
2194
If this is a NULL pointer, then the table is not
2195
put in the thread-open-list.
2196
flags Bitmap of flags to modify how open works:
2197
MYSQL_LOCK_IGNORE_FLUSH - Open table even if
2198
someone has done a flush or namelock on it.
2199
No version number checking is done.
2200
MYSQL_OPEN_TEMPORARY_ONLY - Open only temporary
2201
table not the base table or view.
2204
Uses a cache of open tables to find a table not in use.
2206
If table list element for the table to be opened has "create" flag
2207
set and table does not exist, this function will automatically insert
2208
a placeholder for exclusive name lock into the open tables cache and
2209
will return the TABLE instance that corresponds to this placeholder.
2212
NULL Open failed. If refresh is set then one should close
2213
all other tables and retry the open.
2214
# Success. Pointer to TABLE object for open table.
2218
TABLE *open_table(THD *thd, TABLE_LIST *table_list, MEM_ROOT *mem_root,
2219
bool *refresh, uint flags)
2221
register TABLE *table;
2222
char key[MAX_DBKEY_LENGTH];
2223
unsigned int key_length;
2224
char *alias= table_list->alias;
2225
HASH_SEARCH_STATE state;
2226
DBUG_ENTER("open_table");
2228
/* Parsing of partitioning information from .frm needs thd->lex set up. */
2229
DBUG_ASSERT(thd->lex->is_lex_started);
2231
/* find a unused table in the open table cache */
2235
/* an open table operation needs a lot of the stack space */
2236
if (check_stack_overrun(thd, STACK_MIN_SIZE_FOR_OPEN, (uchar *)&alias))
2242
key_length= (create_table_def_key(thd, key, table_list, 1) -
2243
TMP_TABLE_KEY_EXTRA);
2246
Unless requested otherwise, try to resolve this table in the list
2247
of temporary tables of this thread. In MySQL temporary tables
2248
are always thread-local and "shadow" possible base tables with the
2249
same name. This block implements the behaviour.
2250
TODO: move this block into a separate function.
2253
for (table= thd->temporary_tables; table ; table=table->next)
2255
if (table->s->table_cache_key.length == key_length +
2256
TMP_TABLE_KEY_EXTRA &&
2257
!memcmp(table->s->table_cache_key.str, key,
2258
key_length + TMP_TABLE_KEY_EXTRA))
2261
We're trying to use the same temporary table twice in a query.
2262
Right now we don't support this because a temporary table
2263
is always represented by only one TABLE object in THD, and
2264
it can not be cloned. Emit an error for an unsupported behaviour.
2266
if (table->query_id)
2269
("query_id: %lu server_id: %u pseudo_thread_id: %lu",
2270
(ulong) table->query_id, (uint) thd->server_id,
2271
(ulong) thd->variables.pseudo_thread_id));
2272
my_error(ER_CANT_REOPEN_TABLE, MYF(0), table->alias);
2275
table->query_id= thd->query_id;
2276
thd->thread_specific_used= TRUE;
2277
DBUG_PRINT("info",("Using temporary table"));
2283
if (flags & MYSQL_OPEN_TEMPORARY_ONLY)
2285
my_error(ER_NO_SUCH_TABLE, MYF(0), table_list->db, table_list->table_name);
2290
The table is not temporary - if we're in pre-locked or LOCK TABLES
2291
mode, let's try to find the requested table in the list of pre-opened
2292
and locked tables. If the table is not there, return an error - we can't
2293
open not pre-opened tables in pre-locked/LOCK TABLES mode.
2294
TODO: move this block into a separate function.
2296
if (thd->locked_tables)
2297
{ // Using table locks
2298
TABLE *best_table= 0;
2299
int best_distance= INT_MIN;
2300
bool check_if_used= false;
2301
for (table=thd->open_tables; table ; table=table->next)
2303
if (table->s->table_cache_key.length == key_length &&
2304
!memcmp(table->s->table_cache_key.str, key, key_length))
2306
if (check_if_used && table->query_id &&
2307
table->query_id != thd->query_id)
2310
If we are in stored function or trigger we should ensure that
2311
we won't change table that is already used by calling statement.
2312
So if we are opening table for writing, we should check that it
2313
is not already open by some calling stamement.
2315
my_error(ER_CANT_UPDATE_USED_TABLE_IN_SF_OR_TRG, MYF(0),
2316
table->s->table_name.str);
2320
When looking for a usable TABLE, ignore MERGE children, as they
2321
belong to their parent and cannot be used explicitly.
2323
if (!my_strcasecmp(system_charset_info, table->alias, alias) &&
2324
table->query_id != thd->query_id) /* skip tables already used */
2326
int distance= ((int) table->reginfo.lock_type -
2327
(int) table_list->lock_type);
2329
Find a table that either has the exact lock type requested,
2330
or has the best suitable lock. In case there is no locked
2331
table that has an equal or higher lock than requested,
2332
we us the closest matching lock to be able to produce an error
2333
message about wrong lock mode on the table. The best_table
2334
is changed if bd < 0 <= d or bd < d < 0 or 0 <= d < bd.
2336
distance < 0 - No suitable lock found
2337
distance > 0 - we have lock mode higher then we require
2338
distance == 0 - we have lock mode exactly which we need
2340
if ((best_distance < 0 && distance > best_distance) || (distance >= 0 && distance < best_distance))
2342
best_distance= distance;
2344
if (best_distance == 0 && !check_if_used)
2347
If we have found perfect match and we don't need to check that
2348
table is not used by one of calling statements (assuming that
2349
we are inside of function or trigger) we can finish iterating
2350
through open tables list.
2361
table->query_id= thd->query_id;
2362
DBUG_PRINT("info",("Using locked table"));
2366
No table in the locked tables list. In case of explicit LOCK TABLES
2367
this can happen if a user did not include the able into the list.
2368
In case of pre-locked mode locked tables list is generated automatically,
2369
so we may only end up here if the table did not exist when
2370
locked tables list was created.
2372
my_error(ER_TABLE_NOT_LOCKED, MYF(0), alias);
2377
Non pre-locked/LOCK TABLES mode, and the table is not temporary:
2378
this is the normal use case.
2380
- try to find the table in the table cache.
2381
- if one of the discovered TABLE instances is name-locked
2382
(table->s->version == 0) or some thread has started FLUSH TABLES
2383
(refresh_version > table->s->version), back off -- we have to wait
2384
until no one holds a name lock on the table.
2385
- if there is no such TABLE in the name cache, read the table definition
2386
and insert it into the cache.
2387
We perform all of the above under LOCK_open which currently protects
2388
the open cache (also known as table cache) and table definitions stored
2392
VOID(pthread_mutex_lock(&LOCK_open));
2395
If it's the first table from a list of tables used in a query,
2396
remember refresh_version (the version of open_cache state).
2397
If the version changes while we're opening the remaining tables,
2398
we will have to back off, close all the tables opened-so-far,
2399
and try to reopen them.
2400
Note: refresh_version is currently changed only during FLUSH TABLES.
2402
if (!thd->open_tables)
2403
thd->version=refresh_version;
2404
else if ((thd->version != refresh_version) &&
2405
! (flags & MYSQL_LOCK_IGNORE_FLUSH))
2407
/* Someone did a refresh while thread was opening tables */
2410
VOID(pthread_mutex_unlock(&LOCK_open));
2415
In order for the back off and re-start process to work properly,
2416
handler tables having old versions (due to FLUSH TABLES or pending
2417
name-lock) MUST be closed. This is specially important if a name-lock
2418
is pending for any table of the handler_tables list, otherwise a
2421
if (thd->handler_tables)
2422
mysql_ha_flush(thd);
2425
Actually try to find the table in the open_cache.
2426
The cache may contain several "TABLE" instances for the same
2427
physical table. The instances that are currently "in use" by
2428
some thread have their "in_use" member != NULL.
2429
There is no good reason for having more than one entry in the
2430
hash for the same physical table, except that we use this as
2431
an implicit "pending locks queue" - see
2432
wait_for_locked_table_names for details.
2434
for (table= (TABLE*) hash_first(&open_cache, (uchar*) key, key_length,
2436
table && table->in_use ;
2437
table= (TABLE*) hash_next(&open_cache, (uchar*) key, key_length,
2440
DBUG_PRINT("tcache", ("in_use table: '%s'.'%s' 0x%lx", table->s->db.str,
2441
table->s->table_name.str, (long) table));
2443
Here we flush tables marked for flush.
2444
Normally, table->s->version contains the value of
2445
refresh_version from the moment when this table was
2446
(re-)opened and added to the cache.
2447
If since then we did (or just started) FLUSH TABLES
2448
statement, refresh_version has been increased.
2449
For "name-locked" TABLE instances, table->s->version is set
2450
to 0 (see lock_table_name for details).
2451
In case there is a pending FLUSH TABLES or a name lock, we
2452
need to back off and re-start opening tables.
2453
If we do not back off now, we may dead lock in case of lock
2454
order mismatch with some other thread:
2455
c1: name lock t1; -- sort of exclusive lock
2456
c2: open t2; -- sort of shared lock
2457
c1: name lock t2; -- blocks
2458
c2: open t1; -- blocks
2460
if (table->needs_reopen_or_name_lock())
2463
("Found table '%s.%s' with different refresh version",
2464
table_list->db, table_list->table_name));
2466
if (flags & MYSQL_LOCK_IGNORE_FLUSH)
2468
/* Force close at once after usage */
2469
thd->version= table->s->version;
2473
/* Avoid self-deadlocks by detecting self-dependencies. */
2474
if (table->open_placeholder && table->in_use == thd)
2476
VOID(pthread_mutex_unlock(&LOCK_open));
2477
my_error(ER_UPDATE_TABLE_USED, MYF(0), table->s->table_name.str);
2482
Back off, part 1: mark the table as "unused" for the
2483
purpose of name-locking by setting table->db_stat to 0. Do
2484
that only for the tables in this thread that have an old
2485
table->s->version (this is an optimization (?)).
2486
table->db_stat == 0 signals wait_for_locked_table_names
2487
that the tables in question are not used any more. See
2488
table_is_used call for details.
2490
Notice that HANDLER tables were already taken care of by
2491
the earlier call to mysql_ha_flush() in this same critical
2494
close_old_data_files(thd,thd->open_tables,0,0);
2496
Back-off part 2: try to avoid "busy waiting" on the table:
2497
if the table is in use by some other thread, we suspend
2498
and wait till the operation is complete: when any
2499
operation that juggles with table->s->version completes,
2500
it broadcasts COND_refresh condition variable.
2501
If 'old' table we met is in use by current thread we return
2502
without waiting since in this situation it's this thread
2503
which is responsible for broadcasting on COND_refresh
2504
(and this was done already in close_old_data_files()).
2505
Good example of such situation is when we have statement
2506
that needs two instances of table and FLUSH TABLES comes
2507
after we open first instance but before we open second
2510
if (table->in_use != thd)
2512
/* wait_for_conditionwill unlock LOCK_open for us */
2513
wait_for_condition(thd, &LOCK_open, &COND_refresh);
2517
VOID(pthread_mutex_unlock(&LOCK_open));
2520
There is a refresh in progress for this table.
2521
Signal the caller that it has to try again.
2530
DBUG_PRINT("tcache", ("unused table: '%s'.'%s' 0x%lx", table->s->db.str,
2531
table->s->table_name.str, (long) table));
2532
/* Unlink the table from "unused_tables" list. */
2533
if (table == unused_tables)
2535
unused_tables=unused_tables->next; // Remove from link
2536
if (table == unused_tables)
2539
table->prev->next=table->next; /* Remove from unused list */
2540
table->next->prev=table->prev;
2545
/* Insert a new TABLE instance into the open cache */
2547
DBUG_PRINT("tcache", ("opening new table"));
2548
/* Free cache if too big */
2549
while (open_cache.records > table_cache_size && unused_tables)
2550
VOID(hash_delete(&open_cache,(uchar*) unused_tables)); /* purecov: tested */
2552
if (table_list->create)
2556
if (check_if_table_exists(thd, table_list, &exists))
2558
VOID(pthread_mutex_unlock(&LOCK_open));
2565
Table to be created, so we need to create placeholder in table-cache.
2567
if (!(table= table_cache_insert_placeholder(thd, key, key_length)))
2569
VOID(pthread_mutex_unlock(&LOCK_open));
2573
Link placeholder to the open tables list so it will be automatically
2574
removed once tables are closed. Also mark it so it won't be ignored
2575
by other trying to take name-lock.
2577
table->open_placeholder= 1;
2578
table->next= thd->open_tables;
2579
thd->open_tables= table;
2580
VOID(pthread_mutex_unlock(&LOCK_open));
2583
/* Table exists. Let us try to open it. */
2586
/* make a new table */
2587
if (!(table=(TABLE*) my_malloc(sizeof(*table),MYF(MY_WME))))
2589
VOID(pthread_mutex_unlock(&LOCK_open));
2593
error= open_unireg_entry(thd, table, table_list, alias, key, key_length,
2594
mem_root, (flags & OPEN_VIEW_NO_PARSE));
2595
/* Combine the follow two */
2598
my_free((uchar*)table, MYF(0));
2599
VOID(pthread_mutex_unlock(&LOCK_open));
2604
my_free((uchar*)table, MYF(0));
2605
VOID(pthread_mutex_unlock(&LOCK_open));
2606
DBUG_RETURN(0); // VIEW
2608
DBUG_PRINT("info", ("inserting table '%s'.'%s' 0x%lx into the cache",
2609
table->s->db.str, table->s->table_name.str,
2611
VOID(my_hash_insert(&open_cache,(uchar*) table));
2614
check_unused(); // Debugging call
2616
VOID(pthread_mutex_unlock(&LOCK_open));
2619
table->next=thd->open_tables; /* Link into simple list */
2620
thd->open_tables=table;
2622
table->reginfo.lock_type=TL_READ; /* Assume read */
2625
DBUG_ASSERT(table->s->ref_count > 0 || table->s->tmp_table != NO_TMP_TABLE);
2627
if (thd->lex->need_correct_ident())
2628
table->alias_name_used= my_strcasecmp(table_alias_charset,
2629
table->s->table_name.str, alias);
2630
/* Fix alias if table name changes */
2631
if (strcmp(table->alias, alias))
2633
uint length=(uint) strlen(alias)+1;
2634
table->alias= (char*) my_realloc((char*) table->alias, length,
2636
memcpy((char*) table->alias, alias, length);
2638
/* These variables are also set in reopen_table() */
2639
table->tablenr=thd->current_tablenr++;
2640
table->used_fields=0;
2641
table->const_table=0;
2642
table->null_row= table->maybe_null= table->force_index= 0;
2643
table->status=STATUS_NO_RECORD;
2644
table->insert_values= 0;
2645
table->fulltext_searched= 0;
2646
table->file->ft_handler= 0;
2647
/* Catch wrong handling of the auto_increment_field_not_null. */
2648
DBUG_ASSERT(!table->auto_increment_field_not_null);
2649
table->auto_increment_field_not_null= FALSE;
2650
if (table->timestamp_field)
2651
table->timestamp_field_type= table->timestamp_field->get_auto_set_type();
2652
table->pos_in_table_list= table_list;
2653
table->clear_column_bitmaps();
2654
DBUG_ASSERT(table->key_read == 0);
2659
TABLE *find_locked_table(THD *thd, const char *db,const char *table_name)
2661
char key[MAX_DBKEY_LENGTH];
2662
uint key_length=(uint) (strmov(strmov(key,db)+1,table_name)-key)+1;
2664
for (TABLE *table=thd->open_tables; table ; table=table->next)
2666
if (table->s->table_cache_key.length == key_length &&
2667
!memcmp(table->s->table_cache_key.str, key, key_length))
2675
Reopen an table because the definition has changed.
2682
The data file for the table is already closed and the share is released
2683
The table has a 'dummy' share that mainly contains database and table name.
2687
1 error. The old table object is not changed.
2690
bool reopen_table(TABLE *table)
2696
TABLE_LIST table_list;
2697
THD *thd= table->in_use;
2698
DBUG_ENTER("reopen_table");
2699
DBUG_PRINT("tcache", ("table: '%s'.'%s' 0x%lx", table->s->db.str,
2700
table->s->table_name.str, (long) table));
2702
DBUG_ASSERT(table->s->ref_count == 0);
2703
DBUG_ASSERT(!table->sort.io_cache);
2707
sql_print_error("Table %s had a open data handler in reopen_table",
2710
bzero((char*) &table_list, sizeof(TABLE_LIST));
2711
table_list.db= table->s->db.str;
2712
table_list.table_name= table->s->table_name.str;
2713
table_list.table= table;
2715
if (wait_for_locked_table_names(thd, &table_list))
2716
DBUG_RETURN(1); // Thread was killed
2718
if (open_unireg_entry(thd, &tmp, &table_list,
2720
table->s->table_cache_key.str,
2721
table->s->table_cache_key.length,
2725
/* This list copies variables set by open_table */
2726
tmp.tablenr= table->tablenr;
2727
tmp.used_fields= table->used_fields;
2728
tmp.const_table= table->const_table;
2729
tmp.null_row= table->null_row;
2730
tmp.maybe_null= table->maybe_null;
2731
tmp.status= table->status;
2733
tmp.s->table_map_id= table->s->table_map_id;
2737
tmp.reginfo.lock_type=table->reginfo.lock_type;
2739
/* Replace table in open list */
2740
tmp.next= table->next;
2741
tmp.prev= table->prev;
2744
VOID(closefrm(table, 1)); // close file, free everything
2747
table->default_column_bitmaps();
2748
table->file->change_table_ptr(table, table->s);
2750
DBUG_ASSERT(table->alias != 0);
2751
for (field=table->field ; *field ; field++)
2753
(*field)->table= (*field)->orig_table= table;
2754
(*field)->table_name= &table->alias;
2756
for (key=0 ; key < table->s->keys ; key++)
2758
for (part=0 ; part < table->key_info[key].usable_key_parts ; part++)
2759
table->key_info[key].key_part[part].field->table= table;
2762
Do not attach MERGE children here. The children might be reopened
2763
after the parent. Attach children after reopening all tables that
2764
require reopen. See for example reopen_tables().
2767
broadcast_refresh();
2776
Close all instances of a table open by this thread and replace
2777
them with exclusive name-locks.
2779
@param thd Thread context
2780
@param db Database name for the table to be closed
2781
@param table_name Name of the table to be closed
2783
@note This function assumes that if we are not under LOCK TABLES,
2784
then there is only one table open and locked. This means that
2785
the function probably has to be adjusted before it can be used
2786
anywhere outside ALTER TABLE.
2788
@note Must not use TABLE_SHARE::table_name/db of the table being closed,
2789
the strings are used in a loop even after the share may be freed.
2792
void close_data_files_and_morph_locks(THD *thd, const char *db,
2793
const char *table_name)
2796
DBUG_ENTER("close_data_files_and_morph_locks");
2798
safe_mutex_assert_owner(&LOCK_open);
2803
If we are not under LOCK TABLES we should have only one table
2804
open and locked so it makes sense to remove the lock at once.
2806
mysql_unlock_tables(thd, thd->lock);
2811
Note that open table list may contain a name-lock placeholder
2812
for target table name if we process ALTER TABLE ... RENAME.
2813
So loop below makes sense even if we are not under LOCK TABLES.
2815
for (table=thd->open_tables; table ; table=table->next)
2817
if (!strcmp(table->s->table_name.str, table_name) &&
2818
!strcmp(table->s->db.str, db))
2820
if (thd->locked_tables)
2822
mysql_lock_remove(thd, thd->locked_tables, table, TRUE);
2824
table->open_placeholder= 1;
2825
close_handle_and_leave_table_as_lock(table);
2833
Reopen all tables with closed data files.
2835
@param thd Thread context
2836
@param get_locks Should we get locks after reopening tables ?
2837
@param mark_share_as_old Mark share as old to protect from a impending
2840
@note Since this function can't properly handle prelocking and
2841
create placeholders it should be used in very special
2842
situations like FLUSH TABLES or ALTER TABLE. In general
2843
case one should just repeat open_tables()/lock_tables()
2844
combination when one needs tables to be reopened (for
2845
example see open_and_lock_tables()).
2847
@note One should have lock on LOCK_open when calling this.
2849
@return FALSE in case of success, TRUE - otherwise.
2852
bool reopen_tables(THD *thd, bool get_locks, bool mark_share_as_old)
2854
TABLE *table,*next,**prev;
2855
TABLE **tables,**tables_ptr; // For locks
2856
bool error=0, not_used;
2857
const uint flags= MYSQL_LOCK_NOTIFY_IF_NEED_REOPEN |
2858
MYSQL_LOCK_IGNORE_GLOBAL_READ_LOCK |
2859
MYSQL_LOCK_IGNORE_FLUSH;
2861
DBUG_ENTER("reopen_tables");
2863
if (!thd->open_tables)
2866
safe_mutex_assert_owner(&LOCK_open);
2870
The ptr is checked later
2871
Do not handle locks of MERGE children.
2874
for (table= thd->open_tables; table ; table=table->next)
2876
DBUG_PRINT("tcache", ("open tables to lock: %u", opens));
2877
tables= (TABLE**) my_alloca(sizeof(TABLE*)*opens);
2880
tables= &thd->open_tables;
2883
prev= &thd->open_tables;
2884
for (table=thd->open_tables; table ; table=next)
2886
uint db_stat=table->db_stat;
2888
if (!tables || (!db_stat && reopen_table(table)))
2890
my_error(ER_CANT_REOPEN_TABLE, MYF(0), table->alias);
2891
VOID(hash_delete(&open_cache,(uchar*) table));
2898
/* Do not handle locks of MERGE children. */
2899
if (get_locks && !db_stat)
2900
*tables_ptr++= table; // need new lock on this
2901
if (mark_share_as_old)
2903
table->s->version=0;
2904
table->open_placeholder= 0;
2909
DBUG_PRINT("tcache", ("open tables to lock: %u",
2910
(uint) (tables_ptr - tables)));
2911
if (tables != tables_ptr) // Should we get back old locks
2915
We should always get these locks. Anyway, we must not go into
2916
wait_for_tables() as it tries to acquire LOCK_open, which is
2919
thd->some_tables_deleted=0;
2920
if ((lock= mysql_lock_tables(thd, tables, (uint) (tables_ptr - tables),
2923
thd->locked_tables=mysql_lock_merge(thd->locked_tables,lock);
2928
This case should only happen if there is a bug in the reopen logic.
2929
Need to issue error message to have a reply for the application.
2930
Not exactly what happened though, but close enough.
2932
my_error(ER_LOCK_DEADLOCK, MYF(0));
2936
if (get_locks && tables)
2938
my_afree((uchar*) tables);
2940
broadcast_refresh();
2946
Close handlers for tables in list, but leave the TABLE structure
2947
intact so that we can re-open these quickly.
2949
@param thd Thread context
2950
@param table Head of the list of TABLE objects
2951
@param morph_locks TRUE - remove locks which we have on tables being closed
2952
but ensure that no DML or DDL will sneak in before
2953
we will re-open the table (i.e. temporarily morph
2954
our table-level locks into name-locks).
2956
@param send_refresh Should we awake waiters even if we didn't close any tables?
2959
static void close_old_data_files(THD *thd, TABLE *table, bool morph_locks,
2962
bool found= send_refresh;
2963
DBUG_ENTER("close_old_data_files");
2965
for (; table ; table=table->next)
2967
DBUG_PRINT("tcache", ("checking table: '%s'.'%s' 0x%lx",
2968
table->s->db.str, table->s->table_name.str,
2970
DBUG_PRINT("tcache", ("needs refresh: %d is open: %u",
2971
table->needs_reopen_or_name_lock(), table->db_stat));
2973
Reopen marked for flush.
2975
if (table->needs_reopen_or_name_lock())
2982
TABLE *ulcktbl= table;
2983
if (ulcktbl->lock_count)
2986
Wake up threads waiting for table-level lock on this table
2987
so they won't sneak in when we will temporarily remove our
2988
lock on it. This will also give them a chance to close their
2989
instances of this table.
2991
mysql_lock_abort(thd, ulcktbl, TRUE);
2992
mysql_lock_remove(thd, thd->locked_tables, ulcktbl, TRUE);
2993
ulcktbl->lock_count= 0;
2995
if ((ulcktbl != table) && ulcktbl->db_stat)
2998
Close the parent too. Note that parent can come later in
2999
the list of tables. It will then be noticed as closed and
3000
as a placeholder. When this happens, do not clear the
3001
placeholder flag. See the branch below ("***").
3003
ulcktbl->open_placeholder= 1;
3004
close_handle_and_leave_table_as_lock(ulcktbl);
3007
We want to protect the table from concurrent DDL operations
3008
(like RENAME TABLE) until we will re-open and re-lock it.
3010
table->open_placeholder= 1;
3012
close_handle_and_leave_table_as_lock(table);
3014
else if (table->open_placeholder && !morph_locks)
3017
We come here only in close-for-back-off scenario. So we have to
3018
"close" create placeholder here to avoid deadlocks (for example,
3019
in case of concurrent execution of CREATE TABLE t1 SELECT * FROM t2
3020
and RENAME TABLE t2 TO t1). In close-for-re-open scenario we will
3021
probably want to let it stay.
3023
Note "***": We must not enter this branch if the placeholder
3024
flag has been set because of a former close through a child.
3025
See above the comment that refers to this note.
3027
table->open_placeholder= 0;
3032
broadcast_refresh();
3038
Wait until all threads has closed the tables in the list
3039
We have also to wait if there is thread that has a lock on this table even
3040
if the table is closed
3043
bool table_is_used(TABLE *table, bool wait_for_name_lock)
3045
DBUG_ENTER("table_is_used");
3048
char *key= table->s->table_cache_key.str;
3049
uint key_length= table->s->table_cache_key.length;
3051
DBUG_PRINT("loop", ("table_name: %s", table->alias));
3052
HASH_SEARCH_STATE state;
3053
for (TABLE *search= (TABLE*) hash_first(&open_cache, (uchar*) key,
3054
key_length, &state);
3056
search= (TABLE*) hash_next(&open_cache, (uchar*) key,
3057
key_length, &state))
3059
DBUG_PRINT("info", ("share: 0x%lx "
3060
"open_placeholder: %d locked_by_name: %d "
3061
"db_stat: %u version: %lu",
3063
search->open_placeholder, search->locked_by_name,
3065
search->s->version));
3066
if (search->in_use == table->in_use)
3067
continue; // Name locked by this thread
3069
We can't use the table under any of the following conditions:
3070
- There is an name lock on it (Table is to be deleted or altered)
3071
- If we are in flush table and we didn't execute the flush
3072
- If the table engine is open and it's an old version
3073
(We must wait until all engines are shut down to use the table)
3075
if ( (search->locked_by_name && wait_for_name_lock) ||
3076
(search->is_name_opened() && search->needs_reopen_or_name_lock()))
3079
} while ((table=table->next));
3084
/* Wait until all used tables are refreshed */
3086
bool wait_for_tables(THD *thd)
3089
DBUG_ENTER("wait_for_tables");
3091
thd_proc_info(thd, "Waiting for tables");
3092
pthread_mutex_lock(&LOCK_open);
3093
while (!thd->killed)
3095
thd->some_tables_deleted=0;
3096
close_old_data_files(thd,thd->open_tables,0,dropping_tables != 0);
3097
mysql_ha_flush(thd);
3098
if (!table_is_used(thd->open_tables,1))
3100
(void) pthread_cond_wait(&COND_refresh,&LOCK_open);
3103
result= 1; // aborted
3106
/* Now we can open all tables without any interference */
3107
thd_proc_info(thd, "Reopen tables");
3108
thd->version= refresh_version;
3109
result=reopen_tables(thd,0,0);
3111
pthread_mutex_unlock(&LOCK_open);
3112
thd_proc_info(thd, 0);
3113
DBUG_RETURN(result);
3118
drop tables from locked list
3121
drop_locked_tables()
3124
table_name Table name
3127
This is only called on drop tables
3129
The TABLE object for the dropped table is unlocked but still kept around
3130
as a name lock, which means that the table will be available for other
3131
thread as soon as we call unlock_table_names().
3132
If there is multiple copies of the table locked, all copies except
3133
the first, which acts as a name lock, is removed.
3136
# If table existed, return table
3137
0 Table was not locked
3141
TABLE *drop_locked_tables(THD *thd,const char *db, const char *table_name)
3143
TABLE *table,*next,**prev, *found= 0;
3144
prev= &thd->open_tables;
3145
DBUG_ENTER("drop_locked_tables");
3148
Note that we need to hold LOCK_open while changing the
3149
open_tables list. Another thread may work on it.
3150
(See: remove_table_from_cache(), mysql_wait_completed_table())
3151
Closing a MERGE child before the parent would be fatal if the
3152
other thread tries to abort the MERGE lock in between.
3154
for (table= thd->open_tables; table ; table=next)
3157
if (!strcmp(table->s->table_name.str, table_name) &&
3158
!strcmp(table->s->db.str, db))
3160
mysql_lock_remove(thd, thd->locked_tables, table, TRUE);
3165
/* Close engine table, but keep object around as a name lock */
3169
table->file->close();
3174
/* We already have a name lock, remove copy */
3175
VOID(hash_delete(&open_cache,(uchar*) table));
3186
broadcast_refresh();
3187
if (thd->locked_tables && thd->locked_tables->table_count == 0)
3189
my_free((uchar*) thd->locked_tables,MYF(0));
3190
thd->locked_tables=0;
3197
If we have the table open, which only happens when a LOCK TABLE has been
3198
done on the table, change the lock type to a lock that will abort all
3199
other threads trying to get the lock.
3202
void abort_locked_tables(THD *thd,const char *db, const char *table_name)
3205
for (table= thd->open_tables; table ; table= table->next)
3207
if (!strcmp(table->s->table_name.str, table_name) &&
3208
!strcmp(table->s->db.str, db))
3210
/* If MERGE child, forward lock handling to parent. */
3211
mysql_lock_abort(thd, table, TRUE);
3219
Function to assign a new table map id to a table share.
3223
share - Pointer to table share structure
3227
We are intentionally not checking that share->mutex is locked
3228
since this function should only be called when opening a table
3229
share and before it is entered into the table_def_cache (meaning
3230
that it cannot be fetched by another thread, even accidentally).
3235
The LOCK_open mutex is locked
3239
share->table_map_id is given a value that with a high certainty is
3240
not used by any other table (the only case where a table id can be
3241
reused is on wrap-around, which means more than 4 billion table
3242
share opens have been executed while one table was open all the
3245
share->table_map_id is not ~0UL.
3247
void assign_new_table_id(TABLE_SHARE *share)
3249
static ulong last_table_id= ~0UL;
3251
DBUG_ENTER("assign_new_table_id");
3254
DBUG_ASSERT(share != NULL);
3255
safe_mutex_assert_owner(&LOCK_open);
3257
ulong tid= ++last_table_id; /* get next id */
3259
There is one reserved number that cannot be used. Remember to
3260
change this when 6-byte global table id's are introduced.
3262
if (unlikely(tid == ~0UL))
3263
tid= ++last_table_id;
3264
share->table_map_id= tid;
3265
DBUG_PRINT("info", ("table_id=%lu", tid));
3267
/* Post conditions */
3268
DBUG_ASSERT(share->table_map_id != ~0UL);
3274
Load a table definition from file and open unireg table
3279
entry Store open table definition here
3280
table_list TABLE_LIST with db, table_name & belong_to_view
3282
cache_key Key for share_cache
3283
cache_key_length length of cache_key
3284
mem_root temporary mem_root for parsing
3285
flags the OPEN_VIEW_NO_PARSE flag to be passed to
3286
openfrm()/open_new_frm()
3289
Extra argument for open is taken from thd->open_options
3290
One must have a lock on LOCK_open when calling this function
3297
static int open_unireg_entry(THD *thd, TABLE *entry, TABLE_LIST *table_list,
3299
char *cache_key, uint cache_key_length,
3300
MEM_ROOT *mem_root, uint flags)
3304
uint discover_retry_count= 0;
3305
DBUG_ENTER("open_unireg_entry");
3307
safe_mutex_assert_owner(&LOCK_open);
3309
if (!(share= get_table_share_with_create(thd, table_list, cache_key,
3312
table_list->i_s_requested_object,
3316
while ((error= open_table_from_share(thd, share, alias,
3317
(uint) (HA_OPEN_KEYFILE |
3321
(READ_KEYINFO | COMPUTE_TYPES |
3323
thd->open_options, entry, OTM_OPEN)))
3325
if (error == 7) // Table def changed
3327
share->version= 0; // Mark share as old
3328
if (discover_retry_count++) // Retry once
3333
Here we should wait until all threads has released the table.
3334
For now we do one retry. This may cause a deadlock if there
3335
is other threads waiting for other tables used by this thread.
3337
Proper fix would be to if the second retry failed:
3338
- Mark that table def changed
3339
- Return from open table
3340
- Close all tables used by this thread
3341
- Start waiting that the share is released
3342
- Retry by opening all tables again
3344
if (ha_create_table_from_engine(thd, table_list->db,
3345
table_list->table_name))
3349
To avoid deadlock, only wait for release if no one else is
3352
if (share->ref_count != 1)
3354
/* Free share and wait until it's released by all threads */
3355
release_table_share(share, RELEASE_WAIT_FOR_DROP);
3358
mysql_reset_errors(thd, 1); // Clear warnings
3359
thd->clear_error(); // Clear error message
3364
if (!entry->s || !entry->s->crashed)
3366
// Code below is for repairing a crashed file
3367
if ((error= lock_table_name(thd, table_list, TRUE)))
3371
if (wait_for_locked_table_names(thd, table_list))
3373
unlock_table_name(thd, table_list);
3377
pthread_mutex_unlock(&LOCK_open);
3378
thd->clear_error(); // Clear error message
3380
if (open_table_from_share(thd, share, alias,
3381
(uint) (HA_OPEN_KEYFILE | HA_OPEN_RNDFILE |
3384
READ_KEYINFO | COMPUTE_TYPES | EXTRA_RECORD,
3385
ha_open_options | HA_OPEN_FOR_REPAIR,
3386
entry, OTM_OPEN) || ! entry->file ||
3387
(entry->file->is_crashed() && entry->file->ha_check_and_repair(thd)))
3389
/* Give right error message */
3391
my_error(ER_NOT_KEYFILE, MYF(0), share->table_name.str, my_errno);
3392
sql_print_error("Couldn't repair table: %s.%s", share->db.str,
3393
share->table_name.str);
3399
thd->clear_error(); // Clear error message
3400
pthread_mutex_lock(&LOCK_open);
3401
unlock_table_name(thd, table_list);
3409
If we are here, there was no fatal error (but error may be still
3412
if (unlikely(entry->file->implicit_emptied))
3414
entry->file->implicit_emptied= 0;
3415
if (mysql_bin_log.is_open())
3418
uint query_buf_size= 20 + share->db.length + share->table_name.length +1;
3419
if ((query= (char*) my_malloc(query_buf_size,MYF(MY_WME))))
3421
/* this DELETE FROM is needed even with row-based binlogging */
3422
end = strxmov(strmov(query, "DELETE FROM `"),
3423
share->db.str,"`.`",share->table_name.str,"`", NullS);
3424
thd->binlog_query(THD::STMT_QUERY_TYPE,
3425
query, (ulong)(end-query), FALSE, FALSE);
3426
my_free(query, MYF(0));
3431
As replication is maybe going to be corrupted, we need to warn the
3432
DBA on top of warning the client (which will automatically be done
3433
because of MYF(MY_WME) in my_malloc() above).
3435
sql_print_error("When opening HEAP table, could not allocate memory "
3436
"to write 'DELETE FROM `%s`.`%s`' to the binary log",
3437
table_list->db, table_list->table_name);
3446
release_table_share(share, RELEASE_NORMAL);
3452
Open all tables in list
3456
thd - thread handler
3457
start - list of tables in/out
3458
counter - number of opened tables will be return using this parameter
3459
flags - bitmap of flags to modify how the tables will be open:
3460
MYSQL_LOCK_IGNORE_FLUSH - open table even if someone has
3461
done a flush or namelock on it.
3464
Unless we are already in prelocked mode, this function will also precache
3465
all SP/SFs explicitly or implicitly (via views and triggers) used by the
3466
query and add tables needed for their execution to table list. If resulting
3467
tables list will be non empty it will mark query as requiring precaching.
3468
Prelocked mode will be enabled for such query during lock_tables() call.
3470
If query for which we are opening tables is already marked as requiring
3471
prelocking it won't do such precaching and will simply reuse table list
3472
which is already built.
3479
int open_tables(THD *thd, TABLE_LIST **start, uint *counter, uint flags)
3481
TABLE_LIST *tables= NULL;
3484
MEM_ROOT new_frm_mem;
3485
/* Also used for indicating that prelocking is need */
3486
bool safe_to_ignore_table;
3488
DBUG_ENTER("open_tables");
3490
temporary mem_root for new .frm parsing.
3491
TODO: variables for size
3493
init_sql_alloc(&new_frm_mem, 8024, 8024);
3495
thd->current_tablenr= 0;
3498
thd_proc_info(thd, "Opening tables");
3501
For every table in the list of tables to open, try to find or open
3504
for (tables= *start; tables ;tables= tables->next_global)
3506
DBUG_PRINT("tcache", ("opening table: '%s'.'%s' item: 0x%lx",
3507
tables->db, tables->table_name, (long) tables));
3509
safe_to_ignore_table= FALSE;
3512
Ignore placeholders for derived tables. After derived tables
3513
processing, link to created temporary table will be put here.
3514
If this is derived table for view then we still want to process
3515
routines used by this view.
3517
if (tables->derived)
3522
If this TABLE_LIST object is a placeholder for an information_schema
3523
table, create a temporary table to represent the information_schema
3524
table in the query. Do not fill it yet - will be filled during
3527
if (tables->schema_table)
3529
if (!mysql_schema_table(thd, thd->lex, tables))
3536
Not a placeholder: must be a base table or a view, and the table is
3537
not opened yet. Try to open the table.
3541
tables->table= open_table(thd, tables, &new_frm_mem, &refresh, flags);
3544
DBUG_PRINT("tcache", ("referenced table: '%s'.'%s' 0x%lx",
3545
tables->db, tables->table_name,
3546
(long) tables->table));
3550
free_root(&new_frm_mem, MYF(MY_KEEP_PREALLOC));
3552
if (refresh) // Refresh in progress
3555
We have met name-locked or old version of table. Now we have
3556
to close all tables which are not up to date. We also have to
3557
throw away set of prelocked tables (and thus close tables from
3558
this set that were open by now) since it possible that one of
3559
tables which determined its content was changed.
3561
Instead of implementing complex/non-robust logic mentioned
3562
above we simply close and then reopen all tables.
3564
In order to prepare for recalculation of set of prelocked tables
3565
we pretend that we have finished calculation which we were doing
3568
close_tables_for_reopen(thd, start);
3572
if (safe_to_ignore_table)
3574
DBUG_PRINT("info", ("open_table: ignoring table '%s'.'%s'",
3575
tables->db, tables->alias));
3579
result= -1; // Fatal error
3582
if (tables->lock_type != TL_UNLOCK && ! thd->locked_tables)
3584
if (tables->lock_type == TL_WRITE_DEFAULT)
3585
tables->table->reginfo.lock_type= thd->update_lock_default;
3586
else if (tables->table->s->tmp_table == NO_TMP_TABLE)
3587
tables->table->reginfo.lock_type= tables->lock_type;
3591
thd_proc_info(thd, 0);
3592
free_root(&new_frm_mem, MYF(0)); // Free pre-alloced block
3594
if (result && tables)
3597
Some functions determine success as (tables->table != NULL).
3598
tables->table is in thd->open_tables. It won't go lost. If the
3599
error happens on a MERGE child, clear the parents TABLE reference.
3601
if (tables->parent_l)
3602
tables->parent_l->table= NULL;
3603
tables->table= NULL;
3605
DBUG_PRINT("tcache", ("returning: %d", result));
3606
DBUG_RETURN(result);
3611
Check that lock is ok for tables; Call start stmt if ok
3614
check_lock_and_start_stmt()
3616
table_list Table to check
3617
lock_type Lock used for table
3624
static bool check_lock_and_start_stmt(THD *thd, TABLE *table,
3625
thr_lock_type lock_type)
3628
DBUG_ENTER("check_lock_and_start_stmt");
3630
if ((int) lock_type >= (int) TL_WRITE_ALLOW_READ &&
3631
(int) table->reginfo.lock_type < (int) TL_WRITE_ALLOW_READ)
3633
my_error(ER_TABLE_NOT_LOCKED_FOR_WRITE, MYF(0),table->alias);
3636
if ((error=table->file->start_stmt(thd, lock_type)))
3638
table->file->print_error(error,MYF(0));
3646
@brief Open and lock one table
3648
@param[in] thd thread handle
3649
@param[in] table_l table to open is first table in this list
3650
@param[in] lock_type lock to use for table
3653
@retval != NULL OK, opened table returned
3657
If ok, the following are also set:
3658
table_list->lock_type lock_type
3659
table_list->table table
3662
If table_l is a list, not a single table, the list is temporarily
3666
This function is meant as a replacement for open_ltable() when
3667
MERGE tables can be opened. open_ltable() cannot open MERGE tables.
3669
There may be more differences between open_n_lock_single_table() and
3670
open_ltable(). One known difference is that open_ltable() does
3671
neither call decide_logging_format() nor handle some other logging
3672
and locking issues because it does not call lock_tables().
3675
TABLE *open_n_lock_single_table(THD *thd, TABLE_LIST *table_l,
3676
thr_lock_type lock_type)
3678
TABLE_LIST *save_next_global;
3679
DBUG_ENTER("open_n_lock_single_table");
3681
/* Remember old 'next' pointer. */
3682
save_next_global= table_l->next_global;
3684
table_l->next_global= NULL;
3686
/* Set requested lock type. */
3687
table_l->lock_type= lock_type;
3688
/* Allow to open real tables only. */
3689
table_l->required_type= FRMTYPE_TABLE;
3691
/* Open the table. */
3692
if (simple_open_n_lock_tables(thd, table_l))
3693
table_l->table= NULL; /* Just to be sure. */
3696
table_l->next_global= save_next_global;
3698
DBUG_RETURN(table_l->table);
3703
Open and lock one table
3708
table_list Table to open is first table in this list
3709
lock_type Lock to use for open
3710
lock_flags Flags passed to mysql_lock_table
3713
This function don't do anything like SP/SF/views/triggers analysis done
3714
in open_tables(). It is intended for opening of only one concrete table.
3715
And used only in special contexts.
3721
If ok, the following are also set:
3722
table_list->lock_type lock_type
3723
table_list->table table
3726
TABLE *open_ltable(THD *thd, TABLE_LIST *table_list, thr_lock_type lock_type,
3731
DBUG_ENTER("open_ltable");
3733
thd_proc_info(thd, "Opening table");
3734
thd->current_tablenr= 0;
3735
/* open_ltable can be used only for BASIC TABLEs */
3736
table_list->required_type= FRMTYPE_TABLE;
3737
while (!(table= open_table(thd, table_list, thd->mem_root, &refresh, 0)) &&
3743
table_list->lock_type= lock_type;
3744
table_list->table= table;
3745
if (thd->locked_tables)
3747
if (check_lock_and_start_stmt(thd, table, lock_type))
3752
DBUG_ASSERT(thd->lock == 0); // You must lock everything at once
3753
if ((table->reginfo.lock_type= lock_type) != TL_UNLOCK)
3754
if (! (thd->lock= mysql_lock_tables(thd, &table_list->table, 1,
3755
lock_flags, &refresh)))
3760
thd_proc_info(thd, 0);
3766
Open all tables in list, locks them and optionally process derived tables.
3769
open_and_lock_tables_derived()
3770
thd - thread handler
3771
tables - list of tables for open&locking
3772
derived - if to handle derived tables
3779
The lock will automaticaly be freed by close_thread_tables()
3782
There are two convenience functions:
3783
- simple_open_n_lock_tables(thd, tables) without derived handling
3784
- open_and_lock_tables(thd, tables) with derived handling
3785
Both inline functions call open_and_lock_tables_derived() with
3786
the third argument set appropriately.
3789
int open_and_lock_tables_derived(THD *thd, TABLE_LIST *tables, bool derived)
3793
DBUG_ENTER("open_and_lock_tables_derived");
3794
DBUG_PRINT("enter", ("derived handling: %d", derived));
3798
if (open_tables(thd, &tables, &counter, 0))
3801
DBUG_EXECUTE_IF("sleep_open_and_lock_after_open", {
3802
const char *old_proc_info= thd->proc_info;
3803
thd->proc_info= "DBUG sleep";
3805
thd->proc_info= old_proc_info;});
3807
if (!lock_tables(thd, tables, counter, &need_reopen))
3811
close_tables_for_reopen(thd, &tables);
3814
(mysql_handle_derived(thd->lex, &mysql_derived_prepare) ||
3815
(thd->fill_derived_tables() &&
3816
mysql_handle_derived(thd->lex, &mysql_derived_filling))))
3817
DBUG_RETURN(TRUE); /* purecov: inspected */
3823
Open all tables in list and process derived tables
3826
open_normal_and_derived_tables
3827
thd - thread handler
3828
tables - list of tables for open
3829
flags - bitmap of flags to modify how the tables will be open:
3830
MYSQL_LOCK_IGNORE_FLUSH - open table even if someone has
3831
done a flush or namelock on it.
3838
This is to be used on prepare stage when you don't read any
3839
data from the tables.
3842
bool open_normal_and_derived_tables(THD *thd, TABLE_LIST *tables, uint flags)
3845
DBUG_ENTER("open_normal_and_derived_tables");
3846
DBUG_ASSERT(!thd->fill_derived_tables());
3847
if (open_tables(thd, &tables, &counter, flags) ||
3848
mysql_handle_derived(thd->lex, &mysql_derived_prepare))
3849
DBUG_RETURN(TRUE); /* purecov: inspected */
3855
Decide on logging format to use for the statement.
3857
Compute the capabilities vector for the involved storage engines
3858
and mask out the flags for the binary log. Right now, the binlog
3859
flags only include the capabilities of the storage engines, so this
3862
We now have three alternatives that prevent the statement from
3865
1. If there are no capabilities left (all flags are clear) it is
3866
not possible to log the statement at all, so we roll back the
3867
statement and report an error.
3869
2. Statement mode is set, but the capabilities indicate that
3870
statement format is not possible.
3872
3. Row mode is set, but the capabilities indicate that row
3873
format is not possible.
3875
4. Statement is unsafe, but the capabilities indicate that row
3876
format is not possible.
3878
If we are in MIXED mode, we then decide what logging format to use:
3880
1. If the statement is unsafe, row-based logging is used.
3882
2. If statement-based logging is not possible, row-based logging is
3885
3. Otherwise, statement-based logging is used.
3887
@param thd Client thread
3888
@param tables Tables involved in the query
3891
int decide_logging_format(THD *thd, TABLE_LIST *tables)
3893
if (mysql_bin_log.is_open() && (thd->options & OPTION_BIN_LOG))
3895
handler::Table_flags flags_some_set= handler::Table_flags();
3896
handler::Table_flags flags_all_set= ~handler::Table_flags();
3897
my_bool multi_engine= FALSE;
3898
void* prev_ht= NULL;
3899
for (TABLE_LIST *table= tables; table; table= table->next_global)
3901
if (!table->placeholder() && table->lock_type >= TL_WRITE_ALLOW_WRITE)
3903
ulonglong const flags= table->table->file->ha_table_flags();
3904
DBUG_PRINT("info", ("table: %s; ha_table_flags: %s%s",
3906
FLAGSTR(flags, HA_BINLOG_STMT_CAPABLE),
3907
FLAGSTR(flags, HA_BINLOG_ROW_CAPABLE)));
3908
if (prev_ht && prev_ht != table->table->file->ht)
3910
prev_ht= table->table->file->ht;
3911
flags_all_set &= flags;
3912
flags_some_set |= flags;
3916
DBUG_PRINT("info", ("flags_all_set: %s%s",
3917
FLAGSTR(flags_all_set, HA_BINLOG_STMT_CAPABLE),
3918
FLAGSTR(flags_all_set, HA_BINLOG_ROW_CAPABLE)));
3919
DBUG_PRINT("info", ("flags_some_set: %s%s",
3920
FLAGSTR(flags_some_set, HA_BINLOG_STMT_CAPABLE),
3921
FLAGSTR(flags_some_set, HA_BINLOG_ROW_CAPABLE)));
3922
DBUG_PRINT("info", ("thd->variables.binlog_format: %ld",
3923
thd->variables.binlog_format));
3924
DBUG_PRINT("info", ("multi_engine: %s",
3925
multi_engine ? "TRUE" : "FALSE"));
3928
if (flags_all_set == 0)
3930
my_error((error= ER_BINLOG_LOGGING_IMPOSSIBLE), MYF(0),
3931
"Statement cannot be logged to the binary log in"
3932
" row-based nor statement-based format");
3934
else if (thd->variables.binlog_format == BINLOG_FORMAT_STMT &&
3935
(flags_all_set & HA_BINLOG_STMT_CAPABLE) == 0)
3937
my_error((error= ER_BINLOG_LOGGING_IMPOSSIBLE), MYF(0),
3938
"Statement-based format required for this statement,"
3939
" but not allowed by this combination of engines");
3941
else if ((thd->variables.binlog_format == BINLOG_FORMAT_ROW ||
3942
thd->lex->is_stmt_unsafe()) &&
3943
(flags_all_set & HA_BINLOG_ROW_CAPABLE) == 0)
3945
my_error((error= ER_BINLOG_LOGGING_IMPOSSIBLE), MYF(0),
3946
"Row-based format required for this statement,"
3947
" but not allowed by this combination of engines");
3951
If more than one engine is involved in the statement and at
3952
least one is doing it's own logging (is *self-logging*), the
3953
statement cannot be logged atomically, so we generate an error
3954
rather than allowing the binlog to become corrupt.
3957
(flags_some_set & HA_HAS_OWN_BINLOGGING))
3959
error= ER_BINLOG_LOGGING_IMPOSSIBLE;
3960
my_error(error, MYF(0),
3961
"Statement cannot be written atomically since more"
3962
" than one engine involved and at least one engine"
3963
" is self-logging");
3966
DBUG_PRINT("info", ("error: %d", error));
3972
We switch to row-based format if we are in mixed mode and one of
3973
the following are true:
3975
1. If the statement is unsafe
3976
2. If statement format cannot be used
3978
Observe that point to cannot be decided before the tables
3979
involved in a statement has been checked, i.e., we cannot put
3980
this code in reset_current_stmt_binlog_row_based(), it has to be
3983
if (thd->lex->is_stmt_unsafe() ||
3984
(flags_all_set & HA_BINLOG_STMT_CAPABLE) == 0)
3986
thd->set_current_stmt_binlog_row_based_if_mixed();
3994
Lock all tables in list
3999
tables Tables to lock
4000
count Number of opened tables
4001
need_reopen Out parameter which if TRUE indicates that some
4002
tables were dropped or altered during this call
4003
and therefore invoker should reopen tables and
4004
try to lock them once again (in this case
4005
lock_tables() will also return error).
4008
You can't call lock_tables twice, as this would break the dead-lock-free
4009
handling thr_lock gives us. You most always get all needed locks at
4012
If query for which we are calling this function marked as requring
4013
prelocking, this function will do implicit LOCK TABLES and change
4014
thd::prelocked_mode accordingly.
4021
int lock_tables(THD *thd, TABLE_LIST *tables, uint count, bool *need_reopen)
4025
DBUG_ENTER("lock_tables");
4027
We can't meet statement requiring prelocking if we already
4030
*need_reopen= FALSE;
4033
DBUG_RETURN(decide_logging_format(thd, tables));
4035
if (!thd->locked_tables)
4037
DBUG_ASSERT(thd->lock == 0); // You must lock everything at once
4038
TABLE **start,**ptr;
4039
uint lock_flag= MYSQL_LOCK_NOTIFY_IF_NEED_REOPEN;
4041
if (!(ptr=start=(TABLE**) thd->alloc(sizeof(TABLE*)*count)))
4043
for (table= tables; table; table= table->next_global)
4045
if (!table->placeholder())
4046
*(ptr++)= table->table;
4049
if (!(thd->lock= mysql_lock_tables(thd, start, (uint) (ptr - start),
4050
lock_flag, need_reopen)))
4057
TABLE_LIST *first_not_own= thd->lex->first_not_own_table();
4059
When open_and_lock_tables() is called for a single table out of
4060
a table list, the 'next_global' chain is temporarily broken. We
4061
may not find 'first_not_own' before the end of the "list".
4062
Look for example at those places where open_n_lock_single_table()
4063
is called. That function implements the temporary breaking of
4064
a table list for opening a single table.
4067
table && table != first_not_own;
4068
table= table->next_global)
4070
if (!table->placeholder() &&
4071
check_lock_and_start_stmt(thd, table->table, table->lock_type))
4078
DBUG_RETURN(decide_logging_format(thd, tables));
4083
Prepare statement for reopening of tables and recalculation of set of
4087
close_tables_for_reopen()
4088
thd in Thread context
4089
tables in/out List of tables which we were trying to open and lock
4093
void close_tables_for_reopen(THD *thd, TABLE_LIST **tables)
4096
If table list consists only from tables from prelocking set, table list
4097
for new attempt should be empty, so we have to update list's root pointer.
4099
if (thd->lex->first_not_own_table() == *tables)
4101
thd->lex->chop_off_not_own_tables();
4102
for (TABLE_LIST *tmp= *tables; tmp; tmp= tmp->next_global)
4104
close_thread_tables(thd);
4109
Open a single table without table caching and don't set it in open_list
4112
open_temporary_table()
4114
path Path (without .frm)
4116
table_name Table name
4117
link_in_list 1 if table should be linked into thd->temporary_tables
4120
Used by alter_table to open a temporary table and when creating
4121
a temporary table with CREATE TEMPORARY ...
4128
TABLE *open_temporary_table(THD *thd, const char *path, const char *db,
4129
const char *table_name, bool link_in_list,
4130
open_table_mode open_mode)
4134
char cache_key[MAX_DBKEY_LENGTH], *saved_cache_key, *tmp_path;
4136
TABLE_LIST table_list;
4137
DBUG_ENTER("open_temporary_table");
4139
("table: '%s'.'%s' path: '%s' server_id: %u "
4140
"pseudo_thread_id: %lu",
4141
db, table_name, path,
4142
(uint) thd->server_id, (ulong) thd->variables.pseudo_thread_id));
4144
table_list.db= (char*) db;
4145
table_list.table_name= (char*) table_name;
4146
/* Create the cache_key for temporary tables */
4147
key_length= create_table_def_key(thd, cache_key, &table_list, 1);
4149
if (!(tmp_table= (TABLE*) my_malloc(sizeof(*tmp_table) + sizeof(*share) +
4150
strlen(path)+1 + key_length,
4152
DBUG_RETURN(0); /* purecov: inspected */
4154
share= (TABLE_SHARE*) (tmp_table+1);
4155
tmp_path= (char*) (share+1);
4156
saved_cache_key= strmov(tmp_path, path)+1;
4157
memcpy(saved_cache_key, cache_key, key_length);
4159
init_tmp_table_share(thd, share, saved_cache_key, key_length,
4160
strend(saved_cache_key)+1, tmp_path);
4162
if (open_table_def(thd, share, 0) ||
4163
open_table_from_share(thd, share, table_name,
4164
(open_mode == OTM_ALTER) ? 0 :
4165
(uint) (HA_OPEN_KEYFILE | HA_OPEN_RNDFILE |
4167
(open_mode == OTM_ALTER) ?
4168
(READ_KEYINFO | COMPUTE_TYPES | EXTRA_RECORD |
4170
: (READ_KEYINFO | COMPUTE_TYPES | EXTRA_RECORD),
4172
tmp_table, open_mode))
4174
/* No need to lock share->mutex as this is not needed for tmp tables */
4175
free_table_share(share);
4176
my_free((char*) tmp_table,MYF(0));
4180
tmp_table->reginfo.lock_type= TL_WRITE; // Simulate locked
4181
if (open_mode == OTM_ALTER)
4184
Temporary table has been created with frm_only
4185
and has not been created in any storage engine
4187
share->tmp_table= TMP_TABLE_FRM_FILE_ONLY;
4190
share->tmp_table= (tmp_table->file->has_transactions() ?
4191
TRANSACTIONAL_TMP_TABLE : NON_TRANSACTIONAL_TMP_TABLE);
4195
/* growing temp list at the head */
4196
tmp_table->next= thd->temporary_tables;
4197
if (tmp_table->next)
4198
tmp_table->next->prev= tmp_table;
4199
thd->temporary_tables= tmp_table;
4200
thd->temporary_tables->prev= 0;
4201
if (thd->slave_thread)
4202
slave_open_temp_tables++;
4204
tmp_table->pos_in_table_list= 0;
4205
DBUG_PRINT("tmptable", ("opened table: '%s'.'%s' 0x%lx", tmp_table->s->db.str,
4206
tmp_table->s->table_name.str, (long) tmp_table));
4207
DBUG_RETURN(tmp_table);
4211
bool rm_temporary_table(handlerton *base, char *path, bool frm_only)
4216
DBUG_ENTER("rm_temporary_table");
4218
strmov(ext= strend(path), reg_ext);
4219
if (my_delete(path,MYF(0)))
4220
error=1; /* purecov: inspected */
4221
*ext= 0; // remove extension
4222
file= get_new_handler((TABLE_SHARE*) 0, current_thd->mem_root, base);
4223
if (!frm_only && file && file->ha_delete_table(path))
4226
sql_print_warning("Could not remove temporary table: '%s', error: %d",
4234
/*****************************************************************************
4235
* The following find_field_in_XXX procedures implement the core of the
4236
* name resolution functionality. The entry point to resolve a column name in a
4237
* list of tables is 'find_field_in_tables'. It calls 'find_field_in_table_ref'
4238
* for each table reference. In turn, depending on the type of table reference,
4239
* 'find_field_in_table_ref' calls one of the 'find_field_in_XXX' procedures
4240
* below specific for the type of table reference.
4241
******************************************************************************/
4243
/* Special Field pointers as return values of find_field_in_XXX functions. */
4244
Field *not_found_field= (Field*) 0x1;
4245
Field *view_ref_found= (Field*) 0x2;
4247
#define WRONG_GRANT (Field*) -1
4249
static void update_field_dependencies(THD *thd, Field *field, TABLE *table)
4251
DBUG_ENTER("update_field_dependencies");
4252
if (thd->mark_used_columns != MARK_COLUMNS_NONE)
4254
MY_BITMAP *current_bitmap, *other_bitmap;
4257
We always want to register the used keys, as the column bitmap may have
4258
been set for all fields (for example for view).
4261
table->covering_keys.intersect(field->part_of_key);
4262
table->merge_keys.merge(field->part_of_key);
4264
if (thd->mark_used_columns == MARK_COLUMNS_READ)
4266
current_bitmap= table->read_set;
4267
other_bitmap= table->write_set;
4271
current_bitmap= table->write_set;
4272
other_bitmap= table->read_set;
4275
if (bitmap_fast_test_and_set(current_bitmap, field->field_index))
4277
if (thd->mark_used_columns == MARK_COLUMNS_WRITE)
4279
DBUG_PRINT("warning", ("Found duplicated field"));
4280
thd->dup_field= field;
4284
DBUG_PRINT("note", ("Field found before"));
4288
if (table->get_fields_in_item_tree)
4289
field->flags|= GET_FIXED_FIELDS_FLAG;
4290
table->used_fields++;
4292
else if (table->get_fields_in_item_tree)
4293
field->flags|= GET_FIXED_FIELDS_FLAG;
4299
Find a field by name in a view that uses merge algorithm.
4302
find_field_in_view()
4304
table_list view to search for 'name'
4306
length length of name
4307
item_name name of item if it will be created (VIEW)
4308
ref expression substituted in VIEW should be passed
4309
using this reference (return view_ref_found)
4310
register_tree_change TRUE if ref is not stack variable and we
4311
need register changes in item tree
4314
0 field is not found
4315
view_ref_found found value in VIEW (real result is in *ref)
4316
# pointer to field - only for schema table fields
4320
find_field_in_view(THD *thd, TABLE_LIST *table_list,
4321
const char *name, uint length,
4322
const char *item_name, Item **ref,
4323
bool register_tree_change)
4325
DBUG_ENTER("find_field_in_view");
4327
("view: '%s', field name: '%s', item name: '%s', ref 0x%lx",
4328
table_list->alias, name, item_name, (ulong) ref));
4329
Field_iterator_view field_it;
4330
field_it.set(table_list);
4332
DBUG_ASSERT(table_list->schema_table_reformed ||
4333
(ref != 0 && (0) != 0));
4334
for (; !field_it.end_of_fields(); field_it.next())
4336
if (!my_strcasecmp(system_charset_info, field_it.name(), name))
4339
create_item() may, or may not create a new Item, depending on
4340
the column reference. See create_view_field() for details.
4342
Item *item= field_it.create_item(thd);
4347
*ref != NULL means that *ref contains the item that we need to
4348
replace. If the item was aliased by the user, set the alias to
4350
We need to set alias on both ref itself and on ref real item.
4352
if (*ref && !(*ref)->is_autogenerated_name)
4354
item->set_name((*ref)->name, (*ref)->name_length,
4355
system_charset_info);
4356
item->real_item()->set_name((*ref)->name, (*ref)->name_length,
4357
system_charset_info);
4359
if (register_tree_change)
4360
thd->change_item_tree(ref, item);
4363
DBUG_RETURN((Field*) view_ref_found);
4371
Find field by name in a NATURAL/USING join table reference.
4374
find_field_in_natural_join()
4375
thd [in] thread handler
4376
table_ref [in] table reference to search
4377
name [in] name of field
4378
length [in] length of name
4379
ref [in/out] if 'name' is resolved to a view field, ref is
4380
set to point to the found view field
4381
register_tree_change [in] TRUE if ref is not stack variable and we
4382
need register changes in item tree
4383
actual_table [out] the original table reference where the field
4384
belongs - differs from 'table_list' only for
4388
Search for a field among the result fields of a NATURAL/USING join.
4389
Notice that this procedure is called only for non-qualified field
4390
names. In the case of qualified fields, we search directly the base
4391
tables of a natural join.
4394
NULL if the field was not found
4395
WRONG_GRANT if no access rights to the found field
4396
# Pointer to the found Field
4400
find_field_in_natural_join(THD *thd, TABLE_LIST *table_ref, const char *name,
4401
uint length, Item **ref, bool register_tree_change,
4402
TABLE_LIST **actual_table)
4404
List_iterator_fast<Natural_join_column>
4405
field_it(*(table_ref->join_columns));
4406
Natural_join_column *nj_col, *curr_nj_col;
4408
DBUG_ENTER("find_field_in_natural_join");
4409
DBUG_PRINT("enter", ("field name: '%s', ref 0x%lx",
4410
name, (ulong) ref));
4411
DBUG_ASSERT(table_ref->is_natural_join && table_ref->join_columns);
4412
DBUG_ASSERT(*actual_table == NULL);
4414
for (nj_col= NULL, curr_nj_col= field_it++; curr_nj_col;
4415
curr_nj_col= field_it++)
4417
if (!my_strcasecmp(system_charset_info, curr_nj_col->name(), name))
4421
my_error(ER_NON_UNIQ_ERROR, MYF(0), name, thd->where);
4424
nj_col= curr_nj_col;
4430
if (nj_col->view_field)
4434
create_item() may, or may not create a new Item, depending on the
4435
column reference. See create_view_field() for details.
4437
item= nj_col->create_item(thd);
4439
*ref != NULL means that *ref contains the item that we need to
4440
replace. If the item was aliased by the user, set the alias to
4442
We need to set alias on both ref itself and on ref real item.
4444
if (*ref && !(*ref)->is_autogenerated_name)
4446
item->set_name((*ref)->name, (*ref)->name_length,
4447
system_charset_info);
4448
item->real_item()->set_name((*ref)->name, (*ref)->name_length,
4449
system_charset_info);
4454
DBUG_ASSERT(nj_col->table_field == NULL);
4455
if (nj_col->table_ref->schema_table_reformed)
4458
Translation table items are always Item_fields and fixed
4459
already('mysql_schema_table' function). So we can return
4460
->field. It is used only for 'show & where' commands.
4462
DBUG_RETURN(((Item_field*) (nj_col->view_field->item))->field);
4464
if (register_tree_change)
4465
thd->change_item_tree(ref, item);
4468
found_field= (Field*) view_ref_found;
4472
/* This is a base table. */
4473
DBUG_ASSERT(nj_col->view_field == NULL);
4474
DBUG_ASSERT(nj_col->table_ref->table == nj_col->table_field->table);
4475
found_field= nj_col->table_field;
4476
update_field_dependencies(thd, found_field, nj_col->table_ref->table);
4479
*actual_table= nj_col->table_ref;
4481
DBUG_RETURN(found_field);
4486
Find field by name in a base table or a view with temp table algorithm.
4489
find_field_in_table()
4491
table table where to search for the field
4493
length length of name
4494
allow_rowid do allow finding of "_rowid" field?
4495
cached_field_index_ptr cached position in field list (used to speedup
4496
lookup for fields in prepared tables)
4499
0 field is not found
4504
find_field_in_table(THD *thd, TABLE *table, const char *name, uint length,
4505
bool allow_rowid, uint *cached_field_index_ptr)
4507
Field **field_ptr, *field;
4508
uint cached_field_index= *cached_field_index_ptr;
4509
DBUG_ENTER("find_field_in_table");
4510
DBUG_PRINT("enter", ("table: '%s', field name: '%s'", table->alias, name));
4512
/* We assume here that table->field < NO_CACHED_FIELD_INDEX = UINT_MAX */
4513
if (cached_field_index < table->s->fields &&
4514
!my_strcasecmp(system_charset_info,
4515
table->field[cached_field_index]->field_name, name))
4516
field_ptr= table->field + cached_field_index;
4517
else if (table->s->name_hash.records)
4519
field_ptr= (Field**) hash_search(&table->s->name_hash, (uchar*) name,
4524
field_ptr points to field in TABLE_SHARE. Convert it to the matching
4527
field_ptr= (table->field + (field_ptr - table->s->field));
4532
if (!(field_ptr= table->field))
4533
DBUG_RETURN((Field *)0);
4534
for (; *field_ptr; ++field_ptr)
4535
if (!my_strcasecmp(system_charset_info, (*field_ptr)->field_name, name))
4539
if (field_ptr && *field_ptr)
4541
*cached_field_index_ptr= field_ptr - table->field;
4547
my_strcasecmp(system_charset_info, name, "_rowid") ||
4548
table->s->rowid_field_offset == 0)
4549
DBUG_RETURN((Field*) 0);
4550
field= table->field[table->s->rowid_field_offset-1];
4553
update_field_dependencies(thd, field, table);
4560
Find field in a table reference.
4563
find_field_in_table_ref()
4564
thd [in] thread handler
4565
table_list [in] table reference to search
4566
name [in] name of field
4567
length [in] field length of name
4568
item_name [in] name of item if it will be created (VIEW)
4569
db_name [in] optional database name that qualifies the
4570
table_name [in] optional table name that qualifies the field
4571
ref [in/out] if 'name' is resolved to a view field, ref
4572
is set to point to the found view field
4573
check_privileges [in] check privileges
4574
allow_rowid [in] do allow finding of "_rowid" field?
4575
cached_field_index_ptr [in] cached position in field list (used to
4576
speedup lookup for fields in prepared tables)
4577
register_tree_change [in] TRUE if ref is not stack variable and we
4578
need register changes in item tree
4579
actual_table [out] the original table reference where the field
4580
belongs - differs from 'table_list' only for
4581
NATURAL_USING joins.
4584
Find a field in a table reference depending on the type of table
4585
reference. There are three types of table references with respect
4586
to the representation of their result columns:
4587
- an array of Field_translator objects for MERGE views and some
4588
information_schema tables,
4589
- an array of Field objects (and possibly a name hash) for stored
4591
- a list of Natural_join_column objects for NATURAL/USING joins.
4592
This procedure detects the type of the table reference 'table_list'
4593
and calls the corresponding search routine.
4596
0 field is not found
4597
view_ref_found found value in VIEW (real result is in *ref)
4602
find_field_in_table_ref(THD *thd, TABLE_LIST *table_list,
4603
const char *name, uint length,
4604
const char *item_name, const char *db_name,
4605
const char *table_name, Item **ref,
4606
bool check_privileges, bool allow_rowid,
4607
uint *cached_field_index_ptr,
4608
bool register_tree_change, TABLE_LIST **actual_table)
4611
DBUG_ENTER("find_field_in_table_ref");
4612
DBUG_ASSERT(table_list->alias);
4614
DBUG_ASSERT(item_name);
4616
("table: '%s' field name: '%s' item name: '%s' ref 0x%lx",
4617
table_list->alias, name, item_name, (ulong) ref));
4620
Check that the table and database that qualify the current field name
4621
are the same as the table reference we are going to search for the field.
4623
Exclude from the test below nested joins because the columns in a
4624
nested join generally originate from different tables. Nested joins
4625
also have no table name, except when a nested join is a merge view
4626
or an information schema table.
4628
We include explicitly table references with a 'field_translation' table,
4629
because if there are views over natural joins we don't want to search
4630
inside the view, but we want to search directly in the view columns
4631
which are represented as a 'field_translation'.
4633
TODO: Ensure that table_name, db_name and tables->db always points to
4636
if (/* Exclude nested joins. */
4637
(!table_list->nested_join ||
4638
/* Include merge views and information schema tables. */
4639
table_list->field_translation) &&
4641
Test if the field qualifiers match the table reference we plan
4644
table_name && table_name[0] &&
4645
(my_strcasecmp(table_alias_charset, table_list->alias, table_name) ||
4646
(db_name && db_name[0] && table_list->db && table_list->db[0] &&
4647
strcmp(db_name, table_list->db))))
4650
*actual_table= NULL;
4652
if (table_list->field_translation)
4654
/* 'table_list' is a view or an information schema table. */
4655
if ((fld= find_field_in_view(thd, table_list, name, length, item_name, ref,
4656
register_tree_change)))
4657
*actual_table= table_list;
4659
else if (!table_list->nested_join)
4661
/* 'table_list' is a stored table. */
4662
DBUG_ASSERT(table_list->table);
4663
if ((fld= find_field_in_table(thd, table_list->table, name, length,
4665
cached_field_index_ptr)))
4666
*actual_table= table_list;
4671
'table_list' is a NATURAL/USING join, or an operand of such join that
4672
is a nested join itself.
4674
If the field name we search for is qualified, then search for the field
4675
in the table references used by NATURAL/USING the join.
4677
if (table_name && table_name[0])
4679
List_iterator<TABLE_LIST> it(table_list->nested_join->join_list);
4681
while ((table= it++))
4683
if ((fld= find_field_in_table_ref(thd, table, name, length, item_name,
4684
db_name, table_name, ref,
4685
check_privileges, allow_rowid,
4686
cached_field_index_ptr,
4687
register_tree_change, actual_table)))
4693
Non-qualified field, search directly in the result columns of the
4694
natural join. The condition of the outer IF is true for the top-most
4695
natural join, thus if the field is not qualified, we will search
4696
directly the top-most NATURAL/USING join.
4698
fld= find_field_in_natural_join(thd, table_list, name, length, ref,
4699
register_tree_change, actual_table);
4704
if (thd->mark_used_columns != MARK_COLUMNS_NONE)
4707
Get rw_set correct for this field so that the handler
4708
knows that this field is involved in the query and gets
4711
Field *field_to_set= NULL;
4712
if (fld == view_ref_found)
4714
Item *it= (*ref)->real_item();
4715
if (it->type() == Item::FIELD_ITEM)
4716
field_to_set= ((Item_field*)it)->field;
4719
if (thd->mark_used_columns == MARK_COLUMNS_READ)
4720
it->walk(&Item::register_field_in_read_map, 1, (uchar *) 0);
4727
TABLE *table= field_to_set->table;
4728
if (thd->mark_used_columns == MARK_COLUMNS_READ)
4729
bitmap_set_bit(table->read_set, field_to_set->field_index);
4731
bitmap_set_bit(table->write_set, field_to_set->field_index);
4740
Find field in table, no side effects, only purpose is to check for field
4741
in table object and get reference to the field if found.
4744
find_field_in_table_sef()
4746
table table where to find
4747
name Name of field searched for
4750
0 field is not found
4754
Field *find_field_in_table_sef(TABLE *table, const char *name)
4757
if (table->s->name_hash.records)
4759
field_ptr= (Field**)hash_search(&table->s->name_hash,(uchar*) name,
4764
field_ptr points to field in TABLE_SHARE. Convert it to the matching
4767
field_ptr= (table->field + (field_ptr - table->s->field));
4772
if (!(field_ptr= table->field))
4774
for (; *field_ptr; ++field_ptr)
4775
if (!my_strcasecmp(system_charset_info, (*field_ptr)->field_name, name))
4786
Find field in table list.
4789
find_field_in_tables()
4790
thd pointer to current thread structure
4791
item field item that should be found
4792
first_table list of tables to be searched for item
4793
last_table end of the list of tables to search for item. If NULL
4794
then search to the end of the list 'first_table'.
4795
ref if 'item' is resolved to a view field, ref is set to
4796
point to the found view field
4797
report_error Degree of error reporting:
4798
- IGNORE_ERRORS then do not report any error
4799
- IGNORE_EXCEPT_NON_UNIQUE report only non-unique
4800
fields, suppress all other errors
4801
- REPORT_EXCEPT_NON_UNIQUE report all other errors
4802
except when non-unique fields were found
4804
check_privileges need to check privileges
4805
register_tree_change TRUE if ref is not a stack variable and we
4806
to need register changes in item tree
4809
0 If error: the found field is not unique, or there are
4810
no sufficient access priviliges for the found field,
4811
or the field is qualified with non-existing table.
4812
not_found_field The function was called with report_error ==
4813
(IGNORE_ERRORS || IGNORE_EXCEPT_NON_UNIQUE) and a
4814
field was not found.
4815
view_ref_found View field is found, item passed through ref parameter
4816
found field If a item was resolved to some field
4820
find_field_in_tables(THD *thd, Item_ident *item,
4821
TABLE_LIST *first_table, TABLE_LIST *last_table,
4822
Item **ref, find_item_error_report_type report_error,
4823
bool check_privileges, bool register_tree_change)
4826
const char *db= item->db_name;
4827
const char *table_name= item->table_name;
4828
const char *name= item->field_name;
4829
uint length=(uint) strlen(name);
4830
char name_buff[NAME_LEN+1];
4831
TABLE_LIST *cur_table= first_table;
4832
TABLE_LIST *actual_table;
4835
if (!table_name || !table_name[0])
4837
table_name= 0; // For easier test
4841
allow_rowid= table_name || (cur_table && !cur_table->next_local);
4843
if (item->cached_table)
4846
This shortcut is used by prepared statements. We assume that
4847
TABLE_LIST *first_table is not changed during query execution (which
4848
is true for all queries except RENAME but luckily RENAME doesn't
4849
use fields...) so we can rely on reusing pointer to its member.
4850
With this optimization we also miss case when addition of one more
4851
field makes some prepared query ambiguous and so erroneous, but we
4852
accept this trade off.
4854
TABLE_LIST *table_ref= item->cached_table;
4856
The condition (table_ref->view == NULL) ensures that we will call
4857
find_field_in_table even in the case of information schema tables
4858
when table_ref->field_translation != NULL.
4860
if (table_ref->table)
4861
found= find_field_in_table(thd, table_ref->table, name, length,
4862
TRUE, &(item->cached_field_index));
4864
found= find_field_in_table_ref(thd, table_ref, name, length, item->name,
4865
NULL, NULL, ref, check_privileges,
4866
TRUE, &(item->cached_field_index),
4867
register_tree_change,
4871
if (found == WRONG_GRANT)
4875
Only views fields should be marked as dependent, not an underlying
4878
if (!table_ref->belong_to_view)
4880
SELECT_LEX *current_sel= thd->lex->current_select;
4881
SELECT_LEX *last_select= table_ref->select_lex;
4883
If the field was an outer referencee, mark all selects using this
4884
sub query as dependent on the outer query
4886
if (current_sel != last_select)
4887
mark_select_range_as_dependent(thd, last_select, current_sel,
4894
if (db && lower_case_table_names)
4897
convert database to lower case for comparison.
4898
We can't do this in Item_field as this would change the
4899
'name' of the item which may be used in the select list
4901
strmake(name_buff, db, sizeof(name_buff)-1);
4902
my_casedn_str(files_charset_info, name_buff);
4907
last_table= last_table->next_name_resolution_table;
4909
for (; cur_table != last_table ;
4910
cur_table= cur_table->next_name_resolution_table)
4912
Field *cur_field= find_field_in_table_ref(thd, cur_table, name, length,
4913
item->name, db, table_name, ref,
4914
(thd->lex->sql_command ==
4916
? false : check_privileges,
4918
&(item->cached_field_index),
4919
register_tree_change,
4923
if (cur_field == WRONG_GRANT)
4925
if (thd->lex->sql_command != SQLCOM_SHOW_FIELDS)
4929
cur_field= find_field_in_table_ref(thd, cur_table, name, length,
4930
item->name, db, table_name, ref,
4933
&(item->cached_field_index),
4934
register_tree_change,
4938
Field *nf=new Field_null(NULL,0,Field::NONE,
4939
cur_field->field_name,
4941
nf->init(cur_table->table);
4947
Store the original table of the field, which may be different from
4948
cur_table in the case of NATURAL/USING join.
4950
item->cached_table= (!actual_table->cacheable_table || found) ?
4953
DBUG_ASSERT(thd->where);
4955
If we found a fully qualified field we return it directly as it can't
4963
if (report_error == REPORT_ALL_ERRORS ||
4964
report_error == IGNORE_EXCEPT_NON_UNIQUE)
4965
my_error(ER_NON_UNIQ_ERROR, MYF(0),
4966
table_name ? item->full_name() : name, thd->where);
4977
If the field was qualified and there were no tables to search, issue
4978
an error that an unknown table was given. The situation is detected
4979
as follows: if there were no tables we wouldn't go through the loop
4980
and cur_table wouldn't be updated by the loop increment part, so it
4981
will be equal to the first table.
4983
if (table_name && (cur_table == first_table) &&
4984
(report_error == REPORT_ALL_ERRORS ||
4985
report_error == REPORT_EXCEPT_NON_UNIQUE))
4987
char buff[NAME_LEN*2+1];
4990
strxnmov(buff,sizeof(buff)-1,db,".",table_name,NullS);
4993
my_error(ER_UNKNOWN_TABLE, MYF(0), table_name, thd->where);
4997
if (report_error == REPORT_ALL_ERRORS ||
4998
report_error == REPORT_EXCEPT_NON_UNIQUE)
4999
my_error(ER_BAD_FIELD_ERROR, MYF(0), item->full_name(), thd->where);
5001
found= not_found_field;
5008
Find Item in list of items (find_field_in_tables analog)
5011
is it better return only counter?
5017
counter To return number of found item
5019
REPORT_ALL_ERRORS report errors, return 0 if error
5020
REPORT_EXCEPT_NOT_FOUND Do not report 'not found' error and
5021
return not_found_item, report other errors,
5023
IGNORE_ERRORS Do not report errors, return 0 if error
5024
resolution Set to the resolution type if the item is found
5025
(it says whether the item is resolved
5026
against an alias name,
5027
or as a field name without alias,
5028
or as a field hidden by alias,
5032
0 Item is not found or item is not unique,
5033
error message is reported
5034
not_found_item Function was called with
5035
report_error == REPORT_EXCEPT_NOT_FOUND and
5036
item was not found. No error message was reported
5040
/* Special Item pointer to serve as a return value from find_item_in_list(). */
5041
Item **not_found_item= (Item**) 0x1;
5045
find_item_in_list(Item *find, List<Item> &items, uint *counter,
5046
find_item_error_report_type report_error,
5047
enum_resolution_type *resolution)
5049
List_iterator<Item> li(items);
5050
Item **found=0, **found_unaliased= 0, *item;
5051
const char *db_name=0;
5052
const char *field_name=0;
5053
const char *table_name=0;
5054
bool found_unaliased_non_uniq= 0;
5056
true if the item that we search for is a valid name reference
5057
(and not an item that happens to have a name).
5059
bool is_ref_by_name= 0;
5060
uint unaliased_counter= 0;
5062
*resolution= NOT_RESOLVED;
5064
is_ref_by_name= (find->type() == Item::FIELD_ITEM ||
5065
find->type() == Item::REF_ITEM);
5068
field_name= ((Item_ident*) find)->field_name;
5069
table_name= ((Item_ident*) find)->table_name;
5070
db_name= ((Item_ident*) find)->db_name;
5073
for (uint i= 0; (item=li++); i++)
5075
if (field_name && item->real_item()->type() == Item::FIELD_ITEM)
5077
Item_ident *item_field= (Item_ident*) item;
5080
In case of group_concat() with ORDER BY condition in the QUERY
5081
item_field can be field of temporary table without item name
5082
(if this field created from expression argument of group_concat()),
5083
=> we have to check presence of name before compare
5085
if (!item_field->name)
5091
If table name is specified we should find field 'field_name' in
5092
table 'table_name'. According to SQL-standard we should ignore
5093
aliases in this case.
5095
Since we should NOT prefer fields from the select list over
5096
other fields from the tables participating in this select in
5097
case of ambiguity we have to do extra check outside this function.
5099
We use strcmp for table names and database names as these may be
5100
case sensitive. In cases where they are not case sensitive, they
5101
are always in lower case.
5103
item_field->field_name and item_field->table_name can be 0x0 if
5104
item is not fix_field()'ed yet.
5106
if (item_field->field_name && item_field->table_name &&
5107
!my_strcasecmp(system_charset_info, item_field->field_name,
5109
!my_strcasecmp(table_alias_charset, item_field->table_name,
5111
(!db_name || (item_field->db_name &&
5112
!strcmp(item_field->db_name, db_name))))
5114
if (found_unaliased)
5116
if ((*found_unaliased)->eq(item, 0))
5119
Two matching fields in select list.
5120
We already can bail out because we are searching through
5121
unaliased names only and will have duplicate error anyway.
5123
if (report_error != IGNORE_ERRORS)
5124
my_error(ER_NON_UNIQ_ERROR, MYF(0),
5125
find->full_name(), current_thd->where);
5128
found_unaliased= li.ref();
5129
unaliased_counter= i;
5130
*resolution= RESOLVED_IGNORING_ALIAS;
5132
break; // Perfect match
5137
int fname_cmp= my_strcasecmp(system_charset_info,
5138
item_field->field_name,
5140
if (!my_strcasecmp(system_charset_info,
5141
item_field->name,field_name))
5144
If table name was not given we should scan through aliases
5145
and non-aliased fields first. We are also checking unaliased
5146
name of the field in then next else-if, to be able to find
5147
instantly field (hidden by alias) if no suitable alias or
5148
non-aliased field was found.
5152
if ((*found)->eq(item, 0))
5153
continue; // Same field twice
5154
if (report_error != IGNORE_ERRORS)
5155
my_error(ER_NON_UNIQ_ERROR, MYF(0),
5156
find->full_name(), current_thd->where);
5161
*resolution= fname_cmp ? RESOLVED_AGAINST_ALIAS:
5162
RESOLVED_WITH_NO_ALIAS;
5164
else if (!fname_cmp)
5167
We will use non-aliased field or react on such ambiguities only if
5168
we won't be able to find aliased field.
5169
Again if we have ambiguity with field outside of select list
5170
we should prefer fields from select list.
5172
if (found_unaliased)
5174
if ((*found_unaliased)->eq(item, 0))
5175
continue; // Same field twice
5176
found_unaliased_non_uniq= 1;
5178
found_unaliased= li.ref();
5179
unaliased_counter= i;
5183
else if (!table_name)
5185
if (is_ref_by_name && find->name && item->name &&
5186
!my_strcasecmp(system_charset_info,item->name,find->name))
5190
*resolution= RESOLVED_AGAINST_ALIAS;
5193
else if (find->eq(item,0))
5197
*resolution= RESOLVED_IGNORING_ALIAS;
5201
else if (table_name && item->type() == Item::REF_ITEM &&
5202
((Item_ref *)item)->ref_type() == Item_ref::VIEW_REF)
5205
TODO:Here we process prefixed view references only. What we should
5206
really do is process all types of Item_refs. But this will currently
5207
lead to a clash with the way references to outer SELECTs (from the
5208
HAVING clause) are handled in e.g. :
5209
SELECT 1 FROM t1 AS t1_o GROUP BY a
5210
HAVING (SELECT t1_o.a FROM t1 AS t1_i GROUP BY t1_i.a LIMIT 1).
5211
Processing all Item_refs here will cause t1_o.a to resolve to itself.
5212
We still need to process the special case of Item_direct_view_ref
5213
because in the context of views they have the same meaning as
5214
Item_field for tables.
5216
Item_ident *item_ref= (Item_ident *) item;
5217
if (item_ref->name && item_ref->table_name &&
5218
!my_strcasecmp(system_charset_info, item_ref->name, field_name) &&
5219
!my_strcasecmp(table_alias_charset, item_ref->table_name,
5221
(!db_name || (item_ref->db_name &&
5222
!strcmp (item_ref->db_name, db_name))))
5226
*resolution= RESOLVED_IGNORING_ALIAS;
5233
if (found_unaliased_non_uniq)
5235
if (report_error != IGNORE_ERRORS)
5236
my_error(ER_NON_UNIQ_ERROR, MYF(0),
5237
find->full_name(), current_thd->where);
5240
if (found_unaliased)
5242
found= found_unaliased;
5243
*counter= unaliased_counter;
5244
*resolution= RESOLVED_BEHIND_ALIAS;
5249
if (report_error != REPORT_EXCEPT_NOT_FOUND)
5251
if (report_error == REPORT_ALL_ERRORS)
5252
my_error(ER_BAD_FIELD_ERROR, MYF(0),
5253
find->full_name(), current_thd->where);
5257
return (Item **) not_found_item;
5262
Test if a string is a member of a list of strings.
5265
test_if_string_in_list()
5266
find the string to look for
5267
str_list a list of strings to be searched
5270
Sequentially search a list of strings for a string, and test whether
5271
the list contains the same string.
5274
TRUE if find is in str_list
5279
test_if_string_in_list(const char *find, List<String> *str_list)
5281
List_iterator<String> str_list_it(*str_list);
5283
size_t find_length= strlen(find);
5284
while ((curr_str= str_list_it++))
5286
if (find_length != curr_str->length())
5288
if (!my_strcasecmp(system_charset_info, find, curr_str->ptr()))
5296
Create a new name resolution context for an item so that it is
5297
being resolved in a specific table reference.
5300
set_new_item_local_context()
5301
thd pointer to current thread
5302
item item for which new context is created and set
5303
table_ref table ref where an item showld be resolved
5306
Create a new name resolution context for an item, so that the item
5307
is resolved only the supplied 'table_ref'.
5315
set_new_item_local_context(THD *thd, Item_ident *item, TABLE_LIST *table_ref)
5317
Name_resolution_context *context;
5318
if (!(context= new (thd->mem_root) Name_resolution_context))
5321
context->first_name_resolution_table=
5322
context->last_name_resolution_table= table_ref;
5323
item->context= context;
5329
Find and mark the common columns of two table references.
5332
mark_common_columns()
5333
thd [in] current thread
5334
table_ref_1 [in] the first (left) join operand
5335
table_ref_2 [in] the second (right) join operand
5336
using_fields [in] if the join is JOIN...USING - the join columns,
5337
if NATURAL join, then NULL
5338
found_using_fields [out] number of fields from the USING clause that were
5339
found among the common fields
5342
The procedure finds the common columns of two relations (either
5343
tables or intermediate join results), and adds an equi-join condition
5344
to the ON clause of 'table_ref_2' for each pair of matching columns.
5345
If some of table_ref_XXX represents a base table or view, then we
5346
create new 'Natural_join_column' instances for each column
5347
reference and store them in the 'join_columns' of the table
5351
The procedure assumes that store_natural_using_join_columns() was
5352
called for the previous level of NATURAL/USING joins.
5355
TRUE error when some common column is non-unique, or out of memory
5360
mark_common_columns(THD *thd, TABLE_LIST *table_ref_1, TABLE_LIST *table_ref_2,
5361
List<String> *using_fields, uint *found_using_fields)
5363
Field_iterator_table_ref it_1, it_2;
5364
Natural_join_column *nj_col_1, *nj_col_2;
5366
bool first_outer_loop= TRUE;
5368
Leaf table references to which new natural join columns are added
5369
if the leaves are != NULL.
5371
TABLE_LIST *leaf_1= (table_ref_1->nested_join &&
5372
!table_ref_1->is_natural_join) ?
5374
TABLE_LIST *leaf_2= (table_ref_2->nested_join &&
5375
!table_ref_2->is_natural_join) ?
5378
DBUG_ENTER("mark_common_columns");
5379
DBUG_PRINT("info", ("operand_1: %s operand_2: %s",
5380
table_ref_1->alias, table_ref_2->alias));
5382
*found_using_fields= 0;
5384
for (it_1.set(table_ref_1); !it_1.end_of_fields(); it_1.next())
5387
const char *field_name_1;
5388
/* true if field_name_1 is a member of using_fields */
5389
bool is_using_column_1;
5390
if (!(nj_col_1= it_1.get_or_create_column_ref(leaf_1)))
5392
field_name_1= nj_col_1->name();
5393
is_using_column_1= using_fields &&
5394
test_if_string_in_list(field_name_1, using_fields);
5395
DBUG_PRINT ("info", ("field_name_1=%s.%s",
5396
nj_col_1->table_name() ? nj_col_1->table_name() : "",
5400
Find a field with the same name in table_ref_2.
5402
Note that for the second loop, it_2.set() will iterate over
5403
table_ref_2->join_columns and not generate any new elements or
5407
for (it_2.set(table_ref_2); !it_2.end_of_fields(); it_2.next())
5409
Natural_join_column *cur_nj_col_2;
5410
const char *cur_field_name_2;
5411
if (!(cur_nj_col_2= it_2.get_or_create_column_ref(leaf_2)))
5413
cur_field_name_2= cur_nj_col_2->name();
5414
DBUG_PRINT ("info", ("cur_field_name_2=%s.%s",
5415
cur_nj_col_2->table_name() ?
5416
cur_nj_col_2->table_name() : "",
5420
Compare the two columns and check for duplicate common fields.
5421
A common field is duplicate either if it was already found in
5422
table_ref_2 (then found == TRUE), or if a field in table_ref_2
5423
was already matched by some previous field in table_ref_1
5424
(then cur_nj_col_2->is_common == TRUE).
5425
Note that it is too early to check the columns outside of the
5426
USING list for ambiguity because they are not actually "referenced"
5427
here. These columns must be checked only on unqualified reference
5428
by name (e.g. in SELECT list).
5430
if (!my_strcasecmp(system_charset_info, field_name_1, cur_field_name_2))
5432
DBUG_PRINT ("info", ("match c1.is_common=%d", nj_col_1->is_common));
5433
if (cur_nj_col_2->is_common ||
5434
(found && (!using_fields || is_using_column_1)))
5436
my_error(ER_NON_UNIQ_ERROR, MYF(0), field_name_1, thd->where);
5439
nj_col_2= cur_nj_col_2;
5443
if (first_outer_loop && leaf_2)
5446
Make sure that the next inner loop "knows" that all columns
5447
are materialized already.
5449
leaf_2->is_join_columns_complete= TRUE;
5450
first_outer_loop= FALSE;
5453
continue; // No matching field
5456
field_1 and field_2 have the same names. Check if they are in the USING
5457
clause (if present), mark them as common fields, and add a new
5458
equi-join condition to the ON clause.
5460
if (nj_col_2 && (!using_fields ||is_using_column_1))
5462
Item *item_1= nj_col_1->create_item(thd);
5463
Item *item_2= nj_col_2->create_item(thd);
5464
Field *field_1= nj_col_1->field();
5465
Field *field_2= nj_col_2->field();
5466
Item_ident *item_ident_1, *item_ident_2;
5467
Item_func_eq *eq_cond;
5469
if (!item_1 || !item_2)
5470
goto err; // out of memory
5473
The following assert checks that the two created items are of
5476
DBUG_ASSERT(!thd->lex->current_select->no_wrap_view_item);
5478
In the case of no_wrap_view_item == 0, the created items must be
5479
of sub-classes of Item_ident.
5481
DBUG_ASSERT(item_1->type() == Item::FIELD_ITEM ||
5482
item_1->type() == Item::REF_ITEM);
5483
DBUG_ASSERT(item_2->type() == Item::FIELD_ITEM ||
5484
item_2->type() == Item::REF_ITEM);
5487
We need to cast item_1,2 to Item_ident, because we need to hook name
5488
resolution contexts specific to each item.
5490
item_ident_1= (Item_ident*) item_1;
5491
item_ident_2= (Item_ident*) item_2;
5493
Create and hook special name resolution contexts to each item in the
5494
new join condition . We need this to both speed-up subsequent name
5495
resolution of these items, and to enable proper name resolution of
5496
the items during the execute phase of PS.
5498
if (set_new_item_local_context(thd, item_ident_1, nj_col_1->table_ref) ||
5499
set_new_item_local_context(thd, item_ident_2, nj_col_2->table_ref))
5502
if (!(eq_cond= new Item_func_eq(item_ident_1, item_ident_2)))
5503
goto err; /* Out of memory. */
5506
Add the new equi-join condition to the ON clause. Notice that
5507
fix_fields() is applied to all ON conditions in setup_conds()
5508
so we don't do it here.
5510
add_join_on((table_ref_1->outer_join & JOIN_TYPE_RIGHT ?
5511
table_ref_1 : table_ref_2),
5514
nj_col_1->is_common= nj_col_2->is_common= TRUE;
5515
DBUG_PRINT ("info", ("%s.%s and %s.%s are common",
5516
nj_col_1->table_name() ?
5517
nj_col_1->table_name() : "",
5519
nj_col_2->table_name() ?
5520
nj_col_2->table_name() : "",
5525
TABLE *table_1= nj_col_1->table_ref->table;
5526
/* Mark field_1 used for table cache. */
5527
bitmap_set_bit(table_1->read_set, field_1->field_index);
5528
table_1->covering_keys.intersect(field_1->part_of_key);
5529
table_1->merge_keys.merge(field_1->part_of_key);
5533
TABLE *table_2= nj_col_2->table_ref->table;
5534
/* Mark field_2 used for table cache. */
5535
bitmap_set_bit(table_2->read_set, field_2->field_index);
5536
table_2->covering_keys.intersect(field_2->part_of_key);
5537
table_2->merge_keys.merge(field_2->part_of_key);
5540
if (using_fields != NULL)
5541
++(*found_using_fields);
5545
leaf_1->is_join_columns_complete= TRUE;
5549
Notice that at this point there may be some column names in the USING
5550
clause that are not among the common columns. This is an SQL error and
5551
we check for this error in store_natural_using_join_columns() when
5552
(found_using_fields < length(join_using_fields)).
5557
DBUG_RETURN(result);
5563
Materialize and store the row type of NATURAL/USING join.
5566
store_natural_using_join_columns()
5568
natural_using_join the table reference of the NATURAL/USING join
5569
table_ref_1 the first (left) operand (of a NATURAL/USING join).
5570
table_ref_2 the second (right) operand (of a NATURAL/USING join).
5571
using_fields if the join is JOIN...USING - the join columns,
5572
if NATURAL join, then NULL
5573
found_using_fields number of fields from the USING clause that were
5574
found among the common fields
5577
Iterate over the columns of both join operands and sort and store
5578
all columns into the 'join_columns' list of natural_using_join
5579
where the list is formed by three parts:
5580
part1: The coalesced columns of table_ref_1 and table_ref_2,
5581
sorted according to the column order of the first table.
5582
part2: The other columns of the first table, in the order in
5583
which they were defined in CREATE TABLE.
5584
part3: The other columns of the second table, in the order in
5585
which they were defined in CREATE TABLE.
5586
Time complexity - O(N1+N2), where Ni = length(table_ref_i).
5589
The procedure assumes that mark_common_columns() has been called
5590
for the join that is being processed.
5593
TRUE error: Some common column is ambiguous
5598
store_natural_using_join_columns(THD *thd, TABLE_LIST *natural_using_join,
5599
TABLE_LIST *table_ref_1,
5600
TABLE_LIST *table_ref_2,
5601
List<String> *using_fields,
5602
uint found_using_fields)
5604
Field_iterator_table_ref it_1, it_2;
5605
Natural_join_column *nj_col_1, *nj_col_2;
5607
List<Natural_join_column> *non_join_columns;
5608
DBUG_ENTER("store_natural_using_join_columns");
5610
DBUG_ASSERT(!natural_using_join->join_columns);
5612
if (!(non_join_columns= new List<Natural_join_column>) ||
5613
!(natural_using_join->join_columns= new List<Natural_join_column>))
5616
/* Append the columns of the first join operand. */
5617
for (it_1.set(table_ref_1); !it_1.end_of_fields(); it_1.next())
5619
nj_col_1= it_1.get_natural_column_ref();
5620
if (nj_col_1->is_common)
5622
natural_using_join->join_columns->push_back(nj_col_1);
5623
/* Reset the common columns for the next call to mark_common_columns. */
5624
nj_col_1->is_common= FALSE;
5627
non_join_columns->push_back(nj_col_1);
5631
Check that all columns in the USING clause are among the common
5632
columns. If this is not the case, report the first one that was
5633
not found in an error.
5635
if (using_fields && found_using_fields < using_fields->elements)
5637
String *using_field_name;
5638
List_iterator_fast<String> using_fields_it(*using_fields);
5639
while ((using_field_name= using_fields_it++))
5641
const char *using_field_name_ptr= using_field_name->c_ptr();
5642
List_iterator_fast<Natural_join_column>
5643
it(*(natural_using_join->join_columns));
5644
Natural_join_column *common_field;
5648
/* If reached the end of fields, and none was found, report error. */
5649
if (!(common_field= it++))
5651
my_error(ER_BAD_FIELD_ERROR, MYF(0), using_field_name_ptr,
5652
current_thd->where);
5655
if (!my_strcasecmp(system_charset_info,
5656
common_field->name(), using_field_name_ptr))
5657
break; // Found match
5662
/* Append the non-equi-join columns of the second join operand. */
5663
for (it_2.set(table_ref_2); !it_2.end_of_fields(); it_2.next())
5665
nj_col_2= it_2.get_natural_column_ref();
5666
if (!nj_col_2->is_common)
5667
non_join_columns->push_back(nj_col_2);
5670
/* Reset the common columns for the next call to mark_common_columns. */
5671
nj_col_2->is_common= FALSE;
5675
if (non_join_columns->elements > 0)
5676
natural_using_join->join_columns->concat(non_join_columns);
5677
natural_using_join->is_join_columns_complete= TRUE;
5682
DBUG_RETURN(result);
5687
Precompute and store the row types of the top-most NATURAL/USING joins.
5690
store_top_level_join_columns()
5692
table_ref nested join or table in a FROM clause
5693
left_neighbor neighbor table reference to the left of table_ref at the
5694
same level in the join tree
5695
right_neighbor neighbor table reference to the right of table_ref at the
5696
same level in the join tree
5699
The procedure performs a post-order traversal of a nested join tree
5700
and materializes the row types of NATURAL/USING joins in a
5701
bottom-up manner until it reaches the TABLE_LIST elements that
5702
represent the top-most NATURAL/USING joins. The procedure should be
5703
applied to each element of SELECT_LEX::top_join_list (i.e. to each
5704
top-level element of the FROM clause).
5707
Notice that the table references in the list nested_join->join_list
5708
are in reverse order, thus when we iterate over it, we are moving
5709
from the right to the left in the FROM clause.
5717
store_top_level_join_columns(THD *thd, TABLE_LIST *table_ref,
5718
TABLE_LIST *left_neighbor,
5719
TABLE_LIST *right_neighbor)
5723
DBUG_ENTER("store_top_level_join_columns");
5725
/* Call the procedure recursively for each nested table reference. */
5726
if (table_ref->nested_join)
5728
List_iterator_fast<TABLE_LIST> nested_it(table_ref->nested_join->join_list);
5729
TABLE_LIST *same_level_left_neighbor= nested_it++;
5730
TABLE_LIST *same_level_right_neighbor= NULL;
5731
/* Left/right-most neighbors, possibly at higher levels in the join tree. */
5732
TABLE_LIST *real_left_neighbor, *real_right_neighbor;
5734
while (same_level_left_neighbor)
5736
TABLE_LIST *cur_table_ref= same_level_left_neighbor;
5737
same_level_left_neighbor= nested_it++;
5739
The order of RIGHT JOIN operands is reversed in 'join list' to
5740
transform it into a LEFT JOIN. However, in this procedure we need
5741
the join operands in their lexical order, so below we reverse the
5742
join operands. Notice that this happens only in the first loop,
5743
and not in the second one, as in the second loop
5744
same_level_left_neighbor == NULL.
5745
This is the correct behavior, because the second loop sets
5746
cur_table_ref reference correctly after the join operands are
5747
swapped in the first loop.
5749
if (same_level_left_neighbor &&
5750
cur_table_ref->outer_join & JOIN_TYPE_RIGHT)
5752
/* This can happen only for JOIN ... ON. */
5753
DBUG_ASSERT(table_ref->nested_join->join_list.elements == 2);
5754
swap_variables(TABLE_LIST*, same_level_left_neighbor, cur_table_ref);
5758
Pick the parent's left and right neighbors if there are no immediate
5759
neighbors at the same level.
5761
real_left_neighbor= (same_level_left_neighbor) ?
5762
same_level_left_neighbor : left_neighbor;
5763
real_right_neighbor= (same_level_right_neighbor) ?
5764
same_level_right_neighbor : right_neighbor;
5766
if (cur_table_ref->nested_join &&
5767
store_top_level_join_columns(thd, cur_table_ref,
5768
real_left_neighbor, real_right_neighbor))
5770
same_level_right_neighbor= cur_table_ref;
5775
If this is a NATURAL/USING join, materialize its result columns and
5776
convert to a JOIN ... ON.
5778
if (table_ref->is_natural_join)
5780
DBUG_ASSERT(table_ref->nested_join &&
5781
table_ref->nested_join->join_list.elements == 2);
5782
List_iterator_fast<TABLE_LIST> operand_it(table_ref->nested_join->join_list);
5784
Notice that the order of join operands depends on whether table_ref
5785
represents a LEFT or a RIGHT join. In a RIGHT join, the operands are
5788
TABLE_LIST *table_ref_2= operand_it++; /* Second NATURAL join operand.*/
5789
TABLE_LIST *table_ref_1= operand_it++; /* First NATURAL join operand. */
5790
List<String> *using_fields= table_ref->join_using_fields;
5791
uint found_using_fields;
5794
The two join operands were interchanged in the parser, change the order
5795
back for 'mark_common_columns'.
5797
if (table_ref_2->outer_join & JOIN_TYPE_RIGHT)
5798
swap_variables(TABLE_LIST*, table_ref_1, table_ref_2);
5799
if (mark_common_columns(thd, table_ref_1, table_ref_2,
5800
using_fields, &found_using_fields))
5804
Swap the join operands back, so that we pick the columns of the second
5805
one as the coalesced columns. In this way the coalesced columns are the
5806
same as of an equivalent LEFT JOIN.
5808
if (table_ref_1->outer_join & JOIN_TYPE_RIGHT)
5809
swap_variables(TABLE_LIST*, table_ref_1, table_ref_2);
5810
if (store_natural_using_join_columns(thd, table_ref, table_ref_1,
5811
table_ref_2, using_fields,
5812
found_using_fields))
5816
Change NATURAL JOIN to JOIN ... ON. We do this for both operands
5817
because either one of them or the other is the one with the
5818
natural join flag because RIGHT joins are transformed into LEFT,
5819
and the two tables may be reordered.
5821
table_ref_1->natural_join= table_ref_2->natural_join= NULL;
5823
/* Add a TRUE condition to outer joins that have no common columns. */
5824
if (table_ref_2->outer_join &&
5825
!table_ref_1->on_expr && !table_ref_2->on_expr)
5826
table_ref_2->on_expr= new Item_int((longlong) 1,1); /* Always true. */
5828
/* Change this table reference to become a leaf for name resolution. */
5831
TABLE_LIST *last_leaf_on_the_left;
5832
last_leaf_on_the_left= left_neighbor->last_leaf_for_name_resolution();
5833
last_leaf_on_the_left->next_name_resolution_table= table_ref;
5837
TABLE_LIST *first_leaf_on_the_right;
5838
first_leaf_on_the_right= right_neighbor->first_leaf_for_name_resolution();
5839
table_ref->next_name_resolution_table= first_leaf_on_the_right;
5842
table_ref->next_name_resolution_table= NULL;
5844
result= FALSE; /* All is OK. */
5847
DBUG_RETURN(result);
5852
Compute and store the row types of the top-most NATURAL/USING joins
5856
setup_natural_join_row_types()
5858
from_clause list of top-level table references in a FROM clause
5861
Apply the procedure 'store_top_level_join_columns' to each of the
5862
top-level table referencs of the FROM clause. Adjust the list of tables
5863
for name resolution - context->first_name_resolution_table to the
5864
top-most, lef-most NATURAL/USING join.
5867
Notice that the table references in 'from_clause' are in reverse
5868
order, thus when we iterate over it, we are moving from the right
5869
to the left in the FROM clause.
5875
static bool setup_natural_join_row_types(THD *thd,
5876
List<TABLE_LIST> *from_clause,
5877
Name_resolution_context *context)
5879
thd->where= "from clause";
5880
if (from_clause->elements == 0)
5881
return FALSE; /* We come here in the case of UNIONs. */
5883
List_iterator_fast<TABLE_LIST> table_ref_it(*from_clause);
5884
TABLE_LIST *table_ref; /* Current table reference. */
5885
/* Table reference to the left of the current. */
5886
TABLE_LIST *left_neighbor;
5887
/* Table reference to the right of the current. */
5888
TABLE_LIST *right_neighbor= NULL;
5890
/* Note that tables in the list are in reversed order */
5891
for (left_neighbor= table_ref_it++; left_neighbor ; )
5893
table_ref= left_neighbor;
5894
left_neighbor= table_ref_it++;
5895
/* For stored procedures do not redo work if already done. */
5896
if (context->select_lex->first_execution)
5898
if (store_top_level_join_columns(thd, table_ref,
5899
left_neighbor, right_neighbor))
5903
TABLE_LIST *first_leaf_on_the_right;
5904
first_leaf_on_the_right= table_ref->first_leaf_for_name_resolution();
5905
left_neighbor->next_name_resolution_table= first_leaf_on_the_right;
5908
right_neighbor= table_ref;
5912
Store the top-most, left-most NATURAL/USING join, so that we start
5913
the search from that one instead of context->table_list. At this point
5914
right_neighbor points to the left-most top-level table reference in the
5917
DBUG_ASSERT(right_neighbor);
5918
context->first_name_resolution_table=
5919
right_neighbor->first_leaf_for_name_resolution();
5925
/****************************************************************************
5926
** Expand all '*' in given fields
5927
****************************************************************************/
5929
int setup_wild(THD *thd, TABLE_LIST *tables, List<Item> &fields,
5930
List<Item> *sum_func_list,
5937
List_iterator<Item> it(fields);
5938
DBUG_ENTER("setup_wild");
5940
thd->lex->current_select->cur_pos_in_select_list= 0;
5941
while (wild_num && (item= it++))
5943
if (item->type() == Item::FIELD_ITEM &&
5944
((Item_field*) item)->field_name &&
5945
((Item_field*) item)->field_name[0] == '*' &&
5946
!((Item_field*) item)->field)
5948
uint elem= fields.elements;
5949
bool any_privileges= ((Item_field *) item)->any_privileges;
5950
Item_subselect *subsel= thd->lex->current_select->master_unit()->item;
5952
subsel->substype() == Item_subselect::EXISTS_SUBS)
5955
It is EXISTS(SELECT * ...) and we can replace * by any constant.
5957
Item_int do not need fix_fields() because it is basic constant.
5959
it.replace(new Item_int("Not_used", (longlong) 1,
5960
MY_INT64_NUM_DECIMAL_DIGITS));
5962
else if (insert_fields(thd, ((Item_field*) item)->context,
5963
((Item_field*) item)->db_name,
5964
((Item_field*) item)->table_name, &it,
5972
sum_func_list is a list that has the fields list as a tail.
5973
Because of this we have to update the element count also for this
5974
list after expanding the '*' entry.
5976
sum_func_list->elements+= fields.elements - elem;
5981
thd->lex->current_select->cur_pos_in_select_list++;
5983
thd->lex->current_select->cur_pos_in_select_list= UNDEF_POS;
5987
/****************************************************************************
5988
** Check that all given fields exists and fill struct with current data
5989
****************************************************************************/
5991
bool setup_fields(THD *thd, Item **ref_pointer_array,
5992
List<Item> &fields, enum_mark_columns mark_used_columns,
5993
List<Item> *sum_func_list, bool allow_sum_func)
5995
register Item *item;
5996
enum_mark_columns save_mark_used_columns= thd->mark_used_columns;
5997
nesting_map save_allow_sum_func= thd->lex->allow_sum_func;
5998
List_iterator<Item> it(fields);
5999
bool save_is_item_list_lookup;
6000
DBUG_ENTER("setup_fields");
6002
thd->mark_used_columns= mark_used_columns;
6003
DBUG_PRINT("info", ("thd->mark_used_columns: %d", thd->mark_used_columns));
6005
thd->lex->allow_sum_func|= 1 << thd->lex->current_select->nest_level;
6006
thd->where= THD::DEFAULT_WHERE;
6007
save_is_item_list_lookup= thd->lex->current_select->is_item_list_lookup;
6008
thd->lex->current_select->is_item_list_lookup= 0;
6011
To prevent fail on forward lookup we fill it with zerows,
6012
then if we got pointer on zero after find_item_in_list we will know
6013
that it is forward lookup.
6015
There is other way to solve problem: fill array with pointers to list,
6016
but it will be slower.
6018
TODO: remove it when (if) we made one list for allfields and
6021
if (ref_pointer_array)
6022
bzero(ref_pointer_array, sizeof(Item *) * fields.elements);
6024
Item **ref= ref_pointer_array;
6025
thd->lex->current_select->cur_pos_in_select_list= 0;
6026
while ((item= it++))
6028
if ((!item->fixed && item->fix_fields(thd, it.ref())) || (item= *(it.ref()))->check_cols(1))
6030
thd->lex->current_select->is_item_list_lookup= save_is_item_list_lookup;
6031
thd->lex->allow_sum_func= save_allow_sum_func;
6032
thd->mark_used_columns= save_mark_used_columns;
6033
DBUG_PRINT("info", ("thd->mark_used_columns: %d", thd->mark_used_columns));
6034
DBUG_RETURN(TRUE); /* purecov: inspected */
6038
if (item->with_sum_func && item->type() != Item::SUM_FUNC_ITEM &&
6040
item->split_sum_func(thd, ref_pointer_array, *sum_func_list);
6041
thd->used_tables|= item->used_tables();
6042
thd->lex->current_select->cur_pos_in_select_list++;
6044
thd->lex->current_select->is_item_list_lookup= save_is_item_list_lookup;
6045
thd->lex->current_select->cur_pos_in_select_list= UNDEF_POS;
6047
thd->lex->allow_sum_func= save_allow_sum_func;
6048
thd->mark_used_columns= save_mark_used_columns;
6049
DBUG_PRINT("info", ("thd->mark_used_columns: %d", thd->mark_used_columns));
6050
DBUG_RETURN(test(thd->is_error()));
6055
make list of leaves of join table tree
6059
list pointer to pointer on list first element
6062
RETURN pointer on pointer to next_leaf of last element
6065
TABLE_LIST **make_leaves_list(TABLE_LIST **list, TABLE_LIST *tables)
6067
for (TABLE_LIST *table= tables; table; table= table->next_local)
6071
list= &table->next_leaf;
6083
context name resolution contest to setup table list there
6084
from_clause Top-level list of table references in the FROM clause
6085
tables Table list (select_lex->table_list)
6086
leaves List of join table leaves list (select_lex->leaf_tables)
6087
refresh It is onle refresh for subquery
6088
select_insert It is SELECT ... INSERT command
6091
Check also that the 'used keys' and 'ignored keys' exists and set up the
6092
table structure accordingly.
6093
Create a list of leaf tables. For queries with NATURAL/USING JOINs,
6094
compute the row types of the top most natural/using join table references
6095
and link these into a list of table references for name resolution.
6097
This has to be called for all tables that are used by items, as otherwise
6098
table->map is not set and all Item_field will be regarded as const items.
6101
FALSE ok; In this case *map will includes the chosen index
6105
bool setup_tables(THD *thd, Name_resolution_context *context,
6106
List<TABLE_LIST> *from_clause, TABLE_LIST *tables,
6107
TABLE_LIST **leaves, bool select_insert)
6110
DBUG_ENTER("setup_tables");
6112
DBUG_ASSERT ((select_insert && !tables->next_name_resolution_table) || !tables ||
6113
(context->table_list && context->first_name_resolution_table));
6115
this is used for INSERT ... SELECT.
6116
For select we setup tables except first (and its underlying tables)
6118
TABLE_LIST *first_select_table= (select_insert ?
6122
make_leaves_list(leaves, tables);
6124
TABLE_LIST *table_list;
6125
for (table_list= *leaves;
6127
table_list= table_list->next_leaf, tablenr++)
6129
TABLE *table= table_list->table;
6130
table->pos_in_table_list= table_list;
6131
if (first_select_table &&
6132
table_list->top_table() == first_select_table)
6134
/* new counting for SELECT of INSERT ... SELECT command */
6135
first_select_table= 0;
6138
setup_table_map(table, table_list, tablenr);
6139
if (table_list->process_index_hints(table))
6142
if (tablenr > MAX_TABLES)
6144
my_error(ER_TOO_MANY_TABLES,MYF(0),MAX_TABLES);
6148
/* Precompute and store the row types of NATURAL/USING joins. */
6149
if (setup_natural_join_row_types(thd, from_clause, context))
6157
prepare tables and check access for the view tables
6160
setup_tables_and_check_view_access()
6162
context name resolution contest to setup table list there
6163
from_clause Top-level list of table references in the FROM clause
6164
tables Table list (select_lex->table_list)
6165
conds Condition of current SELECT (can be changed by VIEW)
6166
leaves List of join table leaves list (select_lex->leaf_tables)
6167
refresh It is onle refresh for subquery
6168
select_insert It is SELECT ... INSERT command
6169
want_access what access is needed
6172
a wrapper for check_tables that will also check the resulting
6173
table leaves list for access to all the tables that belong to a view
6176
FALSE ok; In this case *map will include the chosen index
6179
bool setup_tables_and_check_access(THD *thd,
6180
Name_resolution_context *context,
6181
List<TABLE_LIST> *from_clause,
6183
TABLE_LIST **leaves,
6186
TABLE_LIST *leaves_tmp= NULL;
6187
bool first_table= true;
6189
if (setup_tables(thd, context, from_clause, tables,
6190
&leaves_tmp, select_insert))
6194
*leaves= leaves_tmp;
6196
for (; leaves_tmp; leaves_tmp= leaves_tmp->next_leaf)
6198
if (leaves_tmp->belong_to_view)
6209
Create a key_map from a list of index names
6212
get_key_map_from_key_list()
6213
map key_map to fill in
6215
index_list List of index names
6218
0 ok; In this case *map will includes the choosed index
6222
bool get_key_map_from_key_list(key_map *map, TABLE *table,
6223
List<String> *index_list)
6225
List_iterator_fast<String> it(*index_list);
6232
if (table->s->keynames.type_names == 0 ||
6233
(pos= find_type(&table->s->keynames, name->ptr(),
6234
name->length(), 1)) <=
6237
my_error(ER_KEY_DOES_NOT_EXITS, MYF(0), name->c_ptr(),
6238
table->pos_in_table_list->alias);
6242
map->set_bit(pos-1);
6249
Drops in all fields instead of current '*' field
6254
context Context for name resolution
6255
db_name Database name in case of 'database_name.table_name.*'
6256
table_name Table name in case of 'table_name.*'
6258
any_privileges 0 If we should ensure that we have SELECT privileges
6260
1 If any privilege is ok
6262
0 ok 'it' is updated to point at last inserted
6263
1 error. Error message is generated but not sent to client
6267
insert_fields(THD *thd, Name_resolution_context *context, const char *db_name,
6268
const char *table_name, List_iterator<Item> *it,
6269
bool any_privileges)
6271
Field_iterator_table_ref field_iterator;
6273
char name_buff[NAME_LEN+1];
6274
DBUG_ENTER("insert_fields");
6276
if (db_name && lower_case_table_names)
6279
convert database to lower case for comparison
6280
We can't do this in Item_field as this would change the
6281
'name' of the item which may be used in the select list
6283
strmake(name_buff, db_name, sizeof(name_buff)-1);
6284
my_casedn_str(files_charset_info, name_buff);
6291
If table names are qualified, then loop over all tables used in the query,
6292
else treat natural joins as leaves and do not iterate over their underlying
6295
for (TABLE_LIST *tables= (table_name ? context->table_list :
6296
context->first_name_resolution_table);
6298
tables= (table_name ? tables->next_local :
6299
tables->next_name_resolution_table)
6303
TABLE *table= tables->table;
6305
DBUG_ASSERT(tables->is_leaf_for_name_resolution());
6307
if ((table_name && my_strcasecmp(table_alias_charset, table_name, tables->alias)) ||
6308
(db_name && strcmp(tables->db,db_name)))
6312
Update the tables used in the query based on the referenced fields. For
6313
views and natural joins this update is performed inside the loop below.
6316
thd->used_tables|= table->map;
6319
Initialize a generic field iterator for the current table reference.
6320
Notice that it is guaranteed that this iterator will iterate over the
6321
fields of a single table reference, because 'tables' is a leaf (for
6322
name resolution purposes).
6324
field_iterator.set(tables);
6326
for (; !field_iterator.end_of_fields(); field_iterator.next())
6330
if (!(item= field_iterator.create_item(thd)))
6336
it->replace(item); /* Replace '*' with the first found item. */
6339
it->after(item); /* Add 'item' to the SELECT list. */
6341
if ((field= field_iterator.field()))
6343
/* Mark fields as used to allow storage engine to optimze access */
6344
bitmap_set_bit(field->table->read_set, field->field_index);
6347
table->covering_keys.intersect(field->part_of_key);
6348
table->merge_keys.merge(field->part_of_key);
6350
if (tables->is_natural_join)
6354
In this case we are sure that the column ref will not be created
6355
because it was already created and stored with the natural join.
6357
Natural_join_column *nj_col;
6358
if (!(nj_col= field_iterator.get_natural_column_ref()))
6360
DBUG_ASSERT(nj_col->table_field);
6361
field_table= nj_col->table_ref->table;
6364
thd->used_tables|= field_table->map;
6365
field_table->covering_keys.intersect(field->part_of_key);
6366
field_table->merge_keys.merge(field->part_of_key);
6367
field_table->used_fields++;
6372
thd->used_tables|= item->used_tables();
6373
thd->lex->current_select->cur_pos_in_select_list++;
6376
In case of stored tables, all fields are considered as used,
6377
while in the case of views, the fields considered as used are the
6378
ones marked in setup_tables during fix_fields of view columns.
6379
For NATURAL joins, used_tables is updated in the IF above.
6382
table->used_fields= table->s->fields;
6388
TODO: in the case when we skipped all columns because there was a
6389
qualified '*', and all columns were coalesced, we have to give a more
6390
meaningful message than ER_BAD_TABLE_ERROR.
6393
my_message(ER_NO_TABLES_USED, ER(ER_NO_TABLES_USED), MYF(0));
6395
my_error(ER_BAD_TABLE_ERROR, MYF(0), table_name);
6402
Fix all conditions and outer join expressions.
6407
tables list of tables for name resolving (select_lex->table_list)
6408
leaves list of leaves of join table tree (select_lex->leaf_tables)
6415
TRUE if some error occured (e.g. out of memory)
6419
int setup_conds(THD *thd, TABLE_LIST *tables, TABLE_LIST *leaves,
6422
SELECT_LEX *select_lex= thd->lex->current_select;
6423
TABLE_LIST *table= NULL; // For HP compilers
6424
void *save_thd_marker= thd->thd_marker;
6426
it_is_update set to TRUE when tables of primary SELECT_LEX (SELECT_LEX
6427
which belong to LEX, i.e. most up SELECT) will be updated by
6429
NOTE: using this condition helps to prevent call of prepare_check_option()
6430
from subquery of VIEW, because tables of subquery belongs to VIEW
6431
(see condition before prepare_check_option() call)
6433
bool save_is_item_list_lookup= select_lex->is_item_list_lookup;
6434
select_lex->is_item_list_lookup= 0;
6435
DBUG_ENTER("setup_conds");
6437
thd->mark_used_columns= MARK_COLUMNS_READ;
6438
DBUG_PRINT("info", ("thd->mark_used_columns: %d", thd->mark_used_columns));
6439
select_lex->cond_count= 0;
6440
select_lex->between_count= 0;
6441
select_lex->max_equal_elems= 0;
6443
thd->thd_marker= (void*)1;
6446
thd->where="where clause";
6447
if ((!(*conds)->fixed && (*conds)->fix_fields(thd, conds)) ||
6448
(*conds)->check_cols(1))
6451
thd->thd_marker= save_thd_marker;
6454
Apply fix_fields() to all ON clauses at all levels of nesting,
6455
including the ones inside view definitions.
6457
for (table= leaves; table; table= table->next_leaf)
6459
TABLE_LIST *embedded; /* The table at the current level of nesting. */
6460
TABLE_LIST *embedding= table; /* The parent nested table reference. */
6463
embedded= embedding;
6464
if (embedded->on_expr)
6466
/* Make a join an a expression */
6467
thd->thd_marker= (void*)embedded;
6468
thd->where="on clause";
6469
if ((!embedded->on_expr->fixed && embedded->on_expr->fix_fields(thd, &embedded->on_expr)) ||
6470
embedded->on_expr->check_cols(1))
6472
select_lex->cond_count++;
6474
embedding= embedded->embedding;
6477
embedding->nested_join->join_list.head() == embedded);
6480
thd->thd_marker= save_thd_marker;
6482
thd->lex->current_select->is_item_list_lookup= save_is_item_list_lookup;
6483
DBUG_RETURN(test(thd->is_error()));
6486
select_lex->is_item_list_lookup= save_is_item_list_lookup;
6491
/******************************************************************************
6492
** Fill a record with data (for INSERT or UPDATE)
6493
** Returns : 1 if some field has wrong type
6494
******************************************************************************/
6498
Fill fields with given items.
6503
fields Item_fields list to be filled
6504
values values to fill with
6505
ignore_errors TRUE if we should ignore errors
6508
fill_record() may set table->auto_increment_field_not_null and a
6509
caller should make sure that it is reset after their last call to this
6518
fill_record(THD * thd, List<Item> &fields, List<Item> &values, bool ignore_errors)
6520
List_iterator_fast<Item> f(fields),v(values);
6524
DBUG_ENTER("fill_record");
6527
Reset the table->auto_increment_field_not_null as it is valid for
6530
if (fields.elements)
6533
On INSERT or UPDATE fields are checked to be from the same table,
6534
thus we safely can take table from the first field.
6536
fld= (Item_field*)f++;
6537
if (!(field= fld->filed_for_view_update()))
6539
my_error(ER_NONUPDATEABLE_COLUMN, MYF(0), fld->name);
6542
table= field->field->table;
6543
table->auto_increment_field_not_null= FALSE;
6548
if (!(field= fld->filed_for_view_update()))
6550
my_error(ER_NONUPDATEABLE_COLUMN, MYF(0), fld->name);
6554
Field *rfield= field->field;
6555
table= rfield->table;
6556
if (rfield == table->next_number_field)
6557
table->auto_increment_field_not_null= TRUE;
6558
if ((value->save_in_field(rfield, 0) < 0) && !ignore_errors)
6560
my_message(ER_UNKNOWN_ERROR, ER(ER_UNKNOWN_ERROR), MYF(0));
6564
DBUG_RETURN(thd->is_error());
6567
table->auto_increment_field_not_null= FALSE;
6573
Fill field buffer with values from Field list
6578
ptr pointer on pointer to record
6579
values list of fields
6580
ignore_errors TRUE if we should ignore errors
6583
fill_record() may set table->auto_increment_field_not_null and a
6584
caller should make sure that it is reset after their last call to this
6593
fill_record(THD *thd, Field **ptr, List<Item> &values, bool ignore_errors)
6595
List_iterator_fast<Item> v(values);
6598
DBUG_ENTER("fill_record");
6602
Reset the table->auto_increment_field_not_null as it is valid for
6608
On INSERT or UPDATE fields are checked to be from the same table,
6609
thus we safely can take table from the first field.
6611
table= (*ptr)->table;
6612
table->auto_increment_field_not_null= FALSE;
6614
while ((field = *ptr++) && ! thd->is_error())
6617
table= field->table;
6618
if (field == table->next_number_field)
6619
table->auto_increment_field_not_null= TRUE;
6620
if (value->save_in_field(field, 0) < 0)
6623
DBUG_RETURN(thd->is_error());
6627
table->auto_increment_field_not_null= FALSE;
6632
my_bool mysql_rm_tmp_tables(void)
6635
char filePath[FN_REFLEN], *tmpdir, filePathCopy[FN_REFLEN];
6640
DBUG_ENTER("mysql_rm_tmp_tables");
6642
if (!(thd= new THD))
6644
thd->thread_stack= (char*) &thd;
6645
thd->store_globals();
6647
for (i=0; i<=mysql_tmpdir_list.max; i++)
6649
tmpdir=mysql_tmpdir_list.list[i];
6650
/* See if the directory exists */
6651
if (!(dirp = my_dir(tmpdir,MYF(MY_WME | MY_DONT_SORT))))
6654
/* Remove all SQLxxx tables from directory */
6656
for (idx=0 ; idx < (uint) dirp->number_off_files ; idx++)
6658
file=dirp->dir_entry+idx;
6660
/* skiping . and .. */
6661
if (file->name[0] == '.' && (!file->name[1] ||
6662
(file->name[1] == '.' && !file->name[2])))
6665
if (!bcmp((uchar*) file->name, (uchar*) tmp_file_prefix,
6666
tmp_file_prefix_length))
6668
char *ext= fn_ext(file->name);
6669
uint ext_len= strlen(ext);
6670
uint filePath_len= my_snprintf(filePath, sizeof(filePath),
6671
"%s%c%s", tmpdir, FN_LIBCHAR,
6673
if (!bcmp((uchar*) reg_ext, (uchar*) ext, ext_len))
6675
handler *handler_file= 0;
6676
/* We should cut file extention before deleting of table */
6677
memcpy(filePathCopy, filePath, filePath_len - ext_len);
6678
filePathCopy[filePath_len - ext_len]= 0;
6679
init_tmp_table_share(thd, &share, "", 0, "", filePathCopy);
6680
if (!open_table_def(thd, &share, 0) &&
6681
((handler_file= get_new_handler(&share, thd->mem_root,
6684
handler_file->ha_delete_table(filePathCopy);
6685
delete handler_file;
6687
free_table_share(&share);
6690
File can be already deleted by tmp_table.file->delete_table().
6691
So we hide error messages which happnes during deleting of these
6694
VOID(my_delete(filePath, MYF(0)));
6700
my_pthread_setspecific_ptr(THR_THD, 0);
6706
/*****************************************************************************
6707
unireg support functions
6708
*****************************************************************************/
6711
Invalidate any cache entries that are for some DB
6714
remove_db_from_cache()
6715
db Database name. This will be in lower case if
6716
lower_case_table_name is set
6719
We can't use hash_delete when looping hash_elements. We mark them first
6720
and afterwards delete those marked unused.
6723
void remove_db_from_cache(const char *db)
6725
for (uint idx=0 ; idx < open_cache.records ; idx++)
6727
TABLE *table=(TABLE*) hash_element(&open_cache,idx);
6728
if (!strcmp(table->s->db.str, db))
6730
table->s->version= 0L; /* Free when thread is ready */
6732
relink_unused(table);
6735
while (unused_tables && !unused_tables->s->version)
6736
VOID(hash_delete(&open_cache,(uchar*) unused_tables));
6741
free all unused tables
6744
This is called by 'handle_manager' when one wants to periodicly flush
6745
all not used tables.
6750
(void) pthread_mutex_lock(&LOCK_open);
6751
while (unused_tables)
6752
hash_delete(&open_cache,(uchar*) unused_tables);
6753
(void) pthread_mutex_unlock(&LOCK_open);
6758
Mark all entries with the table as deleted to force an reopen of the table
6760
The table will be closed (not stored in cache) by the current thread when
6761
close_thread_tables() is called.
6767
0 This thread now have exclusive access to this table and no other thread
6768
can access the table until close_thread_tables() is called.
6769
1 Table is in use by another thread
6772
bool remove_table_from_cache(THD *thd, const char *db, const char *table_name,
6775
char key[MAX_DBKEY_LENGTH];
6779
bool result= 0, signalled= 0;
6780
DBUG_ENTER("remove_table_from_cache");
6781
DBUG_PRINT("enter", ("table: '%s'.'%s' flags: %u", db, table_name, flags));
6783
key_length=(uint) (strmov(strmov(key,db)+1,table_name)-key)+1;
6786
HASH_SEARCH_STATE state;
6787
result= signalled= 0;
6789
for (table= (TABLE*) hash_first(&open_cache, (uchar*) key, key_length,
6792
table= (TABLE*) hash_next(&open_cache, (uchar*) key, key_length,
6796
DBUG_PRINT("tcache", ("found table: '%s'.'%s' 0x%lx", table->s->db.str,
6797
table->s->table_name.str, (long) table));
6799
table->s->version=0L; /* Free when thread is ready */
6800
if (!(in_use=table->in_use))
6802
DBUG_PRINT("info",("Table was not in use"));
6803
relink_unused(table);
6805
else if (in_use != thd)
6807
DBUG_PRINT("info", ("Table was in use by other thread"));
6809
Mark that table is going to be deleted from cache. This will
6810
force threads that are in mysql_lock_tables() (but not yet
6811
in thr_multi_lock()) to abort it's locks, close all tables and retry
6813
in_use->some_tables_deleted= 1;
6814
if (table->is_name_opened())
6816
DBUG_PRINT("info", ("Found another active instance of the table"));
6819
/* Kill delayed insert threads */
6820
if ((in_use->system_thread & SYSTEM_THREAD_DELAYED_INSERT) &&
6823
in_use->killed= THD::KILL_CONNECTION;
6824
pthread_mutex_lock(&in_use->mysys_var->mutex);
6825
if (in_use->mysys_var->current_cond)
6827
pthread_mutex_lock(in_use->mysys_var->current_mutex);
6829
pthread_cond_broadcast(in_use->mysys_var->current_cond);
6830
pthread_mutex_unlock(in_use->mysys_var->current_mutex);
6832
pthread_mutex_unlock(&in_use->mysys_var->mutex);
6835
Now we must abort all tables locks used by this thread
6836
as the thread may be waiting to get a lock for another table.
6837
Note that we need to hold LOCK_open while going through the
6838
list. So that the other thread cannot change it. The other
6839
thread must also hold LOCK_open whenever changing the
6840
open_tables list. Aborting the MERGE lock after a child was
6841
closed and before the parent is closed would be fatal.
6843
for (TABLE *thd_table= in_use->open_tables;
6845
thd_table= thd_table->next)
6847
/* Do not handle locks of MERGE children. */
6848
if (thd_table->db_stat) // If table is open
6849
signalled|= mysql_lock_abort_for_thread(thd, thd_table);
6854
DBUG_PRINT("info", ("Table was in use by current thread. db_stat: %u",
6856
result= result || (flags & RTFC_OWNED_BY_THD_FLAG);
6859
while (unused_tables && !unused_tables->s->version)
6860
VOID(hash_delete(&open_cache,(uchar*) unused_tables));
6862
DBUG_PRINT("info", ("Removing table from table_def_cache"));
6863
/* Remove table from table definition cache if it's not in use */
6864
if ((share= (TABLE_SHARE*) hash_search(&table_def_cache,(uchar*) key,
6867
DBUG_PRINT("info", ("share version: %lu ref_count: %u",
6868
share->version, share->ref_count));
6869
share->version= 0; // Mark for delete
6870
if (share->ref_count == 0)
6872
pthread_mutex_lock(&share->mutex);
6873
VOID(hash_delete(&table_def_cache, (uchar*) share));
6877
if (result && (flags & RTFC_WAIT_OTHER_THREAD_FLAG))
6880
Signal any thread waiting for tables to be freed to
6883
broadcast_refresh();
6884
DBUG_PRINT("info", ("Waiting for refresh signal"));
6885
if (!(flags & RTFC_CHECK_KILLED_FLAG) || !thd->killed)
6888
if (likely(signalled))
6889
(void) pthread_cond_wait(&COND_refresh, &LOCK_open);
6892
struct timespec abstime;
6894
It can happen that another thread has opened the
6895
table but has not yet locked any table at all. Since
6896
it can be locked waiting for a table that our thread
6897
has done LOCK TABLE x WRITE on previously, we need to
6898
ensure that the thread actually hears our signal
6899
before we go to sleep. Thus we wait for a short time
6900
and then we retry another loop in the
6901
remove_table_from_cache routine.
6903
set_timespec(abstime, 10);
6904
pthread_cond_timedwait(&COND_refresh, &LOCK_open, &abstime);
6912
DBUG_RETURN(result);
6916
bool is_equal(const LEX_STRING *a, const LEX_STRING *b)
6918
return a->length == b->length && !strncmp(a->str, b->str, a->length);
6923
Open and lock system tables for read.
6926
open_system_tables_for_read()
6928
table_list List of tables to open.
6929
backup Pointer to Open_tables_state instance where
6930
information about currently open tables will be
6931
saved, and from which will be restored when we will
6932
end work with system tables.
6935
Thanks to restrictions which we put on opening and locking of
6936
system tables for writing, we can open and lock them for reading
6937
even when we already have some other tables open and locked. One
6938
must call close_system_tables() to close systems tables opened
6947
open_system_tables_for_read(THD *thd, TABLE_LIST *table_list,
6948
Open_tables_state *backup)
6950
DBUG_ENTER("open_system_tables_for_read");
6952
thd->reset_n_backup_open_tables_state(backup);
6956
for (TABLE_LIST *tables= table_list; tables; tables= tables->next_global)
6958
TABLE *table= open_table(thd, tables, thd->mem_root, ¬_used,
6959
MYSQL_LOCK_IGNORE_FLUSH);
6963
DBUG_ASSERT(table->s->table_category == TABLE_CATEGORY_SYSTEM);
6965
table->use_all_columns();
6966
table->reginfo.lock_type= tables->lock_type;
6967
tables->table= table;
6972
TABLE **list= (TABLE**) thd->alloc(sizeof(TABLE*) * count);
6974
for (TABLE_LIST *tables= table_list; tables; tables= tables->next_global)
6975
*(ptr++)= tables->table;
6977
thd->lock= mysql_lock_tables(thd, list, count,
6978
MYSQL_LOCK_IGNORE_FLUSH, ¬_used);
6984
close_system_tables(thd, backup);
6991
Close system tables, opened with open_system_tables_for_read().
6994
close_system_tables()
6996
backup Pointer to Open_tables_state instance which holds
6997
information about tables which were open before we
6998
decided to access system tables.
7002
close_system_tables(THD *thd, Open_tables_state *backup)
7004
close_thread_tables(thd);
7005
thd->restore_backup_open_tables_state(backup);
7010
Open and lock one system table for update.
7013
open_system_table_for_update()
7015
one_table Table to open.
7018
Table opened with this call should closed using close_thread_tables().
7022
# Pointer to TABLE object of system table
7026
open_system_table_for_update(THD *thd, TABLE_LIST *one_table)
7028
DBUG_ENTER("open_system_table_for_update");
7030
TABLE *table= open_ltable(thd, one_table, one_table->lock_type, 0);
7033
DBUG_ASSERT(table->s->table_category == TABLE_CATEGORY_SYSTEM);
7034
table->use_all_columns();
7041
@} (end of group Data_Dictionary)