1
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 */
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
17
/* Basic functions needed by many modules */
18
18
#include <drizzled/server_includes.h>
23
#if TIME_WITH_SYS_TIME
24
# include <sys/time.h>
28
# include <sys/time.h>
33
#include <mysys/my_pthread.h>
19
35
#include <drizzled/sql_select.h>
20
#include <mysys/my_dir.h>
21
#include <drizzled/drizzled_error_messages.h>
23
#define FLAGSTR(S,F) ((S) & (F) ? #F " " : "")
36
#include <drizzled/error.h>
37
#include <drizzled/gettext.h>
38
#include <drizzled/nested_join.h>
39
#include <drizzled/sql_base.h>
40
#include <drizzled/show.h>
41
#include <drizzled/item/cmpfunc.h>
42
#include <drizzled/replication_services.h>
43
#include <drizzled/check_stack_overrun.h>
44
#include <drizzled/lock.h>
45
#include <drizzled/plugin/listen.h>
46
#include <mysys/cached_directory.h>
47
#include <drizzled/field/timestamp.h>
48
#include <drizzled/field/null.h>
49
#include "drizzled/memory/multi_malloc.h"
52
using namespace drizzled;
54
bool drizzle_rm_tmp_tables();
26
57
@defgroup Data_Dictionary Data Dictionary
29
TABLE *unused_tables; /* Used by mysql_test */
60
Table *unused_tables; /* Used by mysql_test */
30
61
HASH open_cache; /* Used by mysql_test */
31
static HASH table_def_cache;
32
static TABLE_SHARE *oldest_unused_share, end_of_unused_share;
33
static pthread_mutex_t LOCK_table_share;
34
static bool table_def_inited= 0;
36
static int open_unireg_entry(THD *thd, TABLE *entry, TABLE_LIST *table_list,
38
char *cache_key, uint cache_key_length,
39
MEM_ROOT *mem_root, uint flags);
40
static void free_cache_entry(TABLE *entry);
41
static void close_old_data_files(THD *thd, TABLE *table, bool morph_locks,
45
extern "C" uchar *table_cache_key(const uchar *record, size_t *length,
46
bool not_used __attribute__((unused)))
48
TABLE *entry=(TABLE*) record;
62
static int open_unireg_entry(Session *session, Table *entry, TableList *table_list,
64
char *cache_key, uint32_t cache_key_length);
67
void free_cache_entry(void *entry);
68
unsigned char *table_cache_key(const unsigned char *record,
71
unsigned char *table_def_key(const unsigned char *record,
78
unsigned char *table_cache_key(const unsigned char *record,
82
Table *entry=(Table*) record;
49
83
*length= entry->s->table_cache_key.length;
50
return (uchar*) entry->s->table_cache_key.str;
84
return (unsigned char*) entry->s->table_cache_key.str;
54
88
bool table_cache_init(void)
56
return hash_init(&open_cache, &my_charset_bin, table_cache_size+16,
57
0, 0, table_cache_key,
58
(hash_free_key) free_cache_entry, 0);
90
return hash_init(&open_cache, &my_charset_bin,
91
(size_t) table_cache_size+16,
92
0, 0, table_cache_key,
61
96
void table_cache_free(void)
65
close_cached_tables(NULL, NULL, false, false, false);
66
if (!open_cache.records) // Safety first
67
hash_free(&open_cache);
98
refresh_version++; // Force close of open tables
100
while (unused_tables)
101
hash_delete(&open_cache,(unsigned char*) unused_tables);
103
if (!open_cache.records) // Safety first
104
hash_free(&open_cache);
72
uint cached_open_tables(void)
107
uint32_t cached_open_tables(void)
74
109
return open_cache.records;
78
Create a table cache key
81
create_table_def_key()
83
key Create key here (must be of size MAX_DBKEY_LENGTH)
84
table_list Table definition
85
tmp_table Set if table is a tmp table
88
The table cache_key is created from:
92
if the table is a tmp table, we add the following to make each tmp table
95
4 bytes for master thread id
96
4 bytes pseudo thread id
102
uint create_table_def_key(THD *thd, char *key, TABLE_LIST *table_list,
105
uint key_length= (uint) (stpcpy(stpcpy(key, table_list->db)+1,
106
table_list->table_name)-key)+1;
109
int4store(key + key_length, thd->server_id);
110
int4store(key + key_length + 4, thd->variables.pseudo_thread_id);
111
key_length+= TMP_TABLE_KEY_EXTRA;
118
/*****************************************************************************
119
Functions to handle table definition cach (TABLE_SHARE)
120
*****************************************************************************/
122
extern "C" uchar *table_def_key(const uchar *record, size_t *length,
123
bool not_used __attribute__((unused)))
125
TABLE_SHARE *entry=(TABLE_SHARE*) record;
126
*length= entry->table_cache_key.length;
127
return (uchar*) entry->table_cache_key.str;
131
static void table_def_free_entry(TABLE_SHARE *share)
135
/* remove from old_unused_share list */
136
pthread_mutex_lock(&LOCK_table_share);
137
*share->prev= share->next;
138
share->next->prev= share->prev;
139
pthread_mutex_unlock(&LOCK_table_share);
141
free_table_share(share);
146
bool table_def_init(void)
149
pthread_mutex_init(&LOCK_table_share, MY_MUTEX_INIT_FAST);
150
oldest_unused_share= &end_of_unused_share;
151
end_of_unused_share.prev= &oldest_unused_share;
153
return hash_init(&table_def_cache, &my_charset_bin, table_def_size,
155
(hash_free_key) table_def_free_entry, 0);
159
void table_def_free(void)
161
if (table_def_inited)
164
pthread_mutex_destroy(&LOCK_table_share);
165
hash_free(&table_def_cache);
171
uint cached_table_definitions(void)
173
return table_def_cache.records;
178
Get TABLE_SHARE for a table.
182
table_list Table that should be opened
184
key_length Length of key
185
db_flags Flags to open_table_def():
187
error out: Error code from open_table_def()
190
Get a table definition from the table definition cache.
191
If it doesn't exist, create a new from the table definition file.
194
We must have wrlock on LOCK_open when we come here
195
(To be changed later)
202
TABLE_SHARE *get_table_share(THD *thd, TABLE_LIST *table_list, char *key,
203
uint key_length, uint db_flags, int *error)
209
/* Read table definition from cache */
210
if ((share= (TABLE_SHARE*) hash_search(&table_def_cache,(uchar*) key,
214
if (!(share= alloc_table_share(table_list, key, key_length)))
220
Lock mutex to be able to read table definition from file without
223
(void) pthread_mutex_lock(&share->mutex);
226
We assign a new table id under the protection of the LOCK_open and
227
the share's own mutex. We do this insted of creating a new mutex
228
and using it for the sole purpose of serializing accesses to a
229
static variable, we assign the table id here. We assign it to the
230
share before inserting it into the table_def_cache to be really
231
sure that it cannot be read from the cache without having a table
234
CAVEAT. This means that the table cannot be used for
235
binlogging/replication purposes, unless get_table_share() has been
236
called directly or indirectly.
238
assign_new_table_id(share);
240
if (my_hash_insert(&table_def_cache, (uchar*) share))
242
free_table_share(share);
243
return(0); // return error
245
if (open_table_def(thd, share, db_flags))
247
*error= share->error;
248
(void) hash_delete(&table_def_cache, (uchar*) share);
251
share->ref_count++; // Mark in use
252
(void) pthread_mutex_unlock(&share->mutex);
257
We found an existing table definition. Return it if we didn't get
258
an error when reading the table definition from file.
261
/* We must do a lock to ensure that the structure is initialized */
262
(void) pthread_mutex_lock(&share->mutex);
265
/* Table definition contained an error */
266
open_table_error(share, share->error, share->open_errno, share->errarg);
267
(void) pthread_mutex_unlock(&share->mutex);
271
if (!share->ref_count++ && share->prev)
274
Share was not used before and it was in the old_unused_share list
275
Unlink share from this list
277
pthread_mutex_lock(&LOCK_table_share);
278
*share->prev= share->next;
279
share->next->prev= share->prev;
282
pthread_mutex_unlock(&LOCK_table_share);
284
(void) pthread_mutex_unlock(&share->mutex);
286
/* Free cache if too big */
287
while (table_def_cache.records > table_def_size &&
288
oldest_unused_share->next)
290
pthread_mutex_lock(&oldest_unused_share->mutex);
291
VOID(hash_delete(&table_def_cache, (uchar*) oldest_unused_share));
299
Get a table share. If it didn't exist, try creating it from engine
301
For arguments and return values, see get_table_from_share()
305
*get_table_share_with_create(THD *thd, TABLE_LIST *table_list,
306
char *key, uint key_length,
307
uint db_flags, int *error)
312
share= get_table_share(thd, table_list, key, key_length, db_flags, error);
314
If share is not NULL, we found an existing share.
316
If share is NULL, and there is no error, we're inside
317
pre-locking, which silences 'ER_NO_SUCH_TABLE' errors
318
with the intention to silently drop non-existing tables
319
from the pre-locking list. In this case we still need to try
320
auto-discover before returning a NULL share.
322
If share is NULL and the error is ER_NO_SUCH_TABLE, this is
323
the same as above, only that the error was not silenced by
324
pre-locking. Once again, we need to try to auto-discover
327
Finally, if share is still NULL, it's a real error and we need
330
@todo Rework alternative ways to deal with ER_NO_SUCH TABLE.
332
if (share || (thd->is_error() && (thd->main_da.sql_errno() != ER_NO_SUCH_TABLE)))
336
/* Table didn't exist. Check if some engine can provide it */
337
if ((tmp= ha_create_table_from_engine(thd, table_list->db,
338
table_list->table_name)) < 0)
341
No such table in any engine.
342
Hide "Table doesn't exist" errors if the table belongs to a view.
343
The check for thd->is_error() is necessary to not push an
344
unwanted error in case of pre-locking, which silences
345
"no such table" errors.
346
@todo Rework the alternative ways to deal with ER_NO_SUCH TABLE.
348
if (thd->is_error() && table_list->belong_to_view)
351
my_error(ER_VIEW_INVALID, MYF(0), "", "");
357
/* Give right error message */
359
my_printf_error(ER_UNKNOWN_ERROR,
360
"Failed to open '%-.64s', error while "
361
"unpacking from engine",
362
MYF(0), table_list->table_name);
365
/* Table existed in engine. Let's open it */
366
drizzle_reset_errors(thd, 1); // Clear warnings
367
thd->clear_error(); // Clear error message
368
return(get_table_share(thd, table_list, key, key_length,
374
Mark that we are not using table share anymore.
377
release_table_share()
379
release_type How the release should be done:
381
- Release without checking
382
RELEASE_WAIT_FOR_DROP
383
- Don't return until we get a signal that the
384
table is deleted or the thread is killed.
387
If ref_count goes to zero and (we have done a refresh or if we have
388
already too many open table shares) then delete the definition.
390
If type == RELEASE_WAIT_FOR_DROP then don't return until we get a signal
391
that the table is deleted or the thread is killed.
394
void release_table_share(TABLE_SHARE *share,
395
enum release_type type __attribute__((unused)))
397
bool to_be_deleted= 0;
399
safe_mutex_assert_owner(&LOCK_open);
401
pthread_mutex_lock(&share->mutex);
402
if (!--share->ref_count)
404
if (share->version != refresh_version)
408
/* Link share last in used_table_share list */
409
assert(share->next == 0);
410
pthread_mutex_lock(&LOCK_table_share);
411
share->prev= end_of_unused_share.prev;
412
*end_of_unused_share.prev= share;
413
end_of_unused_share.prev= &share->next;
414
share->next= &end_of_unused_share;
415
pthread_mutex_unlock(&LOCK_table_share);
417
to_be_deleted= (table_def_cache.records > table_def_size);
423
hash_delete(&table_def_cache, (uchar*) share);
426
pthread_mutex_unlock(&share->mutex);
432
Check if table definition exits in cache
435
get_cached_table_share()
437
table_name Table name
441
# TABLE_SHARE for table
444
TABLE_SHARE *get_cached_table_share(const char *db, const char *table_name)
446
char key[NAME_LEN*2+2];
447
TABLE_LIST table_list;
449
safe_mutex_assert_owner(&LOCK_open);
451
table_list.db= (char*) db;
452
table_list.table_name= (char*) table_name;
453
key_length= create_table_def_key((THD*) 0, key, &table_list, 0);
454
return (TABLE_SHARE*) hash_search(&table_def_cache,(uchar*) key, key_length);
459
114
Close file handle, but leave the table in the table cache
462
close_handle_and_leave_table_as_lock()
117
close_handle_and_leave_table_as_lock()
466
By leaving the table in the table cache, it disallows any other thread
469
thd->killed will be set if we run out of memory
471
If closing a MERGE child, the calling function has to take care for
472
closing the parent too, if necessary.
121
By leaving the table in the table cache, it disallows any other thread
124
session->killed will be set if we run out of memory
126
If closing a MERGE child, the calling function has to take care for
127
closing the parent too, if necessary.
476
void close_handle_and_leave_table_as_lock(TABLE *table)
131
void close_handle_and_leave_table_as_lock(Table *table)
478
TABLE_SHARE *share, *old_share= table->s;
133
TableShare *share, *old_share= table->s;
480
135
MEM_ROOT *mem_root= &table->mem_root;
512
165
Create a list for all open tables matching SQL expression
517
wild SQL like expression
169
wild SQL like expression
520
One gets only a list of tables for which one has any kind of privilege.
521
db and table names are allocated in result struct, so one doesn't need
522
a lock on LOCK_open when traversing the return list.
172
One gets only a list of tables for which one has any kind of privilege.
173
db and table names are allocated in result struct, so one doesn't need
174
a lock on LOCK_open when traversing the return list.
525
NULL Error (Probably OOM)
526
# Pointer to list of names of open tables.
529
OPEN_TABLE_LIST *list_open_tables(THD *thd __attribute__((unused)),
530
const char *db, const char *wild)
180
bool list_open_tables(const char *db, const char *wild, bool(*func)(Table *table, open_table_list_st& open_list), Table *display)
533
OPEN_TABLE_LIST **start_list, *open_list;
534
TABLE_LIST table_list;
536
VOID(pthread_mutex_lock(&LOCK_open));
537
memset(&table_list, 0, sizeof(table_list));
538
start_list= &open_list;
541
for (uint idx=0 ; result == 0 && idx < open_cache.records; idx++)
182
vector<open_table_list_st> open_list;
183
vector<open_table_list_st>::iterator it;
184
open_table_list_st table;
186
/* What we really need is an optimization for knowing unique tables */
188
open_list.reserve(sizeof(open_table_list_st) * (open_cache.records % 2));
190
open_list.reserve(sizeof(open_table_list_st) * open_cache.records);
192
pthread_mutex_lock(&LOCK_open); /* List all open tables */
194
for (uint32_t idx= 0; idx < open_cache.records; idx++)
543
OPEN_TABLE_LIST *table;
544
TABLE *entry=(TABLE*) hash_element(&open_cache,idx);
545
TABLE_SHARE *share= entry->s;
547
if (db && my_strcasecmp(system_charset_info, db, share->db.str))
549
if (wild && wild_compare(share->table_name.str, wild, 0))
552
/* Check if user has SELECT privilege for any column in the table */
553
table_list.db= share->db.str;
554
table_list.table_name= share->table_name.str;
556
/* need to check if we haven't already listed it */
557
for (table= open_list ; table ; table=table->next)
197
Table *entry=(Table*) hash_element(&open_cache,idx);
199
if (db && my_strcasecmp(system_charset_info, db, entry->s->db.str))
201
if (wild && wild_compare(entry->s->table_name.str, wild, 0))
204
for (it= open_list.begin(); it < open_list.end(); it++)
559
if (!strcmp(table->table, share->table_name.str) &&
560
!strcmp(table->db, share->db.str))
206
if (!(*it).table.compare(entry->s->table_name.str) &&
207
!(*it).db.compare(entry->s->db.str))
564
if (entry->locked_by_name)
211
if (entry->locked_by_name)
571
if (!(*start_list = (OPEN_TABLE_LIST *)
572
sql_alloc(sizeof(**start_list)+share->table_cache_key.length)))
574
open_list=0; // Out of memory
577
stpcpy((*start_list)->table=
578
stpcpy(((*start_list)->db= (char*) ((*start_list)+1)),
580
share->table_name.str);
581
(*start_list)->in_use= entry->in_use ? 1 : 0;
582
(*start_list)->locked= entry->locked_by_name ? 1 : 0;
583
start_list= &(*start_list)->next;
586
VOID(pthread_mutex_unlock(&LOCK_open));
223
table.db= entry->s->db.str;
224
table.table= entry->s->table_name.str;
225
open_list.push_back(table);
227
pthread_mutex_unlock(&LOCK_open);
229
for (it= open_list.begin(); it < open_list.end(); it++)
231
if (func(display, *it))
590
238
/*****************************************************************************
810
441
table->s->version= refresh_version;
814
VOID(pthread_mutex_unlock(&LOCK_open));
445
pthread_mutex_unlock(&LOCK_open);
815
447
if (wait_for_refresh)
817
pthread_mutex_lock(&thd->mysys_var->mutex);
818
thd->mysys_var->current_mutex= 0;
819
thd->mysys_var->current_cond= 0;
820
thd_proc_info(thd, 0);
821
pthread_mutex_unlock(&thd->mysys_var->mutex);
828
Close all tables which match specified connection string or
829
if specified string is NULL, then any table with a connection string.
832
bool close_cached_connection_tables(THD *thd, bool if_wait_for_refresh,
833
LEX_STRING *connection, bool have_lock)
836
TABLE_LIST tmp, *tables= NULL;
840
memset(&tmp, 0, sizeof(TABLE_LIST));
843
VOID(pthread_mutex_lock(&LOCK_open));
845
for (idx= 0; idx < table_def_cache.records; idx++)
847
TABLE_SHARE *share= (TABLE_SHARE *) hash_element(&table_def_cache, idx);
849
/* Ignore if table is not open or does not have a connect_string */
850
if (!share->connect_string.length || !share->ref_count)
853
/* Compare the connection string */
855
(connection->length > share->connect_string.length ||
856
(connection->length < share->connect_string.length &&
857
(share->connect_string.str[connection->length] != '/' &&
858
share->connect_string.str[connection->length] != '\\')) ||
859
strncasecmp(connection->str, share->connect_string.str,
860
connection->length)))
863
/* close_cached_tables() only uses these elements */
864
tmp.db= share->db.str;
865
tmp.table_name= share->table_name.str;
866
tmp.next_local= tables;
868
tables= (TABLE_LIST *) memdup_root(thd->mem_root, (char*)&tmp,
873
result= close_cached_tables(thd, tables, true, false, false);
876
VOID(pthread_mutex_unlock(&LOCK_open));
878
if (if_wait_for_refresh)
880
pthread_mutex_lock(&thd->mysys_var->mutex);
881
thd->mysys_var->current_mutex= 0;
882
thd->mysys_var->current_cond= 0;
884
pthread_mutex_unlock(&thd->mysys_var->mutex);
892
Mark all temporary tables which were used by the current statement or
893
substatement as free for reuse, but only if the query_id can be cleared.
895
@param thd thread context
897
@remark For temp tables associated with a open SQL HANDLER the query_id
898
is not reset until the HANDLER is closed.
901
static void mark_temp_tables_as_free_for_reuse(THD *thd)
903
for (TABLE *table= thd->temporary_tables ; table ; table= table->next)
905
if ((table->query_id == thd->query_id) && ! table->open_by_handler)
908
table->file->ha_reset();
915
Mark all tables in the list which were used by current substatement
919
mark_used_tables_as_free_for_reuse()
921
table - head of the list of tables
924
Marks all tables in the list which were used by current substatement
925
(they are marked by its query_id) as free for reuse.
928
The reason we reset query_id is that it's not enough to just test
929
if table->query_id != thd->query_id to know if a table is in use.
932
SELECT f1_that_uses_t1() FROM t1;
933
In f1_that_uses_t1() we will see one instance of t1 where query_id is
934
set to query_id of original query.
937
static void mark_used_tables_as_free_for_reuse(THD *thd, TABLE *table)
939
for (; table ; table= table->next)
941
if (table->query_id == thd->query_id)
944
table->file->ha_reset();
951
Auxiliary function to close all tables in the open_tables list.
953
@param thd Thread context.
955
@remark It should not ordinarily be called directly.
958
static void close_open_tables(THD *thd)
960
bool found_old_table= 0;
962
safe_mutex_assert_not_owner(&LOCK_open);
964
VOID(pthread_mutex_lock(&LOCK_open));
966
while (thd->open_tables)
967
found_old_table|= close_thread_table(thd, &thd->open_tables);
968
thd->some_tables_deleted= 0;
970
/* Free tables to hold down open files */
971
while (open_cache.records > table_cache_size && unused_tables)
972
VOID(hash_delete(&open_cache,(uchar*) unused_tables)); /* purecov: tested */
975
/* Tell threads waiting for refresh that something has happened */
979
VOID(pthread_mutex_unlock(&LOCK_open));
984
Close all tables used by the current substatement, or all tables
985
used by this thread if we are on the upper level.
988
close_thread_tables()
992
Unlocks tables and frees derived tables.
993
Put all normal tables used by thread in free list.
995
It will only close/mark as free for reuse tables opened by this
996
substatement, it will also check if we are closing tables after
997
execution of complete query (i.e. we are on upper level) and will
998
leave prelocked mode if needed.
1001
void close_thread_tables(THD *thd)
1006
We are assuming here that thd->derived_tables contains ONLY derived
1007
tables for this substatement. i.e. instead of approach which uses
1008
query_id matching for determining which of the derived tables belong
1009
to this substatement we rely on the ability of substatements to
1010
save/restore thd->derived_tables during their execution.
1012
TODO: Probably even better approach is to simply associate list of
1013
derived tables with (sub-)statement instead of thread and destroy
1014
them at the end of its execution.
1016
if (thd->derived_tables)
1020
Close all derived tables generated in queries like
1021
SELECT * FROM (SELECT * FROM t1)
1023
for (table= thd->derived_tables ; table ; table= next)
1026
free_tmp_table(thd, table);
1028
thd->derived_tables= 0;
1032
Mark all temporary tables used by this statement as free for reuse.
1034
mark_temp_tables_as_free_for_reuse(thd);
1036
Let us commit transaction for statement. Since in 5.0 we only have
1037
one statement transaction and don't allow several nested statement
1038
transactions this call will do nothing if we are inside of stored
1039
function or trigger (i.e. statement transaction is already active and
1040
does not belong to statement for which we do close_thread_tables()).
1041
TODO: This should be fixed in later releases.
1043
if (!(thd->state_flags & Open_tables_state::BACKUPS_AVAIL))
1045
thd->main_da.can_overwrite_status= true;
1046
ha_autocommit_or_rollback(thd, thd->is_error());
1047
thd->main_da.can_overwrite_status= false;
1048
thd->transaction.stmt.reset();
1051
if (thd->locked_tables)
1054
/* Ensure we are calling ha_reset() for all used tables */
1055
mark_used_tables_as_free_for_reuse(thd, thd->open_tables);
1058
We are under simple LOCK TABLES so should not do anything else.
1066
For RBR we flush the pending event just before we unlock all the
1067
tables. This means that we are at the end of a topmost
1068
statement, so we ensure that the STMT_END_F flag is set on the
1069
pending event. For statements that are *inside* stored
1070
functions, the pending event will not be flushed: that will be
1071
handled either before writing a query log event (inside
1072
binlog_query()) or when preparing a pending event.
1074
thd->binlog_flush_pending_rows_event(true);
1075
mysql_unlock_tables(thd, thd->lock);
1079
Note that we need to hold LOCK_open while changing the
1080
open_tables list. Another thread may work on it.
1081
(See: remove_table_from_cache(), mysql_wait_completed_table())
1082
Closing a MERGE child before the parent would be fatal if the
1083
other thread tries to abort the MERGE lock in between.
1085
if (thd->open_tables)
1086
close_open_tables(thd);
1092
/* move one table to free list */
1094
bool close_thread_table(THD *thd, TABLE **table_ptr)
1096
bool found_old_table= 0;
1097
TABLE *table= *table_ptr;
449
pthread_mutex_lock(&session->mysys_var->mutex);
450
session->mysys_var->current_mutex= 0;
451
session->mysys_var->current_cond= 0;
452
session->set_proc_info(0);
453
pthread_mutex_unlock(&session->mysys_var->mutex);
461
move one table to free list
464
bool Session::free_cached_table()
466
bool found_old_table= false;
467
Table *table= open_tables;
469
safe_mutex_assert_owner(&LOCK_open);
1099
470
assert(table->key_read == 0);
1100
471
assert(!table->file || table->file->inited == handler::NONE);
1102
*table_ptr=table->next;
473
open_tables= table->next;
1104
475
if (table->needs_reopen_or_name_lock() ||
1105
thd->version != refresh_version || !table->db_stat)
476
version != refresh_version || !table->db_stat)
1107
VOID(hash_delete(&open_cache,(uchar*) table));
478
hash_delete(&open_cache,(unsigned char*) table);
479
found_old_table= true;
1113
Open placeholders have TABLE::db_stat set to 0, so they should be
484
Open placeholders have Table::db_stat set to 0, so they should be
1114
485
handled by the first alternative.
1116
487
assert(!table->open_placeholder);
1118
489
/* Free memory and reset for next loop */
1119
490
table->file->ha_reset();
491
table->in_use= false;
1121
493
if (unused_tables)
1123
table->next=unused_tables; /* Link in last */
1124
table->prev=unused_tables->prev;
1125
unused_tables->prev=table;
1126
table->prev->next=table;
495
table->next= unused_tables; /* Link in last */
496
table->prev= unused_tables->prev;
497
unused_tables->prev= table;
498
table->prev->next= table;
1129
unused_tables=table->next=table->prev=table;
501
unused_tables= table->next=table->prev=table;
1131
return(found_old_table);
1135
/* close_temporary_tables' internal, 4 is due to uint4korr definition */
1136
static inline uint tmpkeyval(THD *thd __attribute__((unused)),
1139
return uint4korr(table->s->table_cache_key.str + table->s->table_cache_key.length - 4);
1144
Close all temporary tables created by 'CREATE TEMPORARY TABLE' for thread
1145
creates one DROP TEMPORARY TABLE binlog event for each pseudo-thread
504
return found_old_table;
509
Auxiliary function to close all tables in the open_tables list.
511
@param session Thread context.
513
@remark It should not ordinarily be called directly.
1148
void close_temporary_tables(THD *thd)
516
void Session::close_open_tables()
1153
/* Assume thd->options has OPTION_QUOTE_SHOW_CREATE */
1154
bool was_quote_show= true;
1156
if (!thd->temporary_tables)
1159
if (!mysql_bin_log.is_open() || thd->current_stmt_binlog_row_based)
1162
for (table= thd->temporary_tables; table; table= tmp_next)
1164
tmp_next= table->next;
1165
close_temporary(table, 1, 1);
1167
thd->temporary_tables= 0;
1171
/* Better add "if exists", in case a RESET MASTER has been done */
1172
const char stub[]= "DROP /*!40005 TEMPORARY */ TABLE IF EXISTS ";
1173
uint stub_len= sizeof(stub) - 1;
1175
String s_query= String(buf, sizeof(buf), system_charset_info);
1176
bool found_user_tables= false;
1178
memcpy(buf, stub, stub_len);
1181
Insertion sort of temp tables by pseudo_thread_id to build ordered list
1182
of sublists of equal pseudo_thread_id
1185
for (prev_table= thd->temporary_tables, table= prev_table->next;
1187
prev_table= table, table= table->next)
1189
TABLE *prev_sorted /* same as for prev_table */, *sorted;
1190
if (is_user_table(table))
1192
if (!found_user_tables)
1193
found_user_tables= true;
1194
for (prev_sorted= NULL, sorted= thd->temporary_tables; sorted != table;
1195
prev_sorted= sorted, sorted= sorted->next)
1197
if (!is_user_table(sorted) ||
1198
tmpkeyval(thd, sorted) > tmpkeyval(thd, table))
1200
/* move into the sorted part of the list from the unsorted */
1201
prev_table->next= table->next;
1202
table->next= sorted;
1205
prev_sorted->next= table;
1209
thd->temporary_tables= table;
1218
/* We always quote db,table names though it is slight overkill */
1219
if (found_user_tables &&
1220
!(was_quote_show= test(thd->options & OPTION_QUOTE_SHOW_CREATE)))
1222
thd->options |= OPTION_QUOTE_SHOW_CREATE;
1225
/* scan sorted tmps to generate sequence of DROP */
1226
for (table= thd->temporary_tables; table; table= next)
1228
if (is_user_table(table))
1230
my_thread_id save_pseudo_thread_id= thd->variables.pseudo_thread_id;
1231
/* Set pseudo_thread_id to be that of the processed table */
1232
thd->variables.pseudo_thread_id= tmpkeyval(thd, table);
1234
Loop forward through all tables within the sublist of
1235
common pseudo_thread_id to create single DROP query.
1237
for (s_query.length(stub_len);
1238
table && is_user_table(table) &&
1239
tmpkeyval(thd, table) == thd->variables.pseudo_thread_id;
1243
We are going to add 4 ` around the db/table names and possible more
1244
due to special characters in the names
1246
append_identifier(thd, &s_query, table->s->db.str, strlen(table->s->db.str));
1247
s_query.append('.');
1248
append_identifier(thd, &s_query, table->s->table_name.str,
1249
strlen(table->s->table_name.str));
1250
s_query.append(',');
1252
close_temporary(table, 1, 1);
1255
const CHARSET_INFO * const cs_save= thd->variables.character_set_client;
1256
thd->variables.character_set_client= system_charset_info;
1257
Query_log_event qinfo(thd, s_query.ptr(),
1258
s_query.length() - 1 /* to remove trailing ',' */,
1260
thd->variables.character_set_client= cs_save;
1262
Imagine the thread had created a temp table, then was doing a
1263
SELECT, and the SELECT was killed. Then it's not clever to
1264
mark the statement above as "killed", because it's not really
1265
a statement updating data, and there are 99.99% chances it
1266
will succeed on slave. If a real update (one updating a
1267
persistent table) was killed on the master, then this real
1268
update will be logged with error_code=killed, rightfully
1269
causing the slave to stop.
1271
qinfo.error_code= 0;
1272
mysql_bin_log.write(&qinfo);
1273
thd->variables.pseudo_thread_id= save_pseudo_thread_id;
1278
close_temporary(table, 1, 1);
1281
if (!was_quote_show)
1282
thd->options&= ~OPTION_QUOTE_SHOW_CREATE; /* restore option */
1283
thd->temporary_tables=0;
518
bool found_old_table= false;
520
safe_mutex_assert_not_owner(&LOCK_open);
522
pthread_mutex_lock(&LOCK_open); /* Close all open tables on Session */
525
found_old_table|= free_cached_table();
526
some_tables_deleted= false;
530
/* Tell threads waiting for refresh that something has happened */
534
pthread_mutex_unlock(&LOCK_open);
1287
538
Find table in list.
1290
find_table_in_list()
1291
table Pointer to table list
1292
offset Offset to which list in table structure to use
1293
db_name Data base name
1294
table_name Table name
1297
This is called by find_table_in_local_list() and
1298
find_table_in_global_list().
1301
NULL Table not found
1302
# Pointer to found table.
542
table Pointer to table list
543
offset Offset to which list in table structure to use
544
db_name Data base name
545
table_name Table name
548
This is called by find_table_in_global_list().
552
# Pointer to found table.
1305
TABLE_LIST *find_table_in_list(TABLE_LIST *table,
1306
TABLE_LIST *TABLE_LIST::*link,
1307
const char *db_name,
1308
const char *table_name)
555
TableList *find_table_in_list(TableList *table,
556
TableList *TableList::*link,
558
const char *table_name)
1310
560
for (; table; table= table->*link )
1322
572
Test that table is unique (It's only exists once in the table list)
1327
table table which should be checked
1328
table_list list of tables
1329
check_alias whether to check tables' aliases
1331
NOTE: to exclude derived tables from check we use following mechanism:
1332
a) during derived table processing set THD::derived_tables_processing
1333
b) JOIN::prepare set SELECT::exclude_from_table_unique_test if
1334
THD::derived_tables_processing set. (we can't use JOIN::execute
1335
because for PS we perform only JOIN::prepare, but we can't set this
1336
flag in JOIN::prepare if we are not sure that we are in derived table
1337
processing loop, because multi-update call fix_fields() for some its
1338
items (which mean JOIN::prepare for subqueries) before unique_table
1339
call to detect which tables should be locked for write).
1340
c) unique_table skip all tables which belong to SELECT with
1341
SELECT::exclude_from_table_unique_test set.
1342
Also SELECT::exclude_from_table_unique_test used to exclude from check
1343
tables of main SELECT of multi-delete and multi-update
1345
We also skip tables with TABLE_LIST::prelocking_placeholder set,
1346
because we want to allow SELECTs from them, and their modification
1347
will rise the error anyway.
1349
TODO: when we will have table/view change detection we can do this check
1354
0 if table is unique
576
session thread handle
577
table table which should be checked
578
table_list list of tables
579
check_alias whether to check tables' aliases
581
NOTE: to exclude derived tables from check we use following mechanism:
582
a) during derived table processing set Session::derived_tables_processing
583
b) JOIN::prepare set SELECT::exclude_from_table_unique_test if
584
Session::derived_tables_processing set. (we can't use JOIN::execute
585
because for PS we perform only JOIN::prepare, but we can't set this
586
flag in JOIN::prepare if we are not sure that we are in derived table
587
processing loop, because multi-update call fix_fields() for some its
588
items (which mean JOIN::prepare for subqueries) before unique_table
589
call to detect which tables should be locked for write).
590
c) unique_table skip all tables which belong to SELECT with
591
SELECT::exclude_from_table_unique_test set.
592
Also SELECT::exclude_from_table_unique_test used to exclude from check
593
tables of main SELECT of multi-delete and multi-update
595
We also skip tables with TableList::prelocking_placeholder set,
596
because we want to allow SELECTs from them, and their modification
597
will rise the error anyway.
599
TODO: when we will have table/view change detection we can do this check
1357
TABLE_LIST* unique_table(THD *thd, TABLE_LIST *table, TABLE_LIST *table_list,
607
TableList* unique_table(Session *session, TableList *table, TableList *table_list,
1361
611
const char *d_name, *t_name, *t_alias;
1364
614
If this function called for query which update table (INSERT/UPDATE/...)
1365
then we have in table->table pointer to TABLE object which we are
1366
updating even if it is VIEW so we need TABLE_LIST of this TABLE object
615
then we have in table->table pointer to Table object which we are
616
updating even if it is VIEW so we need TableList of this Table object
1367
617
to get right names (even if lower_case_table_names used).
1369
619
If this function called for CREATE command that we have not opened table
1370
(table->table equal to 0) and right names is in current TABLE_LIST
620
(table->table equal to 0) and right names is in current TableList
1373
623
if (table->table)
1375
625
/* temporary table is always unique */
1376
626
if (table->table && table->table->s->tmp_table != NO_TMP_TABLE)
1378
628
table= table->find_underlying_table(table->table);
1380
as far as we have table->table we have to find real TABLE_LIST of
630
as far as we have table->table we have to find real TableList of
1381
631
it in underlying tables
1411
Issue correct error message in case we found 2 duplicate tables which
1412
prevent some update operation
1415
update_non_unique_table_error()
1416
update table which we try to update
1417
operation name of update operation
1418
duplicate duplicate table which we found
1421
here we hide view underlying tables if we have them
1424
void update_non_unique_table_error(TABLE_LIST *update,
1425
const char *operation __attribute__((unused)),
1426
TABLE_LIST *duplicate __attribute__((unused)))
1428
my_error(ER_UPDATE_TABLE_USED, MYF(0), update->alias);
1432
TABLE *find_temporary_table(THD *thd, const char *db, const char *table_name)
1434
TABLE_LIST table_list;
1436
table_list.db= (char*) db;
1437
table_list.table_name= (char*) table_name;
1438
return find_temporary_table(thd, &table_list);
1442
TABLE *find_temporary_table(THD *thd, TABLE_LIST *table_list)
658
Table *Session::find_temporary_table(const char *new_db, const char *table_name)
1444
660
char key[MAX_DBKEY_LENGTH];
1445
661
uint key_length;
1448
key_length= create_table_def_key(thd, key, table_list, 1);
1449
for (table=thd->temporary_tables ; table ; table= table->next)
664
key_length= TableShare::createKey(key, new_db, table_name);
666
for (table= temporary_tables ; table ; table= table->next)
1451
668
if (table->s->table_cache_key.length == key_length &&
1452
!memcmp(table->s->table_cache_key.str, key, key_length))
669
!memcmp(table->s->table_cache_key.str, key, key_length))
1455
return(0); // Not a temporary table
672
return NULL; // Not a temporary table
675
Table *Session::find_temporary_table(TableList *table_list)
677
return find_temporary_table(table_list->db, table_list->table_name);
1460
682
Drop a temporary table.
1462
Try to locate the table in the list of thd->temporary_tables.
684
Try to locate the table in the list of session->temporary_tables.
1463
685
If the table is found:
1464
- if the table is being used by some outer statement, fail.
1465
- if the table is in thd->locked_tables, unlock it and
1466
remove it from the list of locked tables. Currently only transactional
1467
temporary tables are present in the locked_tables list.
1468
- Close the temporary table, remove its .FRM
1469
- remove the table from the list of temporary tables
686
- if the table is being used by some outer statement, fail.
687
- if the table is in session->locked_tables, unlock it and
688
remove it from the list of locked tables. Currently only transactional
689
temporary tables are present in the locked_tables list.
690
- Close the temporary table, remove its .FRM
691
- remove the table from the list of temporary tables
1471
693
This function is used to drop user temporary tables, as well as
1472
694
internal tables created in CREATE TEMPORARY TABLE ... SELECT
1473
or ALTER TABLE. Even though part of the work done by this function
695
or ALTER Table. Even though part of the work done by this function
1474
696
is redundant when the table is internal, as long as we
1475
697
link both internal and user temporary tables into the same
1476
thd->temporary_tables list, it's impossible to tell here whether
698
session->temporary_tables list, it's impossible to tell here whether
1477
699
we're dealing with an internal or a user temporary table.
1479
701
@retval 0 the table was found and dropped successfully.
1480
702
@retval 1 the table was not found in the list of temporary tables
1482
704
@retval -1 the table is in use by a outer query
1485
int drop_temporary_table(THD *thd, TABLE_LIST *table_list)
707
int Session::drop_temporary_table(TableList *table_list)
1489
if (!(table= find_temporary_table(thd, table_list)))
711
if (!(table= find_temporary_table(table_list)))
1492
714
/* Table might be in use by some outer statement. */
1493
if (table->query_id && table->query_id != thd->query_id)
715
if (table->query_id && table->query_id != query_id)
1495
717
my_error(ER_CANT_REOPEN_TABLE, MYF(0), table->alias);
1500
If LOCK TABLES list is not empty and contains this table,
1501
unlock the table and remove the table from this list.
1503
mysql_lock_remove(thd, thd->locked_tables, table, false);
1504
close_temporary_table(thd, table, 1, 1);
1509
unlink from thd->temporary tables and close temporary table
1512
void close_temporary_table(THD *thd, TABLE *table,
1513
bool free_share, bool delete_table)
1517
table->prev->next= table->next;
1518
if (table->prev->next)
1519
table->next->prev= table->prev;
1523
/* removing the item from the list */
1524
assert(table == thd->temporary_tables);
1526
slave must reset its temporary list pointer to zero to exclude
1527
passing non-zero value to end_slave via rli->save_temporary_tables
1528
when no temp tables opened, see an invariant below.
1530
thd->temporary_tables= table->next;
1531
if (thd->temporary_tables)
1532
table->next->prev= 0;
1534
if (thd->slave_thread)
1536
/* natural invariant of temporary_tables */
1537
assert(slave_open_temp_tables || !thd->temporary_tables);
1538
slave_open_temp_tables--;
1540
close_temporary(table, free_share, delete_table);
1546
Close and delete a temporary table
1549
This dosn't unlink table from thd->temporary
1550
If this is needed, use close_temporary_table()
1553
void close_temporary(TABLE *table, bool free_share, bool delete_table)
1555
handlerton *table_type= table->s->db_type();
1557
free_io_cache(table);
1560
Check that temporary table has not been created with
1561
frm_only because it has then not been created in any storage engine
1564
rm_temporary_table(table_type, table->s->path.str,
1565
table->s->tmp_table == TMP_TABLE_FRM_FILE_ONLY);
1568
free_table_share(table->s);
1569
my_free((char*) table,MYF(0));
1576
Used by ALTER TABLE when the table is a temporary one. It changes something
1577
only if the ALTER contained a RENAME clause (otherwise, table_name is the old
1579
Prepares a table cache key, which is the concatenation of db, table_name and
1580
thd->slave_proxy_id, separated by '\0'.
1583
bool rename_temporary_table(THD* thd, TABLE *table, const char *db,
1584
const char *table_name)
1588
TABLE_SHARE *share= table->s;
1589
TABLE_LIST table_list;
1591
if (!(key=(char*) alloc_root(&share->mem_root, MAX_DBKEY_LENGTH)))
1592
return(1); /* purecov: inspected */
1594
table_list.db= (char*) db;
1595
table_list.table_name= (char*) table_name;
1596
key_length= create_table_def_key(thd, key, &table_list, 1);
1597
share->set_table_cache_key(key, key_length);
1602
/* move table first in unused links */
1604
static void relink_unused(TABLE *table)
721
close_temporary_table(table, true, true);
727
/* move table first in unused links */
729
static void relink_unused(Table *table)
1606
731
if (table != unused_tables)
1672
787
// Notify any 'refresh' threads
1673
788
broadcast_refresh();
1679
Auxiliary routine which closes and drops open table.
1681
@param thd Thread handle
1682
@param table TABLE object for table to be dropped
1683
@param db_name Name of database for this table
1684
@param table_name Name of this table
1686
@note This routine assumes that table to be closed is open only
1687
by calling thread so we needn't wait until other threads
1688
will close the table. Also unless called under implicit or
1689
explicit LOCK TABLES mode it assumes that table to be
1690
dropped is already unlocked. In the former case it will
1691
also remove lock on the table. But one should not rely on
1692
this behaviour as it may change in future.
1693
Currently, however, this function is never called for a
1694
table that was locked with LOCK TABLES.
793
Auxiliary routine which closes and drops open table.
795
@param session Thread handle
796
@param table Table object for table to be dropped
797
@param db_name Name of database for this table
798
@param table_name Name of this table
800
@note This routine assumes that table to be closed is open only
801
by calling thread so we needn't wait until other threads
802
will close the table. Also unless called under implicit or
803
explicit LOCK TABLES mode it assumes that table to be
804
dropped is already unlocked. In the former case it will
805
also remove lock on the table. But one should not rely on
806
this behaviour as it may change in future.
807
Currently, however, this function is never called for a
808
table that was locked with LOCK TABLES.
1697
void drop_open_table(THD *thd, TABLE *table, const char *db_name,
1698
const char *table_name)
811
void Session::drop_open_table(Table *table, const char *db_name,
812
const char *table_name)
1700
814
if (table->s->tmp_table)
1701
close_temporary_table(thd, table, 1, 1);
815
close_temporary_table(table, true, true);
1704
handlerton *table_type= table->s->db_type();
1705
VOID(pthread_mutex_lock(&LOCK_open));
818
plugin::StorageEngine *table_type= table->s->db_type();
819
pthread_mutex_lock(&LOCK_open); /* Close and drop a table (AUX routine) */
1707
821
unlink_open_table() also tells threads waiting for refresh or close
1708
822
that something has happened.
1710
unlink_open_table(thd, table, false);
1711
quick_rm_table(table_type, db_name, table_name, 0);
1712
VOID(pthread_mutex_unlock(&LOCK_open));
824
unlink_open_table(table);
825
quick_rm_table(table_type, db_name, table_name, false);
826
pthread_mutex_unlock(&LOCK_open);
1718
Wait for condition but allow the user to send a kill to mysqld
832
Wait for condition but allow the user to send a kill to mysqld
1721
wait_for_condition()
1723
mutex mutex that is currently hold that is associated with condition
1724
Will be unlocked on return
1725
cond Condition to wait for
836
session Thread handler
837
mutex mutex that is currently hold that is associated with condition
838
Will be unlocked on return
839
cond Condition to wait for
1728
void wait_for_condition(THD *thd, pthread_mutex_t *mutex, pthread_cond_t *cond)
842
void Session::wait_for_condition(pthread_mutex_t *mutex, pthread_cond_t *cond)
1730
844
/* Wait until the current table is up to date */
1731
const char *proc_info;
1732
thd->mysys_var->current_mutex= mutex;
1733
thd->mysys_var->current_cond= cond;
1734
proc_info=thd->proc_info;
1735
thd_proc_info(thd, "Waiting for table");
845
const char *saved_proc_info;
846
mysys_var->current_mutex= mutex;
847
mysys_var->current_cond= cond;
848
saved_proc_info= get_proc_info();
849
set_proc_info("Waiting for table");
1737
851
(void) pthread_cond_wait(cond, mutex);
1852
932
before we will get table-level lock on this table.
1854
934
share->version=0;
1855
table->in_use = thd;
935
table->in_use = this;
1859
table->next= thd->open_tables;
1860
thd->open_tables= table;
939
table->next= open_tables;
1865
TABLE object should be already in THD::open_tables list so we just
1866
need to set TABLE::next correctly.
945
Table object should be already in Session::open_tables list so we just
946
need to set Table::next correctly.
1868
948
table->next= orig_table.next;
1871
table->tablenr=thd->current_tablenr++;
1872
table->used_fields=0;
1873
table->const_table=0;
951
table->tablenr= current_tablenr++;
952
table->used_fields= 0;
953
table->const_table= 0;
1874
954
table->null_row= false;
1875
955
table->maybe_null= false;
1876
956
table->force_index= false;
1877
table->status=STATUS_NO_RECORD;
957
table->status= STATUS_NO_RECORD;
1883
Create and insert into table cache placeholder for table
1884
which will prevent its opening (or creation) (a.k.a lock
1887
@param thd Thread context
1888
@param key Table cache key for name to be locked
1889
@param key_length Table cache key length
1891
@return Pointer to TABLE object used for name locking or 0 in
964
Create and insert into table cache placeholder for table
965
which will prevent its opening (or creation) (a.k.a lock
968
@param session Thread context
969
@param key Table cache key for name to be locked
970
@param key_length Table cache key length
972
@return Pointer to Table object used for name locking or 0 in
1895
TABLE *table_cache_insert_placeholder(THD *thd, const char *key,
976
Table *Session::table_cache_insert_placeholder(const char *key, uint32_t key_length)
1902
982
safe_mutex_assert_owner(&LOCK_open);
1905
985
Create a table entry with the right key and with an old refresh version
1906
Note that we must use my_multi_malloc() here as this is freed by the
986
Note that we must use multi_malloc() here as this is freed by the
1909
if (!my_multi_malloc(MYF(MY_WME | MY_ZEROFILL),
1910
&table, sizeof(*table),
1911
&share, sizeof(*share),
1912
&key_buff, key_length,
989
if (! memory::multi_malloc(true,
990
&table, sizeof(*table),
991
&share, sizeof(*share),
992
&key_buff, key_length,
1916
996
table->s= share;
1917
997
share->set_table_cache_key(key_buff, key, key_length);
1918
998
share->tmp_table= INTERNAL_TMP_TABLE; // for intern_close_table
1920
1000
table->locked_by_name=1;
1922
if (my_hash_insert(&open_cache, (uchar*)table))
1002
if (my_hash_insert(&open_cache, (unsigned char*)table))
1924
my_free((uchar*) table, MYF(0));
1004
free((unsigned char*) table);
1933
Obtain an exclusive name lock on the table if it is not cached
1936
@param thd Thread context
1937
@param db Name of database
1938
@param table_name Name of table
1939
@param[out] table Out parameter which is either:
1940
- set to NULL if table cache contains record for
1942
- set to point to the TABLE instance used for
1945
@note This function takes into account all records for table in table
1946
cache, even placeholders used for name-locking. This means that
1947
'table' parameter can be set to NULL for some situations when
1948
table does not really exist.
1950
@retval true Error occured (OOM)
1951
@retval false Success. 'table' parameter set according to above rules.
1013
Obtain an exclusive name lock on the table if it is not cached
1016
@param session Thread context
1017
@param db Name of database
1018
@param table_name Name of table
1019
@param[out] table Out parameter which is either:
1020
- set to NULL if table cache contains record for
1022
- set to point to the Table instance used for
1025
@note This function takes into account all records for table in table
1026
cache, even placeholders used for name-locking. This means that
1027
'table' parameter can be set to NULL for some situations when
1028
table does not really exist.
1030
@retval true Error occured (OOM)
1031
@retval false Success. 'table' parameter set according to above rules.
1954
bool lock_table_name_if_not_cached(THD *thd, const char *db,
1955
const char *table_name, TABLE **table)
1034
bool Session::lock_table_name_if_not_cached(const char *new_db,
1035
const char *table_name, Table **table)
1957
1037
char key[MAX_DBKEY_LENGTH];
1960
key_length= (uint)(stpcpy(stpcpy(key, db) + 1, table_name) - key) + 1;
1961
VOID(pthread_mutex_lock(&LOCK_open));
1963
if (hash_search(&open_cache, (uchar *)key, key_length))
1039
uint32_t key_length;
1041
key_pos= strcpy(key_pos, new_db) + strlen(new_db);
1042
key_pos= strcpy(key_pos+1, table_name) + strlen(table_name);
1043
key_length= (uint32_t) (key_pos-key)+1;
1045
pthread_mutex_lock(&LOCK_open); /* Obtain a name lock even though table is not in cache (like for create table) */
1047
if (hash_search(&open_cache, (unsigned char *)key, key_length))
1965
VOID(pthread_mutex_unlock(&LOCK_open));
1049
pthread_mutex_unlock(&LOCK_open);
1969
if (!(*table= table_cache_insert_placeholder(thd, key, key_length)))
1971
VOID(pthread_mutex_unlock(&LOCK_open));
1974
(*table)->open_placeholder= 1;
1975
(*table)->next= thd->open_tables;
1976
thd->open_tables= *table;
1977
VOID(pthread_mutex_unlock(&LOCK_open));
1983
Check that table exists in table definition cache, on disk
1984
or in some storage engine.
1986
@param thd Thread context
1987
@param table Table list element
1988
@param[out] exists Out parameter which is set to true if table
1989
exists and to false otherwise.
1991
@note This function assumes that caller owns LOCK_open mutex.
1992
It also assumes that the fact that there are no name-locks
1993
on the table was checked beforehand.
1995
@note If there is no .FRM file for the table but it exists in one
1996
of engines (e.g. it was created on another node of NDB cluster)
1997
this function will fetch and create proper .FRM file for it.
1999
@retval true Some error occured
2000
@retval false No error. 'exists' out parameter set accordingly.
2003
bool check_if_table_exists(THD *thd, TABLE_LIST *table, bool *exists)
2005
char path[FN_REFLEN];
2008
safe_mutex_assert_owner(&LOCK_open);
2012
if (get_cached_table_share(table->db, table->table_name))
2015
build_table_filename(path, sizeof(path) - 1, table->db, table->table_name,
2018
if (!access(path, F_OK))
2021
/* .FRM file doesn't exist. Check if some engine can provide it. */
2023
rc= ha_create_table_from_engine(thd, table->db, table->table_name);
2027
/* Table does not exists in engines as well. */
2033
/* Table exists in some engine and .FRM for it was created. */
2038
my_printf_error(ER_UNKNOWN_ERROR, "Failed to open '%-.64s', error while "
2039
"unpacking from engine", MYF(0), table->table_name);
1053
if (!(*table= table_cache_insert_placeholder(key, key_length)))
1055
pthread_mutex_unlock(&LOCK_open);
1058
(*table)->open_placeholder= true;
1059
(*table)->next= open_tables;
1060
open_tables= *table;
1061
pthread_mutex_unlock(&LOCK_open);
2051
table_list Open first table in list.
2052
refresh INOUT Pointer to memory that will be set to 1 if
2053
we need to close all tables and reopen them.
2054
If this is a NULL pointer, then the table is not
2055
put in the thread-open-list.
2056
flags Bitmap of flags to modify how open works:
2057
DRIZZLE_LOCK_IGNORE_FLUSH - Open table even if
2058
someone has done a flush or namelock on it.
2059
No version number checking is done.
2060
DRIZZLE_OPEN_TEMPORARY_ONLY - Open only temporary
2061
table not the base table or view.
1071
session Thread context.
1072
table_list Open first table in list.
1073
refresh INOUT Pointer to memory that will be set to 1 if
1074
we need to close all tables and reopen them.
1075
If this is a NULL pointer, then the table is not
1076
put in the thread-open-list.
1077
flags Bitmap of flags to modify how open works:
1078
DRIZZLE_LOCK_IGNORE_FLUSH - Open table even if
1079
someone has done a flush or namelock on it.
1080
No version number checking is done.
1081
DRIZZLE_OPEN_TEMPORARY_ONLY - Open only temporary
1082
table not the base table or view.
2064
Uses a cache of open tables to find a table not in use.
1085
Uses a cache of open tables to find a table not in use.
2066
If table list element for the table to be opened has "create" flag
2067
set and table does not exist, this function will automatically insert
2068
a placeholder for exclusive name lock into the open tables cache and
2069
will return the TABLE instance that corresponds to this placeholder.
1087
If table list element for the table to be opened has "create" flag
1088
set and table does not exist, this function will automatically insert
1089
a placeholder for exclusive name lock into the open tables cache and
1090
will return the Table instance that corresponds to this placeholder.
2072
NULL Open failed. If refresh is set then one should close
2073
all other tables and retry the open.
2074
# Success. Pointer to TABLE object for open table.
1093
NULL Open failed. If refresh is set then one should close
1094
all other tables and retry the open.
1095
# Success. Pointer to Table object for open table.
2078
TABLE *open_table(THD *thd, TABLE_LIST *table_list, MEM_ROOT *mem_root,
2079
bool *refresh, uint flags)
1099
Table *Session::openTable(TableList *table_list, bool *refresh, uint32_t flags)
2081
register TABLE *table;
1101
register Table *table;
2082
1102
char key[MAX_DBKEY_LENGTH];
2083
1103
unsigned int key_length;
2084
char *alias= table_list->alias;
1104
const char *alias= table_list->alias;
2085
1105
HASH_SEARCH_STATE state;
2087
/* Parsing of partitioning information from .frm needs thd->lex set up. */
2088
assert(thd->lex->is_lex_started);
1107
/* Parsing of partitioning information from .frm needs session->lex set up. */
1108
assert(lex->is_lex_started);
2090
1110
/* find a unused table in the open table cache */
2094
1114
/* an open table operation needs a lot of the stack space */
2095
if (check_stack_overrun(thd, STACK_MIN_SIZE_FOR_OPEN, (uchar *)&alias))
2101
key_length= (create_table_def_key(thd, key, table_list, 1) -
2102
TMP_TABLE_KEY_EXTRA);
1115
if (check_stack_overrun(this, STACK_MIN_SIZE_FOR_OPEN, (unsigned char *)&alias))
1121
key_length= table_list->create_table_def_key(key);
2105
1124
Unless requested otherwise, try to resolve this table in the list
2106
1125
of temporary tables of this thread. In MySQL temporary tables
2107
1126
are always thread-local and "shadow" possible base tables with the
2108
1127
same name. This block implements the behaviour.
2109
TODO: move this block into a separate function.
1128
TODO -> move this block into a separate function.
1130
for (table= temporary_tables; table ; table=table->next)
2112
for (table= thd->temporary_tables; table ; table=table->next)
1132
if (table->s->table_cache_key.length == key_length && !memcmp(table->s->table_cache_key.str, key, key_length))
2114
if (table->s->table_cache_key.length == key_length +
2115
TMP_TABLE_KEY_EXTRA &&
2116
!memcmp(table->s->table_cache_key.str, key,
2117
key_length + TMP_TABLE_KEY_EXTRA))
1135
We're trying to use the same temporary table twice in a query.
1136
Right now we don't support this because a temporary table
1137
is always represented by only one Table object in Session, and
1138
it can not be cloned. Emit an error for an unsupported behaviour.
1140
if (table->query_id)
2120
We're trying to use the same temporary table twice in a query.
2121
Right now we don't support this because a temporary table
2122
is always represented by only one TABLE object in THD, and
2123
it can not be cloned. Emit an error for an unsupported behaviour.
2125
if (table->query_id)
2127
my_error(ER_CANT_REOPEN_TABLE, MYF(0), table->alias);
2130
table->query_id= thd->query_id;
2131
thd->thread_specific_used= true;
1142
my_error(ER_CANT_REOPEN_TABLE, MYF(0), table->alias);
1145
table->query_id= query_id;
2137
1150
if (flags & DRIZZLE_OPEN_TEMPORARY_ONLY)
2139
1152
my_error(ER_NO_SUCH_TABLE, MYF(0), table_list->db, table_list->table_name);
2144
The table is not temporary - if we're in pre-locked or LOCK TABLES
2145
mode, let's try to find the requested table in the list of pre-opened
2146
and locked tables. If the table is not there, return an error - we can't
2147
open not pre-opened tables in pre-locked/LOCK TABLES mode.
2148
TODO: move this block into a separate function.
2150
if (thd->locked_tables)
2151
{ // Using table locks
2152
TABLE *best_table= 0;
2153
int best_distance= INT_MIN;
2154
bool check_if_used= false;
2155
for (table=thd->open_tables; table ; table=table->next)
2157
if (table->s->table_cache_key.length == key_length &&
2158
!memcmp(table->s->table_cache_key.str, key, key_length))
2160
if (check_if_used && table->query_id &&
2161
table->query_id != thd->query_id)
2164
If we are in stored function or trigger we should ensure that
2165
we won't change table that is already used by calling statement.
2166
So if we are opening table for writing, we should check that it
2167
is not already open by some calling stamement.
2169
my_error(ER_CANT_UPDATE_USED_TABLE_IN_SF_OR_TRG, MYF(0),
2170
table->s->table_name.str);
2174
When looking for a usable TABLE, ignore MERGE children, as they
2175
belong to their parent and cannot be used explicitly.
2177
if (!my_strcasecmp(system_charset_info, table->alias, alias) &&
2178
table->query_id != thd->query_id) /* skip tables already used */
2180
int distance= ((int) table->reginfo.lock_type -
2181
(int) table_list->lock_type);
2183
Find a table that either has the exact lock type requested,
2184
or has the best suitable lock. In case there is no locked
2185
table that has an equal or higher lock than requested,
2186
we us the closest matching lock to be able to produce an error
2187
message about wrong lock mode on the table. The best_table
2188
is changed if bd < 0 <= d or bd < d < 0 or 0 <= d < bd.
2190
distance < 0 - No suitable lock found
2191
distance > 0 - we have lock mode higher then we require
2192
distance == 0 - we have lock mode exactly which we need
2194
if ((best_distance < 0 && distance > best_distance) || (distance >= 0 && distance < best_distance))
2196
best_distance= distance;
2198
if (best_distance == 0 && !check_if_used)
2201
If we have found perfect match and we don't need to check that
2202
table is not used by one of calling statements (assuming that
2203
we are inside of function or trigger) we can finish iterating
2204
through open tables list.
2215
table->query_id= thd->query_id;
2219
No table in the locked tables list. In case of explicit LOCK TABLES
2220
this can happen if a user did not include the able into the list.
2221
In case of pre-locked mode locked tables list is generated automatically,
2222
so we may only end up here if the table did not exist when
2223
locked tables list was created.
2225
my_error(ER_TABLE_NOT_LOCKED, MYF(0), alias);
1157
If it's the first table from a list of tables used in a query,
1158
remember refresh_version (the version of open_cache state).
1159
If the version changes while we're opening the remaining tables,
1160
we will have to back off, close all the tables opened-so-far,
1161
and try to reopen them.
1163
Note-> refresh_version is currently changed only during FLUSH TABLES.
1166
version= refresh_version;
1167
else if ((version != refresh_version) &&
1168
! (flags & DRIZZLE_LOCK_IGNORE_FLUSH))
1170
/* Someone did a refresh while thread was opening tables */
1178
Before we test the global cache, we test our local session cache.
1182
assert(false); /* Not implemented yet */
2348
1270
If 'old' table we met is in use by current thread we return
2349
1271
without waiting since in this situation it's this thread
2350
1272
which is responsible for broadcasting on COND_refresh
2351
(and this was done already in close_old_data_files()).
1273
(and this was done already in Session::close_old_data_files()).
2352
1274
Good example of such situation is when we have statement
2353
1275
that needs two instances of table and FLUSH TABLES comes
2354
1276
after we open first instance but before we open second
2357
if (table->in_use != thd)
1279
if (table->in_use != this)
2359
1281
/* wait_for_conditionwill unlock LOCK_open for us */
2360
wait_for_condition(thd, &LOCK_open, &COND_refresh);
1282
wait_for_condition(&LOCK_open, &COND_refresh);
2364
VOID(pthread_mutex_unlock(&LOCK_open));
1286
pthread_mutex_unlock(&LOCK_open);
2367
1289
There is a refresh in progress for this table.
2368
1290
Signal the caller that it has to try again.
2377
1299
/* Unlink the table from "unused_tables" list. */
2378
1300
if (table == unused_tables)
2380
unused_tables=unused_tables->next; // Remove from link
1302
unused_tables=unused_tables->next; // Remove from link
2381
1303
if (table == unused_tables)
1304
unused_tables= NULL;
2384
table->prev->next=table->next; /* Remove from unused list */
1306
table->prev->next=table->next; /* Remove from unused list */
2385
1307
table->next->prev=table->prev;
1308
table->in_use= this;
2390
/* Insert a new TABLE instance into the open cache */
1312
/* Insert a new Table instance into the open cache */
2392
1314
/* Free cache if too big */
2393
1315
while (open_cache.records > table_cache_size && unused_tables)
2394
VOID(hash_delete(&open_cache,(uchar*) unused_tables)); /* purecov: tested */
1316
hash_delete(&open_cache,(unsigned char*) unused_tables);
2396
1318
if (table_list->create)
2400
if (check_if_table_exists(thd, table_list, &exists))
2402
VOID(pthread_mutex_unlock(&LOCK_open));
1320
char path[FN_REFLEN];
1323
length= build_table_filename(path, sizeof(path),
1324
table_list->db, table_list->table_name,
1327
if (plugin::StorageEngine::getTableProto(path, NULL) != EEXIST)
2409
1330
Table to be created, so we need to create placeholder in table-cache.
2411
if (!(table= table_cache_insert_placeholder(thd, key, key_length)))
1332
if (!(table= table_cache_insert_placeholder(key, key_length)))
2413
VOID(pthread_mutex_unlock(&LOCK_open));
1334
pthread_mutex_unlock(&LOCK_open);
2417
1338
Link placeholder to the open tables list so it will be automatically
2418
1339
removed once tables are closed. Also mark it so it won't be ignored
2419
1340
by other trying to take name-lock.
2421
table->open_placeholder= 1;
2422
table->next= thd->open_tables;
2423
thd->open_tables= table;
2424
VOID(pthread_mutex_unlock(&LOCK_open));
1342
table->open_placeholder= true;
1343
table->next= open_tables;
1345
pthread_mutex_unlock(&LOCK_open);
2427
1349
/* Table exists. Let us try to open it. */
2430
1352
/* make a new table */
2431
if (!(table=(TABLE*) my_malloc(sizeof(*table),MYF(MY_WME))))
1353
table= (Table *)malloc(sizeof(Table));
2433
VOID(pthread_mutex_unlock(&LOCK_open));
1356
pthread_mutex_unlock(&LOCK_open);
2437
error= open_unireg_entry(thd, table, table_list, alias, key, key_length,
2438
mem_root, (flags & OPEN_VIEW_NO_PARSE));
2439
/* Combine the follow two */
2442
my_free((uchar*)table, MYF(0));
2443
VOID(pthread_mutex_unlock(&LOCK_open));
2448
my_free((uchar*)table, MYF(0));
2449
VOID(pthread_mutex_unlock(&LOCK_open));
2452
VOID(my_hash_insert(&open_cache,(uchar*) table));
1360
error= open_unireg_entry(this, table, table_list, alias, key, key_length);
1364
pthread_mutex_unlock(&LOCK_open);
1367
my_hash_insert(&open_cache, (unsigned char*) table);
2455
VOID(pthread_mutex_unlock(&LOCK_open));
1370
pthread_mutex_unlock(&LOCK_open);
2458
table->next=thd->open_tables; /* Link into simple list */
2459
thd->open_tables=table;
1373
table->next= open_tables; /* Link into simple list */
2461
table->reginfo.lock_type=TL_READ; /* Assume read */
1376
table->reginfo.lock_type= TL_READ; /* Assume read */
2464
1379
assert(table->s->ref_count > 0 || table->s->tmp_table != NO_TMP_TABLE);
2466
if (thd->lex->need_correct_ident())
1381
if (lex->need_correct_ident())
2467
1382
table->alias_name_used= my_strcasecmp(table_alias_charset,
2468
1383
table->s->table_name.str, alias);
2469
1384
/* Fix alias if table name changes */
2470
1385
if (strcmp(table->alias, alias))
2472
uint length=(uint) strlen(alias)+1;
2473
table->alias= (char*) my_realloc((char*) table->alias, length,
1387
uint32_t length=(uint32_t) strlen(alias)+1;
1388
table->alias= (char*) realloc((char*) table->alias, length);
2475
1389
memcpy((void*) table->alias, alias, length);
2477
1392
/* These variables are also set in reopen_table() */
2478
table->tablenr=thd->current_tablenr++;
2479
table->used_fields=0;
2480
table->const_table=0;
1393
table->tablenr= current_tablenr++;
1394
table->used_fields= 0;
1395
table->const_table= 0;
2481
1396
table->null_row= false;
2482
1397
table->maybe_null= false;
2483
1398
table->force_index= false;
2594
1491
for (part=0 ; part < table->key_info[key].usable_key_parts ; part++)
2595
1492
table->key_info[key].key_part[part].field->table= table;
2598
Do not attach MERGE children here. The children might be reopened
2599
after the parent. Attach children after reopening all tables that
2600
require reopen. See for example reopen_tables().
2603
1495
broadcast_refresh();
2612
Close all instances of a table open by this thread and replace
2613
them with exclusive name-locks.
2615
@param thd Thread context
2616
@param db Database name for the table to be closed
2617
@param table_name Name of the table to be closed
2619
@note This function assumes that if we are not under LOCK TABLES,
2620
then there is only one table open and locked. This means that
2621
the function probably has to be adjusted before it can be used
2622
anywhere outside ALTER TABLE.
2624
@note Must not use TABLE_SHARE::table_name/db of the table being closed,
2625
the strings are used in a loop even after the share may be freed.
1504
Close all instances of a table open by this thread and replace
1505
them with exclusive name-locks.
1507
@param session Thread context
1508
@param db Database name for the table to be closed
1509
@param table_name Name of the table to be closed
1511
@note This function assumes that if we are not under LOCK TABLES,
1512
then there is only one table open and locked. This means that
1513
the function probably has to be adjusted before it can be used
1514
anywhere outside ALTER Table.
1516
@note Must not use TableShare::table_name/db of the table being closed,
1517
the strings are used in a loop even after the share may be freed.
2628
void close_data_files_and_morph_locks(THD *thd, const char *db,
2629
const char *table_name)
1520
void Session::close_data_files_and_morph_locks(const char *new_db, const char *new_table_name)
2633
safe_mutex_assert_owner(&LOCK_open);
1524
safe_mutex_assert_owner(&LOCK_open); /* Adjust locks at the end of ALTER TABLEL */
2638
1529
If we are not under LOCK TABLES we should have only one table
2639
1530
open and locked so it makes sense to remove the lock at once.
2641
mysql_unlock_tables(thd, thd->lock);
1532
mysql_unlock_tables(this, lock);
2646
1537
Note that open table list may contain a name-lock placeholder
2647
for target table name if we process ALTER TABLE ... RENAME.
1538
for target table name if we process ALTER Table ... RENAME.
2648
1539
So loop below makes sense even if we are not under LOCK TABLES.
2650
for (table=thd->open_tables; table ; table=table->next)
1541
for (table= open_tables; table ; table=table->next)
2652
if (!strcmp(table->s->table_name.str, table_name) &&
2653
!strcmp(table->s->db.str, db))
1543
if (!strcmp(table->s->table_name.str, new_table_name) &&
1544
!strcmp(table->s->db.str, new_db))
2655
if (thd->locked_tables)
2657
mysql_lock_remove(thd, thd->locked_tables, table, true);
2659
table->open_placeholder= 1;
1546
table->open_placeholder= true;
2660
1547
close_handle_and_leave_table_as_lock(table);
2668
Reopen all tables with closed data files.
2670
@param thd Thread context
2671
@param get_locks Should we get locks after reopening tables ?
2672
@param mark_share_as_old Mark share as old to protect from a impending
2675
@note Since this function can't properly handle prelocking and
2676
create placeholders it should be used in very special
2677
situations like FLUSH TABLES or ALTER TABLE. In general
2678
case one should just repeat open_tables()/lock_tables()
2679
combination when one needs tables to be reopened (for
2680
example see open_and_lock_tables()).
2682
@note One should have lock on LOCK_open when calling this.
2684
@return false in case of success, true - otherwise.
1554
Reopen all tables with closed data files.
1556
@param session Thread context
1557
@param get_locks Should we get locks after reopening tables ?
1558
@param mark_share_as_old Mark share as old to protect from a impending
1561
@note Since this function can't properly handle prelocking and
1562
create placeholders it should be used in very special
1563
situations like FLUSH TABLES or ALTER Table. In general
1564
case one should just repeat open_tables()/lock_tables()
1565
combination when one needs tables to be reopened (for
1566
example see openTablesLock()).
1568
@note One should have lock on LOCK_open when calling this.
1570
@return false in case of success, true - otherwise.
2687
bool reopen_tables(THD *thd, bool get_locks, bool mark_share_as_old)
1573
bool Session::reopen_tables(bool get_locks, bool mark_share_as_old)
2689
TABLE *table,*next,**prev;
2690
TABLE **tables,**tables_ptr; // For locks
1575
Table *table,*next,**prev;
1576
Table **tables,**tables_ptr; // For locks
2691
1577
bool error=0, not_used;
2692
const uint flags= DRIZZLE_LOCK_NOTIFY_IF_NEED_REOPEN |
2693
DRIZZLE_LOCK_IGNORE_GLOBAL_READ_LOCK |
2694
DRIZZLE_LOCK_IGNORE_FLUSH;
1578
const uint32_t flags= DRIZZLE_LOCK_NOTIFY_IF_NEED_REOPEN |
1579
DRIZZLE_LOCK_IGNORE_GLOBAL_READ_LOCK |
1580
DRIZZLE_LOCK_IGNORE_FLUSH;
2696
if (!thd->open_tables)
1582
if (open_tables == NULL)
2699
1585
safe_mutex_assert_owner(&LOCK_open);
2999
1888
broadcast_refresh();
3000
if (thd->locked_tables && thd->locked_tables->table_count == 0)
3002
my_free((uchar*) thd->locked_tables,MYF(0));
3003
thd->locked_tables=0;
3010
If we have the table open, which only happens when a LOCK TABLE has been
1895
If we have the table open, which only happens when a LOCK Table has been
3011
1896
done on the table, change the lock type to a lock that will abort all
3012
1897
other threads trying to get the lock.
3015
void abort_locked_tables(THD *thd,const char *db, const char *table_name)
1900
void abort_locked_tables(Session *session,const char *db, const char *table_name)
3018
for (table= thd->open_tables; table ; table= table->next)
1903
for (table= session->open_tables; table ; table= table->next)
3020
1905
if (!strcmp(table->s->table_name.str, table_name) &&
3021
!strcmp(table->s->db.str, db))
1906
!strcmp(table->s->db.str, db))
3023
1908
/* If MERGE child, forward lock handling to parent. */
3024
mysql_lock_abort(thd, table, true);
1909
mysql_lock_abort(session, table);
3032
Function to assign a new table map id to a table share.
3036
share - Pointer to table share structure
3040
We are intentionally not checking that share->mutex is locked
3041
since this function should only be called when opening a table
3042
share and before it is entered into the table_def_cache (meaning
3043
that it cannot be fetched by another thread, even accidentally).
3048
The LOCK_open mutex is locked
3052
share->table_map_id is given a value that with a high certainty is
3053
not used by any other table (the only case where a table id can be
3054
reused is on wrap-around, which means more than 4 billion table
3055
share opens have been executed while one table was open all the
3058
share->table_map_id is not ~0UL.
3060
void assign_new_table_id(TABLE_SHARE *share)
3062
static ulong last_table_id= ~0UL;
3065
assert(share != NULL);
3066
safe_mutex_assert_owner(&LOCK_open);
3068
ulong tid= ++last_table_id; /* get next id */
3070
There is one reserved number that cannot be used. Remember to
3071
change this when 6-byte global table id's are introduced.
3073
if (unlikely(tid == ~0UL))
3074
tid= ++last_table_id;
3075
share->table_map_id= tid;
3077
/* Post conditions */
3078
assert(share->table_map_id != ~0UL);
3084
1916
Load a table definition from file and open unireg table
3089
entry Store open table definition here
3090
table_list TABLE_LIST with db, table_name & belong_to_view
3092
cache_key Key for share_cache
3093
cache_key_length length of cache_key
3094
mem_root temporary mem_root for parsing
3095
flags the OPEN_VIEW_NO_PARSE flag to be passed to
3096
openfrm()/open_new_frm()
1920
session Thread handle
1921
entry Store open table definition here
1922
table_list TableList with db, table_name
1924
cache_key Key for share_cache
1925
cache_key_length length of cache_key
3099
Extra argument for open is taken from thd->open_options
3100
One must have a lock on LOCK_open when calling this function
1928
Extra argument for open is taken from session->open_options
1929
One must have a lock on LOCK_open when calling this function
3107
static int open_unireg_entry(THD *thd, TABLE *entry, TABLE_LIST *table_list,
1936
static int open_unireg_entry(Session *session, Table *entry, TableList *table_list,
3108
1937
const char *alias,
3109
char *cache_key, uint cache_key_length,
3110
MEM_ROOT *mem_root __attribute__((unused)),
3111
uint flags __attribute__((unused)))
1938
char *cache_key, uint32_t cache_key_length)
3115
uint discover_retry_count= 0;
1942
uint32_t discover_retry_count= 0;
3117
1944
safe_mutex_assert_owner(&LOCK_open);
3119
if (!(share= get_table_share_with_create(thd, table_list, cache_key,
3122
table_list->i_s_requested_object,
1946
if (!(share= TableShare::getShare(session, table_list, cache_key,
1948
table_list->i_s_requested_object,
3126
while ((error= open_table_from_share(thd, share, alias,
3127
(uint) (HA_OPEN_KEYFILE |
3131
(READ_KEYINFO | COMPUTE_TYPES |
3133
thd->open_options, entry, OTM_OPEN)))
1952
while ((error= open_table_from_share(session, share, alias,
1953
(uint32_t) (HA_OPEN_KEYFILE |
1958
session->open_options, entry, OTM_OPEN)))
3135
1960
if (error == 7) // Table def changed
3375
2191
result= -1; // Fatal error
3378
if (tables->lock_type != TL_UNLOCK && ! thd->locked_tables)
2194
if (tables->lock_type != TL_UNLOCK)
3380
2196
if (tables->lock_type == TL_WRITE_DEFAULT)
3381
tables->table->reginfo.lock_type= thd->update_lock_default;
2197
tables->table->reginfo.lock_type= update_lock_default;
3382
2198
else if (tables->table->s->tmp_table == NO_TMP_TABLE)
3383
2199
tables->table->reginfo.lock_type= tables->lock_type;
3387
thd_proc_info(thd, 0);
3388
free_root(&new_frm_mem, MYF(0)); // Free pre-alloced block
3390
2205
if (result && tables)
3393
2208
Some functions determine success as (tables->table != NULL).
3394
tables->table is in thd->open_tables. It won't go lost. If the
3395
error happens on a MERGE child, clear the parents TABLE reference.
2209
tables->table is in session->open_tables.
3397
if (tables->parent_l)
3398
tables->parent_l->table= NULL;
3399
2211
tables->table= NULL;
3401
2214
return(result);
3406
Check that lock is ok for tables; Call start stmt if ok
3409
check_lock_and_start_stmt()
3411
table_list Table to check
3412
lock_type Lock used for table
3419
static bool check_lock_and_start_stmt(THD *thd, TABLE *table,
3420
thr_lock_type lock_type)
3424
if ((int) lock_type >= (int) TL_WRITE_ALLOW_READ &&
3425
(int) table->reginfo.lock_type < (int) TL_WRITE_ALLOW_READ)
3427
my_error(ER_TABLE_NOT_LOCKED_FOR_WRITE, MYF(0),table->alias);
3430
if ((error=table->file->start_stmt(thd, lock_type)))
3432
table->file->print_error(error,MYF(0));
3440
@brief Open and lock one table
3442
@param[in] thd thread handle
3443
@param[in] table_l table to open is first table in this list
3444
@param[in] lock_type lock to use for table
3447
@retval != NULL OK, opened table returned
3451
If ok, the following are also set:
3452
table_list->lock_type lock_type
3453
table_list->table table
3456
If table_l is a list, not a single table, the list is temporarily
3460
This function is meant as a replacement for open_ltable() when
3461
MERGE tables can be opened. open_ltable() cannot open MERGE tables.
3463
There may be more differences between open_n_lock_single_table() and
3464
open_ltable(). One known difference is that open_ltable() does
3465
neither call decide_logging_format() nor handle some other logging
3466
and locking issues because it does not call lock_tables().
3469
TABLE *open_n_lock_single_table(THD *thd, TABLE_LIST *table_l,
3470
thr_lock_type lock_type)
3472
TABLE_LIST *save_next_global;
3474
/* Remember old 'next' pointer. */
3475
save_next_global= table_l->next_global;
3477
table_l->next_global= NULL;
3479
/* Set requested lock type. */
3480
table_l->lock_type= lock_type;
3481
/* Allow to open real tables only. */
3482
table_l->required_type= FRMTYPE_TABLE;
3484
/* Open the table. */
3485
if (simple_open_n_lock_tables(thd, table_l))
3486
table_l->table= NULL; /* Just to be sure. */
3489
table_l->next_global= save_next_global;
3491
return(table_l->table);
3496
2219
Open and lock one table
3501
table_list Table to open is first table in this list
3502
lock_type Lock to use for open
3503
lock_flags Flags passed to mysql_lock_table
2223
session Thread handler
2224
table_list Table to open is first table in this list
2225
lock_type Lock to use for open
2226
lock_flags Flags passed to mysql_lock_table
3506
This function don't do anything like SP/SF/views/triggers analysis done
3507
in open_tables(). It is intended for opening of only one concrete table.
3508
And used only in special contexts.
2229
This function don't do anything like SP/SF/views/triggers analysis done
2230
in open_tables(). It is intended for opening of only one concrete table.
2231
And used only in special contexts.
3514
If ok, the following are also set:
3515
table_list->lock_type lock_type
3516
table_list->table table
2237
If ok, the following are also set:
2238
table_list->lock_type lock_type
2239
table_list->table table
3519
TABLE *open_ltable(THD *thd, TABLE_LIST *table_list, thr_lock_type lock_type,
2242
Table *Session::openTableLock(TableList *table_list, thr_lock_type lock_type)
3525
thd_proc_info(thd, "Opening table");
3526
thd->current_tablenr= 0;
3527
/* open_ltable can be used only for BASIC TABLEs */
3528
table_list->required_type= FRMTYPE_TABLE;
3529
while (!(table= open_table(thd, table_list, thd->mem_root, &refresh, 0)) &&
2247
set_proc_info("Opening table");
2249
while (!(table= openTable(table_list, &refresh)) &&
3535
2255
table_list->lock_type= lock_type;
3536
2256
table_list->table= table;
3537
if (thd->locked_tables)
3539
if (check_lock_and_start_stmt(thd, table, lock_type))
3544
assert(thd->lock == 0); // You must lock everything at once
3545
if ((table->reginfo.lock_type= lock_type) != TL_UNLOCK)
3546
if (! (thd->lock= mysql_lock_tables(thd, &table_list->table, 1,
3547
lock_flags, &refresh)))
3552
thd_proc_info(thd, 0);
3558
Open all tables in list, locks them and optionally process derived tables.
3561
open_and_lock_tables_derived()
3562
thd - thread handler
3563
tables - list of tables for open&locking
3564
derived - if to handle derived tables
3571
The lock will automaticaly be freed by close_thread_tables()
3574
There are two convenience functions:
3575
- simple_open_n_lock_tables(thd, tables) without derived handling
3576
- open_and_lock_tables(thd, tables) with derived handling
3577
Both inline functions call open_and_lock_tables_derived() with
3578
the third argument set appropriately.
3581
int open_and_lock_tables_derived(THD *thd, TABLE_LIST *tables, bool derived)
3588
if (open_tables(thd, &tables, &counter, 0))
3591
if (!lock_tables(thd, tables, counter, &need_reopen))
3595
close_tables_for_reopen(thd, &tables);
3598
(mysql_handle_derived(thd->lex, &mysql_derived_prepare) ||
3599
(thd->fill_derived_tables() &&
3600
mysql_handle_derived(thd->lex, &mysql_derived_filling))))
3601
return(true); /* purecov: inspected */
3607
Open all tables in list and process derived tables
3610
open_normal_and_derived_tables
3611
thd - thread handler
3612
tables - list of tables for open
3613
flags - bitmap of flags to modify how the tables will be open:
3614
DRIZZLE_LOCK_IGNORE_FLUSH - open table even if someone has
3615
done a flush or namelock on it.
3622
This is to be used on prepare stage when you don't read any
3623
data from the tables.
3626
bool open_normal_and_derived_tables(THD *thd, TABLE_LIST *tables, uint flags)
3629
assert(!thd->fill_derived_tables());
3630
if (open_tables(thd, &tables, &counter, flags) ||
3631
mysql_handle_derived(thd->lex, &mysql_derived_prepare))
3632
return(true); /* purecov: inspected */
3638
Decide on logging format to use for the statement.
3640
Compute the capabilities vector for the involved storage engines
3641
and mask out the flags for the binary log. Right now, the binlog
3642
flags only include the capabilities of the storage engines, so this
3645
We now have three alternatives that prevent the statement from
3648
1. If there are no capabilities left (all flags are clear) it is
3649
not possible to log the statement at all, so we roll back the
3650
statement and report an error.
3652
2. Statement mode is set, but the capabilities indicate that
3653
statement format is not possible.
3655
3. Row mode is set, but the capabilities indicate that row
3656
format is not possible.
3658
4. Statement is unsafe, but the capabilities indicate that row
3659
format is not possible.
3661
If we are in MIXED mode, we then decide what logging format to use:
3663
1. If the statement is unsafe, row-based logging is used.
3665
2. If statement-based logging is not possible, row-based logging is
3668
3. Otherwise, statement-based logging is used.
3670
@param thd Client thread
3671
@param tables Tables involved in the query
3674
int decide_logging_format(THD *thd, TABLE_LIST *tables)
3676
if (mysql_bin_log.is_open() && (thd->options & OPTION_BIN_LOG))
3678
handler::Table_flags flags_some_set= handler::Table_flags();
3679
handler::Table_flags flags_all_set= ~handler::Table_flags();
3680
bool multi_engine= false;
3681
void* prev_ht= NULL;
3682
for (TABLE_LIST *table= tables; table; table= table->next_global)
3684
if (!table->placeholder() && table->lock_type >= TL_WRITE_ALLOW_WRITE)
3686
uint64_t const flags= table->table->file->ha_table_flags();
3687
if (prev_ht && prev_ht != table->table->file->ht)
3689
prev_ht= table->table->file->ht;
3690
flags_all_set &= flags;
3691
flags_some_set |= flags;
3696
if (flags_all_set == 0)
3698
my_error((error= ER_BINLOG_LOGGING_IMPOSSIBLE), MYF(0),
3699
"Statement cannot be logged to the binary log in"
3700
" row-based nor statement-based format");
3702
else if (thd->variables.binlog_format == BINLOG_FORMAT_STMT &&
3703
(flags_all_set & HA_BINLOG_STMT_CAPABLE) == 0)
3705
my_error((error= ER_BINLOG_LOGGING_IMPOSSIBLE), MYF(0),
3706
"Statement-based format required for this statement,"
3707
" but not allowed by this combination of engines");
3709
else if ((thd->variables.binlog_format == BINLOG_FORMAT_ROW ||
3710
thd->lex->is_stmt_unsafe()) &&
3711
(flags_all_set & HA_BINLOG_ROW_CAPABLE) == 0)
3713
my_error((error= ER_BINLOG_LOGGING_IMPOSSIBLE), MYF(0),
3714
"Row-based format required for this statement,"
3715
" but not allowed by this combination of engines");
3719
If more than one engine is involved in the statement and at
3720
least one is doing it's own logging (is *self-logging*), the
3721
statement cannot be logged atomically, so we generate an error
3722
rather than allowing the binlog to become corrupt.
3725
(flags_some_set & HA_HAS_OWN_BINLOGGING))
3727
error= ER_BINLOG_LOGGING_IMPOSSIBLE;
3728
my_error(error, MYF(0),
3729
"Statement cannot be written atomically since more"
3730
" than one engine involved and at least one engine"
3731
" is self-logging");
3738
We switch to row-based format if we are in mixed mode and one of
3739
the following are true:
3741
1. If the statement is unsafe
3742
2. If statement format cannot be used
3744
Observe that point to cannot be decided before the tables
3745
involved in a statement has been checked, i.e., we cannot put
3746
this code in reset_current_stmt_binlog_row_based(), it has to be
3749
if (thd->lex->is_stmt_unsafe() ||
3750
(flags_all_set & HA_BINLOG_STMT_CAPABLE) == 0)
3752
thd->set_current_stmt_binlog_row_based_if_mixed();
2258
assert(lock == 0); // You must lock everything at once
2259
if ((table->reginfo.lock_type= lock_type) != TL_UNLOCK)
2260
if (! (lock= mysql_lock_tables(this, &table_list->table, 1, 0, &refresh)))
3760
2270
Lock all tables in list
3765
tables Tables to lock
3766
count Number of opened tables
3767
need_reopen Out parameter which if true indicates that some
3768
tables were dropped or altered during this call
3769
and therefore invoker should reopen tables and
3770
try to lock them once again (in this case
3771
lock_tables() will also return error).
2274
session Thread handler
2275
tables Tables to lock
2276
count Number of opened tables
2277
need_reopen Out parameter which if true indicates that some
2278
tables were dropped or altered during this call
2279
and therefore invoker should reopen tables and
2280
try to lock them once again (in this case
2281
lock_tables() will also return error).
3774
You can't call lock_tables twice, as this would break the dead-lock-free
3775
handling thr_lock gives us. You most always get all needed locks at
2284
You can't call lock_tables twice, as this would break the dead-lock-free
2285
handling thr_lock gives us. You most always get all needed locks at
3778
If query for which we are calling this function marked as requring
3779
prelocking, this function will do implicit LOCK TABLES and change
3780
thd::prelocked_mode accordingly.
2288
If query for which we are calling this function marked as requring
2289
prelocking, this function will do implicit LOCK TABLES and change
2290
session::prelocked_mode accordingly.
3787
int lock_tables(THD *thd, TABLE_LIST *tables, uint count, bool *need_reopen)
2297
int Session::lock_tables(TableList *tables, uint32_t count, bool *need_reopen)
2300
Session *session= this;
3792
2303
We can't meet statement requiring prelocking if we already
3874
2334
Open a single table without table caching and don't set it in open_list
3877
open_temporary_table()
3879
path Path (without .frm)
3881
table_name Table name
3882
link_in_list 1 if table should be linked into thd->temporary_tables
3885
Used by alter_table to open a temporary table and when creating
3886
a temporary table with CREATE TEMPORARY ...
2337
open_temporary_table()
2338
session Thread object
2339
path Path (without .frm)
2341
table_name Table name
2342
link_in_list 1 if table should be linked into session->temporary_tables
2345
Used by alter_table to open a temporary table and when creating
2346
a temporary table with CREATE TEMPORARY ...
3893
TABLE *open_temporary_table(THD *thd, const char *path, const char *db,
3894
const char *table_name, bool link_in_list,
3895
open_table_mode open_mode)
2353
Table *Session::open_temporary_table(const char *path, const char *db_arg,
2354
const char *table_name_arg, bool link_in_list,
2355
open_table_mode open_mode)
2357
Table *new_tmp_table;
3899
2359
char cache_key[MAX_DBKEY_LENGTH], *saved_cache_key, *tmp_path;
3901
TABLE_LIST table_list;
2360
uint32_t key_length, path_length;
2361
TableList table_list;
3903
table_list.db= (char*) db;
3904
table_list.table_name= (char*) table_name;
2363
table_list.db= (char*) db_arg;
2364
table_list.table_name= (char*) table_name_arg;
3905
2365
/* Create the cache_key for temporary tables */
3906
key_length= create_table_def_key(thd, cache_key, &table_list, 1);
3908
if (!(tmp_table= (TABLE*) my_malloc(sizeof(*tmp_table) + sizeof(*share) +
3909
strlen(path)+1 + key_length,
3911
return(0); /* purecov: inspected */
3913
share= (TABLE_SHARE*) (tmp_table+1);
2366
key_length= table_list.create_table_def_key(cache_key);
2367
path_length= strlen(path);
2369
if (!(new_tmp_table= (Table*) malloc(sizeof(*new_tmp_table) + sizeof(*share) +
2370
path_length + 1 + key_length)))
2373
share= (TableShare*) (new_tmp_table+1);
3914
2374
tmp_path= (char*) (share+1);
3915
saved_cache_key= stpcpy(tmp_path, path)+1;
2375
saved_cache_key= strcpy(tmp_path, path)+path_length+1;
3916
2376
memcpy(saved_cache_key, cache_key, key_length);
3918
init_tmp_table_share(thd, share, saved_cache_key, key_length,
3919
strend(saved_cache_key)+1, tmp_path);
2378
share->init(saved_cache_key, key_length, strchr(saved_cache_key, '\0')+1, tmp_path);
3921
if (open_table_def(thd, share, 0) ||
3922
open_table_from_share(thd, share, table_name,
2381
First open the share, and then open the table from the share we just opened.
2383
if (open_table_def(this, share) ||
2384
open_table_from_share(this, share, table_name_arg,
3923
2385
(open_mode == OTM_ALTER) ? 0 :
3924
(uint) (HA_OPEN_KEYFILE | HA_OPEN_RNDFILE |
2386
(uint32_t) (HA_OPEN_KEYFILE | HA_OPEN_RNDFILE |
3926
2388
(open_mode == OTM_ALTER) ?
3927
(READ_KEYINFO | COMPUTE_TYPES | EXTRA_RECORD |
3929
: (READ_KEYINFO | COMPUTE_TYPES | EXTRA_RECORD),
2389
(EXTRA_RECORD | OPEN_FRM_FILE_ONLY)
3930
2391
ha_open_options,
3931
tmp_table, open_mode))
2392
new_tmp_table, open_mode))
3933
2394
/* No need to lock share->mutex as this is not needed for tmp tables */
3934
free_table_share(share);
3935
my_free((char*) tmp_table,MYF(0));
2395
share->free_table_share();
2396
free((char*) new_tmp_table);
3939
tmp_table->reginfo.lock_type= TL_WRITE; // Simulate locked
2400
new_tmp_table->reginfo.lock_type= TL_WRITE; // Simulate locked
3940
2401
if (open_mode == OTM_ALTER)
3943
Temporary table has been created with frm_only
3944
and has not been created in any storage engine
2404
Temporary table has been created with frm_only
2405
and has not been created in any storage engine
3946
2407
share->tmp_table= TMP_TABLE_FRM_FILE_ONLY;
3949
share->tmp_table= (tmp_table->file->has_transactions() ?
2410
share->tmp_table= (new_tmp_table->file->has_transactions() ?
3950
2411
TRANSACTIONAL_TMP_TABLE : NON_TRANSACTIONAL_TMP_TABLE);
3952
2413
if (link_in_list)
3954
2415
/* growing temp list at the head */
3955
tmp_table->next= thd->temporary_tables;
3956
if (tmp_table->next)
3957
tmp_table->next->prev= tmp_table;
3958
thd->temporary_tables= tmp_table;
3959
thd->temporary_tables->prev= 0;
3960
if (thd->slave_thread)
3961
slave_open_temp_tables++;
3963
tmp_table->pos_in_table_list= 0;
3968
bool rm_temporary_table(handlerton *base, char *path, bool frm_only)
3974
stpcpy(ext= strend(path), reg_ext);
3975
if (my_delete(path,MYF(0)))
3976
error=1; /* purecov: inspected */
3977
*ext= 0; // remove extension
3978
file= get_new_handler((TABLE_SHARE*) 0, current_thd->mem_root, base);
3979
if (!frm_only && file && file->ha_delete_table(path))
3982
sql_print_warning("Could not remove temporary table: '%s', error: %d",
2416
new_tmp_table->next= this->temporary_tables;
2417
if (new_tmp_table->next)
2418
new_tmp_table->next->prev= new_tmp_table;
2419
this->temporary_tables= new_tmp_table;
2420
this->temporary_tables->prev= 0;
2422
new_tmp_table->pos_in_table_list= 0;
2424
return new_tmp_table;
3990
2428
/*****************************************************************************
3991
* The following find_field_in_XXX procedures implement the core of the
3992
* name resolution functionality. The entry point to resolve a column name in a
3993
* list of tables is 'find_field_in_tables'. It calls 'find_field_in_table_ref'
3994
* for each table reference. In turn, depending on the type of table reference,
3995
* 'find_field_in_table_ref' calls one of the 'find_field_in_XXX' procedures
3996
* below specific for the type of table reference.
3997
******************************************************************************/
2429
* The following find_field_in_XXX procedures implement the core of the
2430
* name resolution functionality. The entry point to resolve a column name in a
2431
* list of tables is 'find_field_in_tables'. It calls 'find_field_in_table_ref'
2432
* for each table reference. In turn, depending on the type of table reference,
2433
* 'find_field_in_table_ref' calls one of the 'find_field_in_XXX' procedures
2434
* below specific for the type of table reference.
2435
******************************************************************************/
3999
2437
/* Special Field pointers as return values of find_field_in_XXX functions. */
4000
2438
Field *not_found_field= (Field*) 0x1;
4001
Field *view_ref_found= (Field*) 0x2;
4003
#define WRONG_GRANT (Field*) -1
4005
static void update_field_dependencies(THD *thd, Field *field, TABLE *table)
2439
Field *view_ref_found= (Field*) 0x2;
2441
static void update_field_dependencies(Session *session, Field *field, Table *table)
4007
if (thd->mark_used_columns != MARK_COLUMNS_NONE)
2443
if (session->mark_used_columns != MARK_COLUMNS_NONE)
4009
MY_BITMAP *current_bitmap, *other_bitmap;
2445
MyBitmap *current_bitmap, *other_bitmap;
4012
2448
We always want to register the used keys, as the column bitmap may have
4013
2449
been set for all fields (for example for view).
4016
table->covering_keys.intersect(field->part_of_key);
4017
table->merge_keys.merge(field->part_of_key);
4019
if (thd->mark_used_columns == MARK_COLUMNS_READ)
2452
table->covering_keys&= field->part_of_key;
2453
table->merge_keys|= field->part_of_key;
2455
if (session->mark_used_columns == MARK_COLUMNS_READ)
4021
2457
current_bitmap= table->read_set;
4022
2458
other_bitmap= table->write_set;
4302
2619
Find field in a table reference.
4305
find_field_in_table_ref()
4306
thd [in] thread handler
4307
table_list [in] table reference to search
4308
name [in] name of field
4309
length [in] field length of name
4310
item_name [in] name of item if it will be created (VIEW)
4311
db_name [in] optional database name that qualifies the
4312
table_name [in] optional table name that qualifies the field
4313
ref [in/out] if 'name' is resolved to a view field, ref
4314
is set to point to the found view field
4315
check_privileges [in] check privileges
4316
allow_rowid [in] do allow finding of "_rowid" field?
4317
cached_field_index_ptr [in] cached position in field list (used to
4318
speedup lookup for fields in prepared tables)
4319
register_tree_change [in] true if ref is not stack variable and we
4320
need register changes in item tree
4321
actual_table [out] the original table reference where the field
4322
belongs - differs from 'table_list' only for
4323
NATURAL_USING joins.
2622
find_field_in_table_ref()
2623
session [in] thread handler
2624
table_list [in] table reference to search
2625
name [in] name of field
2626
length [in] field length of name
2627
item_name [in] name of item if it will be created (VIEW)
2628
db_name [in] optional database name that qualifies the
2629
table_name [in] optional table name that qualifies the field
2630
ref [in/out] if 'name' is resolved to a view field, ref
2631
is set to point to the found view field
2632
allow_rowid [in] do allow finding of "_rowid" field?
2633
cached_field_index_ptr [in] cached position in field list (used to
2634
speedup lookup for fields in prepared tables)
2635
register_tree_change [in] true if ref is not stack variable and we
2636
need register changes in item tree
2637
actual_table [out] the original table reference where the field
2638
belongs - differs from 'table_list' only for
2639
NATURAL_USING joins.
4326
Find a field in a table reference depending on the type of table
4327
reference. There are three types of table references with respect
4328
to the representation of their result columns:
4329
- an array of Field_translator objects for MERGE views and some
4330
information_schema tables,
4331
- an array of Field objects (and possibly a name hash) for stored
4333
- a list of Natural_join_column objects for NATURAL/USING joins.
4334
This procedure detects the type of the table reference 'table_list'
4335
and calls the corresponding search routine.
2642
Find a field in a table reference depending on the type of table
2643
reference. There are three types of table references with respect
2644
to the representation of their result columns:
2645
- an array of Field_translator objects for MERGE views and some
2646
information_schema tables,
2647
- an array of Field objects (and possibly a name hash) for stored
2649
- a list of Natural_join_column objects for NATURAL/USING joins.
2650
This procedure detects the type of the table reference 'table_list'
2651
and calls the corresponding search routine.
4338
0 field is not found
4339
view_ref_found found value in VIEW (real result is in *ref)
2654
0 field is not found
2655
view_ref_found found value in VIEW (real result is in *ref)
4344
find_field_in_table_ref(THD *thd, TABLE_LIST *table_list,
4345
const char *name, uint length,
2660
find_field_in_table_ref(Session *session, TableList *table_list,
2661
const char *name, uint32_t length,
4346
2662
const char *item_name, const char *db_name,
4347
2663
const char *table_name, Item **ref,
4348
bool check_privileges, bool allow_rowid,
4349
uint *cached_field_index_ptr,
4350
bool register_tree_change, TABLE_LIST **actual_table)
2665
uint32_t *cached_field_index_ptr,
2666
bool register_tree_change, TableList **actual_table)
4354
2670
assert(table_list->alias);
4434
2742
natural join, thus if the field is not qualified, we will search
4435
2743
directly the top-most NATURAL/USING join.
4437
fld= find_field_in_natural_join(thd, table_list, name, length, ref,
2745
fld= find_field_in_natural_join(session, table_list, name, length, ref,
4438
2746
register_tree_change, actual_table);
4443
if (thd->mark_used_columns != MARK_COLUMNS_NONE)
4446
Get rw_set correct for this field so that the handler
4447
knows that this field is involved in the query and gets
4450
Field *field_to_set= NULL;
4451
if (fld == view_ref_found)
4453
Item *it= (*ref)->real_item();
4454
if (it->type() == Item::FIELD_ITEM)
4455
field_to_set= ((Item_field*)it)->field;
4458
if (thd->mark_used_columns == MARK_COLUMNS_READ)
4459
it->walk(&Item::register_field_in_read_map, 1, (uchar *) 0);
4466
TABLE *table= field_to_set->table;
4467
if (thd->mark_used_columns == MARK_COLUMNS_READ)
4468
bitmap_set_bit(table->read_set, field_to_set->field_index);
4470
bitmap_set_bit(table->write_set, field_to_set->field_index);
2751
if (session->mark_used_columns != MARK_COLUMNS_NONE)
2754
Get rw_set correct for this field so that the handler
2755
knows that this field is involved in the query and gets
2758
Field *field_to_set= NULL;
2759
if (fld == view_ref_found)
2761
Item *it= (*ref)->real_item();
2762
if (it->type() == Item::FIELD_ITEM)
2763
field_to_set= ((Item_field*)it)->field;
2766
if (session->mark_used_columns == MARK_COLUMNS_READ)
2767
it->walk(&Item::register_field_in_read_map, 1, (unsigned char *) 0);
2774
Table *table= field_to_set->table;
2775
if (session->mark_used_columns == MARK_COLUMNS_READ)
2776
table->setReadSet(field_to_set->field_index);
2778
table->setWriteSet(field_to_set->field_index);
4479
Find field in table, no side effects, only purpose is to check for field
4480
in table object and get reference to the field if found.
4483
find_field_in_table_sef()
4485
table table where to find
4486
name Name of field searched for
4489
0 field is not found
4493
Field *find_field_in_table_sef(TABLE *table, const char *name)
4496
if (table->s->name_hash.records)
4498
field_ptr= (Field**)hash_search(&table->s->name_hash,(uchar*) name,
4503
field_ptr points to field in TABLE_SHARE. Convert it to the matching
4506
field_ptr= (table->field + (field_ptr - table->s->field));
4511
if (!(field_ptr= table->field))
4513
for (; *field_ptr; ++field_ptr)
4514
if (!my_strcasecmp(system_charset_info, (*field_ptr)->field_name, name))
4525
2787
Find field in table list.
4528
find_field_in_tables()
4529
thd pointer to current thread structure
4530
item field item that should be found
4531
first_table list of tables to be searched for item
4532
last_table end of the list of tables to search for item. If NULL
4533
then search to the end of the list 'first_table'.
4534
ref if 'item' is resolved to a view field, ref is set to
4535
point to the found view field
4536
report_error Degree of error reporting:
4537
- IGNORE_ERRORS then do not report any error
4538
- IGNORE_EXCEPT_NON_UNIQUE report only non-unique
4539
fields, suppress all other errors
4540
- REPORT_EXCEPT_NON_UNIQUE report all other errors
4541
except when non-unique fields were found
4543
check_privileges need to check privileges
4544
register_tree_change true if ref is not a stack variable and we
4545
to need register changes in item tree
2790
find_field_in_tables()
2791
session pointer to current thread structure
2792
item field item that should be found
2793
first_table list of tables to be searched for item
2794
last_table end of the list of tables to search for item. If NULL
2795
then search to the end of the list 'first_table'.
2796
ref if 'item' is resolved to a view field, ref is set to
2797
point to the found view field
2798
report_error Degree of error reporting:
2799
- IGNORE_ERRORS then do not report any error
2800
- IGNORE_EXCEPT_NON_UNIQUE report only non-unique
2801
fields, suppress all other errors
2802
- REPORT_EXCEPT_NON_UNIQUE report all other errors
2803
except when non-unique fields were found
2805
register_tree_change true if ref is not a stack variable and we
2806
to need register changes in item tree
4548
0 If error: the found field is not unique, or there are
4549
no sufficient access priviliges for the found field,
4550
or the field is qualified with non-existing table.
4551
not_found_field The function was called with report_error ==
4552
(IGNORE_ERRORS || IGNORE_EXCEPT_NON_UNIQUE) and a
4553
field was not found.
4554
view_ref_found View field is found, item passed through ref parameter
4555
found field If a item was resolved to some field
2809
0 If error: the found field is not unique, or there are
2810
no sufficient access priviliges for the found field,
2811
or the field is qualified with non-existing table.
2812
not_found_field The function was called with report_error ==
2813
(IGNORE_ERRORS || IGNORE_EXCEPT_NON_UNIQUE) and a
2814
field was not found.
2815
view_ref_found View field is found, item passed through ref parameter
2816
found field If a item was resolved to some field
4559
find_field_in_tables(THD *thd, Item_ident *item,
4560
TABLE_LIST *first_table, TABLE_LIST *last_table,
4561
Item **ref, find_item_error_report_type report_error,
4562
bool check_privileges, bool register_tree_change)
2820
find_field_in_tables(Session *session, Item_ident *item,
2821
TableList *first_table, TableList *last_table,
2822
Item **ref, find_item_error_report_type report_error,
2823
bool register_tree_change)
4564
2825
Field *found=0;
4565
2826
const char *db= item->db_name;
4566
2827
const char *table_name= item->table_name;
4567
2828
const char *name= item->field_name;
4568
uint length=(uint) strlen(name);
2829
uint32_t length=(uint32_t) strlen(name);
4569
2830
char name_buff[NAME_LEN+1];
4570
TABLE_LIST *cur_table= first_table;
4571
TABLE_LIST *actual_table;
2831
TableList *cur_table= first_table;
2832
TableList *actual_table;
4572
2833
bool allow_rowid;
4574
2835
if (!table_name || !table_name[0])
5278
3485
Materialize and store the row type of NATURAL/USING join.
5281
store_natural_using_join_columns()
5283
natural_using_join the table reference of the NATURAL/USING join
5284
table_ref_1 the first (left) operand (of a NATURAL/USING join).
5285
table_ref_2 the second (right) operand (of a NATURAL/USING join).
5286
using_fields if the join is JOIN...USING - the join columns,
5287
if NATURAL join, then NULL
5288
found_using_fields number of fields from the USING clause that were
5289
found among the common fields
3488
store_natural_using_join_columns()
3489
session current thread
3490
natural_using_join the table reference of the NATURAL/USING join
3491
table_ref_1 the first (left) operand (of a NATURAL/USING join).
3492
table_ref_2 the second (right) operand (of a NATURAL/USING join).
3493
using_fields if the join is JOIN...USING - the join columns,
3494
if NATURAL join, then NULL
3495
found_using_fields number of fields from the USING clause that were
3496
found among the common fields
5292
Iterate over the columns of both join operands and sort and store
5293
all columns into the 'join_columns' list of natural_using_join
5294
where the list is formed by three parts:
5295
part1: The coalesced columns of table_ref_1 and table_ref_2,
5296
sorted according to the column order of the first table.
5297
part2: The other columns of the first table, in the order in
5298
which they were defined in CREATE TABLE.
5299
part3: The other columns of the second table, in the order in
5300
which they were defined in CREATE TABLE.
5301
Time complexity - O(N1+N2), where Ni = length(table_ref_i).
5304
The procedure assumes that mark_common_columns() has been called
5305
for the join that is being processed.
5308
true error: Some common column is ambiguous
3499
Iterate over the columns of both join operands and sort and store
3500
all columns into the 'join_columns' list of natural_using_join
3501
where the list is formed by three parts:
3502
part1: The coalesced columns of table_ref_1 and table_ref_2,
3503
sorted according to the column order of the first table.
3504
part2: The other columns of the first table, in the order in
3505
which they were defined in CREATE TABLE.
3506
part3: The other columns of the second table, in the order in
3507
which they were defined in CREATE TABLE.
3508
Time complexity - O(N1+N2), where Ni = length(table_ref_i).
3511
The procedure assumes that mark_common_columns() has been called
3512
for the join that is being processed.
3515
true error: Some common column is ambiguous
5313
store_natural_using_join_columns(THD *thd __attribute__((unused)),
5314
TABLE_LIST *natural_using_join,
5315
TABLE_LIST *table_ref_1,
5316
TABLE_LIST *table_ref_2,
3520
store_natural_using_join_columns(Session *,
3521
TableList *natural_using_join,
3522
TableList *table_ref_1,
3523
TableList *table_ref_2,
5317
3524
List<String> *using_fields,
5318
uint found_using_fields)
3525
uint32_t found_using_fields)
5320
3527
Field_iterator_table_ref it_1, it_2;
5321
3528
Natural_join_column *nj_col_1, *nj_col_2;
5402
3609
Precompute and store the row types of the top-most NATURAL/USING joins.
5405
store_top_level_join_columns()
5407
table_ref nested join or table in a FROM clause
5408
left_neighbor neighbor table reference to the left of table_ref at the
5409
same level in the join tree
5410
right_neighbor neighbor table reference to the right of table_ref at the
5411
same level in the join tree
3612
store_top_level_join_columns()
3613
session current thread
3614
table_ref nested join or table in a FROM clause
3615
left_neighbor neighbor table reference to the left of table_ref at the
3616
same level in the join tree
3617
right_neighbor neighbor table reference to the right of table_ref at the
3618
same level in the join tree
5414
The procedure performs a post-order traversal of a nested join tree
5415
and materializes the row types of NATURAL/USING joins in a
5416
bottom-up manner until it reaches the TABLE_LIST elements that
5417
represent the top-most NATURAL/USING joins. The procedure should be
5418
applied to each element of SELECT_LEX::top_join_list (i.e. to each
5419
top-level element of the FROM clause).
3621
The procedure performs a post-order traversal of a nested join tree
3622
and materializes the row types of NATURAL/USING joins in a
3623
bottom-up manner until it reaches the TableList elements that
3624
represent the top-most NATURAL/USING joins. The procedure should be
3625
applied to each element of Select_Lex::top_join_list (i.e. to each
3626
top-level element of the FROM clause).
5422
Notice that the table references in the list nested_join->join_list
5423
are in reverse order, thus when we iterate over it, we are moving
5424
from the right to the left in the FROM clause.
3629
Notice that the table references in the list nested_join->join_list
3630
are in reverse order, thus when we iterate over it, we are moving
3631
from the right to the left in the FROM clause.
5432
store_top_level_join_columns(THD *thd, TABLE_LIST *table_ref,
5433
TABLE_LIST *left_neighbor,
5434
TABLE_LIST *right_neighbor)
3639
store_top_level_join_columns(Session *session, TableList *table_ref,
3640
TableList *left_neighbor,
3641
TableList *right_neighbor)
5436
3643
bool result= true;
5438
3645
/* Call the procedure recursively for each nested table reference. */
5439
3646
if (table_ref->nested_join)
5441
List_iterator_fast<TABLE_LIST> nested_it(table_ref->nested_join->join_list);
5442
TABLE_LIST *same_level_left_neighbor= nested_it++;
5443
TABLE_LIST *same_level_right_neighbor= NULL;
3648
List_iterator_fast<TableList> nested_it(table_ref->nested_join->join_list);
3649
TableList *same_level_left_neighbor= nested_it++;
3650
TableList *same_level_right_neighbor= NULL;
5444
3651
/* Left/right-most neighbors, possibly at higher levels in the join tree. */
5445
TABLE_LIST *real_left_neighbor, *real_right_neighbor;
3652
TableList *real_left_neighbor, *real_right_neighbor;
5447
3654
while (same_level_left_neighbor)
5449
TABLE_LIST *cur_table_ref= same_level_left_neighbor;
3656
TableList *cur_table_ref= same_level_left_neighbor;
5450
3657
same_level_left_neighbor= nested_it++;
5452
3659
The order of RIGHT JOIN operands is reversed in 'join list' to
5566
3773
in a FROM clause.
5569
setup_natural_join_row_types()
5571
from_clause list of top-level table references in a FROM clause
3776
setup_natural_join_row_types()
3777
session current thread
3778
from_clause list of top-level table references in a FROM clause
5574
Apply the procedure 'store_top_level_join_columns' to each of the
5575
top-level table referencs of the FROM clause. Adjust the list of tables
5576
for name resolution - context->first_name_resolution_table to the
5577
top-most, lef-most NATURAL/USING join.
3781
Apply the procedure 'store_top_level_join_columns' to each of the
3782
top-level table referencs of the FROM clause. Adjust the list of tables
3783
for name resolution - context->first_name_resolution_table to the
3784
top-most, lef-most NATURAL/USING join.
5580
Notice that the table references in 'from_clause' are in reverse
5581
order, thus when we iterate over it, we are moving from the right
5582
to the left in the FROM clause.
3787
Notice that the table references in 'from_clause' are in reverse
3788
order, thus when we iterate over it, we are moving from the right
3789
to the left in the FROM clause.
5588
static bool setup_natural_join_row_types(THD *thd,
5589
List<TABLE_LIST> *from_clause,
3795
static bool setup_natural_join_row_types(Session *session,
3796
List<TableList> *from_clause,
5590
3797
Name_resolution_context *context)
5592
thd->where= "from clause";
3799
session->where= "from clause";
5593
3800
if (from_clause->elements == 0)
5594
3801
return false; /* We come here in the case of UNIONs. */
5596
List_iterator_fast<TABLE_LIST> table_ref_it(*from_clause);
5597
TABLE_LIST *table_ref; /* Current table reference. */
3803
List_iterator_fast<TableList> table_ref_it(*from_clause);
3804
TableList *table_ref; /* Current table reference. */
5598
3805
/* Table reference to the left of the current. */
5599
TABLE_LIST *left_neighbor;
3806
TableList *left_neighbor;
5600
3807
/* Table reference to the right of the current. */
5601
TABLE_LIST *right_neighbor= NULL;
3808
TableList *right_neighbor= NULL;
5603
3810
/* Note that tables in the list are in reversed order */
5604
3811
for (left_neighbor= table_ref_it++; left_neighbor ; )
5606
3813
table_ref= left_neighbor;
5607
3814
left_neighbor= table_ref_it++;
5608
/* For stored procedures do not redo work if already done. */
5609
if (context->select_lex->first_execution)
3815
if (store_top_level_join_columns(session, table_ref,
3816
left_neighbor, right_neighbor))
5611
if (store_top_level_join_columns(thd, table_ref,
5612
left_neighbor, right_neighbor))
5616
TABLE_LIST *first_leaf_on_the_right;
5617
first_leaf_on_the_right= table_ref->first_leaf_for_name_resolution();
5618
left_neighbor->next_name_resolution_table= first_leaf_on_the_right;
3820
TableList *first_leaf_on_the_right;
3821
first_leaf_on_the_right= table_ref->first_leaf_for_name_resolution();
3822
left_neighbor->next_name_resolution_table= first_leaf_on_the_right;
5621
3824
right_neighbor= table_ref;
5866
4067
prepare tables and check access for the view tables
5869
setup_tables_and_check_view_access()
5871
context name resolution contest to setup table list there
5872
from_clause Top-level list of table references in the FROM clause
5873
tables Table list (select_lex->table_list)
5874
conds Condition of current SELECT (can be changed by VIEW)
5875
leaves List of join table leaves list (select_lex->leaf_tables)
5876
refresh It is onle refresh for subquery
5877
select_insert It is SELECT ... INSERT command
5878
want_access what access is needed
4070
setup_tables_and_check_view_access()
4071
session Thread handler
4072
context name resolution contest to setup table list there
4073
from_clause Top-level list of table references in the FROM clause
4074
tables Table list (select_lex->table_list)
4075
conds Condition of current SELECT (can be changed by VIEW)
4076
leaves List of join table leaves list (select_lex->leaf_tables)
4077
refresh It is onle refresh for subquery
4078
select_insert It is SELECT ... INSERT command
4079
want_access what access is needed
5881
a wrapper for check_tables that will also check the resulting
5882
table leaves list for access to all the tables that belong to a view
4082
a wrapper for check_tables that will also check the resulting
4083
table leaves list for access to all the tables that belong to a view
5885
false ok; In this case *map will include the chosen index
4086
false ok; In this case *map will include the chosen index
5888
bool setup_tables_and_check_access(THD *thd,
4089
bool setup_tables_and_check_access(Session *session,
5889
4090
Name_resolution_context *context,
5890
List<TABLE_LIST> *from_clause,
5892
TABLE_LIST **leaves,
4091
List<TableList> *from_clause,
5893
4094
bool select_insert)
5895
TABLE_LIST *leaves_tmp= NULL;
5896
bool first_table= true;
4096
TableList *leaves_tmp= NULL;
5898
if (setup_tables(thd, context, from_clause, tables,
4098
if (setup_tables(session, context, from_clause, tables,
5899
4099
&leaves_tmp, select_insert))
5903
4103
*leaves= leaves_tmp;
5905
for (; leaves_tmp; leaves_tmp= leaves_tmp->next_leaf)
5907
if (leaves_tmp->belong_to_view)
5918
Create a key_map from a list of index names
5921
get_key_map_from_key_list()
5922
map key_map to fill in
5924
index_list List of index names
5927
0 ok; In this case *map will includes the choosed index
5931
bool get_key_map_from_key_list(key_map *map, TABLE *table,
5932
List<String> *index_list)
5934
List_iterator_fast<String> it(*index_list);
5941
if (table->s->keynames.type_names == 0 ||
5942
(pos= find_type(&table->s->keynames, name->ptr(),
5943
name->length(), 1)) <=
5946
my_error(ER_KEY_DOES_NOT_EXITS, MYF(0), name->c_ptr(),
5947
table->pos_in_table_list->alias);
5951
map->set_bit(pos-1);
5958
4110
Drops in all fields instead of current '*' field
5963
context Context for name resolution
5964
db_name Database name in case of 'database_name.table_name.*'
5965
table_name Table name in case of 'table_name.*'
5967
any_privileges 0 If we should ensure that we have SELECT privileges
5969
1 If any privilege is ok
4114
session Thread handler
4115
context Context for name resolution
4116
db_name Database name in case of 'database_name.table_name.*'
4117
table_name Table name in case of 'table_name.*'
4119
any_privileges 0 If we should ensure that we have SELECT privileges
4121
1 If any privilege is ok
5971
0 ok 'it' is updated to point at last inserted
5972
1 error. Error message is generated but not sent to client
4123
0 ok 'it' is updated to point at last inserted
4124
1 error. Error message is generated but not sent to client
5976
insert_fields(THD *thd, Name_resolution_context *context, const char *db_name,
4128
insert_fields(Session *session, Name_resolution_context *context, const char *db_name,
5977
4129
const char *table_name, List_iterator<Item> *it,
5978
bool any_privileges __attribute__((unused)))
5980
4132
Field_iterator_table_ref field_iterator;
5982
4134
char name_buff[NAME_LEN+1];
5984
if (db_name && lower_case_table_names)
5987
4139
convert database to lower case for comparison
5988
4140
We can't do this in Item_field as this would change the
5989
4141
'name' of the item which may be used in the select list
5991
strmake(name_buff, db_name, sizeof(name_buff)-1);
4143
strncpy(name_buff, db_name, sizeof(name_buff)-1);
5992
4144
my_casedn_str(files_charset_info, name_buff);
5993
4145
db_name= name_buff;
6325
4502
table->auto_increment_field_not_null= true;
6326
4503
if (value->save_in_field(field, 0) < 0)
6329
return(thd->is_error());
4505
tbl_list.push_back(table);
4507
/* Update virtual fields*/
4508
session->abort_on_warning= false;
4509
if (tbl_list.head())
4511
List_iterator_fast<Table> t(tbl_list);
4512
Table *prev_table= 0;
4513
while ((table= t++))
4516
Do simple optimization to prevent unnecessary re-generating
4517
values for virtual fields
4519
if (table != prev_table)
4525
session->abort_on_warning= abort_on_warning_saved;
4526
return(session->is_error());
4529
session->abort_on_warning= abort_on_warning_saved;
6333
4531
table->auto_increment_field_not_null= false;
6338
bool mysql_rm_tmp_tables(void)
4536
bool drizzle_rm_tmp_tables()
6341
char filePath[FN_REFLEN], *tmpdir, filePathCopy[FN_REFLEN];
6347
if (!(thd= new THD))
6349
thd->thread_stack= (char*) &thd;
6350
thd->store_globals();
6352
for (i=0; i<=mysql_tmpdir_list.max; i++)
6354
tmpdir=mysql_tmpdir_list.list[i];
6355
/* See if the directory exists */
6356
if (!(dirp = my_dir(tmpdir,MYF(MY_WME | MY_DONT_SORT))))
6359
/* Remove all SQLxxx tables from directory */
6361
for (idx=0 ; idx < (uint) dirp->number_off_files ; idx++)
4538
char filePath[FN_REFLEN], filePathCopy[FN_REFLEN];
4541
assert(drizzle_tmpdir);
4543
if (!(session= new Session(plugin::Listen::getNullClient())))
4545
session->thread_stack= (char*) &session;
4546
session->storeGlobals();
4548
CachedDirectory dir(drizzle_tmpdir);
4552
my_errno= dir.getError();
4553
my_error(ER_CANT_READ_DIR, MYF(0), drizzle_tmpdir, my_errno);
4557
CachedDirectory::Entries files= dir.getEntries();
4558
CachedDirectory::Entries::iterator fileIter= files.begin();
4560
/* Remove all temp tables in the tmpdir */
4561
while (fileIter != files.end())
4563
CachedDirectory::Entry *entry= *fileIter;
4564
string prefix= entry->filename.substr(0, TMP_FILE_PREFIX_LENGTH);
4566
if (prefix == TMP_FILE_PREFIX)
6363
file=dirp->dir_entry+idx;
6365
/* skiping . and .. */
6366
if (file->name[0] == '.' && (!file->name[1] ||
6367
(file->name[1] == '.' && !file->name[2])))
6370
if (!memcmp(file->name, tmp_file_prefix, tmp_file_prefix_length))
4568
char *ext= fn_ext(entry->filename.c_str());
4569
uint32_t ext_len= strlen(ext);
4570
uint32_t filePath_len= snprintf(filePath, sizeof(filePath),
4571
"%s%c%s", drizzle_tmpdir, FN_LIBCHAR,
4572
entry->filename.c_str());
4574
if (ext_len && !memcmp(".dfe", ext, ext_len))
6372
char *ext= fn_ext(file->name);
6373
uint ext_len= strlen(ext);
6374
uint filePath_len= snprintf(filePath, sizeof(filePath),
6375
"%s%c%s", tmpdir, FN_LIBCHAR,
6377
if (!memcmp(reg_ext, ext, ext_len))
4577
/* We should cut file extention before deleting of table */
4578
memcpy(filePathCopy, filePath, filePath_len - ext_len);
4579
filePathCopy[filePath_len - ext_len]= 0;
4580
share.init(NULL, filePathCopy);
4581
if (!open_table_def(session, &share))
6379
handler *handler_file= 0;
6380
/* We should cut file extention before deleting of table */
6381
memcpy(filePathCopy, filePath, filePath_len - ext_len);
6382
filePathCopy[filePath_len - ext_len]= 0;
6383
init_tmp_table_share(thd, &share, "", 0, "", filePathCopy);
6384
if (!open_table_def(thd, &share, 0) &&
6385
((handler_file= get_new_handler(&share, thd->mem_root,
6388
handler_file->ha_delete_table(filePathCopy);
6389
delete handler_file;
6391
free_table_share(&share);
4583
share.db_type()->deleteTable(session, filePathCopy);
6394
File can be already deleted by tmp_table.file->delete_table().
6395
So we hide error messages which happnes during deleting of these
6398
VOID(my_delete(filePath, MYF(0)));
4585
share.free_table_share();
4588
File can be already deleted by tmp_table.file->delete_table().
4589
So we hide error messages which happnes during deleting of these
4592
my_delete(filePath, MYF(0));
6404
my_pthread_setspecific_ptr(THR_THD, 0);
6410
4605
/*****************************************************************************
6411
unireg support functions
6412
*****************************************************************************/
4606
unireg support functions
4607
*****************************************************************************/
6415
4610
Invalidate any cache entries that are for some DB
6418
remove_db_from_cache()
6419
db Database name. This will be in lower case if
6420
lower_case_table_name is set
4613
remove_db_from_cache()
4614
db Database name. This will be in lower case if
4615
lower_case_table_name is set
6423
We can't use hash_delete when looping hash_elements. We mark them first
6424
and afterwards delete those marked unused.
4618
We can't use hash_delete when looping hash_elements. We mark them first
4619
and afterwards delete those marked unused.
6427
4622
void remove_db_from_cache(const char *db)
6429
for (uint idx=0 ; idx < open_cache.records ; idx++)
4624
safe_mutex_assert_owner(&LOCK_open);
4626
for (uint32_t idx=0 ; idx < open_cache.records ; idx++)
6431
TABLE *table=(TABLE*) hash_element(&open_cache,idx);
4628
Table *table=(Table*) hash_element(&open_cache,idx);
6432
4629
if (!strcmp(table->s->db.str, db))
6434
4631
table->s->version= 0L; /* Free when thread is ready */
6435
4632
if (!table->in_use)
6436
relink_unused(table);
4633
relink_unused(table);
6439
4636
while (unused_tables && !unused_tables->s->version)
6440
VOID(hash_delete(&open_cache,(uchar*) unused_tables));
6445
free all unused tables
6448
This is called by 'handle_manager' when one wants to periodicly flush
6449
all not used tables.
6454
(void) pthread_mutex_lock(&LOCK_open);
6455
while (unused_tables)
6456
hash_delete(&open_cache,(uchar*) unused_tables);
6457
(void) pthread_mutex_unlock(&LOCK_open);
4637
hash_delete(&open_cache,(unsigned char*) unused_tables);
6465
4645
close_thread_tables() is called.
6471
0 This thread now have exclusive access to this table and no other thread
6472
can access the table until close_thread_tables() is called.
6473
1 Table is in use by another thread
4651
0 This thread now have exclusive access to this table and no other thread
4652
can access the table until close_thread_tables() is called.
4653
1 Table is in use by another thread
6476
bool remove_table_from_cache(THD *thd, const char *db, const char *table_name,
4656
bool remove_table_from_cache(Session *session, const char *db, const char *table_name,
6479
4659
char key[MAX_DBKEY_LENGTH];
6483
bool result= 0, signalled= 0;
6485
key_length=(uint) (stpcpy(stpcpy(key,db)+1,table_name)-key)+1;
4661
uint32_t key_length;
4664
bool signalled= false;
4666
key_pos= strcpy(key_pos, db) + strlen(db);
4667
key_pos= strcpy(key_pos+1, table_name) + strlen(table_name);
4668
key_length= (uint32_t) (key_pos-key)+1;
6488
4672
HASH_SEARCH_STATE state;
6489
result= signalled= 0;
4673
result= signalled= false;
6491
for (table= (TABLE*) hash_first(&open_cache, (uchar*) key, key_length,
4675
for (table= (Table*) hash_first(&open_cache, (unsigned char*) key, key_length,
6494
table= (TABLE*) hash_next(&open_cache, (uchar*) key, key_length,
4678
table= (Table*) hash_next(&open_cache, (unsigned char*) key, key_length,
6499
4683
table->s->version=0L; /* Free when thread is ready */
6500
4684
if (!(in_use=table->in_use))
6502
4686
relink_unused(table);
6504
else if (in_use != thd)
4688
else if (in_use != session)
6507
4691
Mark that table is going to be deleted from cache. This will
6508
4692
force threads that are in mysql_lock_tables() (but not yet
6509
4693
in thr_multi_lock()) to abort it's locks, close all tables and retry
6511
in_use->some_tables_deleted= 1;
4695
in_use->some_tables_deleted= true;
6512
4696
if (table->is_name_opened())
6517
Now we must abort all tables locks used by this thread
6518
as the thread may be waiting to get a lock for another table.
4701
Now we must abort all tables locks used by this thread
4702
as the thread may be waiting to get a lock for another table.
6519
4703
Note that we need to hold LOCK_open while going through the
6520
4704
list. So that the other thread cannot change it. The other
6521
4705
thread must also hold LOCK_open whenever changing the
6522
4706
open_tables list. Aborting the MERGE lock after a child was
6523
4707
closed and before the parent is closed would be fatal.
6525
for (TABLE *thd_table= in_use->open_tables;
6527
thd_table= thd_table->next)
4709
for (Table *session_table= in_use->open_tables;
4711
session_table= session_table->next)
6529
4713
/* Do not handle locks of MERGE children. */
6530
if (thd_table->db_stat) // If table is open
6531
signalled|= mysql_lock_abort_for_thread(thd, thd_table);
4714
if (session_table->db_stat) // If table is open
4715
signalled|= mysql_lock_abort_for_thread(session, session_table);
6535
result= result || (flags & RTFC_OWNED_BY_THD_FLAG);
4719
result= result || (flags & RTFC_OWNED_BY_Session_FLAG);
6537
4721
while (unused_tables && !unused_tables->s->version)
6538
VOID(hash_delete(&open_cache,(uchar*) unused_tables));
4722
hash_delete(&open_cache,(unsigned char*) unused_tables);
6540
4724
/* Remove table from table definition cache if it's not in use */
6541
if ((share= (TABLE_SHARE*) hash_search(&table_def_cache,(uchar*) key,
6544
share->version= 0; // Mark for delete
6545
if (share->ref_count == 0)
6547
pthread_mutex_lock(&share->mutex);
6548
VOID(hash_delete(&table_def_cache, (uchar*) share));
4725
TableShare::release(key, key_length);
6552
4727
if (result && (flags & RTFC_WAIT_OTHER_THREAD_FLAG))