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 */
23
#if TIME_WITH_SYS_TIME
24
# include <sys/time.h>
28
# include <sys/time.h>
33
#include "drizzled/internal/my_pthread.h"
35
#include <drizzled/sql_select.h>
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 "drizzled/cached_directory.h"
47
#include <drizzled/field/timestamp.h>
48
#include <drizzled/field/null.h>
49
#include "drizzled/memory/multi_malloc.h"
50
#include "drizzled/sql_table.h"
51
#include "drizzled/global_charset_info.h"
52
#include "drizzled/pthread_globals.h"
53
#include "drizzled/internal/iocache.h"
60
extern bool volatile shutdown_in_progress;
62
bool drizzle_rm_tmp_tables();
19
#include "mysql_priv.h"
20
#include "sql_select.h"
25
#define FLAGSTR(S,F) ((S) & (F) ? #F " " : "")
65
28
@defgroup Data_Dictionary Data Dictionary
68
Table *unused_tables; /* Used by mysql_test */
31
TABLE *unused_tables; /* Used by mysql_test */
69
32
HASH open_cache; /* Used by mysql_test */
70
static int open_unireg_entry(Session *session, Table *entry, TableList *table_list,
72
char *cache_key, uint32_t cache_key_length);
73
void free_cache_entry(void *entry);
74
unsigned char *table_cache_key(const unsigned char *record,
79
unsigned char *table_cache_key(const unsigned char *record,
33
static HASH table_def_cache;
34
static TABLE_SHARE *oldest_unused_share, end_of_unused_share;
35
static pthread_mutex_t LOCK_table_share;
36
static bool table_def_inited= 0;
38
static int open_unireg_entry(THD *thd, TABLE *entry, TABLE_LIST *table_list,
40
char *cache_key, uint cache_key_length,
41
MEM_ROOT *mem_root, uint flags);
42
static void free_cache_entry(TABLE *entry);
43
static void close_old_data_files(THD *thd, TABLE *table, bool morph_locks,
47
extern "C" uchar *table_cache_key(const uchar *record, size_t *length,
48
my_bool not_used __attribute__((unused)))
83
Table *entry=(Table*) record;
50
TABLE *entry=(TABLE*) record;
84
51
*length= entry->s->table_cache_key.length;
85
return (unsigned char*) entry->s->table_cache_key.str;
52
return (uchar*) entry->s->table_cache_key.str;
89
56
bool table_cache_init(void)
91
return hash_init(&open_cache, &my_charset_bin,
92
(size_t) table_cache_size+16,
93
0, 0, table_cache_key,
58
return hash_init(&open_cache, &my_charset_bin, table_cache_size+16,
59
0, 0, table_cache_key,
60
(hash_free_key) free_cache_entry, 0) != 0;
97
63
void table_cache_free(void)
99
refresh_version++; // Force close of open tables
101
while (unused_tables)
102
hash_delete(&open_cache,(unsigned char*) unused_tables);
104
if (!open_cache.records) // Safety first
105
hash_free(&open_cache);
65
DBUG_ENTER("table_cache_free");
68
close_cached_tables(NULL, NULL, FALSE, FALSE, FALSE);
69
if (!open_cache.records) // Safety first
70
hash_free(&open_cache);
108
uint32_t cached_open_tables(void)
75
uint cached_open_tables(void)
110
77
return open_cache.records;
115
Close cursor handle, but leave the table in the table cache
118
close_handle_and_leave_table_as_lock()
122
By leaving the table in the table cache, it disallows any other thread
125
session->killed will be set if we run out of memory
127
If closing a MERGE child, the calling function has to take care for
128
closing the parent too, if necessary.
132
void close_handle_and_leave_table_as_lock(Table *table)
134
TableShare *share, *old_share= table->s;
82
static void check_unused(void)
84
uint count= 0, open_files= 0, idx= 0;
85
TABLE *cur_link,*start_link;
87
if ((start_link=cur_link=unused_tables))
91
if (cur_link != cur_link->next->prev || cur_link != cur_link->prev->next)
93
DBUG_PRINT("error",("Unused_links aren't linked properly")); /* purecov: inspected */
94
return; /* purecov: inspected */
96
} while (count++ < open_cache.records &&
97
(cur_link=cur_link->next) != start_link);
98
if (cur_link != start_link)
100
DBUG_PRINT("error",("Unused_links aren't connected")); /* purecov: inspected */
103
for (idx=0 ; idx < open_cache.records ; idx++)
105
TABLE *entry=(TABLE*) hash_element(&open_cache,idx);
113
DBUG_PRINT("error",("Unused_links doesn't match open_cache: diff: %d", /* purecov: inspected */
114
count)); /* purecov: inspected */
117
#ifdef NOT_SAFE_FOR_REPAIR
119
check that open cache and table definition cache has same number of
123
for (idx=0 ; idx < table_def_cache.records ; idx++)
125
TABLE_SHARE *entry= (TABLE_SHARE*) hash_element(&table_def_cache,idx);
126
count+= entry->ref_count;
128
if (count != open_files)
130
DBUG_PRINT("error", ("table_def ref_count: %u open_cache: %u",
132
DBUG_ASSERT(count == open_files);
137
#define check_unused()
142
Create a table cache key
145
create_table_def_key()
147
key Create key here (must be of size MAX_DBKEY_LENGTH)
148
table_list Table definition
149
tmp_table Set if table is a tmp table
152
The table cache_key is created from:
156
if the table is a tmp table, we add the following to make each tmp table
159
4 bytes for master thread id
160
4 bytes pseudo thread id
166
uint create_table_def_key(THD *thd, char *key, TABLE_LIST *table_list,
169
uint key_length= (uint) (strmov(strmov(key, table_list->db)+1,
170
table_list->table_name)-key)+1;
173
int4store(key + key_length, thd->server_id);
174
int4store(key + key_length + 4, thd->variables.pseudo_thread_id);
175
key_length+= TMP_TABLE_KEY_EXTRA;
182
/*****************************************************************************
183
Functions to handle table definition cach (TABLE_SHARE)
184
*****************************************************************************/
186
extern "C" uchar *table_def_key(const uchar *record, size_t *length,
187
my_bool not_used __attribute__((unused)))
189
TABLE_SHARE *entry=(TABLE_SHARE*) record;
190
*length= entry->table_cache_key.length;
191
return (uchar*) entry->table_cache_key.str;
195
static void table_def_free_entry(TABLE_SHARE *share)
197
DBUG_ENTER("table_def_free_entry");
200
/* remove from old_unused_share list */
201
pthread_mutex_lock(&LOCK_table_share);
202
*share->prev= share->next;
203
share->next->prev= share->prev;
204
pthread_mutex_unlock(&LOCK_table_share);
206
free_table_share(share);
211
bool table_def_init(void)
214
pthread_mutex_init(&LOCK_table_share, MY_MUTEX_INIT_FAST);
215
oldest_unused_share= &end_of_unused_share;
216
end_of_unused_share.prev= &oldest_unused_share;
218
return hash_init(&table_def_cache, &my_charset_bin, table_def_size,
220
(hash_free_key) table_def_free_entry, 0) != 0;
224
void table_def_free(void)
226
DBUG_ENTER("table_def_free");
227
if (table_def_inited)
230
pthread_mutex_destroy(&LOCK_table_share);
231
hash_free(&table_def_cache);
237
uint cached_table_definitions(void)
239
return table_def_cache.records;
244
Get TABLE_SHARE for a table.
248
table_list Table that should be opened
250
key_length Length of key
251
db_flags Flags to open_table_def():
253
error out: Error code from open_table_def()
256
Get a table definition from the table definition cache.
257
If it doesn't exist, create a new from the table definition file.
260
We must have wrlock on LOCK_open when we come here
261
(To be changed later)
268
TABLE_SHARE *get_table_share(THD *thd, TABLE_LIST *table_list, char *key,
269
uint key_length, uint db_flags, int *error)
272
DBUG_ENTER("get_table_share");
276
/* Read table definition from cache */
277
if ((share= (TABLE_SHARE*) hash_search(&table_def_cache,(uchar*) key,
281
if (!(share= alloc_table_share(table_list, key, key_length)))
287
Lock mutex to be able to read table definition from file without
290
(void) pthread_mutex_lock(&share->mutex);
293
We assign a new table id under the protection of the LOCK_open and
294
the share's own mutex. We do this insted of creating a new mutex
295
and using it for the sole purpose of serializing accesses to a
296
static variable, we assign the table id here. We assign it to the
297
share before inserting it into the table_def_cache to be really
298
sure that it cannot be read from the cache without having a table
301
CAVEAT. This means that the table cannot be used for
302
binlogging/replication purposes, unless get_table_share() has been
303
called directly or indirectly.
305
assign_new_table_id(share);
307
if (my_hash_insert(&table_def_cache, (uchar*) share))
309
free_table_share(share);
310
DBUG_RETURN(0); // return error
312
if (open_table_def(thd, share, db_flags))
314
*error= share->error;
315
(void) hash_delete(&table_def_cache, (uchar*) share);
318
share->ref_count++; // Mark in use
319
DBUG_PRINT("exit", ("share: 0x%lx ref_count: %u",
320
(ulong) share, share->ref_count));
321
(void) pthread_mutex_unlock(&share->mutex);
326
We found an existing table definition. Return it if we didn't get
327
an error when reading the table definition from file.
330
/* We must do a lock to ensure that the structure is initialized */
331
(void) pthread_mutex_lock(&share->mutex);
334
/* Table definition contained an error */
335
open_table_error(share, share->error, share->open_errno, share->errarg);
336
(void) pthread_mutex_unlock(&share->mutex);
340
if (!share->ref_count++ && share->prev)
343
Share was not used before and it was in the old_unused_share list
344
Unlink share from this list
346
DBUG_PRINT("info", ("Unlinking from not used list"));
347
pthread_mutex_lock(&LOCK_table_share);
348
*share->prev= share->next;
349
share->next->prev= share->prev;
352
pthread_mutex_unlock(&LOCK_table_share);
354
(void) pthread_mutex_unlock(&share->mutex);
356
/* Free cache if too big */
357
while (table_def_cache.records > table_def_size &&
358
oldest_unused_share->next)
360
pthread_mutex_lock(&oldest_unused_share->mutex);
361
VOID(hash_delete(&table_def_cache, (uchar*) oldest_unused_share));
364
DBUG_PRINT("exit", ("share: 0x%lx ref_count: %u",
365
(ulong) share, share->ref_count));
371
Get a table share. If it didn't exist, try creating it from engine
373
For arguments and return values, see get_table_from_share()
377
*get_table_share_with_create(THD *thd, TABLE_LIST *table_list,
378
char *key, uint key_length,
379
uint db_flags, int *error)
383
DBUG_ENTER("get_table_share_with_create");
385
share= get_table_share(thd, table_list, key, key_length, db_flags, error);
387
If share is not NULL, we found an existing share.
389
If share is NULL, and there is no error, we're inside
390
pre-locking, which silences 'ER_NO_SUCH_TABLE' errors
391
with the intention to silently drop non-existing tables
392
from the pre-locking list. In this case we still need to try
393
auto-discover before returning a NULL share.
395
If share is NULL and the error is ER_NO_SUCH_TABLE, this is
396
the same as above, only that the error was not silenced by
397
pre-locking. Once again, we need to try to auto-discover
400
Finally, if share is still NULL, it's a real error and we need
403
@todo Rework alternative ways to deal with ER_NO_SUCH TABLE.
405
if (share || (thd->is_error() && (thd->main_da.sql_errno() != ER_NO_SUCH_TABLE)))
409
/* Table didn't exist. Check if some engine can provide it */
410
if ((tmp= ha_create_table_from_engine(thd, table_list->db,
411
table_list->table_name)) < 0)
414
No such table in any engine.
415
Hide "Table doesn't exist" errors if the table belongs to a view.
416
The check for thd->is_error() is necessary to not push an
417
unwanted error in case of pre-locking, which silences
418
"no such table" errors.
419
@todo Rework the alternative ways to deal with ER_NO_SUCH TABLE.
421
if (thd->is_error() && table_list->belong_to_view)
424
my_error(ER_VIEW_INVALID, MYF(0), "", "");
430
/* Give right error message */
432
DBUG_PRINT("error", ("Discovery of %s/%s failed", table_list->db,
433
table_list->table_name));
434
my_printf_error(ER_UNKNOWN_ERROR,
435
"Failed to open '%-.64s', error while "
436
"unpacking from engine",
437
MYF(0), table_list->table_name);
440
/* Table existed in engine. Let's open it */
441
mysql_reset_errors(thd, 1); // Clear warnings
442
thd->clear_error(); // Clear error message
443
DBUG_RETURN(get_table_share(thd, table_list, key, key_length,
449
Mark that we are not using table share anymore.
452
release_table_share()
454
release_type How the release should be done:
456
- Release without checking
457
RELEASE_WAIT_FOR_DROP
458
- Don't return until we get a signal that the
459
table is deleted or the thread is killed.
462
If ref_count goes to zero and (we have done a refresh or if we have
463
already too many open table shares) then delete the definition.
465
If type == RELEASE_WAIT_FOR_DROP then don't return until we get a signal
466
that the table is deleted or the thread is killed.
469
void release_table_share(TABLE_SHARE *share, enum release_type type)
471
bool to_be_deleted= 0;
472
DBUG_ENTER("release_table_share");
474
("share: 0x%lx table: %s.%s ref_count: %u version: %lu",
475
(ulong) share, share->db.str, share->table_name.str,
476
share->ref_count, share->version));
478
safe_mutex_assert_owner(&LOCK_open);
480
pthread_mutex_lock(&share->mutex);
481
if (!--share->ref_count)
483
if (share->version != refresh_version)
487
/* Link share last in used_table_share list */
488
DBUG_PRINT("info",("moving share to unused list"));
490
DBUG_ASSERT(share->next == 0);
491
pthread_mutex_lock(&LOCK_table_share);
492
share->prev= end_of_unused_share.prev;
493
*end_of_unused_share.prev= share;
494
end_of_unused_share.prev= &share->next;
495
share->next= &end_of_unused_share;
496
pthread_mutex_unlock(&LOCK_table_share);
498
to_be_deleted= (table_def_cache.records > table_def_size);
504
DBUG_PRINT("info", ("Deleting share"));
505
hash_delete(&table_def_cache, (uchar*) share);
508
pthread_mutex_unlock(&share->mutex);
514
Check if table definition exits in cache
517
get_cached_table_share()
519
table_name Table name
523
# TABLE_SHARE for table
526
TABLE_SHARE *get_cached_table_share(const char *db, const char *table_name)
528
char key[NAME_LEN*2+2];
529
TABLE_LIST table_list;
531
safe_mutex_assert_owner(&LOCK_open);
533
table_list.db= (char*) db;
534
table_list.table_name= (char*) table_name;
535
key_length= create_table_def_key((THD*) 0, key, &table_list, 0);
536
return (TABLE_SHARE*) hash_search(&table_def_cache,(uchar*) key, key_length);
541
Close file handle, but leave the table in the table cache
544
close_handle_and_leave_table_as_lock()
548
By leaving the table in the table cache, it disallows any other thread
551
thd->killed will be set if we run out of memory
553
If closing a MERGE child, the calling function has to take care for
554
closing the parent too, if necessary.
558
void close_handle_and_leave_table_as_lock(TABLE *table)
560
TABLE_SHARE *share, *old_share= table->s;
136
memory::Root *mem_root= &table->mem_root;
562
MEM_ROOT *mem_root= &table->mem_root;
563
DBUG_ENTER("close_handle_and_leave_table_as_lock");
138
assert(table->db_stat);
565
DBUG_ASSERT(table->db_stat);
141
568
Make a local copy of the table share and free the current one.
166
595
Create a list for all open tables matching SQL expression
170
wild SQL like expression
600
wild SQL like expression
173
One gets only a list of tables for which one has any kind of privilege.
174
db and table names are allocated in result struct, so one doesn't need
175
a lock on LOCK_open when traversing the return list.
603
One gets only a list of tables for which one has any kind of privilege.
604
db and table names are allocated in result struct, so one doesn't need
605
a lock on LOCK_open when traversing the return list.
608
NULL Error (Probably OOM)
609
# Pointer to list of names of open tables.
181
bool list_open_tables(const char *db,
183
bool(*func)(Table *table,
184
open_table_list_st& open_list,
185
plugin::InfoSchemaTable *schema_table),
187
plugin::InfoSchemaTable *schema_table)
612
OPEN_TABLE_LIST *list_open_tables(THD *thd, const char *db, const char *wild)
189
vector<open_table_list_st> open_list;
190
vector<open_table_list_st>::iterator it;
191
open_table_list_st table;
193
/* What we really need is an optimization for knowing unique tables */
195
open_list.reserve(sizeof(open_table_list_st) * (open_cache.records % 2));
197
open_list.reserve(sizeof(open_table_list_st) * open_cache.records);
199
pthread_mutex_lock(&LOCK_open); /* List all open tables */
201
for (uint32_t idx= 0; idx < open_cache.records; idx++)
615
OPEN_TABLE_LIST **start_list, *open_list;
616
TABLE_LIST table_list;
617
DBUG_ENTER("list_open_tables");
619
VOID(pthread_mutex_lock(&LOCK_open));
620
bzero((char*) &table_list,sizeof(table_list));
621
start_list= &open_list;
624
for (uint idx=0 ; result == 0 && idx < open_cache.records; idx++)
204
Table *entry=(Table*) hash_element(&open_cache,idx);
206
if (db && my_strcasecmp(system_charset_info, db, entry->s->db.str))
208
if (wild && internal::wild_compare(entry->s->table_name.str, wild, 0))
211
for (it= open_list.begin(); it < open_list.end(); it++)
626
OPEN_TABLE_LIST *table;
627
TABLE *entry=(TABLE*) hash_element(&open_cache,idx);
628
TABLE_SHARE *share= entry->s;
630
if (db && my_strcasecmp(system_charset_info, db, share->db.str))
632
if (wild && wild_compare(share->table_name.str, wild, 0))
635
/* Check if user has SELECT privilege for any column in the table */
636
table_list.db= share->db.str;
637
table_list.table_name= share->table_name.str;
639
/* need to check if we haven't already listed it */
640
for (table= open_list ; table ; table=table->next)
213
if (!(*it).table.compare(entry->s->table_name.str) &&
214
!(*it).db.compare(entry->s->db.str))
642
if (!strcmp(table->table, share->table_name.str) &&
643
!strcmp(table->db, share->db.str))
218
if (entry->locked_by_name)
647
if (entry->locked_by_name)
230
table.db= entry->s->db.str;
231
table.table= entry->s->table_name.str;
232
open_list.push_back(table);
234
pthread_mutex_unlock(&LOCK_open);
236
for (it= open_list.begin(); it < open_list.end(); it++)
238
if (func(display, *it, schema_table))
654
if (!(*start_list = (OPEN_TABLE_LIST *)
655
sql_alloc(sizeof(**start_list)+share->table_cache_key.length)))
657
open_list=0; // Out of memory
660
strmov((*start_list)->table=
661
strmov(((*start_list)->db= (char*) ((*start_list)+1)),
663
share->table_name.str);
664
(*start_list)->in_use= entry->in_use ? 1 : 0;
665
(*start_list)->locked= entry->locked_by_name ? 1 : 0;
666
start_list= &(*start_list)->next;
669
VOID(pthread_mutex_unlock(&LOCK_open));
670
DBUG_RETURN(open_list);
245
673
/*****************************************************************************
448
909
table->s->version= refresh_version;
452
pthread_mutex_unlock(&LOCK_open);
913
VOID(pthread_mutex_unlock(&LOCK_open));
454
914
if (wait_for_refresh)
456
pthread_mutex_lock(&session->mysys_var->mutex);
457
session->mysys_var->current_mutex= 0;
458
session->mysys_var->current_cond= 0;
459
session->set_proc_info(0);
460
pthread_mutex_unlock(&session->mysys_var->mutex);
916
pthread_mutex_lock(&thd->mysys_var->mutex);
917
thd->mysys_var->current_mutex= 0;
918
thd->mysys_var->current_cond= 0;
919
thd_proc_info(thd, 0);
920
pthread_mutex_unlock(&thd->mysys_var->mutex);
927
Close all tables which match specified connection string or
928
if specified string is NULL, then any table with a connection string.
931
bool close_cached_connection_tables(THD *thd, bool if_wait_for_refresh,
932
LEX_STRING *connection, bool have_lock)
935
TABLE_LIST tmp, *tables= NULL;
937
DBUG_ENTER("close_cached_connections");
940
bzero(&tmp, sizeof(TABLE_LIST));
943
VOID(pthread_mutex_lock(&LOCK_open));
945
for (idx= 0; idx < table_def_cache.records; idx++)
947
TABLE_SHARE *share= (TABLE_SHARE *) hash_element(&table_def_cache, idx);
949
/* Ignore if table is not open or does not have a connect_string */
950
if (!share->connect_string.length || !share->ref_count)
953
/* Compare the connection string */
955
(connection->length > share->connect_string.length ||
956
(connection->length < share->connect_string.length &&
957
(share->connect_string.str[connection->length] != '/' &&
958
share->connect_string.str[connection->length] != '\\')) ||
959
strncasecmp(connection->str, share->connect_string.str,
960
connection->length)))
963
/* close_cached_tables() only uses these elements */
964
tmp.db= share->db.str;
965
tmp.table_name= share->table_name.str;
966
tmp.next_local= tables;
968
tables= (TABLE_LIST *) memdup_root(thd->mem_root, (char*)&tmp,
973
result= close_cached_tables(thd, tables, TRUE, FALSE, FALSE);
976
VOID(pthread_mutex_unlock(&LOCK_open));
978
if (if_wait_for_refresh)
980
pthread_mutex_lock(&thd->mysys_var->mutex);
981
thd->mysys_var->current_mutex= 0;
982
thd->mysys_var->current_cond= 0;
984
pthread_mutex_unlock(&thd->mysys_var->mutex);
468
move one table to free list
471
bool Session::free_cached_table()
473
bool found_old_table= false;
474
Table *table= open_tables;
476
safe_mutex_assert_owner(&LOCK_open);
477
assert(table->key_read == 0);
478
assert(!table->cursor || table->cursor->inited == Cursor::NONE);
480
open_tables= table->next;
482
if (table->needs_reopen_or_name_lock() ||
483
version != refresh_version || !table->db_stat)
485
hash_delete(&open_cache,(unsigned char*) table);
486
found_old_table= true;
491
Open placeholders have Table::db_stat set to 0, so they should be
492
handled by the first alternative.
494
assert(!table->open_placeholder);
496
/* Free memory and reset for next loop */
497
table->cursor->ha_reset();
498
table->in_use= false;
502
table->next= unused_tables; /* Link in last */
503
table->prev= unused_tables->prev;
504
unused_tables->prev= table;
505
table->prev->next= table;
508
unused_tables= table->next=table->prev=table;
511
return found_old_table;
992
Mark all temporary tables which were used by the current statement or
993
substatement as free for reuse, but only if the query_id can be cleared.
995
@param thd thread context
997
@remark For temp tables associated with a open SQL HANDLER the query_id
998
is not reset until the HANDLER is closed.
1001
static void mark_temp_tables_as_free_for_reuse(THD *thd)
1003
for (TABLE *table= thd->temporary_tables ; table ; table= table->next)
1005
if ((table->query_id == thd->query_id) && ! table->open_by_handler)
1008
table->file->ha_reset();
1015
Mark all tables in the list which were used by current substatement
1019
mark_used_tables_as_free_for_reuse()
1020
thd - thread context
1021
table - head of the list of tables
1024
Marks all tables in the list which were used by current substatement
1025
(they are marked by its query_id) as free for reuse.
1028
The reason we reset query_id is that it's not enough to just test
1029
if table->query_id != thd->query_id to know if a table is in use.
1032
SELECT f1_that_uses_t1() FROM t1;
1033
In f1_that_uses_t1() we will see one instance of t1 where query_id is
1034
set to query_id of original query.
1037
static void mark_used_tables_as_free_for_reuse(THD *thd, TABLE *table)
1039
for (; table ; table= table->next)
1041
if (table->query_id == thd->query_id)
1044
table->file->ha_reset();
516
1051
Auxiliary function to close all tables in the open_tables list.
518
@param session Thread context.
1053
@param thd Thread context.
520
1055
@remark It should not ordinarily be called directly.
523
void Session::close_open_tables()
1058
static void close_open_tables(THD *thd)
525
bool found_old_table= false;
1060
bool found_old_table= 0;
527
1062
safe_mutex_assert_not_owner(&LOCK_open);
529
pthread_mutex_lock(&LOCK_open); /* Close all open tables on Session */
532
found_old_table|= free_cached_table();
533
some_tables_deleted= false;
1064
VOID(pthread_mutex_lock(&LOCK_open));
1066
DBUG_PRINT("info", ("thd->open_tables: 0x%lx", (long) thd->open_tables));
1068
while (thd->open_tables)
1069
found_old_table|= close_thread_table(thd, &thd->open_tables);
1070
thd->some_tables_deleted= 0;
1072
/* Free tables to hold down open files */
1073
while (open_cache.records > table_cache_size && unused_tables)
1074
VOID(hash_delete(&open_cache,(uchar*) unused_tables)); /* purecov: tested */
535
1076
if (found_old_table)
537
1078
/* Tell threads waiting for refresh that something has happened */
538
1079
broadcast_refresh();
541
pthread_mutex_unlock(&LOCK_open);
1082
VOID(pthread_mutex_unlock(&LOCK_open));
1087
Close all tables used by the current substatement, or all tables
1088
used by this thread if we are on the upper level.
1091
close_thread_tables()
1095
Unlocks tables and frees derived tables.
1096
Put all normal tables used by thread in free list.
1098
It will only close/mark as free for reuse tables opened by this
1099
substatement, it will also check if we are closing tables after
1100
execution of complete query (i.e. we are on upper level) and will
1101
leave prelocked mode if needed.
1104
void close_thread_tables(THD *thd)
1107
DBUG_ENTER("close_thread_tables");
1110
We are assuming here that thd->derived_tables contains ONLY derived
1111
tables for this substatement. i.e. instead of approach which uses
1112
query_id matching for determining which of the derived tables belong
1113
to this substatement we rely on the ability of substatements to
1114
save/restore thd->derived_tables during their execution.
1116
TODO: Probably even better approach is to simply associate list of
1117
derived tables with (sub-)statement instead of thread and destroy
1118
them at the end of its execution.
1120
if (thd->derived_tables)
1124
Close all derived tables generated in queries like
1125
SELECT * FROM (SELECT * FROM t1)
1127
for (table= thd->derived_tables ; table ; table= next)
1130
free_tmp_table(thd, table);
1132
thd->derived_tables= 0;
1136
Mark all temporary tables used by this statement as free for reuse.
1138
mark_temp_tables_as_free_for_reuse(thd);
1140
Let us commit transaction for statement. Since in 5.0 we only have
1141
one statement transaction and don't allow several nested statement
1142
transactions this call will do nothing if we are inside of stored
1143
function or trigger (i.e. statement transaction is already active and
1144
does not belong to statement for which we do close_thread_tables()).
1145
TODO: This should be fixed in later releases.
1147
if (!(thd->state_flags & Open_tables_state::BACKUPS_AVAIL))
1149
thd->main_da.can_overwrite_status= TRUE;
1150
ha_autocommit_or_rollback(thd, thd->is_error());
1151
thd->main_da.can_overwrite_status= FALSE;
1152
thd->transaction.stmt.reset();
1155
if (thd->locked_tables)
1158
/* Ensure we are calling ha_reset() for all used tables */
1159
mark_used_tables_as_free_for_reuse(thd, thd->open_tables);
1162
We are under simple LOCK TABLES so should not do anything else.
1170
For RBR we flush the pending event just before we unlock all the
1171
tables. This means that we are at the end of a topmost
1172
statement, so we ensure that the STMT_END_F flag is set on the
1173
pending event. For statements that are *inside* stored
1174
functions, the pending event will not be flushed: that will be
1175
handled either before writing a query log event (inside
1176
binlog_query()) or when preparing a pending event.
1178
thd->binlog_flush_pending_rows_event(TRUE);
1179
mysql_unlock_tables(thd, thd->lock);
1183
Note that we need to hold LOCK_open while changing the
1184
open_tables list. Another thread may work on it.
1185
(See: remove_table_from_cache(), mysql_wait_completed_table())
1186
Closing a MERGE child before the parent would be fatal if the
1187
other thread tries to abort the MERGE lock in between.
1189
if (thd->open_tables)
1190
close_open_tables(thd);
1196
/* move one table to free list */
1198
bool close_thread_table(THD *thd, TABLE **table_ptr)
1200
bool found_old_table= 0;
1201
TABLE *table= *table_ptr;
1202
DBUG_ENTER("close_thread_table");
1203
DBUG_ASSERT(table->key_read == 0);
1204
DBUG_ASSERT(!table->file || table->file->inited == handler::NONE);
1205
DBUG_PRINT("tcache", ("table: '%s'.'%s' 0x%lx", table->s->db.str,
1206
table->s->table_name.str, (long) table));
1208
*table_ptr=table->next;
1210
if (table->needs_reopen_or_name_lock() ||
1211
thd->version != refresh_version || !table->db_stat)
1213
VOID(hash_delete(&open_cache,(uchar*) table));
1219
Open placeholders have TABLE::db_stat set to 0, so they should be
1220
handled by the first alternative.
1222
DBUG_ASSERT(!table->open_placeholder);
1224
/* Free memory and reset for next loop */
1225
table->file->ha_reset();
1229
table->next=unused_tables; /* Link in last */
1230
table->prev=unused_tables->prev;
1231
unused_tables->prev=table;
1232
table->prev->next=table;
1235
unused_tables=table->next=table->prev=table;
1237
DBUG_RETURN(found_old_table);
1241
/* close_temporary_tables' internal, 4 is due to uint4korr definition */
1242
static inline uint tmpkeyval(THD *thd, TABLE *table)
1244
return uint4korr(table->s->table_cache_key.str + table->s->table_cache_key.length - 4);
1249
Close all temporary tables created by 'CREATE TEMPORARY TABLE' for thread
1250
creates one DROP TEMPORARY TABLE binlog event for each pseudo-thread
1253
void close_temporary_tables(THD *thd)
1258
/* Assume thd->options has OPTION_QUOTE_SHOW_CREATE */
1259
bool was_quote_show= TRUE;
1261
if (!thd->temporary_tables)
1264
if (!mysql_bin_log.is_open() || thd->current_stmt_binlog_row_based)
1267
for (table= thd->temporary_tables; table; table= tmp_next)
1269
tmp_next= table->next;
1270
close_temporary(table, 1, 1);
1272
thd->temporary_tables= 0;
1276
/* Better add "if exists", in case a RESET MASTER has been done */
1277
const char stub[]= "DROP /*!40005 TEMPORARY */ TABLE IF EXISTS ";
1278
uint stub_len= sizeof(stub) - 1;
1280
String s_query= String(buf, sizeof(buf), system_charset_info);
1281
bool found_user_tables= FALSE;
1283
memcpy(buf, stub, stub_len);
1286
Insertion sort of temp tables by pseudo_thread_id to build ordered list
1287
of sublists of equal pseudo_thread_id
1290
for (prev_table= thd->temporary_tables, table= prev_table->next;
1292
prev_table= table, table= table->next)
1294
TABLE *prev_sorted /* same as for prev_table */, *sorted;
1295
if (is_user_table(table))
1297
if (!found_user_tables)
1298
found_user_tables= true;
1299
for (prev_sorted= NULL, sorted= thd->temporary_tables; sorted != table;
1300
prev_sorted= sorted, sorted= sorted->next)
1302
if (!is_user_table(sorted) ||
1303
tmpkeyval(thd, sorted) > tmpkeyval(thd, table))
1305
/* move into the sorted part of the list from the unsorted */
1306
prev_table->next= table->next;
1307
table->next= sorted;
1310
prev_sorted->next= table;
1314
thd->temporary_tables= table;
1323
/* We always quote db,table names though it is slight overkill */
1324
if (found_user_tables &&
1325
!(was_quote_show= test(thd->options & OPTION_QUOTE_SHOW_CREATE)))
1327
thd->options |= OPTION_QUOTE_SHOW_CREATE;
1330
/* scan sorted tmps to generate sequence of DROP */
1331
for (table= thd->temporary_tables; table; table= next)
1333
if (is_user_table(table))
1335
my_thread_id save_pseudo_thread_id= thd->variables.pseudo_thread_id;
1336
/* Set pseudo_thread_id to be that of the processed table */
1337
thd->variables.pseudo_thread_id= tmpkeyval(thd, table);
1339
Loop forward through all tables within the sublist of
1340
common pseudo_thread_id to create single DROP query.
1342
for (s_query.length(stub_len);
1343
table && is_user_table(table) &&
1344
tmpkeyval(thd, table) == thd->variables.pseudo_thread_id;
1348
We are going to add 4 ` around the db/table names and possible more
1349
due to special characters in the names
1351
append_identifier(thd, &s_query, table->s->db.str, strlen(table->s->db.str));
1352
s_query.append('.');
1353
append_identifier(thd, &s_query, table->s->table_name.str,
1354
strlen(table->s->table_name.str));
1355
s_query.append(',');
1357
close_temporary(table, 1, 1);
1360
CHARSET_INFO *cs_save= thd->variables.character_set_client;
1361
thd->variables.character_set_client= system_charset_info;
1362
Query_log_event qinfo(thd, s_query.ptr(),
1363
s_query.length() - 1 /* to remove trailing ',' */,
1365
thd->variables.character_set_client= cs_save;
1367
Imagine the thread had created a temp table, then was doing a
1368
SELECT, and the SELECT was killed. Then it's not clever to
1369
mark the statement above as "killed", because it's not really
1370
a statement updating data, and there are 99.99% chances it
1371
will succeed on slave. If a real update (one updating a
1372
persistent table) was killed on the master, then this real
1373
update will be logged with error_code=killed, rightfully
1374
causing the slave to stop.
1376
qinfo.error_code= 0;
1377
mysql_bin_log.write(&qinfo);
1378
thd->variables.pseudo_thread_id= save_pseudo_thread_id;
1383
close_temporary(table, 1, 1);
1386
if (!was_quote_show)
1387
thd->options&= ~OPTION_QUOTE_SHOW_CREATE; /* restore option */
1388
thd->temporary_tables=0;
545
1392
Find table in list.
549
table Pointer to table list
550
offset Offset to which list in table structure to use
551
db_name Data base name
552
table_name Table name
555
This is called by find_table_in_global_list().
559
# Pointer to found table.
1395
find_table_in_list()
1396
table Pointer to table list
1397
offset Offset to which list in table structure to use
1398
db_name Data base name
1399
table_name Table name
1402
This is called by find_table_in_local_list() and
1403
find_table_in_global_list().
1406
NULL Table not found
1407
# Pointer to found table.
562
TableList *find_table_in_list(TableList *table,
563
TableList *TableList::*link,
565
const char *table_name)
1410
TABLE_LIST *find_table_in_list(TABLE_LIST *table,
1411
TABLE_LIST *TABLE_LIST::*link,
1412
const char *db_name,
1413
const char *table_name)
567
1415
for (; table; table= table->*link )
579
1427
Test that table is unique (It's only exists once in the table list)
583
session thread handle
584
table table which should be checked
585
table_list list of tables
586
check_alias whether to check tables' aliases
588
NOTE: to exclude derived tables from check we use following mechanism:
589
a) during derived table processing set Session::derived_tables_processing
590
b) JOIN::prepare set SELECT::exclude_from_table_unique_test if
591
Session::derived_tables_processing set. (we can't use JOIN::execute
592
because for PS we perform only JOIN::prepare, but we can't set this
593
flag in JOIN::prepare if we are not sure that we are in derived table
594
processing loop, because multi-update call fix_fields() for some its
595
items (which mean JOIN::prepare for subqueries) before unique_table
596
call to detect which tables should be locked for write).
597
c) unique_table skip all tables which belong to SELECT with
598
SELECT::exclude_from_table_unique_test set.
599
Also SELECT::exclude_from_table_unique_test used to exclude from check
600
tables of main SELECT of multi-delete and multi-update
602
We also skip tables with TableList::prelocking_placeholder set,
603
because we want to allow SELECTs from them, and their modification
604
will rise the error anyway.
606
TODO: when we will have table/view change detection we can do this check
1432
table table which should be checked
1433
table_list list of tables
1434
check_alias whether to check tables' aliases
1436
NOTE: to exclude derived tables from check we use following mechanism:
1437
a) during derived table processing set THD::derived_tables_processing
1438
b) JOIN::prepare set SELECT::exclude_from_table_unique_test if
1439
THD::derived_tables_processing set. (we can't use JOIN::execute
1440
because for PS we perform only JOIN::prepare, but we can't set this
1441
flag in JOIN::prepare if we are not sure that we are in derived table
1442
processing loop, because multi-update call fix_fields() for some its
1443
items (which mean JOIN::prepare for subqueries) before unique_table
1444
call to detect which tables should be locked for write).
1445
c) unique_table skip all tables which belong to SELECT with
1446
SELECT::exclude_from_table_unique_test set.
1447
Also SELECT::exclude_from_table_unique_test used to exclude from check
1448
tables of main SELECT of multi-delete and multi-update
1450
We also skip tables with TABLE_LIST::prelocking_placeholder set,
1451
because we want to allow SELECTs from them, and their modification
1452
will rise the error anyway.
1454
TODO: when we will have table/view change detection we can do this check
1459
0 if table is unique
614
TableList* unique_table(TableList *table, TableList *table_list,
1462
TABLE_LIST* unique_table(THD *thd, TABLE_LIST *table, TABLE_LIST *table_list,
618
1466
const char *d_name, *t_name, *t_alias;
1467
DBUG_ENTER("unique_table");
1468
DBUG_PRINT("enter", ("table alias: %s", table->alias));
621
1471
If this function called for query which update table (INSERT/UPDATE/...)
622
then we have in table->table pointer to Table object which we are
623
updating even if it is VIEW so we need TableList of this Table object
1472
then we have in table->table pointer to TABLE object which we are
1473
updating even if it is VIEW so we need TABLE_LIST of this TABLE object
624
1474
to get right names (even if lower_case_table_names used).
626
1476
If this function called for CREATE command that we have not opened table
627
(table->table equal to 0) and right names is in current TableList
1477
(table->table equal to 0) and right names is in current TABLE_LIST
630
1480
if (table->table)
632
1482
/* temporary table is always unique */
633
1483
if (table->table && table->table->s->tmp_table != NO_TMP_TABLE)
635
1485
table= table->find_underlying_table(table->table);
637
as far as we have table->table we have to find real TableList of
1487
as far as we have table->table we have to find real TABLE_LIST of
638
1488
it in underlying tables
642
1492
d_name= table->db;
643
1493
t_name= table->table_name;
644
1494
t_alias= table->alias;
1496
DBUG_PRINT("info", ("real table: %s.%s", d_name, t_name));
648
if ((! (res= find_table_in_global_list(table_list, d_name, t_name))) ||
1499
if (((! (res= find_table_in_global_list(table_list, d_name, t_name))) &&
1500
(! (res= mysql_lock_have_duplicate(thd, table, table_list)))) ||
649
1501
((!res->table || res->table != table->table) &&
650
(!check_alias || !(my_strcasecmp(files_charset_info, t_alias, res->alias))) &&
1502
(!check_alias || !(lower_case_table_names ?
1503
my_strcasecmp(files_charset_info, t_alias, res->alias) :
1504
strcmp(t_alias, res->alias))) &&
651
1505
res->select_lex && !res->select_lex->exclude_from_table_unique_test))
656
1510
(exclude_from_table_unique_test) or prelocking placeholder.
658
1512
table_list= res->next_global;
1514
("found same copy of table or table which we should skip"));
664
Table *Session::find_temporary_table(const char *new_db, const char *table_name)
1521
Issue correct error message in case we found 2 duplicate tables which
1522
prevent some update operation
1525
update_non_unique_table_error()
1526
update table which we try to update
1527
operation name of update operation
1528
duplicate duplicate table which we found
1531
here we hide view underlying tables if we have them
1534
void update_non_unique_table_error(TABLE_LIST *update,
1535
const char *operation,
1536
TABLE_LIST *duplicate)
1538
my_error(ER_UPDATE_TABLE_USED, MYF(0), update->alias);
1542
TABLE *find_temporary_table(THD *thd, const char *db, const char *table_name)
1544
TABLE_LIST table_list;
1546
table_list.db= (char*) db;
1547
table_list.table_name= (char*) table_name;
1548
return find_temporary_table(thd, &table_list);
1552
TABLE *find_temporary_table(THD *thd, TABLE_LIST *table_list)
666
1554
char key[MAX_DBKEY_LENGTH];
667
1555
uint key_length;
670
key_length= TableShare::createKey(key, new_db, table_name);
672
for (table= temporary_tables ; table ; table= table->next)
1557
DBUG_ENTER("find_temporary_table");
1558
DBUG_PRINT("enter", ("table: '%s'.'%s'",
1559
table_list->db, table_list->table_name));
1561
key_length= create_table_def_key(thd, key, table_list, 1);
1562
for (table=thd->temporary_tables ; table ; table= table->next)
674
1564
if (table->s->table_cache_key.length == key_length &&
675
!memcmp(table->s->table_cache_key.str, key, key_length))
1565
!memcmp(table->s->table_cache_key.str, key, key_length))
1568
("Found table. server_id: %u pseudo_thread_id: %lu",
1569
(uint) thd->server_id,
1570
(ulong) thd->variables.pseudo_thread_id));
678
return NULL; // Not a temporary table
681
Table *Session::find_temporary_table(TableList *table_list)
683
return find_temporary_table(table_list->db, table_list->table_name);
1574
DBUG_RETURN(0); // Not a temporary table
688
1579
Drop a temporary table.
690
Try to locate the table in the list of session->temporary_tables.
1581
Try to locate the table in the list of thd->temporary_tables.
691
1582
If the table is found:
692
- if the table is being used by some outer statement, fail.
693
- if the table is in session->locked_tables, unlock it and
694
remove it from the list of locked tables. Currently only transactional
695
temporary tables are present in the locked_tables list.
696
- Close the temporary table, remove its .FRM
697
- remove the table from the list of temporary tables
1583
- if the table is being used by some outer statement, fail.
1584
- if the table is in thd->locked_tables, unlock it and
1585
remove it from the list of locked tables. Currently only transactional
1586
temporary tables are present in the locked_tables list.
1587
- Close the temporary table, remove its .FRM
1588
- remove the table from the list of temporary tables
699
1590
This function is used to drop user temporary tables, as well as
700
1591
internal tables created in CREATE TEMPORARY TABLE ... SELECT
701
or ALTER Table. Even though part of the work done by this function
1592
or ALTER TABLE. Even though part of the work done by this function
702
1593
is redundant when the table is internal, as long as we
703
1594
link both internal and user temporary tables into the same
704
session->temporary_tables list, it's impossible to tell here whether
1595
thd->temporary_tables list, it's impossible to tell here whether
705
1596
we're dealing with an internal or a user temporary table.
707
1598
@retval 0 the table was found and dropped successfully.
708
1599
@retval 1 the table was not found in the list of temporary tables
710
1601
@retval -1 the table is in use by a outer query
713
int Session::drop_temporary_table(TableList *table_list)
1604
int drop_temporary_table(THD *thd, TABLE_LIST *table_list)
1607
DBUG_ENTER("drop_temporary_table");
1608
DBUG_PRINT("tmptable", ("closing table: '%s'.'%s'",
1609
table_list->db, table_list->table_name));
717
if (!(table= find_temporary_table(table_list)))
1611
if (!(table= find_temporary_table(thd, table_list)))
720
1614
/* Table might be in use by some outer statement. */
721
if (table->query_id && table->query_id != query_id)
1615
if (table->query_id && table->query_id != thd->query_id)
723
1617
my_error(ER_CANT_REOPEN_TABLE, MYF(0), table->alias);
727
close_temporary_table(table);
733
/* move table first in unused links */
735
static void relink_unused(Table *table)
1622
If LOCK TABLES list is not empty and contains this table,
1623
unlock the table and remove the table from this list.
1625
mysql_lock_remove(thd, thd->locked_tables, table, FALSE);
1626
close_temporary_table(thd, table, 1, 1);
1631
unlink from thd->temporary tables and close temporary table
1634
void close_temporary_table(THD *thd, TABLE *table,
1635
bool free_share, bool delete_table)
1637
DBUG_ENTER("close_temporary_table");
1638
DBUG_PRINT("tmptable", ("closing table: '%s'.'%s' 0x%lx alias: '%s'",
1639
table->s->db.str, table->s->table_name.str,
1640
(long) table, table->alias));
1644
table->prev->next= table->next;
1645
if (table->prev->next)
1646
table->next->prev= table->prev;
1650
/* removing the item from the list */
1651
DBUG_ASSERT(table == thd->temporary_tables);
1653
slave must reset its temporary list pointer to zero to exclude
1654
passing non-zero value to end_slave via rli->save_temporary_tables
1655
when no temp tables opened, see an invariant below.
1657
thd->temporary_tables= table->next;
1658
if (thd->temporary_tables)
1659
table->next->prev= 0;
1661
if (thd->slave_thread)
1663
/* natural invariant of temporary_tables */
1664
DBUG_ASSERT(slave_open_temp_tables || !thd->temporary_tables);
1665
slave_open_temp_tables--;
1667
close_temporary(table, free_share, delete_table);
1673
Close and delete a temporary table
1676
This dosn't unlink table from thd->temporary
1677
If this is needed, use close_temporary_table()
1680
void close_temporary(TABLE *table, bool free_share, bool delete_table)
1682
handlerton *table_type= table->s->db_type();
1683
DBUG_ENTER("close_temporary");
1684
DBUG_PRINT("tmptable", ("closing table: '%s'.'%s'",
1685
table->s->db.str, table->s->table_name.str));
1687
free_io_cache(table);
1690
Check that temporary table has not been created with
1691
frm_only because it has then not been created in any storage engine
1694
rm_temporary_table(table_type, table->s->path.str,
1695
table->s->tmp_table == TMP_TABLE_FRM_FILE_ONLY);
1698
free_table_share(table->s);
1699
my_free((char*) table,MYF(0));
1706
Used by ALTER TABLE when the table is a temporary one. It changes something
1707
only if the ALTER contained a RENAME clause (otherwise, table_name is the old
1709
Prepares a table cache key, which is the concatenation of db, table_name and
1710
thd->slave_proxy_id, separated by '\0'.
1713
bool rename_temporary_table(THD* thd, TABLE *table, const char *db,
1714
const char *table_name)
1718
TABLE_SHARE *share= table->s;
1719
TABLE_LIST table_list;
1720
DBUG_ENTER("rename_temporary_table");
1722
if (!(key=(char*) alloc_root(&share->mem_root, MAX_DBKEY_LENGTH)))
1723
DBUG_RETURN(1); /* purecov: inspected */
1725
table_list.db= (char*) db;
1726
table_list.table_name= (char*) table_name;
1727
key_length= create_table_def_key(thd, key, &table_list, 1);
1728
share->set_table_cache_key(key, key_length);
1733
/* move table first in unused links */
1735
static void relink_unused(TABLE *table)
737
1737
if (table != unused_tables)
793
1805
// Notify any 'refresh' threads
794
1806
broadcast_refresh();
799
Auxiliary routine which closes and drops open table.
801
@param session Thread handle
802
@param table Table object for table to be dropped
803
@param db_name Name of database for this table
804
@param table_name Name of this table
806
@note This routine assumes that table to be closed is open only
807
by calling thread so we needn't wait until other threads
808
will close the table. Also unless called under implicit or
809
explicit LOCK TABLES mode it assumes that table to be
810
dropped is already unlocked. In the former case it will
811
also remove lock on the table. But one should not rely on
812
this behaviour as it may change in future.
813
Currently, however, this function is never called for a
814
table that was locked with LOCK TABLES.
1812
Auxiliary routine which closes and drops open table.
1814
@param thd Thread handle
1815
@param table TABLE object for table to be dropped
1816
@param db_name Name of database for this table
1817
@param table_name Name of this table
1819
@note This routine assumes that table to be closed is open only
1820
by calling thread so we needn't wait until other threads
1821
will close the table. Also unless called under implicit or
1822
explicit LOCK TABLES mode it assumes that table to be
1823
dropped is already unlocked. In the former case it will
1824
also remove lock on the table. But one should not rely on
1825
this behaviour as it may change in future.
1826
Currently, however, this function is never called for a
1827
table that was locked with LOCK TABLES.
817
void Session::drop_open_table(Table *table, const char *db_name,
818
const char *table_name)
1830
void drop_open_table(THD *thd, TABLE *table, const char *db_name,
1831
const char *table_name)
820
1833
if (table->s->tmp_table)
822
close_temporary_table(table);
1834
close_temporary_table(thd, table, 1, 1);
826
pthread_mutex_lock(&LOCK_open); /* Close and drop a table (AUX routine) */
1837
handlerton *table_type= table->s->db_type();
1838
VOID(pthread_mutex_lock(&LOCK_open));
828
1840
unlink_open_table() also tells threads waiting for refresh or close
829
1841
that something has happened.
831
unlink_open_table(table);
832
TableIdentifier identifier(db_name, table_name, NO_TMP_TABLE);
833
quick_rm_table(*this, identifier);
834
pthread_mutex_unlock(&LOCK_open);
1843
unlink_open_table(thd, table, FALSE);
1844
quick_rm_table(table_type, db_name, table_name, 0);
1845
VOID(pthread_mutex_unlock(&LOCK_open));
840
Wait for condition but allow the user to send a kill to mysqld
1851
Wait for condition but allow the user to send a kill to mysqld
844
session Thread Cursor
845
mutex mutex that is currently hold that is associated with condition
846
Will be unlocked on return
847
cond Condition to wait for
1854
wait_for_condition()
1856
mutex mutex that is currently hold that is associated with condition
1857
Will be unlocked on return
1858
cond Condition to wait for
850
void Session::wait_for_condition(pthread_mutex_t *mutex, pthread_cond_t *cond)
1861
void wait_for_condition(THD *thd, pthread_mutex_t *mutex, pthread_cond_t *cond)
852
1863
/* Wait until the current table is up to date */
853
const char *saved_proc_info;
854
mysys_var->current_mutex= mutex;
855
mysys_var->current_cond= cond;
856
saved_proc_info= get_proc_info();
857
set_proc_info("Waiting for table");
1864
const char *proc_info;
1865
thd->mysys_var->current_mutex= mutex;
1866
thd->mysys_var->current_cond= cond;
1867
proc_info=thd->proc_info;
1868
thd_proc_info(thd, "Waiting for table");
1869
DBUG_ENTER("wait_for_condition");
859
1871
(void) pthread_cond_wait(cond, mutex);
927
1976
object to its original state.
929
1978
*table= orig_table;
933
1982
share= table->s;
935
1984
We want to prevent other connections from opening this table until end
936
1985
of statement as it is likely that modifications of table's metadata are
937
not yet finished (for example CREATE TRIGGER have to change .TRG cursor,
1986
not yet finished (for example CREATE TRIGGER have to change .TRG file,
938
1987
or we might want to drop table if CREATE TABLE ... SELECT fails).
939
1988
This also allows us to assume that no other connection will sneak in
940
1989
before we will get table-level lock on this table.
942
1991
share->version=0;
943
table->in_use = this;
1992
table->in_use = thd;
947
table->next= open_tables;
1997
table->next= thd->open_tables;
1998
thd->open_tables= table;
953
Table object should be already in Session::open_tables list so we just
954
need to set Table::next correctly.
2003
TABLE object should be already in THD::open_tables list so we just
2004
need to set TABLE::next correctly.
956
2006
table->next= orig_table.next;
959
table->tablenr= current_tablenr++;
960
table->used_fields= 0;
961
table->const_table= 0;
962
table->null_row= false;
963
table->maybe_null= false;
964
table->force_index= false;
965
table->status= STATUS_NO_RECORD;
2009
table->tablenr=thd->current_tablenr++;
2010
table->used_fields=0;
2011
table->const_table=0;
2012
table->null_row= table->maybe_null= table->force_index= 0;
2013
table->status=STATUS_NO_RECORD;
972
Create and insert into table cache placeholder for table
973
which will prevent its opening (or creation) (a.k.a lock
976
@param session Thread context
977
@param key Table cache key for name to be locked
978
@param key_length Table cache key length
980
@return Pointer to Table object used for name locking or 0 in
2019
Create and insert into table cache placeholder for table
2020
which will prevent its opening (or creation) (a.k.a lock
2023
@param thd Thread context
2024
@param key Table cache key for name to be locked
2025
@param key_length Table cache key length
2027
@return Pointer to TABLE object used for name locking or 0 in
984
Table *Session::table_cache_insert_placeholder(const char *key, uint32_t key_length)
2031
TABLE *table_cache_insert_placeholder(THD *thd, const char *key,
2037
DBUG_ENTER("table_cache_insert_placeholder");
990
2039
safe_mutex_assert_owner(&LOCK_open);
993
2042
Create a table entry with the right key and with an old refresh version
994
Note that we must use multi_malloc() here as this is freed by the
2043
Note that we must use my_multi_malloc() here as this is freed by the
997
if (! memory::multi_malloc(true,
998
&table, sizeof(*table),
999
&share, sizeof(*share),
1000
&key_buff, key_length,
2046
if (!my_multi_malloc(MYF(MY_WME | MY_ZEROFILL),
2047
&table, sizeof(*table),
2048
&share, sizeof(*share),
2049
&key_buff, key_length,
1004
2053
table->s= share;
1005
2054
share->set_table_cache_key(key_buff, key, key_length);
1006
2055
share->tmp_table= INTERNAL_TMP_TABLE; // for intern_close_table
1007
table->in_use= this;
1008
2057
table->locked_by_name=1;
1010
if (my_hash_insert(&open_cache, (unsigned char*)table))
2059
if (my_hash_insert(&open_cache, (uchar*)table))
1012
free((unsigned char*) table);
2061
my_free((uchar*) table, MYF(0));
1021
Obtain an exclusive name lock on the table if it is not cached
1024
@param session Thread context
1025
@param db Name of database
1026
@param table_name Name of table
1027
@param[out] table Out parameter which is either:
1028
- set to NULL if table cache contains record for
1030
- set to point to the Table instance used for
1033
@note This function takes into account all records for table in table
1034
cache, even placeholders used for name-locking. This means that
1035
'table' parameter can be set to NULL for some situations when
1036
table does not really exist.
1038
@retval true Error occured (OOM)
1039
@retval false Success. 'table' parameter set according to above rules.
2070
Obtain an exclusive name lock on the table if it is not cached
2073
@param thd Thread context
2074
@param db Name of database
2075
@param table_name Name of table
2076
@param[out] table Out parameter which is either:
2077
- set to NULL if table cache contains record for
2079
- set to point to the TABLE instance used for
2082
@note This function takes into account all records for table in table
2083
cache, even placeholders used for name-locking. This means that
2084
'table' parameter can be set to NULL for some situations when
2085
table does not really exist.
2087
@retval TRUE Error occured (OOM)
2088
@retval FALSE Success. 'table' parameter set according to above rules.
1042
bool Session::lock_table_name_if_not_cached(const char *new_db,
1043
const char *table_name, Table **table)
2091
bool lock_table_name_if_not_cached(THD *thd, const char *db,
2092
const char *table_name, TABLE **table)
1045
2094
char key[MAX_DBKEY_LENGTH];
1047
uint32_t key_length;
1049
key_pos= strcpy(key_pos, new_db) + strlen(new_db);
1050
key_pos= strcpy(key_pos+1, table_name) + strlen(table_name);
1051
key_length= (uint32_t) (key_pos-key)+1;
1053
pthread_mutex_lock(&LOCK_open); /* Obtain a name lock even though table is not in cache (like for create table) */
1055
if (hash_search(&open_cache, (unsigned char *)key, key_length))
2096
DBUG_ENTER("lock_table_name_if_not_cached");
2098
key_length= (uint)(strmov(strmov(key, db) + 1, table_name) - key) + 1;
2099
VOID(pthread_mutex_lock(&LOCK_open));
2101
if (hash_search(&open_cache, (uchar *)key, key_length))
1057
pthread_mutex_unlock(&LOCK_open);
2103
VOID(pthread_mutex_unlock(&LOCK_open));
2104
DBUG_PRINT("info", ("Table is cached, name-lock is not obtained"));
1061
if (!(*table= table_cache_insert_placeholder(key, key_length)))
1063
pthread_mutex_unlock(&LOCK_open);
1066
(*table)->open_placeholder= true;
1067
(*table)->next= open_tables;
1068
open_tables= *table;
1069
pthread_mutex_unlock(&LOCK_open);
2108
if (!(*table= table_cache_insert_placeholder(thd, key, key_length)))
2110
VOID(pthread_mutex_unlock(&LOCK_open));
2113
(*table)->open_placeholder= 1;
2114
(*table)->next= thd->open_tables;
2115
thd->open_tables= *table;
2116
VOID(pthread_mutex_unlock(&LOCK_open));
2122
Check that table exists in table definition cache, on disk
2123
or in some storage engine.
2125
@param thd Thread context
2126
@param table Table list element
2127
@param[out] exists Out parameter which is set to TRUE if table
2128
exists and to FALSE otherwise.
2130
@note This function assumes that caller owns LOCK_open mutex.
2131
It also assumes that the fact that there are no name-locks
2132
on the table was checked beforehand.
2134
@note If there is no .FRM file for the table but it exists in one
2135
of engines (e.g. it was created on another node of NDB cluster)
2136
this function will fetch and create proper .FRM file for it.
2138
@retval TRUE Some error occured
2139
@retval FALSE No error. 'exists' out parameter set accordingly.
2142
bool check_if_table_exists(THD *thd, TABLE_LIST *table, bool *exists)
2144
char path[FN_REFLEN];
2146
DBUG_ENTER("check_if_table_exists");
2148
safe_mutex_assert_owner(&LOCK_open);
2152
if (get_cached_table_share(table->db, table->table_name))
2155
build_table_filename(path, sizeof(path) - 1, table->db, table->table_name,
2158
if (!access(path, F_OK))
2161
/* .FRM file doesn't exist. Check if some engine can provide it. */
2163
rc= ha_create_table_from_engine(thd, table->db, table->table_name);
2167
/* Table does not exists in engines as well. */
2173
/* Table exists in some engine and .FRM for it was created. */
2178
my_printf_error(ER_UNKNOWN_ERROR, "Failed to open '%-.64s', error while "
2179
"unpacking from engine", MYF(0), table->table_name);
1079
session Thread context.
1080
table_list Open first table in list.
1081
refresh INOUT Pointer to memory that will be set to 1 if
1082
we need to close all tables and reopen them.
1083
If this is a NULL pointer, then the table is not
1084
put in the thread-open-list.
1085
flags Bitmap of flags to modify how open works:
1086
DRIZZLE_LOCK_IGNORE_FLUSH - Open table even if
1087
someone has done a flush or namelock on it.
1088
No version number checking is done.
1089
DRIZZLE_OPEN_TEMPORARY_ONLY - Open only temporary
1090
table not the base table or view.
2191
table_list Open first table in list.
2192
refresh INOUT Pointer to memory that will be set to 1 if
2193
we need to close all tables and reopen them.
2194
If this is a NULL pointer, then the table is not
2195
put in the thread-open-list.
2196
flags Bitmap of flags to modify how open works:
2197
MYSQL_LOCK_IGNORE_FLUSH - Open table even if
2198
someone has done a flush or namelock on it.
2199
No version number checking is done.
2200
MYSQL_OPEN_TEMPORARY_ONLY - Open only temporary
2201
table not the base table or view.
1093
Uses a cache of open tables to find a table not in use.
2204
Uses a cache of open tables to find a table not in use.
1095
If table list element for the table to be opened has "create" flag
1096
set and table does not exist, this function will automatically insert
1097
a placeholder for exclusive name lock into the open tables cache and
1098
will return the Table instance that corresponds to this placeholder.
2206
If table list element for the table to be opened has "create" flag
2207
set and table does not exist, this function will automatically insert
2208
a placeholder for exclusive name lock into the open tables cache and
2209
will return the TABLE instance that corresponds to this placeholder.
1101
NULL Open failed. If refresh is set then one should close
1102
all other tables and retry the open.
1103
# Success. Pointer to Table object for open table.
2212
NULL Open failed. If refresh is set then one should close
2213
all other tables and retry the open.
2214
# Success. Pointer to TABLE object for open table.
1107
Table *Session::openTable(TableList *table_list, bool *refresh, uint32_t flags)
2218
TABLE *open_table(THD *thd, TABLE_LIST *table_list, MEM_ROOT *mem_root,
2219
bool *refresh, uint flags)
2221
register TABLE *table;
1110
2222
char key[MAX_DBKEY_LENGTH];
1111
2223
unsigned int key_length;
1112
const char *alias= table_list->alias;
2224
char *alias= table_list->alias;
1113
2225
HASH_SEARCH_STATE state;
2226
DBUG_ENTER("open_table");
1115
/* Parsing of partitioning information from .frm needs session->lex set up. */
1116
assert(lex->is_lex_started);
2228
/* Parsing of partitioning information from .frm needs thd->lex set up. */
2229
DBUG_ASSERT(thd->lex->is_lex_started);
1118
2231
/* find a unused table in the open table cache */
1122
2235
/* an open table operation needs a lot of the stack space */
1123
if (check_stack_overrun(this, STACK_MIN_SIZE_FOR_OPEN, (unsigned char *)&alias))
1129
key_length= table_list->create_table_def_key(key);
2236
if (check_stack_overrun(thd, STACK_MIN_SIZE_FOR_OPEN, (uchar *)&alias))
2242
key_length= (create_table_def_key(thd, key, table_list, 1) -
2243
TMP_TABLE_KEY_EXTRA);
1132
2246
Unless requested otherwise, try to resolve this table in the list
1133
2247
of temporary tables of this thread. In MySQL temporary tables
1134
2248
are always thread-local and "shadow" possible base tables with the
1135
2249
same name. This block implements the behaviour.
1136
TODO -> move this block into a separate function.
1138
for (table= temporary_tables; table ; table=table->next)
1140
if (table->s->table_cache_key.length == key_length && !memcmp(table->s->table_cache_key.str, key, key_length))
1143
We're trying to use the same temporary table twice in a query.
1144
Right now we don't support this because a temporary table
1145
is always represented by only one Table object in Session, and
1146
it can not be cloned. Emit an error for an unsupported behaviour.
1148
if (table->query_id)
1150
my_error(ER_CANT_REOPEN_TABLE, MYF(0), table->alias);
1153
table->query_id= getQueryId();
2250
TODO: move this block into a separate function.
2253
for (table= thd->temporary_tables; table ; table=table->next)
2255
if (table->s->table_cache_key.length == key_length +
2256
TMP_TABLE_KEY_EXTRA &&
2257
!memcmp(table->s->table_cache_key.str, key,
2258
key_length + TMP_TABLE_KEY_EXTRA))
2261
We're trying to use the same temporary table twice in a query.
2262
Right now we don't support this because a temporary table
2263
is always represented by only one TABLE object in THD, and
2264
it can not be cloned. Emit an error for an unsupported behaviour.
2266
if (table->query_id)
2269
("query_id: %lu server_id: %u pseudo_thread_id: %lu",
2270
(ulong) table->query_id, (uint) thd->server_id,
2271
(ulong) thd->variables.pseudo_thread_id));
2272
my_error(ER_CANT_REOPEN_TABLE, MYF(0), table->alias);
2275
table->query_id= thd->query_id;
2276
thd->thread_specific_used= TRUE;
2277
DBUG_PRINT("info",("Using temporary table"));
2283
if (flags & MYSQL_OPEN_TEMPORARY_ONLY)
2285
my_error(ER_NO_SUCH_TABLE, MYF(0), table_list->db, table_list->table_name);
2290
The table is not temporary - if we're in pre-locked or LOCK TABLES
2291
mode, let's try to find the requested table in the list of pre-opened
2292
and locked tables. If the table is not there, return an error - we can't
2293
open not pre-opened tables in pre-locked/LOCK TABLES mode.
2294
TODO: move this block into a separate function.
2296
if (thd->locked_tables)
2297
{ // Using table locks
2298
TABLE *best_table= 0;
2299
int best_distance= INT_MIN;
2300
bool check_if_used= false;
2301
for (table=thd->open_tables; table ; table=table->next)
2303
if (table->s->table_cache_key.length == key_length &&
2304
!memcmp(table->s->table_cache_key.str, key, key_length))
2306
if (check_if_used && table->query_id &&
2307
table->query_id != thd->query_id)
2310
If we are in stored function or trigger we should ensure that
2311
we won't change table that is already used by calling statement.
2312
So if we are opening table for writing, we should check that it
2313
is not already open by some calling stamement.
2315
my_error(ER_CANT_UPDATE_USED_TABLE_IN_SF_OR_TRG, MYF(0),
2316
table->s->table_name.str);
2320
When looking for a usable TABLE, ignore MERGE children, as they
2321
belong to their parent and cannot be used explicitly.
2323
if (!my_strcasecmp(system_charset_info, table->alias, alias) &&
2324
table->query_id != thd->query_id) /* skip tables already used */
2326
int distance= ((int) table->reginfo.lock_type -
2327
(int) table_list->lock_type);
2329
Find a table that either has the exact lock type requested,
2330
or has the best suitable lock. In case there is no locked
2331
table that has an equal or higher lock than requested,
2332
we us the closest matching lock to be able to produce an error
2333
message about wrong lock mode on the table. The best_table
2334
is changed if bd < 0 <= d or bd < d < 0 or 0 <= d < bd.
2336
distance < 0 - No suitable lock found
2337
distance > 0 - we have lock mode higher then we require
2338
distance == 0 - we have lock mode exactly which we need
2340
if ((best_distance < 0 && distance > best_distance) || (distance >= 0 && distance < best_distance))
2342
best_distance= distance;
2344
if (best_distance == 0 && !check_if_used)
2347
If we have found perfect match and we don't need to check that
2348
table is not used by one of calling statements (assuming that
2349
we are inside of function or trigger) we can finish iterating
2350
through open tables list.
2361
table->query_id= thd->query_id;
2362
DBUG_PRINT("info",("Using locked table"));
1158
if (flags & DRIZZLE_OPEN_TEMPORARY_ONLY)
1160
my_error(ER_NO_SUCH_TABLE, MYF(0), table_list->db, table_list->table_name);
1165
If it's the first table from a list of tables used in a query,
1166
remember refresh_version (the version of open_cache state).
1167
If the version changes while we're opening the remaining tables,
1168
we will have to back off, close all the tables opened-so-far,
1169
and try to reopen them.
1171
Note-> refresh_version is currently changed only during FLUSH TABLES.
1174
version= refresh_version;
1175
else if ((version != refresh_version) &&
1176
! (flags & DRIZZLE_LOCK_IGNORE_FLUSH))
1178
/* Someone did a refresh while thread was opening tables */
1186
Before we test the global cache, we test our local session cache.
1190
assert(false); /* Not implemented yet */
2366
No table in the locked tables list. In case of explicit LOCK TABLES
2367
this can happen if a user did not include the able into the list.
2368
In case of pre-locked mode locked tables list is generated automatically,
2369
so we may only end up here if the table did not exist when
2370
locked tables list was created.
2372
my_error(ER_TABLE_NOT_LOCKED, MYF(0), alias);
1278
2501
If 'old' table we met is in use by current thread we return
1279
2502
without waiting since in this situation it's this thread
1280
2503
which is responsible for broadcasting on COND_refresh
1281
(and this was done already in Session::close_old_data_files()).
2504
(and this was done already in close_old_data_files()).
1282
2505
Good example of such situation is when we have statement
1283
2506
that needs two instances of table and FLUSH TABLES comes
1284
2507
after we open first instance but before we open second
1287
if (table->in_use != this)
2510
if (table->in_use != thd)
1289
2512
/* wait_for_conditionwill unlock LOCK_open for us */
1290
wait_for_condition(&LOCK_open, &COND_refresh);
2513
wait_for_condition(thd, &LOCK_open, &COND_refresh);
1294
pthread_mutex_unlock(&LOCK_open);
2517
VOID(pthread_mutex_unlock(&LOCK_open));
1297
2520
There is a refresh in progress for this table.
1298
2521
Signal the caller that it has to try again.
2530
DBUG_PRINT("tcache", ("unused table: '%s'.'%s' 0x%lx", table->s->db.str,
2531
table->s->table_name.str, (long) table));
1307
2532
/* Unlink the table from "unused_tables" list. */
1308
2533
if (table == unused_tables)
1310
unused_tables=unused_tables->next; // Remove from link
2535
unused_tables=unused_tables->next; // Remove from link
1311
2536
if (table == unused_tables)
1312
unused_tables= NULL;
1314
table->prev->next=table->next; /* Remove from unused list */
2539
table->prev->next=table->next; /* Remove from unused list */
1315
2540
table->next->prev=table->prev;
1316
table->in_use= this;
1320
/* Insert a new Table instance into the open cache */
2545
/* Insert a new TABLE instance into the open cache */
2547
DBUG_PRINT("tcache", ("opening new table"));
1322
2548
/* Free cache if too big */
1323
2549
while (open_cache.records > table_cache_size && unused_tables)
1324
hash_delete(&open_cache,(unsigned char*) unused_tables);
2550
VOID(hash_delete(&open_cache,(uchar*) unused_tables)); /* purecov: tested */
1326
2552
if (table_list->create)
1328
TableIdentifier lock_table_identifier(table_list->db, table_list->table_name, NO_TMP_TABLE);
1330
if (plugin::StorageEngine::getTableDefinition(*this, lock_table_identifier) != EEXIST)
2556
if (check_if_table_exists(thd, table_list, &exists))
2558
VOID(pthread_mutex_unlock(&LOCK_open));
1333
2565
Table to be created, so we need to create placeholder in table-cache.
1335
if (!(table= table_cache_insert_placeholder(key, key_length)))
2567
if (!(table= table_cache_insert_placeholder(thd, key, key_length)))
1337
pthread_mutex_unlock(&LOCK_open);
2569
VOID(pthread_mutex_unlock(&LOCK_open));
1341
2573
Link placeholder to the open tables list so it will be automatically
1342
2574
removed once tables are closed. Also mark it so it won't be ignored
1343
2575
by other trying to take name-lock.
1345
table->open_placeholder= true;
1346
table->next= open_tables;
1348
pthread_mutex_unlock(&LOCK_open);
2577
table->open_placeholder= 1;
2578
table->next= thd->open_tables;
2579
thd->open_tables= table;
2580
VOID(pthread_mutex_unlock(&LOCK_open));
1352
2583
/* Table exists. Let us try to open it. */
1355
2586
/* make a new table */
1356
table= (Table *)malloc(sizeof(Table));
2587
if (!(table=(TABLE*) my_malloc(sizeof(*table),MYF(MY_WME))))
1359
pthread_mutex_unlock(&LOCK_open);
2589
VOID(pthread_mutex_unlock(&LOCK_open));
1363
error= open_unireg_entry(this, table, table_list, alias, key, key_length);
1367
pthread_mutex_unlock(&LOCK_open);
1370
my_hash_insert(&open_cache, (unsigned char*) table);
2593
error= open_unireg_entry(thd, table, table_list, alias, key, key_length,
2594
mem_root, (flags & OPEN_VIEW_NO_PARSE));
2595
/* Combine the follow two */
2598
my_free((uchar*)table, MYF(0));
2599
VOID(pthread_mutex_unlock(&LOCK_open));
2604
my_free((uchar*)table, MYF(0));
2605
VOID(pthread_mutex_unlock(&LOCK_open));
2606
DBUG_RETURN(0); // VIEW
2608
DBUG_PRINT("info", ("inserting table '%s'.'%s' 0x%lx into the cache",
2609
table->s->db.str, table->s->table_name.str,
2611
VOID(my_hash_insert(&open_cache,(uchar*) table));
1373
pthread_mutex_unlock(&LOCK_open);
2614
check_unused(); // Debugging call
2616
VOID(pthread_mutex_unlock(&LOCK_open));
1376
table->next= open_tables; /* Link into simple list */
2619
table->next=thd->open_tables; /* Link into simple list */
2620
thd->open_tables=table;
1379
table->reginfo.lock_type= TL_READ; /* Assume read */
1382
assert(table->s->ref_count > 0 || table->s->tmp_table != NO_TMP_TABLE);
1384
if (lex->need_correct_ident())
2622
table->reginfo.lock_type=TL_READ; /* Assume read */
2625
DBUG_ASSERT(table->s->ref_count > 0 || table->s->tmp_table != NO_TMP_TABLE);
2627
if (thd->lex->need_correct_ident())
1385
2628
table->alias_name_used= my_strcasecmp(table_alias_charset,
1386
2629
table->s->table_name.str, alias);
1387
2630
/* Fix alias if table name changes */
1388
2631
if (strcmp(table->alias, alias))
1390
uint32_t length=(uint32_t) strlen(alias)+1;
1391
table->alias= (char*) realloc((char*) table->alias, length);
1392
memcpy((void*) table->alias, alias, length);
2633
uint length=(uint) strlen(alias)+1;
2634
table->alias= (char*) my_realloc((char*) table->alias, length,
2636
memcpy((char*) table->alias, alias, length);
1395
2638
/* These variables are also set in reopen_table() */
1396
table->tablenr= current_tablenr++;
1397
table->used_fields= 0;
1398
table->const_table= 0;
1399
table->null_row= false;
1400
table->maybe_null= false;
1401
table->force_index= false;
2639
table->tablenr=thd->current_tablenr++;
2640
table->used_fields=0;
2641
table->const_table=0;
2642
table->null_row= table->maybe_null= table->force_index= 0;
1402
2643
table->status=STATUS_NO_RECORD;
1403
2644
table->insert_values= 0;
2645
table->fulltext_searched= 0;
2646
table->file->ft_handler= 0;
1404
2647
/* Catch wrong handling of the auto_increment_field_not_null. */
1405
assert(!table->auto_increment_field_not_null);
1406
table->auto_increment_field_not_null= false;
2648
DBUG_ASSERT(!table->auto_increment_field_not_null);
2649
table->auto_increment_field_not_null= FALSE;
1407
2650
if (table->timestamp_field)
1408
2651
table->timestamp_field_type= table->timestamp_field->get_auto_set_type();
1409
2652
table->pos_in_table_list= table_list;
1410
2653
table->clear_column_bitmaps();
1411
assert(table->key_read == 0);
2654
DBUG_ASSERT(table->key_read == 0);
2659
TABLE *find_locked_table(THD *thd, const char *db,const char *table_name)
2661
char key[MAX_DBKEY_LENGTH];
2662
uint key_length=(uint) (strmov(strmov(key,db)+1,table_name)-key)+1;
2664
for (TABLE *table=thd->open_tables; table ; table=table->next)
2666
if (table->s->table_cache_key.length == key_length &&
2667
!memcmp(table->s->table_cache_key.str, key, key_length))
1494
2758
for (part=0 ; part < table->key_info[key].usable_key_parts ; part++)
1495
2759
table->key_info[key].key_part[part].field->table= table;
2762
Do not attach MERGE children here. The children might be reopened
2763
after the parent. Attach children after reopening all tables that
2764
require reopen. See for example reopen_tables().
1498
2767
broadcast_refresh();
1507
Close all instances of a table open by this thread and replace
1508
them with exclusive name-locks.
1510
@param session Thread context
1511
@param db Database name for the table to be closed
1512
@param table_name Name of the table to be closed
1514
@note This function assumes that if we are not under LOCK TABLES,
1515
then there is only one table open and locked. This means that
1516
the function probably has to be adjusted before it can be used
1517
anywhere outside ALTER Table.
1519
@note Must not use TableShare::table_name/db of the table being closed,
1520
the strings are used in a loop even after the share may be freed.
2776
Close all instances of a table open by this thread and replace
2777
them with exclusive name-locks.
2779
@param thd Thread context
2780
@param db Database name for the table to be closed
2781
@param table_name Name of the table to be closed
2783
@note This function assumes that if we are not under LOCK TABLES,
2784
then there is only one table open and locked. This means that
2785
the function probably has to be adjusted before it can be used
2786
anywhere outside ALTER TABLE.
2788
@note Must not use TABLE_SHARE::table_name/db of the table being closed,
2789
the strings are used in a loop even after the share may be freed.
1523
void Session::close_data_files_and_morph_locks(const char *new_db, const char *new_table_name)
2792
void close_data_files_and_morph_locks(THD *thd, const char *db,
2793
const char *table_name)
1527
safe_mutex_assert_owner(&LOCK_open); /* Adjust locks at the end of ALTER TABLEL */
2796
DBUG_ENTER("close_data_files_and_morph_locks");
2798
safe_mutex_assert_owner(&LOCK_open);
1532
2803
If we are not under LOCK TABLES we should have only one table
1533
2804
open and locked so it makes sense to remove the lock at once.
1535
mysql_unlock_tables(this, lock);
2806
mysql_unlock_tables(thd, thd->lock);
1540
2811
Note that open table list may contain a name-lock placeholder
1541
for target table name if we process ALTER Table ... RENAME.
2812
for target table name if we process ALTER TABLE ... RENAME.
1542
2813
So loop below makes sense even if we are not under LOCK TABLES.
1544
for (table= open_tables; table ; table=table->next)
2815
for (table=thd->open_tables; table ; table=table->next)
1546
if (!strcmp(table->s->table_name.str, new_table_name) &&
1547
!strcmp(table->s->db.str, new_db))
2817
if (!strcmp(table->s->table_name.str, table_name) &&
2818
!strcmp(table->s->db.str, db))
1549
table->open_placeholder= true;
2820
if (thd->locked_tables)
2822
mysql_lock_remove(thd, thd->locked_tables, table, TRUE);
2824
table->open_placeholder= 1;
1550
2825
close_handle_and_leave_table_as_lock(table);
1557
Reopen all tables with closed data files.
1559
@param session Thread context
1560
@param get_locks Should we get locks after reopening tables ?
1561
@param mark_share_as_old Mark share as old to protect from a impending
1564
@note Since this function can't properly handle prelocking and
1565
create placeholders it should be used in very special
1566
situations like FLUSH TABLES or ALTER Table. In general
1567
case one should just repeat open_tables()/lock_tables()
1568
combination when one needs tables to be reopened (for
1569
example see openTablesLock()).
1571
@note One should have lock on LOCK_open when calling this.
1573
@return false in case of success, true - otherwise.
2833
Reopen all tables with closed data files.
2835
@param thd Thread context
2836
@param get_locks Should we get locks after reopening tables ?
2837
@param mark_share_as_old Mark share as old to protect from a impending
2840
@note Since this function can't properly handle prelocking and
2841
create placeholders it should be used in very special
2842
situations like FLUSH TABLES or ALTER TABLE. In general
2843
case one should just repeat open_tables()/lock_tables()
2844
combination when one needs tables to be reopened (for
2845
example see open_and_lock_tables()).
2847
@note One should have lock on LOCK_open when calling this.
2849
@return FALSE in case of success, TRUE - otherwise.
1576
bool Session::reopen_tables(bool get_locks, bool mark_share_as_old)
2852
bool reopen_tables(THD *thd, bool get_locks, bool mark_share_as_old)
1578
Table *table,*next,**prev;
1579
Table **tables,**tables_ptr; // For locks
2854
TABLE *table,*next,**prev;
2855
TABLE **tables,**tables_ptr; // For locks
1580
2856
bool error=0, not_used;
1581
const uint32_t flags= DRIZZLE_LOCK_NOTIFY_IF_NEED_REOPEN |
1582
DRIZZLE_LOCK_IGNORE_GLOBAL_READ_LOCK |
1583
DRIZZLE_LOCK_IGNORE_FLUSH;
1585
if (open_tables == NULL)
2857
const uint flags= MYSQL_LOCK_NOTIFY_IF_NEED_REOPEN |
2858
MYSQL_LOCK_IGNORE_GLOBAL_READ_LOCK |
2859
MYSQL_LOCK_IGNORE_FLUSH;
2861
DBUG_ENTER("reopen_tables");
2863
if (!thd->open_tables)
1588
2866
safe_mutex_assert_owner(&LOCK_open);
1891
3186
broadcast_refresh();
3187
if (thd->locked_tables && thd->locked_tables->table_count == 0)
3189
my_free((uchar*) thd->locked_tables,MYF(0));
3190
thd->locked_tables=0;
1898
If we have the table open, which only happens when a LOCK Table has been
3197
If we have the table open, which only happens when a LOCK TABLE has been
1899
3198
done on the table, change the lock type to a lock that will abort all
1900
3199
other threads trying to get the lock.
1903
void abort_locked_tables(Session *session,const char *db, const char *table_name)
3202
void abort_locked_tables(THD *thd,const char *db, const char *table_name)
1906
for (table= session->open_tables; table ; table= table->next)
3205
for (table= thd->open_tables; table ; table= table->next)
1908
3207
if (!strcmp(table->s->table_name.str, table_name) &&
1909
!strcmp(table->s->db.str, db))
3208
!strcmp(table->s->db.str, db))
1911
3210
/* If MERGE child, forward lock handling to parent. */
1912
mysql_lock_abort(session, table);
3211
mysql_lock_abort(thd, table, TRUE);
1919
Load a table definition from cursor and open unireg table
3219
Function to assign a new table map id to a table share.
3223
share - Pointer to table share structure
3227
We are intentionally not checking that share->mutex is locked
3228
since this function should only be called when opening a table
3229
share and before it is entered into the table_def_cache (meaning
3230
that it cannot be fetched by another thread, even accidentally).
3235
The LOCK_open mutex is locked
3239
share->table_map_id is given a value that with a high certainty is
3240
not used by any other table (the only case where a table id can be
3241
reused is on wrap-around, which means more than 4 billion table
3242
share opens have been executed while one table was open all the
3245
share->table_map_id is not ~0UL.
3247
void assign_new_table_id(TABLE_SHARE *share)
3249
static ulong last_table_id= ~0UL;
3251
DBUG_ENTER("assign_new_table_id");
3254
DBUG_ASSERT(share != NULL);
3255
safe_mutex_assert_owner(&LOCK_open);
3257
ulong tid= ++last_table_id; /* get next id */
3259
There is one reserved number that cannot be used. Remember to
3260
change this when 6-byte global table id's are introduced.
3262
if (unlikely(tid == ~0UL))
3263
tid= ++last_table_id;
3264
share->table_map_id= tid;
3265
DBUG_PRINT("info", ("table_id=%lu", tid));
3267
/* Post conditions */
3268
DBUG_ASSERT(share->table_map_id != ~0UL);
3274
Load a table definition from file and open unireg table
1923
session Thread handle
1924
entry Store open table definition here
1925
table_list TableList with db, table_name
1927
cache_key Key for share_cache
1928
cache_key_length length of cache_key
3279
entry Store open table definition here
3280
table_list TABLE_LIST with db, table_name & belong_to_view
3282
cache_key Key for share_cache
3283
cache_key_length length of cache_key
3284
mem_root temporary mem_root for parsing
3285
flags the OPEN_VIEW_NO_PARSE flag to be passed to
3286
openfrm()/open_new_frm()
1931
Extra argument for open is taken from session->open_options
1932
One must have a lock on LOCK_open when calling this function
3289
Extra argument for open is taken from thd->open_options
3290
One must have a lock on LOCK_open when calling this function
1939
static int open_unireg_entry(Session *session, Table *entry, TableList *table_list,
3297
static int open_unireg_entry(THD *thd, TABLE *entry, TABLE_LIST *table_list,
1940
3298
const char *alias,
1941
char *cache_key, uint32_t cache_key_length)
3299
char *cache_key, uint cache_key_length,
3300
MEM_ROOT *mem_root, uint flags)
1945
uint32_t discover_retry_count= 0;
3304
uint discover_retry_count= 0;
3305
DBUG_ENTER("open_unireg_entry");
1947
3307
safe_mutex_assert_owner(&LOCK_open);
1949
if (!(share= TableShare::getShare(session, table_list, cache_key,
1951
table_list->i_s_requested_object,
3309
if (!(share= get_table_share_with_create(thd, table_list, cache_key,
3312
table_list->i_s_requested_object,
1955
while ((error= open_table_from_share(session, share, alias,
1956
(uint32_t) (HA_OPEN_KEYFILE |
1960
session->open_options, entry)))
3316
while ((error= open_table_from_share(thd, share, alias,
3317
(uint) (HA_OPEN_KEYFILE |
3321
(READ_KEYINFO | COMPUTE_TYPES |
3323
thd->open_options, entry, OTM_OPEN)))
1962
3325
if (error == 7) // Table def changed
2170
3743
table_list->lock_type= lock_type;
2171
3744
table_list->table= table;
2173
assert(lock == 0); // You must lock everything at once
2174
if ((table->reginfo.lock_type= lock_type) != TL_UNLOCK)
2175
if (! (lock= mysql_lock_tables(this, &table_list->table, 1, 0, &refresh)))
3745
if (thd->locked_tables)
3747
if (check_lock_and_start_stmt(thd, table, lock_type))
3752
DBUG_ASSERT(thd->lock == 0); // You must lock everything at once
3753
if ((table->reginfo.lock_type= lock_type) != TL_UNLOCK)
3754
if (! (thd->lock= mysql_lock_tables(thd, &table_list->table, 1,
3755
lock_flags, &refresh)))
3760
thd_proc_info(thd, 0);
3766
Open all tables in list, locks them and optionally process derived tables.
3769
open_and_lock_tables_derived()
3770
thd - thread handler
3771
tables - list of tables for open&locking
3772
derived - if to handle derived tables
3779
The lock will automaticaly be freed by close_thread_tables()
3782
There are two convenience functions:
3783
- simple_open_n_lock_tables(thd, tables) without derived handling
3784
- open_and_lock_tables(thd, tables) with derived handling
3785
Both inline functions call open_and_lock_tables_derived() with
3786
the third argument set appropriately.
3789
int open_and_lock_tables_derived(THD *thd, TABLE_LIST *tables, bool derived)
3793
DBUG_ENTER("open_and_lock_tables_derived");
3794
DBUG_PRINT("enter", ("derived handling: %d", derived));
3798
if (open_tables(thd, &tables, &counter, 0))
3801
DBUG_EXECUTE_IF("sleep_open_and_lock_after_open", {
3802
const char *old_proc_info= thd->proc_info;
3803
thd->proc_info= "DBUG sleep";
3805
thd->proc_info= old_proc_info;});
3807
if (!lock_tables(thd, tables, counter, &need_reopen))
3811
close_tables_for_reopen(thd, &tables);
3814
(mysql_handle_derived(thd->lex, &mysql_derived_prepare) ||
3815
(thd->fill_derived_tables() &&
3816
mysql_handle_derived(thd->lex, &mysql_derived_filling))))
3817
DBUG_RETURN(TRUE); /* purecov: inspected */
3823
Open all tables in list and process derived tables
3826
open_normal_and_derived_tables
3827
thd - thread handler
3828
tables - list of tables for open
3829
flags - bitmap of flags to modify how the tables will be open:
3830
MYSQL_LOCK_IGNORE_FLUSH - open table even if someone has
3831
done a flush or namelock on it.
3838
This is to be used on prepare stage when you don't read any
3839
data from the tables.
3842
bool open_normal_and_derived_tables(THD *thd, TABLE_LIST *tables, uint flags)
3845
DBUG_ENTER("open_normal_and_derived_tables");
3846
DBUG_ASSERT(!thd->fill_derived_tables());
3847
if (open_tables(thd, &tables, &counter, flags) ||
3848
mysql_handle_derived(thd->lex, &mysql_derived_prepare))
3849
DBUG_RETURN(TRUE); /* purecov: inspected */
3855
Decide on logging format to use for the statement.
3857
Compute the capabilities vector for the involved storage engines
3858
and mask out the flags for the binary log. Right now, the binlog
3859
flags only include the capabilities of the storage engines, so this
3862
We now have three alternatives that prevent the statement from
3865
1. If there are no capabilities left (all flags are clear) it is
3866
not possible to log the statement at all, so we roll back the
3867
statement and report an error.
3869
2. Statement mode is set, but the capabilities indicate that
3870
statement format is not possible.
3872
3. Row mode is set, but the capabilities indicate that row
3873
format is not possible.
3875
4. Statement is unsafe, but the capabilities indicate that row
3876
format is not possible.
3878
If we are in MIXED mode, we then decide what logging format to use:
3880
1. If the statement is unsafe, row-based logging is used.
3882
2. If statement-based logging is not possible, row-based logging is
3885
3. Otherwise, statement-based logging is used.
3887
@param thd Client thread
3888
@param tables Tables involved in the query
3891
int decide_logging_format(THD *thd, TABLE_LIST *tables)
3893
if (mysql_bin_log.is_open() && (thd->options & OPTION_BIN_LOG))
3895
handler::Table_flags flags_some_set= handler::Table_flags();
3896
handler::Table_flags flags_all_set= ~handler::Table_flags();
3897
my_bool multi_engine= FALSE;
3898
void* prev_ht= NULL;
3899
for (TABLE_LIST *table= tables; table; table= table->next_global)
3901
if (!table->placeholder() && table->lock_type >= TL_WRITE_ALLOW_WRITE)
3903
ulonglong const flags= table->table->file->ha_table_flags();
3904
DBUG_PRINT("info", ("table: %s; ha_table_flags: %s%s",
3906
FLAGSTR(flags, HA_BINLOG_STMT_CAPABLE),
3907
FLAGSTR(flags, HA_BINLOG_ROW_CAPABLE)));
3908
if (prev_ht && prev_ht != table->table->file->ht)
3910
prev_ht= table->table->file->ht;
3911
flags_all_set &= flags;
3912
flags_some_set |= flags;
3916
DBUG_PRINT("info", ("flags_all_set: %s%s",
3917
FLAGSTR(flags_all_set, HA_BINLOG_STMT_CAPABLE),
3918
FLAGSTR(flags_all_set, HA_BINLOG_ROW_CAPABLE)));
3919
DBUG_PRINT("info", ("flags_some_set: %s%s",
3920
FLAGSTR(flags_some_set, HA_BINLOG_STMT_CAPABLE),
3921
FLAGSTR(flags_some_set, HA_BINLOG_ROW_CAPABLE)));
3922
DBUG_PRINT("info", ("thd->variables.binlog_format: %ld",
3923
thd->variables.binlog_format));
3924
DBUG_PRINT("info", ("multi_engine: %s",
3925
multi_engine ? "TRUE" : "FALSE"));
3928
if (flags_all_set == 0)
3930
my_error((error= ER_BINLOG_LOGGING_IMPOSSIBLE), MYF(0),
3931
"Statement cannot be logged to the binary log in"
3932
" row-based nor statement-based format");
3934
else if (thd->variables.binlog_format == BINLOG_FORMAT_STMT &&
3935
(flags_all_set & HA_BINLOG_STMT_CAPABLE) == 0)
3937
my_error((error= ER_BINLOG_LOGGING_IMPOSSIBLE), MYF(0),
3938
"Statement-based format required for this statement,"
3939
" but not allowed by this combination of engines");
3941
else if ((thd->variables.binlog_format == BINLOG_FORMAT_ROW ||
3942
thd->lex->is_stmt_unsafe()) &&
3943
(flags_all_set & HA_BINLOG_ROW_CAPABLE) == 0)
3945
my_error((error= ER_BINLOG_LOGGING_IMPOSSIBLE), MYF(0),
3946
"Row-based format required for this statement,"
3947
" but not allowed by this combination of engines");
3951
If more than one engine is involved in the statement and at
3952
least one is doing it's own logging (is *self-logging*), the
3953
statement cannot be logged atomically, so we generate an error
3954
rather than allowing the binlog to become corrupt.
3957
(flags_some_set & HA_HAS_OWN_BINLOGGING))
3959
error= ER_BINLOG_LOGGING_IMPOSSIBLE;
3960
my_error(error, MYF(0),
3961
"Statement cannot be written atomically since more"
3962
" than one engine involved and at least one engine"
3963
" is self-logging");
3966
DBUG_PRINT("info", ("error: %d", error));
3972
We switch to row-based format if we are in mixed mode and one of
3973
the following are true:
3975
1. If the statement is unsafe
3976
2. If statement format cannot be used
3978
Observe that point to cannot be decided before the tables
3979
involved in a statement has been checked, i.e., we cannot put
3980
this code in reset_current_stmt_binlog_row_based(), it has to be
3983
if (thd->lex->is_stmt_unsafe() ||
3984
(flags_all_set & HA_BINLOG_STMT_CAPABLE) == 0)
3986
thd->set_current_stmt_binlog_row_based_if_mixed();
2185
3994
Lock all tables in list
2189
session Thread Cursor
2190
tables Tables to lock
2191
count Number of opened tables
2192
need_reopen Out parameter which if true indicates that some
2193
tables were dropped or altered during this call
2194
and therefore invoker should reopen tables and
2195
try to lock them once again (in this case
2196
lock_tables() will also return error).
3999
tables Tables to lock
4000
count Number of opened tables
4001
need_reopen Out parameter which if TRUE indicates that some
4002
tables were dropped or altered during this call
4003
and therefore invoker should reopen tables and
4004
try to lock them once again (in this case
4005
lock_tables() will also return error).
2199
You can't call lock_tables twice, as this would break the dead-lock-free
2200
handling thr_lock gives us. You most always get all needed locks at
4008
You can't call lock_tables twice, as this would break the dead-lock-free
4009
handling thr_lock gives us. You most always get all needed locks at
2203
If query for which we are calling this function marked as requring
2204
prelocking, this function will do implicit LOCK TABLES and change
2205
session::prelocked_mode accordingly.
4012
If query for which we are calling this function marked as requring
4013
prelocking, this function will do implicit LOCK TABLES and change
4014
thd::prelocked_mode accordingly.
2212
int Session::lock_tables(TableList *tables, uint32_t count, bool *need_reopen)
4021
int lock_tables(THD *thd, TABLE_LIST *tables, uint count, bool *need_reopen)
2215
Session *session= this;
4025
DBUG_ENTER("lock_tables");
2218
4027
We can't meet statement requiring prelocking if we already
2219
4028
in prelocked mode.
2221
*need_reopen= false;
2226
assert(session->lock == 0); // You must lock everything at once
2227
Table **start,**ptr;
2228
uint32_t lock_flag= DRIZZLE_LOCK_NOTIFY_IF_NEED_REOPEN;
2230
if (!(ptr=start=(Table**) session->alloc(sizeof(Table*)*count)))
2232
for (table= tables; table; table= table->next_global)
2234
if (!table->placeholder())
2235
*(ptr++)= table->table;
2238
if (!(session->lock= mysql_lock_tables(session, start, (uint32_t) (ptr - start),
2239
lock_flag, need_reopen)))
4030
*need_reopen= FALSE;
4033
DBUG_RETURN(decide_logging_format(thd, tables));
4035
if (!thd->locked_tables)
4037
DBUG_ASSERT(thd->lock == 0); // You must lock everything at once
4038
TABLE **start,**ptr;
4039
uint lock_flag= MYSQL_LOCK_NOTIFY_IF_NEED_REOPEN;
4041
if (!(ptr=start=(TABLE**) thd->alloc(sizeof(TABLE*)*count)))
4043
for (table= tables; table; table= table->next_global)
4045
if (!table->placeholder())
4046
*(ptr++)= table->table;
4049
if (!(thd->lock= mysql_lock_tables(thd, start, (uint) (ptr - start),
4050
lock_flag, need_reopen)))
4057
TABLE_LIST *first_not_own= thd->lex->first_not_own_table();
4059
When open_and_lock_tables() is called for a single table out of
4060
a table list, the 'next_global' chain is temporarily broken. We
4061
may not find 'first_not_own' before the end of the "list".
4062
Look for example at those places where open_n_lock_single_table()
4063
is called. That function implements the temporary breaking of
4064
a table list for opening a single table.
4067
table && table != first_not_own;
4068
table= table->next_global)
4070
if (!table->placeholder() &&
4071
check_lock_and_start_stmt(thd, table->table, table->lock_type))
4078
DBUG_RETURN(decide_logging_format(thd, tables));
4083
Prepare statement for reopening of tables and recalculation of set of
4087
close_tables_for_reopen()
4088
thd in Thread context
4089
tables in/out List of tables which we were trying to open and lock
4093
void close_tables_for_reopen(THD *thd, TABLE_LIST **tables)
4096
If table list consists only from tables from prelocking set, table list
4097
for new attempt should be empty, so we have to update list's root pointer.
4099
if (thd->lex->first_not_own_table() == *tables)
4101
thd->lex->chop_off_not_own_tables();
4102
for (TABLE_LIST *tmp= *tables; tmp; tmp= tmp->next_global)
4104
close_thread_tables(thd);
2249
4109
Open a single table without table caching and don't set it in open_list
2252
open_temporary_table()
2253
session Thread object
2254
path Path (without .frm)
2256
table_name Table name
2257
link_in_list 1 if table should be linked into session->temporary_tables
2260
Used by alter_table to open a temporary table and when creating
2261
a temporary table with CREATE TEMPORARY ...
4112
open_temporary_table()
4114
path Path (without .frm)
4116
table_name Table name
4117
link_in_list 1 if table should be linked into thd->temporary_tables
4120
Used by alter_table to open a temporary table and when creating
4121
a temporary table with CREATE TEMPORARY ...
2268
Table *Session::open_temporary_table(TableIdentifier &identifier,
4128
TABLE *open_temporary_table(THD *thd, const char *path, const char *db,
4129
const char *table_name, bool link_in_list,
4130
open_table_mode open_mode)
2271
Table *new_tmp_table;
2273
4134
char cache_key[MAX_DBKEY_LENGTH], *saved_cache_key, *tmp_path;
2274
uint32_t key_length, path_length;
2275
TableList table_list;
4136
TABLE_LIST table_list;
4137
DBUG_ENTER("open_temporary_table");
4139
("table: '%s'.'%s' path: '%s' server_id: %u "
4140
"pseudo_thread_id: %lu",
4141
db, table_name, path,
4142
(uint) thd->server_id, (ulong) thd->variables.pseudo_thread_id));
2277
table_list.db= (char*) identifier.getDBName();
2278
table_list.table_name= (char*) identifier.getTableName();
4144
table_list.db= (char*) db;
4145
table_list.table_name= (char*) table_name;
2279
4146
/* Create the cache_key for temporary tables */
2280
key_length= table_list.create_table_def_key(cache_key);
2281
path_length= strlen(identifier.getPath());
2283
if (!(new_tmp_table= (Table*) malloc(sizeof(*new_tmp_table) + sizeof(*share) +
2284
path_length + 1 + key_length)))
2287
share= (TableShare*) (new_tmp_table+1);
4147
key_length= create_table_def_key(thd, cache_key, &table_list, 1);
4149
if (!(tmp_table= (TABLE*) my_malloc(sizeof(*tmp_table) + sizeof(*share) +
4150
strlen(path)+1 + key_length,
4152
DBUG_RETURN(0); /* purecov: inspected */
4154
share= (TABLE_SHARE*) (tmp_table+1);
2288
4155
tmp_path= (char*) (share+1);
2289
saved_cache_key= strcpy(tmp_path, identifier.getPath())+path_length+1;
4156
saved_cache_key= strmov(tmp_path, path)+1;
2290
4157
memcpy(saved_cache_key, cache_key, key_length);
2292
share->init(saved_cache_key, key_length, strchr(saved_cache_key, '\0')+1, tmp_path);
4159
init_tmp_table_share(thd, share, saved_cache_key, key_length,
4160
strend(saved_cache_key)+1, tmp_path);
2295
First open the share, and then open the table from the share we just opened.
2297
if (open_table_def(*this, share) ||
2298
open_table_from_share(this, share, identifier.getTableName(),
2299
(uint32_t) (HA_OPEN_KEYFILE | HA_OPEN_RNDFILE |
4162
if (open_table_def(thd, share, 0) ||
4163
open_table_from_share(thd, share, table_name,
4164
(open_mode == OTM_ALTER) ? 0 :
4165
(uint) (HA_OPEN_KEYFILE | HA_OPEN_RNDFILE |
4167
(open_mode == OTM_ALTER) ?
4168
(READ_KEYINFO | COMPUTE_TYPES | EXTRA_RECORD |
4170
: (READ_KEYINFO | COMPUTE_TYPES | EXTRA_RECORD),
2301
4171
ha_open_options,
4172
tmp_table, open_mode))
2304
4174
/* No need to lock share->mutex as this is not needed for tmp tables */
2305
share->free_table_share();
2306
free((char*) new_tmp_table);
4175
free_table_share(share);
4176
my_free((char*) tmp_table,MYF(0));
2310
new_tmp_table->reginfo.lock_type= TL_WRITE; // Simulate locked
2311
share->tmp_table= TEMP_TABLE;
4180
tmp_table->reginfo.lock_type= TL_WRITE; // Simulate locked
4181
if (open_mode == OTM_ALTER)
4184
Temporary table has been created with frm_only
4185
and has not been created in any storage engine
4187
share->tmp_table= TMP_TABLE_FRM_FILE_ONLY;
4190
share->tmp_table= (tmp_table->file->has_transactions() ?
4191
TRANSACTIONAL_TMP_TABLE : NON_TRANSACTIONAL_TMP_TABLE);
2313
4193
if (link_in_list)
2315
4195
/* growing temp list at the head */
2316
new_tmp_table->next= this->temporary_tables;
2317
if (new_tmp_table->next)
2318
new_tmp_table->next->prev= new_tmp_table;
2319
this->temporary_tables= new_tmp_table;
2320
this->temporary_tables->prev= 0;
2322
new_tmp_table->pos_in_table_list= 0;
2324
return new_tmp_table;
4196
tmp_table->next= thd->temporary_tables;
4197
if (tmp_table->next)
4198
tmp_table->next->prev= tmp_table;
4199
thd->temporary_tables= tmp_table;
4200
thd->temporary_tables->prev= 0;
4201
if (thd->slave_thread)
4202
slave_open_temp_tables++;
4204
tmp_table->pos_in_table_list= 0;
4205
DBUG_PRINT("tmptable", ("opened table: '%s'.'%s' 0x%lx", tmp_table->s->db.str,
4206
tmp_table->s->table_name.str, (long) tmp_table));
4207
DBUG_RETURN(tmp_table);
4211
bool rm_temporary_table(handlerton *base, char *path, bool frm_only)
4216
DBUG_ENTER("rm_temporary_table");
4218
strmov(ext= strend(path), reg_ext);
4219
if (my_delete(path,MYF(0)))
4220
error=1; /* purecov: inspected */
4221
*ext= 0; // remove extension
4222
file= get_new_handler((TABLE_SHARE*) 0, current_thd->mem_root, base);
4223
if (!frm_only && file && file->ha_delete_table(path))
4226
sql_print_warning("Could not remove temporary table: '%s', error: %d",
2328
4234
/*****************************************************************************
2329
* The following find_field_in_XXX procedures implement the core of the
2330
* name resolution functionality. The entry point to resolve a column name in a
2331
* list of tables is 'find_field_in_tables'. It calls 'find_field_in_table_ref'
2332
* for each table reference. In turn, depending on the type of table reference,
2333
* 'find_field_in_table_ref' calls one of the 'find_field_in_XXX' procedures
2334
* below specific for the type of table reference.
2335
******************************************************************************/
4235
* The following find_field_in_XXX procedures implement the core of the
4236
* name resolution functionality. The entry point to resolve a column name in a
4237
* list of tables is 'find_field_in_tables'. It calls 'find_field_in_table_ref'
4238
* for each table reference. In turn, depending on the type of table reference,
4239
* 'find_field_in_table_ref' calls one of the 'find_field_in_XXX' procedures
4240
* below specific for the type of table reference.
4241
******************************************************************************/
2337
4243
/* Special Field pointers as return values of find_field_in_XXX functions. */
2338
4244
Field *not_found_field= (Field*) 0x1;
2339
Field *view_ref_found= (Field*) 0x2;
2341
static void update_field_dependencies(Session *session, Field *field, Table *table)
4245
Field *view_ref_found= (Field*) 0x2;
4247
#define WRONG_GRANT (Field*) -1
4249
static void update_field_dependencies(THD *thd, Field *field, TABLE *table)
2343
if (session->mark_used_columns != MARK_COLUMNS_NONE)
4251
DBUG_ENTER("update_field_dependencies");
4252
if (thd->mark_used_columns != MARK_COLUMNS_NONE)
2345
MyBitmap *current_bitmap, *other_bitmap;
4254
MY_BITMAP *current_bitmap, *other_bitmap;
2348
4257
We always want to register the used keys, as the column bitmap may have
2349
4258
been set for all fields (for example for view).
2352
table->covering_keys&= field->part_of_key;
2353
table->merge_keys|= field->part_of_key;
2355
if (session->mark_used_columns == MARK_COLUMNS_READ)
4261
table->covering_keys.intersect(field->part_of_key);
4262
table->merge_keys.merge(field->part_of_key);
4264
if (thd->mark_used_columns == MARK_COLUMNS_READ)
2357
4266
current_bitmap= table->read_set;
2358
4267
other_bitmap= table->write_set;
2378
4371
Find field by name in a NATURAL/USING join table reference.
2381
find_field_in_natural_join()
2382
session [in] thread Cursor
2383
table_ref [in] table reference to search
2384
name [in] name of field
2385
length [in] length of name
2386
ref [in/out] if 'name' is resolved to a view field, ref is
2387
set to point to the found view field
2388
register_tree_change [in] true if ref is not stack variable and we
2389
need register changes in item tree
2390
actual_table [out] the original table reference where the field
2391
belongs - differs from 'table_list' only for
4374
find_field_in_natural_join()
4375
thd [in] thread handler
4376
table_ref [in] table reference to search
4377
name [in] name of field
4378
length [in] length of name
4379
ref [in/out] if 'name' is resolved to a view field, ref is
4380
set to point to the found view field
4381
register_tree_change [in] TRUE if ref is not stack variable and we
4382
need register changes in item tree
4383
actual_table [out] the original table reference where the field
4384
belongs - differs from 'table_list' only for
2395
Search for a field among the result fields of a NATURAL/USING join.
2396
Notice that this procedure is called only for non-qualified field
2397
names. In the case of qualified fields, we search directly the base
2398
tables of a natural join.
4388
Search for a field among the result fields of a NATURAL/USING join.
4389
Notice that this procedure is called only for non-qualified field
4390
names. In the case of qualified fields, we search directly the base
4391
tables of a natural join.
2401
NULL if the field was not found
2402
PTR Pointer to the found Field
4394
NULL if the field was not found
4395
WRONG_GRANT if no access rights to the found field
4396
# Pointer to the found Field
2406
find_field_in_natural_join(Session *session, TableList *table_ref,
2407
const char *name, uint32_t , Item **,
2408
bool, TableList **actual_table)
4400
find_field_in_natural_join(THD *thd, TABLE_LIST *table_ref, const char *name,
4401
uint length, Item **ref, bool register_tree_change,
4402
TABLE_LIST **actual_table)
2410
4404
List_iterator_fast<Natural_join_column>
2411
4405
field_it(*(table_ref->join_columns));
2412
4406
Natural_join_column *nj_col, *curr_nj_col;
2413
4407
Field *found_field;
2415
assert(table_ref->is_natural_join && table_ref->join_columns);
2416
assert(*actual_table == NULL);
2418
for (nj_col= NULL, curr_nj_col= field_it++; curr_nj_col;
4408
DBUG_ENTER("find_field_in_natural_join");
4409
DBUG_PRINT("enter", ("field name: '%s', ref 0x%lx",
4410
name, (ulong) ref));
4411
DBUG_ASSERT(table_ref->is_natural_join && table_ref->join_columns);
4412
DBUG_ASSERT(*actual_table == NULL);
4414
for (nj_col= NULL, curr_nj_col= field_it++; curr_nj_col;
2419
4415
curr_nj_col= field_it++)
2421
4417
if (!my_strcasecmp(system_charset_info, curr_nj_col->name(), name))
2425
my_error(ER_NON_UNIQ_ERROR, MYF(0), name, session->where);
4421
my_error(ER_NON_UNIQ_ERROR, MYF(0), name, thd->where);
2428
4424
nj_col= curr_nj_col;
4430
if (nj_col->view_field)
4434
create_item() may, or may not create a new Item, depending on the
4435
column reference. See create_view_field() for details.
4437
item= nj_col->create_item(thd);
4439
*ref != NULL means that *ref contains the item that we need to
4440
replace. If the item was aliased by the user, set the alias to
4442
We need to set alias on both ref itself and on ref real item.
4444
if (*ref && !(*ref)->is_autogenerated_name)
4446
item->set_name((*ref)->name, (*ref)->name_length,
4447
system_charset_info);
4448
item->real_item()->set_name((*ref)->name, (*ref)->name_length,
4449
system_charset_info);
4454
DBUG_ASSERT(nj_col->table_field == NULL);
4455
if (nj_col->table_ref->schema_table_reformed)
4458
Translation table items are always Item_fields and fixed
4459
already('mysql_schema_table' function). So we can return
4460
->field. It is used only for 'show & where' commands.
4462
DBUG_RETURN(((Item_field*) (nj_col->view_field->item))->field);
4464
if (register_tree_change)
4465
thd->change_item_tree(ref, item);
4468
found_field= (Field*) view_ref_found;
2434
4472
/* This is a base table. */
2435
assert(nj_col->table_ref->table == nj_col->table_field->table);
4473
DBUG_ASSERT(nj_col->view_field == NULL);
4474
DBUG_ASSERT(nj_col->table_ref->table == nj_col->table_field->table);
2436
4475
found_field= nj_col->table_field;
2437
update_field_dependencies(session, found_field, nj_col->table_ref->table);
4476
update_field_dependencies(thd, found_field, nj_col->table_ref->table);
2440
4479
*actual_table= nj_col->table_ref;
2442
return(found_field);
4481
DBUG_RETURN(found_field);
2519
4560
Find field in a table reference.
2522
find_field_in_table_ref()
2523
session [in] thread Cursor
2524
table_list [in] table reference to search
2525
name [in] name of field
2526
length [in] field length of name
2527
item_name [in] name of item if it will be created (VIEW)
2528
db_name [in] optional database name that qualifies the
2529
table_name [in] optional table name that qualifies the field
2530
ref [in/out] if 'name' is resolved to a view field, ref
2531
is set to point to the found view field
2532
allow_rowid [in] do allow finding of "_rowid" field?
2533
cached_field_index_ptr [in] cached position in field list (used to
2534
speedup lookup for fields in prepared tables)
2535
register_tree_change [in] true if ref is not stack variable and we
2536
need register changes in item tree
2537
actual_table [out] the original table reference where the field
2538
belongs - differs from 'table_list' only for
2539
NATURAL_USING joins.
4563
find_field_in_table_ref()
4564
thd [in] thread handler
4565
table_list [in] table reference to search
4566
name [in] name of field
4567
length [in] field length of name
4568
item_name [in] name of item if it will be created (VIEW)
4569
db_name [in] optional database name that qualifies the
4570
table_name [in] optional table name that qualifies the field
4571
ref [in/out] if 'name' is resolved to a view field, ref
4572
is set to point to the found view field
4573
check_privileges [in] check privileges
4574
allow_rowid [in] do allow finding of "_rowid" field?
4575
cached_field_index_ptr [in] cached position in field list (used to
4576
speedup lookup for fields in prepared tables)
4577
register_tree_change [in] TRUE if ref is not stack variable and we
4578
need register changes in item tree
4579
actual_table [out] the original table reference where the field
4580
belongs - differs from 'table_list' only for
4581
NATURAL_USING joins.
2542
Find a field in a table reference depending on the type of table
2543
reference. There are three types of table references with respect
2544
to the representation of their result columns:
2545
- an array of Field_translator objects for MERGE views and some
2546
information_schema tables,
2547
- an array of Field objects (and possibly a name hash) for stored
2549
- a list of Natural_join_column objects for NATURAL/USING joins.
2550
This procedure detects the type of the table reference 'table_list'
2551
and calls the corresponding search routine.
4584
Find a field in a table reference depending on the type of table
4585
reference. There are three types of table references with respect
4586
to the representation of their result columns:
4587
- an array of Field_translator objects for MERGE views and some
4588
information_schema tables,
4589
- an array of Field objects (and possibly a name hash) for stored
4591
- a list of Natural_join_column objects for NATURAL/USING joins.
4592
This procedure detects the type of the table reference 'table_list'
4593
and calls the corresponding search routine.
2554
0 field is not found
2555
view_ref_found found value in VIEW (real result is in *ref)
4596
0 field is not found
4597
view_ref_found found value in VIEW (real result is in *ref)
2560
find_field_in_table_ref(Session *session, TableList *table_list,
2561
const char *name, uint32_t length,
4602
find_field_in_table_ref(THD *thd, TABLE_LIST *table_list,
4603
const char *name, uint length,
2562
4604
const char *item_name, const char *db_name,
2563
4605
const char *table_name, Item **ref,
2565
uint32_t *cached_field_index_ptr,
2566
bool register_tree_change, TableList **actual_table)
4606
bool check_privileges, bool allow_rowid,
4607
uint *cached_field_index_ptr,
4608
bool register_tree_change, TABLE_LIST **actual_table)
2570
assert(table_list->alias);
4611
DBUG_ENTER("find_field_in_table_ref");
4612
DBUG_ASSERT(table_list->alias);
4614
DBUG_ASSERT(item_name);
4616
("table: '%s' field name: '%s' item name: '%s' ref 0x%lx",
4617
table_list->alias, name, item_name, (ulong) ref));
2575
4620
Check that the table and database that qualify the current field name
2687
4786
Find field in table list.
2690
find_field_in_tables()
2691
session pointer to current thread structure
2692
item field item that should be found
2693
first_table list of tables to be searched for item
2694
last_table end of the list of tables to search for item. If NULL
2695
then search to the end of the list 'first_table'.
2696
ref if 'item' is resolved to a view field, ref is set to
2697
point to the found view field
2698
report_error Degree of error reporting:
2699
- IGNORE_ERRORS then do not report any error
2700
- IGNORE_EXCEPT_NON_UNIQUE report only non-unique
2701
fields, suppress all other errors
2702
- REPORT_EXCEPT_NON_UNIQUE report all other errors
2703
except when non-unique fields were found
2705
register_tree_change true if ref is not a stack variable and we
2706
to need register changes in item tree
4789
find_field_in_tables()
4790
thd pointer to current thread structure
4791
item field item that should be found
4792
first_table list of tables to be searched for item
4793
last_table end of the list of tables to search for item. If NULL
4794
then search to the end of the list 'first_table'.
4795
ref if 'item' is resolved to a view field, ref is set to
4796
point to the found view field
4797
report_error Degree of error reporting:
4798
- IGNORE_ERRORS then do not report any error
4799
- IGNORE_EXCEPT_NON_UNIQUE report only non-unique
4800
fields, suppress all other errors
4801
- REPORT_EXCEPT_NON_UNIQUE report all other errors
4802
except when non-unique fields were found
4804
check_privileges need to check privileges
4805
register_tree_change TRUE if ref is not a stack variable and we
4806
to need register changes in item tree
2709
0 If error: the found field is not unique, or there are
2710
no sufficient access priviliges for the found field,
2711
or the field is qualified with non-existing table.
2712
not_found_field The function was called with report_error ==
2713
(IGNORE_ERRORS || IGNORE_EXCEPT_NON_UNIQUE) and a
2714
field was not found.
2715
view_ref_found View field is found, item passed through ref parameter
2716
found field If a item was resolved to some field
4809
0 If error: the found field is not unique, or there are
4810
no sufficient access priviliges for the found field,
4811
or the field is qualified with non-existing table.
4812
not_found_field The function was called with report_error ==
4813
(IGNORE_ERRORS || IGNORE_EXCEPT_NON_UNIQUE) and a
4814
field was not found.
4815
view_ref_found View field is found, item passed through ref parameter
4816
found field If a item was resolved to some field
2720
find_field_in_tables(Session *session, Item_ident *item,
2721
TableList *first_table, TableList *last_table,
2722
Item **ref, find_item_error_report_type report_error,
2723
bool register_tree_change)
4820
find_field_in_tables(THD *thd, Item_ident *item,
4821
TABLE_LIST *first_table, TABLE_LIST *last_table,
4822
Item **ref, find_item_error_report_type report_error,
4823
bool check_privileges, bool register_tree_change)
2725
4825
Field *found=0;
2726
4826
const char *db= item->db_name;
2727
4827
const char *table_name= item->table_name;
2728
4828
const char *name= item->field_name;
2729
uint32_t length=(uint32_t) strlen(name);
4829
uint length=(uint) strlen(name);
2730
4830
char name_buff[NAME_LEN+1];
2731
TableList *cur_table= first_table;
2732
TableList *actual_table;
4831
TABLE_LIST *cur_table= first_table;
4832
TABLE_LIST *actual_table;
2733
4833
bool allow_rowid;
2735
4835
if (!table_name || !table_name[0])
3175
5329
Find and mark the common columns of two table references.
3178
mark_common_columns()
3179
session [in] current thread
3180
table_ref_1 [in] the first (left) join operand
3181
table_ref_2 [in] the second (right) join operand
3182
using_fields [in] if the join is JOIN...USING - the join columns,
3183
if NATURAL join, then NULL
3184
found_using_fields [out] number of fields from the USING clause that were
3185
found among the common fields
5332
mark_common_columns()
5333
thd [in] current thread
5334
table_ref_1 [in] the first (left) join operand
5335
table_ref_2 [in] the second (right) join operand
5336
using_fields [in] if the join is JOIN...USING - the join columns,
5337
if NATURAL join, then NULL
5338
found_using_fields [out] number of fields from the USING clause that were
5339
found among the common fields
3188
The procedure finds the common columns of two relations (either
3189
tables or intermediate join results), and adds an equi-join condition
3190
to the ON clause of 'table_ref_2' for each pair of matching columns.
3191
If some of table_ref_XXX represents a base table or view, then we
3192
create new 'Natural_join_column' instances for each column
3193
reference and store them in the 'join_columns' of the table
5342
The procedure finds the common columns of two relations (either
5343
tables or intermediate join results), and adds an equi-join condition
5344
to the ON clause of 'table_ref_2' for each pair of matching columns.
5345
If some of table_ref_XXX represents a base table or view, then we
5346
create new 'Natural_join_column' instances for each column
5347
reference and store them in the 'join_columns' of the table
3197
The procedure assumes that store_natural_using_join_columns() was
3198
called for the previous level of NATURAL/USING joins.
5351
The procedure assumes that store_natural_using_join_columns() was
5352
called for the previous level of NATURAL/USING joins.
3201
true error when some common column is non-unique, or out of memory
5355
TRUE error when some common column is non-unique, or out of memory
3206
mark_common_columns(Session *session, TableList *table_ref_1, TableList *table_ref_2,
3207
List<String> *using_fields, uint32_t *found_using_fields)
5360
mark_common_columns(THD *thd, TABLE_LIST *table_ref_1, TABLE_LIST *table_ref_2,
5361
List<String> *using_fields, uint *found_using_fields)
3209
5363
Field_iterator_table_ref it_1, it_2;
3210
5364
Natural_join_column *nj_col_1, *nj_col_2;
3212
bool first_outer_loop= true;
5366
bool first_outer_loop= TRUE;
3214
5368
Leaf table references to which new natural join columns are added
3215
5369
if the leaves are != NULL.
3217
TableList *leaf_1= (table_ref_1->nested_join &&
3218
!table_ref_1->is_natural_join) ?
3220
TableList *leaf_2= (table_ref_2->nested_join &&
3221
!table_ref_2->is_natural_join) ?
5371
TABLE_LIST *leaf_1= (table_ref_1->nested_join &&
5372
!table_ref_1->is_natural_join) ?
5374
TABLE_LIST *leaf_2= (table_ref_2->nested_join &&
5375
!table_ref_2->is_natural_join) ?
5378
DBUG_ENTER("mark_common_columns");
5379
DBUG_PRINT("info", ("operand_1: %s operand_2: %s",
5380
table_ref_1->alias, table_ref_2->alias));
3224
5382
*found_using_fields= 0;
3226
5384
for (it_1.set(table_ref_1); !it_1.end_of_fields(); it_1.next())
3229
5387
const char *field_name_1;
3230
5388
/* true if field_name_1 is a member of using_fields */
3231
5389
bool is_using_column_1;
3232
5390
if (!(nj_col_1= it_1.get_or_create_column_ref(leaf_1)))
3234
5392
field_name_1= nj_col_1->name();
3235
is_using_column_1= using_fields &&
5393
is_using_column_1= using_fields &&
3236
5394
test_if_string_in_list(field_name_1, using_fields);
5395
DBUG_PRINT ("info", ("field_name_1=%s.%s",
5396
nj_col_1->table_name() ? nj_col_1->table_name() : "",
3239
5400
Find a field with the same name in table_ref_2.
4359
6609
thus we safely can take table from the first field.
4361
6611
table= (*ptr)->table;
4362
table->auto_increment_field_not_null= false;
6612
table->auto_increment_field_not_null= FALSE;
4364
while ((field = *ptr++) && ! session->is_error())
6614
while ((field = *ptr++) && ! thd->is_error())
4367
6617
table= field->table;
4368
6618
if (field == table->next_number_field)
4369
table->auto_increment_field_not_null= true;
6619
table->auto_increment_field_not_null= TRUE;
4370
6620
if (value->save_in_field(field, 0) < 0)
4374
return(session->is_error());
6623
DBUG_RETURN(thd->is_error());
4378
table->auto_increment_field_not_null= false;
6627
table->auto_increment_field_not_null= FALSE;
4384
bool drizzle_rm_tmp_tables()
6632
my_bool mysql_rm_tmp_tables(void)
4388
assert(drizzle_tmpdir);
4390
if (!(session= new Session(plugin::Listen::getNullClient())))
4392
session->thread_stack= (char*) &session;
4393
session->storeGlobals();
4395
plugin::StorageEngine::removeLostTemporaryTables(*session, drizzle_tmpdir);
6635
char filePath[FN_REFLEN], *tmpdir, filePathCopy[FN_REFLEN];
6640
DBUG_ENTER("mysql_rm_tmp_tables");
6642
if (!(thd= new THD))
6644
thd->thread_stack= (char*) &thd;
6645
thd->store_globals();
6647
for (i=0; i<=mysql_tmpdir_list.max; i++)
6649
tmpdir=mysql_tmpdir_list.list[i];
6650
/* See if the directory exists */
6651
if (!(dirp = my_dir(tmpdir,MYF(MY_WME | MY_DONT_SORT))))
6654
/* Remove all SQLxxx tables from directory */
6656
for (idx=0 ; idx < (uint) dirp->number_off_files ; idx++)
6658
file=dirp->dir_entry+idx;
6660
/* skiping . and .. */
6661
if (file->name[0] == '.' && (!file->name[1] ||
6662
(file->name[1] == '.' && !file->name[2])))
6665
if (!bcmp((uchar*) file->name, (uchar*) tmp_file_prefix,
6666
tmp_file_prefix_length))
6668
char *ext= fn_ext(file->name);
6669
uint ext_len= strlen(ext);
6670
uint filePath_len= my_snprintf(filePath, sizeof(filePath),
6671
"%s%c%s", tmpdir, FN_LIBCHAR,
6673
if (!bcmp((uchar*) reg_ext, (uchar*) ext, ext_len))
6675
handler *handler_file= 0;
6676
/* We should cut file extention before deleting of table */
6677
memcpy(filePathCopy, filePath, filePath_len - ext_len);
6678
filePathCopy[filePath_len - ext_len]= 0;
6679
init_tmp_table_share(thd, &share, "", 0, "", filePathCopy);
6680
if (!open_table_def(thd, &share, 0) &&
6681
((handler_file= get_new_handler(&share, thd->mem_root,
6684
handler_file->ha_delete_table(filePathCopy);
6685
delete handler_file;
6687
free_table_share(&share);
6690
File can be already deleted by tmp_table.file->delete_table().
6691
So we hide error messages which happnes during deleting of these
6694
VOID(my_delete(filePath, MYF(0)));
6700
my_pthread_setspecific_ptr(THR_THD, 0);
4404
6706
/*****************************************************************************
4405
unireg support functions
4406
*****************************************************************************/
6707
unireg support functions
6708
*****************************************************************************/
4409
6711
Invalidate any cache entries that are for some DB
4412
remove_db_from_cache()
4413
db Database name. This will be in lower case if
4414
lower_case_table_name is set
6714
remove_db_from_cache()
6715
db Database name. This will be in lower case if
6716
lower_case_table_name is set
4417
We can't use hash_delete when looping hash_elements. We mark them first
4418
and afterwards delete those marked unused.
6719
We can't use hash_delete when looping hash_elements. We mark them first
6720
and afterwards delete those marked unused.
4421
6723
void remove_db_from_cache(const char *db)
4423
safe_mutex_assert_owner(&LOCK_open);
4425
for (uint32_t idx=0 ; idx < open_cache.records ; idx++)
6725
for (uint idx=0 ; idx < open_cache.records ; idx++)
4427
Table *table=(Table*) hash_element(&open_cache,idx);
6727
TABLE *table=(TABLE*) hash_element(&open_cache,idx);
4428
6728
if (!strcmp(table->s->db.str, db))
4430
6730
table->s->version= 0L; /* Free when thread is ready */
4431
6731
if (!table->in_use)
4432
relink_unused(table);
6732
relink_unused(table);
4435
6735
while (unused_tables && !unused_tables->s->version)
4436
hash_delete(&open_cache,(unsigned char*) unused_tables);
6736
VOID(hash_delete(&open_cache,(uchar*) unused_tables));
6741
free all unused tables
6744
This is called by 'handle_manager' when one wants to periodicly flush
6745
all not used tables.
6750
(void) pthread_mutex_lock(&LOCK_open);
6751
while (unused_tables)
6752
hash_delete(&open_cache,(uchar*) unused_tables);
6753
(void) pthread_mutex_unlock(&LOCK_open);
4444
6761
close_thread_tables() is called.
4450
0 This thread now have exclusive access to this table and no other thread
4451
can access the table until close_thread_tables() is called.
4452
1 Table is in use by another thread
6767
0 This thread now have exclusive access to this table and no other thread
6768
can access the table until close_thread_tables() is called.
6769
1 Table is in use by another thread
4455
bool remove_table_from_cache(Session *session, const char *db, const char *table_name,
6772
bool remove_table_from_cache(THD *thd, const char *db, const char *table_name,
4458
6775
char key[MAX_DBKEY_LENGTH];
4460
uint32_t key_length;
4463
bool signalled= false;
4465
key_pos= strcpy(key_pos, db) + strlen(db);
4466
key_pos= strcpy(key_pos+1, table_name) + strlen(table_name);
4467
key_length= (uint32_t) (key_pos-key)+1;
6779
bool result= 0, signalled= 0;
6780
DBUG_ENTER("remove_table_from_cache");
6781
DBUG_PRINT("enter", ("table: '%s'.'%s' flags: %u", db, table_name, flags));
6783
key_length=(uint) (strmov(strmov(key,db)+1,table_name)-key)+1;
4471
6786
HASH_SEARCH_STATE state;
4472
result= signalled= false;
6787
result= signalled= 0;
4474
for (table= (Table*) hash_first(&open_cache, (unsigned char*) key, key_length,
6789
for (table= (TABLE*) hash_first(&open_cache, (uchar*) key, key_length,
4477
table= (Table*) hash_next(&open_cache, (unsigned char*) key, key_length,
6792
table= (TABLE*) hash_next(&open_cache, (uchar*) key, key_length,
6796
DBUG_PRINT("tcache", ("found table: '%s'.'%s' 0x%lx", table->s->db.str,
6797
table->s->table_name.str, (long) table));
4482
6799
table->s->version=0L; /* Free when thread is ready */
4483
6800
if (!(in_use=table->in_use))
6802
DBUG_PRINT("info",("Table was not in use"));
4485
6803
relink_unused(table);
4487
else if (in_use != session)
6805
else if (in_use != thd)
6807
DBUG_PRINT("info", ("Table was in use by other thread"));
4490
6809
Mark that table is going to be deleted from cache. This will
4491
6810
force threads that are in mysql_lock_tables() (but not yet
4492
6811
in thr_multi_lock()) to abort it's locks, close all tables and retry
4494
in_use->some_tables_deleted= true;
6813
in_use->some_tables_deleted= 1;
4495
6814
if (table->is_name_opened())
6816
DBUG_PRINT("info", ("Found another active instance of the table"));
6819
/* Kill delayed insert threads */
6820
if ((in_use->system_thread & SYSTEM_THREAD_DELAYED_INSERT) &&
6823
in_use->killed= THD::KILL_CONNECTION;
6824
pthread_mutex_lock(&in_use->mysys_var->mutex);
6825
if (in_use->mysys_var->current_cond)
6827
pthread_mutex_lock(in_use->mysys_var->current_mutex);
6829
pthread_cond_broadcast(in_use->mysys_var->current_cond);
6830
pthread_mutex_unlock(in_use->mysys_var->current_mutex);
6832
pthread_mutex_unlock(&in_use->mysys_var->mutex);
4500
Now we must abort all tables locks used by this thread
4501
as the thread may be waiting to get a lock for another table.
6835
Now we must abort all tables locks used by this thread
6836
as the thread may be waiting to get a lock for another table.
4502
6837
Note that we need to hold LOCK_open while going through the
4503
6838
list. So that the other thread cannot change it. The other
4504
6839
thread must also hold LOCK_open whenever changing the
4505
6840
open_tables list. Aborting the MERGE lock after a child was
4506
6841
closed and before the parent is closed would be fatal.
4508
for (Table *session_table= in_use->open_tables;
4510
session_table= session_table->next)
6843
for (TABLE *thd_table= in_use->open_tables;
6845
thd_table= thd_table->next)
4512
6847
/* Do not handle locks of MERGE children. */
4513
if (session_table->db_stat) // If table is open
4514
signalled|= mysql_lock_abort_for_thread(session, session_table);
6848
if (thd_table->db_stat) // If table is open
6849
signalled|= mysql_lock_abort_for_thread(thd, thd_table);
4518
result= result || (flags & RTFC_OWNED_BY_Session_FLAG);
6854
DBUG_PRINT("info", ("Table was in use by current thread. db_stat: %u",
6856
result= result || (flags & RTFC_OWNED_BY_THD_FLAG);
4520
6859
while (unused_tables && !unused_tables->s->version)
4521
hash_delete(&open_cache,(unsigned char*) unused_tables);
6860
VOID(hash_delete(&open_cache,(uchar*) unused_tables));
6862
DBUG_PRINT("info", ("Removing table from table_def_cache"));
4523
6863
/* Remove table from table definition cache if it's not in use */
4524
TableShare::release(key, key_length);
6864
if ((share= (TABLE_SHARE*) hash_search(&table_def_cache,(uchar*) key,
6867
DBUG_PRINT("info", ("share version: %lu ref_count: %u",
6868
share->version, share->ref_count));
6869
share->version= 0; // Mark for delete
6870
if (share->ref_count == 0)
6872
pthread_mutex_lock(&share->mutex);
6873
VOID(hash_delete(&table_def_cache, (uchar*) share));
4526
6877
if (result && (flags & RTFC_WAIT_OTHER_THREAD_FLAG))