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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 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"
34
#include "drizzled/internal/thread_var.h"
36
#include <drizzled/sql_select.h>
37
#include <drizzled/error.h>
38
#include <drizzled/gettext.h>
39
#include <drizzled/nested_join.h>
40
#include <drizzled/sql_base.h>
41
#include <drizzled/show.h>
42
#include <drizzled/item/cmpfunc.h>
43
#include <drizzled/replication_services.h>
44
#include <drizzled/check_stack_overrun.h>
45
#include <drizzled/lock.h>
46
#include <drizzled/plugin/listen.h>
47
#include "drizzled/cached_directory.h"
48
#include <drizzled/field/timestamp.h>
49
#include <drizzled/field/null.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"
54
#include "drizzled/drizzled.h"
55
#include "drizzled/plugin/authorization.h"
56
#include "drizzled/table/temporary.h"
57
#include "drizzled/table/placeholder.h"
58
#include "drizzled/table/unused.h"
19
#include "mysql_priv.h"
20
#include "sql_select.h"
25
#define FLAGSTR(S,F) ((S) & (F) ? #F " " : "")
28
@defgroup Data_Dictionary Data Dictionary
31
TABLE *unused_tables; /* Used by mysql_test */
32
HASH open_cache; /* Used by mysql_test */
33
static HASH table_def_cache;
34
static TABLE_SHARE *oldest_unused_share, end_of_unused_share;
35
static pthread_mutex_t LOCK_table_share;
36
static bool table_def_inited= 0;
38
static int open_unireg_entry(THD *thd, TABLE *entry, TABLE_LIST *table_list,
40
char *cache_key, uint cache_key_length,
41
MEM_ROOT *mem_root, uint flags);
42
static void free_cache_entry(TABLE *entry);
43
static void close_old_data_files(THD *thd, TABLE *table, bool morph_locks,
47
extern "C" uchar *table_cache_key(const uchar *record, size_t *length,
48
my_bool not_used __attribute__((unused)))
50
TABLE *entry=(TABLE*) record;
51
*length= entry->s->table_cache_key.length;
52
return (uchar*) entry->s->table_cache_key.str;
65
extern bool volatile shutdown_in_progress;
67
56
bool table_cache_init(void)
72
uint32_t cached_open_tables(void)
74
return table::getCache().size();
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;
77
63
void table_cache_free(void)
79
refresh_version++; // Force close of open tables
81
table::getUnused().clear();
82
table::getCache().clear();
86
Close cursor handle, but leave the table in the table cache
89
close_handle_and_leave_table_as_lock()
93
By leaving the table in the table cache, it disallows any other thread
96
session->getKilled() will be set if we run out of memory
98
If closing a MERGE child, the calling function has to take care for
99
closing the parent too, if necessary.
103
void close_handle_and_leave_table_as_lock(Table *table)
105
assert(table->db_stat);
106
assert(table->getShare()->getType() == message::Table::STANDARD);
65
DBUG_ENTER("table_cache_free");
68
close_cached_tables(NULL, NULL, FALSE, FALSE, FALSE);
69
if (!open_cache.records) // Safety first
70
hash_free(&open_cache);
75
uint cached_open_tables(void)
77
return open_cache.records;
82
static void check_unused(void)
84
uint count= 0, open_files= 0, idx= 0;
85
TABLE *cur_link,*start_link;
87
if ((start_link=cur_link=unused_tables))
91
if (cur_link != cur_link->next->prev || cur_link != cur_link->prev->next)
93
DBUG_PRINT("error",("Unused_links aren't linked properly")); /* purecov: inspected */
94
return; /* purecov: inspected */
96
} while (count++ < open_cache.records &&
97
(cur_link=cur_link->next) != start_link);
98
if (cur_link != start_link)
100
DBUG_PRINT("error",("Unused_links aren't connected")); /* purecov: inspected */
103
for (idx=0 ; idx < open_cache.records ; idx++)
105
TABLE *entry=(TABLE*) hash_element(&open_cache,idx);
113
DBUG_PRINT("error",("Unused_links doesn't match open_cache: diff: %d", /* purecov: inspected */
114
count)); /* purecov: inspected */
117
#ifdef NOT_SAFE_FOR_REPAIR
119
check that open cache and table definition cache has same number of
123
for (idx=0 ; idx < table_def_cache.records ; idx++)
125
TABLE_SHARE *entry= (TABLE_SHARE*) hash_element(&table_def_cache,idx);
126
count+= entry->ref_count;
128
if (count != open_files)
130
DBUG_PRINT("error", ("table_def ref_count: %u open_cache: %u",
132
DBUG_ASSERT(count == open_files);
137
#define check_unused()
142
Create a table cache key
145
create_table_def_key()
147
key Create key here (must be of size MAX_DBKEY_LENGTH)
148
table_list Table definition
149
tmp_table Set if table is a tmp table
152
The table cache_key is created from:
156
if the table is a tmp table, we add the following to make each tmp table
159
4 bytes for master thread id
160
4 bytes pseudo thread id
166
uint create_table_def_key(THD *thd, char *key, TABLE_LIST *table_list,
169
uint key_length= (uint) (strmov(strmov(key, table_list->db)+1,
170
table_list->table_name)-key)+1;
173
int4store(key + key_length, thd->server_id);
174
int4store(key + key_length + 4, thd->variables.pseudo_thread_id);
175
key_length+= TMP_TABLE_KEY_EXTRA;
182
/*****************************************************************************
183
Functions to handle table definition cach (TABLE_SHARE)
184
*****************************************************************************/
186
extern "C" uchar *table_def_key(const uchar *record, size_t *length,
187
my_bool not_used __attribute__((unused)))
189
TABLE_SHARE *entry=(TABLE_SHARE*) record;
190
*length= entry->table_cache_key.length;
191
return (uchar*) entry->table_cache_key.str;
195
static void table_def_free_entry(TABLE_SHARE *share)
197
DBUG_ENTER("table_def_free_entry");
200
/* remove from old_unused_share list */
201
pthread_mutex_lock(&LOCK_table_share);
202
*share->prev= share->next;
203
share->next->prev= share->prev;
204
pthread_mutex_unlock(&LOCK_table_share);
206
free_table_share(share);
211
bool table_def_init(void)
214
pthread_mutex_init(&LOCK_table_share, MY_MUTEX_INIT_FAST);
215
oldest_unused_share= &end_of_unused_share;
216
end_of_unused_share.prev= &oldest_unused_share;
218
return hash_init(&table_def_cache, &my_charset_bin, table_def_size,
220
(hash_free_key) table_def_free_entry, 0) != 0;
224
void table_def_free(void)
226
DBUG_ENTER("table_def_free");
227
if (table_def_inited)
230
pthread_mutex_destroy(&LOCK_table_share);
231
hash_free(&table_def_cache);
237
uint cached_table_definitions(void)
239
return table_def_cache.records;
244
Get TABLE_SHARE for a table.
248
table_list Table that should be opened
250
key_length Length of key
251
db_flags Flags to open_table_def():
253
error out: Error code from open_table_def()
256
Get a table definition from the table definition cache.
257
If it doesn't exist, create a new from the table definition file.
260
We must have wrlock on LOCK_open when we come here
261
(To be changed later)
268
TABLE_SHARE *get_table_share(THD *thd, TABLE_LIST *table_list, char *key,
269
uint key_length, uint db_flags, int *error)
272
DBUG_ENTER("get_table_share");
276
/* Read table definition from cache */
277
if ((share= (TABLE_SHARE*) hash_search(&table_def_cache,(uchar*) key,
281
if (!(share= alloc_table_share(table_list, key, key_length)))
287
Lock mutex to be able to read table definition from file without
290
(void) pthread_mutex_lock(&share->mutex);
293
We assign a new table id under the protection of the LOCK_open and
294
the share's own mutex. We do this insted of creating a new mutex
295
and using it for the sole purpose of serializing accesses to a
296
static variable, we assign the table id here. We assign it to the
297
share before inserting it into the table_def_cache to be really
298
sure that it cannot be read from the cache without having a table
301
CAVEAT. This means that the table cannot be used for
302
binlogging/replication purposes, unless get_table_share() has been
303
called directly or indirectly.
305
assign_new_table_id(share);
307
if (my_hash_insert(&table_def_cache, (uchar*) share))
309
free_table_share(share);
310
DBUG_RETURN(0); // return error
312
if (open_table_def(thd, share, db_flags))
314
*error= share->error;
315
(void) hash_delete(&table_def_cache, (uchar*) share);
318
share->ref_count++; // Mark in use
319
DBUG_PRINT("exit", ("share: 0x%lx ref_count: %u",
320
(ulong) share, share->ref_count));
321
(void) pthread_mutex_unlock(&share->mutex);
326
We found an existing table definition. Return it if we didn't get
327
an error when reading the table definition from file.
330
/* We must do a lock to ensure that the structure is initialized */
331
(void) pthread_mutex_lock(&share->mutex);
334
/* Table definition contained an error */
335
open_table_error(share, share->error, share->open_errno, share->errarg);
336
(void) pthread_mutex_unlock(&share->mutex);
340
if (!share->ref_count++ && share->prev)
343
Share was not used before and it was in the old_unused_share list
344
Unlink share from this list
346
DBUG_PRINT("info", ("Unlinking from not used list"));
347
pthread_mutex_lock(&LOCK_table_share);
348
*share->prev= share->next;
349
share->next->prev= share->prev;
352
pthread_mutex_unlock(&LOCK_table_share);
354
(void) pthread_mutex_unlock(&share->mutex);
356
/* Free cache if too big */
357
while (table_def_cache.records > table_def_size &&
358
oldest_unused_share->next)
360
pthread_mutex_lock(&oldest_unused_share->mutex);
361
VOID(hash_delete(&table_def_cache, (uchar*) oldest_unused_share));
364
DBUG_PRINT("exit", ("share: 0x%lx ref_count: %u",
365
(ulong) share, share->ref_count));
371
Get a table share. If it didn't exist, try creating it from engine
373
For arguments and return values, see get_table_from_share()
377
*get_table_share_with_create(THD *thd, TABLE_LIST *table_list,
378
char *key, uint key_length,
379
uint db_flags, int *error)
383
DBUG_ENTER("get_table_share_with_create");
385
share= get_table_share(thd, table_list, key, key_length, db_flags, error);
387
If share is not NULL, we found an existing share.
389
If share is NULL, and there is no error, we're inside
390
pre-locking, which silences 'ER_NO_SUCH_TABLE' errors
391
with the intention to silently drop non-existing tables
392
from the pre-locking list. In this case we still need to try
393
auto-discover before returning a NULL share.
395
If share is NULL and the error is ER_NO_SUCH_TABLE, this is
396
the same as above, only that the error was not silenced by
397
pre-locking. Once again, we need to try to auto-discover
400
Finally, if share is still NULL, it's a real error and we need
403
@todo Rework alternative ways to deal with ER_NO_SUCH TABLE.
405
if (share || (thd->is_error() && (thd->main_da.sql_errno() != ER_NO_SUCH_TABLE)))
409
/* Table didn't exist. Check if some engine can provide it */
410
if ((tmp= ha_create_table_from_engine(thd, table_list->db,
411
table_list->table_name)) < 0)
414
No such table in any engine.
415
Hide "Table doesn't exist" errors if the table belongs to a view.
416
The check for thd->is_error() is necessary to not push an
417
unwanted error in case of pre-locking, which silences
418
"no such table" errors.
419
@todo Rework the alternative ways to deal with ER_NO_SUCH TABLE.
421
if (thd->is_error() && table_list->belong_to_view)
424
my_error(ER_VIEW_INVALID, MYF(0), "", "");
430
/* Give right error message */
432
DBUG_PRINT("error", ("Discovery of %s/%s failed", table_list->db,
433
table_list->table_name));
434
my_printf_error(ER_UNKNOWN_ERROR,
435
"Failed to open '%-.64s', error while "
436
"unpacking from engine",
437
MYF(0), table_list->table_name);
440
/* Table existed in engine. Let's open it */
441
mysql_reset_errors(thd, 1); // Clear warnings
442
thd->clear_error(); // Clear error message
443
DBUG_RETURN(get_table_share(thd, table_list, key, key_length,
449
Mark that we are not using table share anymore.
452
release_table_share()
454
release_type How the release should be done:
456
- Release without checking
457
RELEASE_WAIT_FOR_DROP
458
- Don't return until we get a signal that the
459
table is deleted or the thread is killed.
462
If ref_count goes to zero and (we have done a refresh or if we have
463
already too many open table shares) then delete the definition.
465
If type == RELEASE_WAIT_FOR_DROP then don't return until we get a signal
466
that the table is deleted or the thread is killed.
469
void release_table_share(TABLE_SHARE *share, enum release_type type)
471
bool to_be_deleted= 0;
472
DBUG_ENTER("release_table_share");
474
("share: 0x%lx table: %s.%s ref_count: %u version: %lu",
475
(ulong) share, share->db.str, share->table_name.str,
476
share->ref_count, share->version));
478
safe_mutex_assert_owner(&LOCK_open);
480
pthread_mutex_lock(&share->mutex);
481
if (!--share->ref_count)
483
if (share->version != refresh_version)
487
/* Link share last in used_table_share list */
488
DBUG_PRINT("info",("moving share to unused list"));
490
DBUG_ASSERT(share->next == 0);
491
pthread_mutex_lock(&LOCK_table_share);
492
share->prev= end_of_unused_share.prev;
493
*end_of_unused_share.prev= share;
494
end_of_unused_share.prev= &share->next;
495
share->next= &end_of_unused_share;
496
pthread_mutex_unlock(&LOCK_table_share);
498
to_be_deleted= (table_def_cache.records > table_def_size);
504
DBUG_PRINT("info", ("Deleting share"));
505
hash_delete(&table_def_cache, (uchar*) share);
508
pthread_mutex_unlock(&share->mutex);
514
Check if table definition exits in cache
517
get_cached_table_share()
519
table_name Table name
523
# TABLE_SHARE for table
526
TABLE_SHARE *get_cached_table_share(const char *db, const char *table_name)
528
char key[NAME_LEN*2+2];
529
TABLE_LIST table_list;
531
safe_mutex_assert_owner(&LOCK_open);
533
table_list.db= (char*) db;
534
table_list.table_name= (char*) table_name;
535
key_length= create_table_def_key((THD*) 0, key, &table_list, 0);
536
return (TABLE_SHARE*) hash_search(&table_def_cache,(uchar*) key, key_length);
541
Close file handle, but leave the table in the table cache
544
close_handle_and_leave_table_as_lock()
548
By leaving the table in the table cache, it disallows any other thread
551
thd->killed will be set if we run out of memory
553
If closing a MERGE child, the calling function has to take care for
554
closing the parent too, if necessary.
558
void close_handle_and_leave_table_as_lock(TABLE *table)
560
TABLE_SHARE *share, *old_share= table->s;
562
MEM_ROOT *mem_root= &table->mem_root;
563
DBUG_ENTER("close_handle_and_leave_table_as_lock");
565
DBUG_ASSERT(table->db_stat);
109
568
Make a local copy of the table share and free the current one.
110
569
This has to be done to ensure that the table share is removed from
111
570
the table defintion cache as soon as the last instance is removed
113
TableIdentifier identifier(table->getShare()->getSchemaName(), table->getShare()->getTableName(), message::Table::INTERNAL);
114
const TableIdentifier::Key &key(identifier.getKey());
115
TableShare *share= new TableShare(identifier.getType(),
117
const_cast<char *>(key.vector()), static_cast<uint32_t>(table->getShare()->getCacheKeySize()));
119
table->cursor->close();
120
table->db_stat= 0; // Mark cursor closed
121
TableShare::release(table->getMutableShare());
122
table->setShare(share);
572
if (multi_alloc_root(mem_root,
573
&share, sizeof(*share),
574
&key_buff, old_share->table_cache_key.length,
577
bzero((char*) share, sizeof(*share));
578
share->set_table_cache_key(key_buff, old_share->table_cache_key.str,
579
old_share->table_cache_key.length);
580
share->tmp_table= INTERNAL_TMP_TABLE; // for intern_close_table()
583
table->file->close();
584
table->db_stat= 0; // Mark file closed
585
release_table_share(table->s, RELEASE_NORMAL);
587
table->file->change_table_ptr(table, table->s);
595
Create a list for all open tables matching SQL expression
600
wild SQL like expression
603
One gets only a list of tables for which one has any kind of privilege.
604
db and table names are allocated in result struct, so one doesn't need
605
a lock on LOCK_open when traversing the return list.
608
NULL Error (Probably OOM)
609
# Pointer to list of names of open tables.
612
OPEN_TABLE_LIST *list_open_tables(THD *thd, const char *db, const char *wild)
615
OPEN_TABLE_LIST **start_list, *open_list;
616
TABLE_LIST table_list;
617
DBUG_ENTER("list_open_tables");
619
VOID(pthread_mutex_lock(&LOCK_open));
620
bzero((char*) &table_list,sizeof(table_list));
621
start_list= &open_list;
624
for (uint idx=0 ; result == 0 && idx < open_cache.records; idx++)
626
OPEN_TABLE_LIST *table;
627
TABLE *entry=(TABLE*) hash_element(&open_cache,idx);
628
TABLE_SHARE *share= entry->s;
630
if (db && my_strcasecmp(system_charset_info, db, share->db.str))
632
if (wild && wild_compare(share->table_name.str, wild, 0))
635
/* Check if user has SELECT privilege for any column in the table */
636
table_list.db= share->db.str;
637
table_list.table_name= share->table_name.str;
639
/* need to check if we haven't already listed it */
640
for (table= open_list ; table ; table=table->next)
642
if (!strcmp(table->table, share->table_name.str) &&
643
!strcmp(table->db, share->db.str))
647
if (entry->locked_by_name)
654
if (!(*start_list = (OPEN_TABLE_LIST *)
655
sql_alloc(sizeof(**start_list)+share->table_cache_key.length)))
657
open_list=0; // Out of memory
660
strmov((*start_list)->table=
661
strmov(((*start_list)->db= (char*) ((*start_list)+1)),
663
share->table_name.str);
664
(*start_list)->in_use= entry->in_use ? 1 : 0;
665
(*start_list)->locked= entry->locked_by_name ? 1 : 0;
666
start_list= &(*start_list)->next;
669
VOID(pthread_mutex_unlock(&LOCK_open));
670
DBUG_RETURN(open_list);
126
673
/*****************************************************************************
127
674
* Functions to free open table cache
128
675
****************************************************************************/
131
void Table::intern_close_table()
678
void intern_close_table(TABLE *table)
132
679
{ // Free all structures
134
if (cursor) // Not true if name lock
680
DBUG_ENTER("intern_close_table");
681
DBUG_PRINT("tcache", ("table: '%s'.'%s' 0x%lx",
682
table->s ? table->s->db.str : "?",
683
table->s ? table->s->table_name.str : "?",
686
free_io_cache(table);
687
if (table->file) // Not true if name lock
688
VOID(closefrm(table, 1)); // close file
693
Remove table from the open table cache
697
table Table to remove
700
We need to have a lock on LOCK_open when calling this
703
static void free_cache_entry(TABLE *table)
705
DBUG_ENTER("free_cache_entry");
707
intern_close_table(table);
136
delete_table(true); // close cursor
710
table->next->prev=table->prev; /* remove from used chain */
711
table->prev->next=table->next;
712
if (table == unused_tables)
714
unused_tables=unused_tables->next;
715
if (table == unused_tables)
718
check_unused(); // consisty check
720
my_free((uchar*) table,MYF(0));
140
724
/* Free resources allocated by filesort() and read_record() */
142
void Table::free_io_cache()
726
void free_io_cache(TABLE *table)
728
DBUG_ENTER("free_io_cache");
729
if (table->sort.io_cache)
146
sort.io_cache->close_cached_file();
147
delete sort.io_cache;
731
close_cached_file(table->sort.io_cache);
732
my_free((uchar*) table->sort.io_cache,MYF(0));
733
table->sort.io_cache=0;
154
740
Close all tables which aren't in use by any thread
156
@param session Thread context (may be NULL)
742
@param thd Thread context
157
743
@param tables List of tables to remove from the cache
158
@param have_lock If table::Cache::singleton().mutex() is locked
744
@param have_lock If LOCK_open is locked
159
745
@param wait_for_refresh Wait for a impending flush
160
746
@param wait_for_placeholders Wait for tables being reopened so that the GRL
161
won't proceed while write-locked tables are being reopened by other
747
won't proceed while write-locked tables are being reopened by other
164
@remark Session can be NULL, but then wait_for_refresh must be false
165
and tables must be NULL.
750
@remark THD can be NULL, but then wait_for_refresh must be FALSE
751
and tables must be NULL.
168
bool Session::close_cached_tables(TableList *tables, bool wait_for_refresh, bool wait_for_placeholders)
754
bool close_cached_tables(THD *thd, TABLE_LIST *tables, bool have_lock,
755
bool wait_for_refresh, bool wait_for_placeholders)
171
Session *session= this;
758
DBUG_ENTER("close_cached_tables");
759
DBUG_ASSERT(thd || (!wait_for_refresh && !tables));
762
VOID(pthread_mutex_lock(&LOCK_open));
174
table::Cache::singleton().mutex().lock(); /* Optionally lock for remove tables from open_cahe if not in use */
178
refresh_version++; // Force close of open tables
180
table::getUnused().clear();
182
if (wait_for_refresh)
185
Other threads could wait in a loop in open_and_lock_tables(),
186
trying to lock one or more of our tables.
188
If they wait for the locks in thr_multi_lock(), their lock
189
request is aborted. They loop in open_and_lock_tables() and
190
enter open_table(). Here they notice the table is refreshed and
191
wait for COND_refresh. Then they loop again in
192
openTablesLock() and this time open_table() succeeds. At
193
this moment, if we (the FLUSH TABLES thread) are scheduled and
194
on another FLUSH TABLES enter close_cached_tables(), they could
195
awake while we sleep below, waiting for others threads (us) to
196
close their open tables. If this happens, the other threads
197
would find the tables unlocked. They would get the locks, one
198
after the other, and could do their destructive work. This is an
199
issue if we have LOCK TABLES in effect.
201
The problem is that the other threads passed all checks in
202
open_table() before we refresh the table.
204
The fix for this problem is to set some_tables_deleted for all
205
threads with open tables. These threads can still get their
206
locks, but will immediately release them again after checking
207
this variable. They will then loop in openTablesLock()
208
again. There they will wait until we update all tables version
211
Setting some_tables_deleted is done by table::Cache::singleton().removeTable()
214
In other words (reviewer suggestion): You need this setting of
215
some_tables_deleted for the case when table was opened and all
216
related checks were passed before incrementing refresh_version
217
(which you already have) but attempt to lock the table happened
218
after the call to Session::close_old_data_files() i.e. after removal of
219
current thread locks.
221
for (table::CacheMap::const_iterator iter= table::getCache().begin();
222
iter != table::getCache().end();
225
Table *table= (*iter).second;
227
table->in_use->some_tables_deleted= false;
234
for (TableList *table= tables; table; table= table->next_local)
236
TableIdentifier identifier(table->getSchemaName(), table->getTableName());
237
if (table::Cache::singleton().removeTable(session, identifier,
238
RTFC_OWNED_BY_Session_FLAG))
244
wait_for_refresh= false; // Nothing to wait for
765
refresh_version++; // Force close of open tables
766
while (unused_tables)
769
if (hash_delete(&open_cache,(uchar*) unused_tables))
770
printf("Warning: Couldn't delete open table from hash\n");
772
VOID(hash_delete(&open_cache,(uchar*) unused_tables));
775
/* Free table shares */
776
while (oldest_unused_share->next)
778
pthread_mutex_lock(&oldest_unused_share->mutex);
779
VOID(hash_delete(&table_def_cache, (uchar*) oldest_unused_share));
781
DBUG_PRINT("tcache", ("incremented global refresh_version to: %lu",
247
783
if (wait_for_refresh)
250
If there is any table that has a lower refresh_version, wait until
251
this is closed (or this thread is killed) before returning
786
Other threads could wait in a loop in open_and_lock_tables(),
787
trying to lock one or more of our tables.
789
If they wait for the locks in thr_multi_lock(), their lock
790
request is aborted. They loop in open_and_lock_tables() and
791
enter open_table(). Here they notice the table is refreshed and
792
wait for COND_refresh. Then they loop again in
793
open_and_lock_tables() and this time open_table() succeeds. At
794
this moment, if we (the FLUSH TABLES thread) are scheduled and
795
on another FLUSH TABLES enter close_cached_tables(), they could
796
awake while we sleep below, waiting for others threads (us) to
797
close their open tables. If this happens, the other threads
798
would find the tables unlocked. They would get the locks, one
799
after the other, and could do their destructive work. This is an
800
issue if we have LOCK TABLES in effect.
802
The problem is that the other threads passed all checks in
803
open_table() before we refresh the table.
805
The fix for this problem is to set some_tables_deleted for all
806
threads with open tables. These threads can still get their
807
locks, but will immediately release them again after checking
808
this variable. They will then loop in open_and_lock_tables()
809
again. There they will wait until we update all tables version
812
Setting some_tables_deleted is done by remove_table_from_cache()
815
In other words (reviewer suggestion): You need this setting of
816
some_tables_deleted for the case when table was opened and all
817
related checks were passed before incrementing refresh_version
818
(which you already have) but attempt to lock the table happened
819
after the call to close_old_data_files() i.e. after removal of
820
current thread locks.
253
session->mysys_var->current_mutex= &table::Cache::singleton().mutex();
254
session->mysys_var->current_cond= &COND_refresh;
255
session->set_proc_info("Flushing tables");
257
session->close_old_data_files();
260
/* Wait until all threads has closed all the tables we had locked */
261
while (found && ! session->getKilled())
822
for (uint idx=0 ; idx < open_cache.records ; idx++)
264
for (table::CacheMap::const_iterator iter= table::getCache().begin();
265
iter != table::getCache().end();
268
Table *table= (*iter).second;
269
/* Avoid a self-deadlock. */
270
if (table->in_use == session)
273
Note that we wait here only for tables which are actually open, and
274
not for placeholders with Table::open_placeholder set. Waiting for
275
latter will cause deadlock in the following scenario, for example:
277
conn1-> lock table t1 write;
278
conn2-> lock table t2 write;
279
conn1-> flush tables;
280
conn2-> flush tables;
282
It also does not make sense to wait for those of placeholders that
283
are employed by CREATE TABLE as in this case table simply does not
286
if (table->needs_reopen_or_name_lock() && (table->db_stat ||
287
(table->open_placeholder && wait_for_placeholders)))
290
boost_unique_lock_t scoped(table::Cache::singleton().mutex(), boost::adopt_lock_t());
291
COND_refresh.wait(scoped);
824
TABLE *table=(TABLE*) hash_element(&open_cache,idx);
826
table->in_use->some_tables_deleted= 1;
298
No other thread has the locked tables open; reopen them and get the
299
old locks. This should always succeed (unless some external process
300
has removed the tables)
302
result= session->reopen_tables(true, true);
304
/* Set version for table */
305
for (Table *table= session->open_tables; table ; table= table->getNext())
833
for (TABLE_LIST *table= tables; table; table= table->next_local)
835
if (remove_table_from_cache(thd, table->db, table->table_name,
836
RTFC_OWNED_BY_THD_FLAG))
840
wait_for_refresh=0; // Nothing to wait for
843
if (wait_for_refresh)
846
If there is any table that has a lower refresh_version, wait until
847
this is closed (or this thread is killed) before returning
849
thd->mysys_var->current_mutex= &LOCK_open;
850
thd->mysys_var->current_cond= &COND_refresh;
851
thd_proc_info(thd, "Flushing tables");
853
close_old_data_files(thd,thd->open_tables,1,1);
857
/* Wait until all threads has closed all the tables we had locked */
859
("Waiting for other threads to close their open tables"));
860
while (found && ! thd->killed)
863
for (uint idx=0 ; idx < open_cache.records ; idx++)
865
TABLE *table=(TABLE*) hash_element(&open_cache,idx);
866
/* Avoid a self-deadlock. */
867
if (table->in_use == thd)
308
Preserve the version (0) of write locked tables so that a impending
309
global read lock won't sneak in.
870
Note that we wait here only for tables which are actually open, and
871
not for placeholders with TABLE::open_placeholder set. Waiting for
872
latter will cause deadlock in the following scenario, for example:
874
conn1: lock table t1 write;
875
conn2: lock table t2 write;
879
It also does not make sense to wait for those of placeholders that
880
are employed by CREATE TABLE as in this case table simply does not
311
if (table->reginfo.lock_type < TL_WRITE_ALLOW_WRITE)
312
table->getMutableShare()->refreshVersion();
883
if (table->needs_reopen_or_name_lock() && (table->db_stat ||
884
(table->open_placeholder && wait_for_placeholders)))
887
DBUG_PRINT("signal", ("Waiting for COND_refresh"));
888
pthread_cond_wait(&COND_refresh,&LOCK_open);
316
table::Cache::singleton().mutex().unlock();
319
if (wait_for_refresh)
321
boost_unique_lock_t scopedLock(session->mysys_var->mutex);
322
session->mysys_var->current_mutex= 0;
323
session->mysys_var->current_cond= 0;
324
session->set_proc_info(0);
332
move one table to free list
335
bool Session::free_cached_table()
337
bool found_old_table= false;
338
table::Concurrent *table= static_cast<table::Concurrent *>(open_tables);
340
safe_mutex_assert_owner(table::Cache::singleton().mutex().native_handle());
341
assert(table->key_read == 0);
342
assert(!table->cursor || table->cursor->inited == Cursor::NONE);
344
open_tables= table->getNext();
346
if (table->needs_reopen_or_name_lock() ||
347
version != refresh_version || !table->db_stat)
349
table::remove_table(table);
350
found_old_table= true;
355
Open placeholders have Table::db_stat set to 0, so they should be
356
handled by the first alternative.
894
No other thread has the locked tables open; reopen them and get the
895
old locks. This should always succeed (unless some external process
896
has removed the tables)
358
assert(not table->open_placeholder);
360
/* Free memory and reset for next loop */
361
table->cursor->ha_reset();
364
table::getUnused().link(table);
367
return found_old_table;
898
thd->in_lock_tables=1;
899
result=reopen_tables(thd,1,1);
900
thd->in_lock_tables=0;
901
/* Set version for table */
902
for (TABLE *table=thd->open_tables; table ; table= table->next)
905
Preserve the version (0) of write locked tables so that a impending
906
global read lock won't sneak in.
908
if (table->reginfo.lock_type < TL_WRITE_ALLOW_WRITE)
909
table->s->version= refresh_version;
913
VOID(pthread_mutex_unlock(&LOCK_open));
914
if (wait_for_refresh)
916
pthread_mutex_lock(&thd->mysys_var->mutex);
917
thd->mysys_var->current_mutex= 0;
918
thd->mysys_var->current_cond= 0;
919
thd_proc_info(thd, 0);
920
pthread_mutex_unlock(&thd->mysys_var->mutex);
927
Close all tables which match specified connection string or
928
if specified string is NULL, then any table with a connection string.
931
bool close_cached_connection_tables(THD *thd, bool if_wait_for_refresh,
932
LEX_STRING *connection, bool have_lock)
935
TABLE_LIST tmp, *tables= NULL;
937
DBUG_ENTER("close_cached_connections");
940
bzero(&tmp, sizeof(TABLE_LIST));
943
VOID(pthread_mutex_lock(&LOCK_open));
945
for (idx= 0; idx < table_def_cache.records; idx++)
947
TABLE_SHARE *share= (TABLE_SHARE *) hash_element(&table_def_cache, idx);
949
/* Ignore if table is not open or does not have a connect_string */
950
if (!share->connect_string.length || !share->ref_count)
953
/* Compare the connection string */
955
(connection->length > share->connect_string.length ||
956
(connection->length < share->connect_string.length &&
957
(share->connect_string.str[connection->length] != '/' &&
958
share->connect_string.str[connection->length] != '\\')) ||
959
strncasecmp(connection->str, share->connect_string.str,
960
connection->length)))
963
/* close_cached_tables() only uses these elements */
964
tmp.db= share->db.str;
965
tmp.table_name= share->table_name.str;
966
tmp.next_local= tables;
968
tables= (TABLE_LIST *) memdup_root(thd->mem_root, (char*)&tmp,
973
result= close_cached_tables(thd, tables, TRUE, FALSE, FALSE);
976
VOID(pthread_mutex_unlock(&LOCK_open));
978
if (if_wait_for_refresh)
980
pthread_mutex_lock(&thd->mysys_var->mutex);
981
thd->mysys_var->current_mutex= 0;
982
thd->mysys_var->current_cond= 0;
984
pthread_mutex_unlock(&thd->mysys_var->mutex);
992
Mark all temporary tables which were used by the current statement or
993
substatement as free for reuse, but only if the query_id can be cleared.
995
@param thd thread context
997
@remark For temp tables associated with a open SQL HANDLER the query_id
998
is not reset until the HANDLER is closed.
1001
static void mark_temp_tables_as_free_for_reuse(THD *thd)
1003
for (TABLE *table= thd->temporary_tables ; table ; table= table->next)
1005
if ((table->query_id == thd->query_id) && ! table->open_by_handler)
1008
table->file->ha_reset();
1015
Mark all tables in the list which were used by current substatement
1019
mark_used_tables_as_free_for_reuse()
1020
thd - thread context
1021
table - head of the list of tables
1024
Marks all tables in the list which were used by current substatement
1025
(they are marked by its query_id) as free for reuse.
1028
The reason we reset query_id is that it's not enough to just test
1029
if table->query_id != thd->query_id to know if a table is in use.
1032
SELECT f1_that_uses_t1() FROM t1;
1033
In f1_that_uses_t1() we will see one instance of t1 where query_id is
1034
set to query_id of original query.
1037
static void mark_used_tables_as_free_for_reuse(THD *thd, TABLE *table)
1039
for (; table ; table= table->next)
1041
if (table->query_id == thd->query_id)
1044
table->file->ha_reset();
372
1051
Auxiliary function to close all tables in the open_tables list.
374
@param session Thread context.
1053
@param thd Thread context.
376
1055
@remark It should not ordinarily be called directly.
379
void Session::close_open_tables()
1058
static void close_open_tables(THD *thd)
381
bool found_old_table= false;
383
safe_mutex_assert_not_owner(table::Cache::singleton().mutex().native_handle());
385
boost_unique_lock_t scoped_lock(table::Cache::singleton().mutex()); /* Close all open tables on Session */
389
found_old_table|= free_cached_table();
391
some_tables_deleted= false;
1060
bool found_old_table= 0;
1062
safe_mutex_assert_not_owner(&LOCK_open);
1064
VOID(pthread_mutex_lock(&LOCK_open));
1066
DBUG_PRINT("info", ("thd->open_tables: 0x%lx", (long) thd->open_tables));
1068
while (thd->open_tables)
1069
found_old_table|= close_thread_table(thd, &thd->open_tables);
1070
thd->some_tables_deleted= 0;
1072
/* Free tables to hold down open files */
1073
while (open_cache.records > table_cache_size && unused_tables)
1074
VOID(hash_delete(&open_cache,(uchar*) unused_tables)); /* purecov: tested */
393
1076
if (found_old_table)
395
1078
/* Tell threads waiting for refresh that something has happened */
396
locking::broadcast_refresh();
1079
broadcast_refresh();
1082
VOID(pthread_mutex_unlock(&LOCK_open));
1087
Close all tables used by the current substatement, or all tables
1088
used by this thread if we are on the upper level.
1091
close_thread_tables()
1095
Unlocks tables and frees derived tables.
1096
Put all normal tables used by thread in free list.
1098
It will only close/mark as free for reuse tables opened by this
1099
substatement, it will also check if we are closing tables after
1100
execution of complete query (i.e. we are on upper level) and will
1101
leave prelocked mode if needed.
1104
void close_thread_tables(THD *thd)
1107
DBUG_ENTER("close_thread_tables");
1110
We are assuming here that thd->derived_tables contains ONLY derived
1111
tables for this substatement. i.e. instead of approach which uses
1112
query_id matching for determining which of the derived tables belong
1113
to this substatement we rely on the ability of substatements to
1114
save/restore thd->derived_tables during their execution.
1116
TODO: Probably even better approach is to simply associate list of
1117
derived tables with (sub-)statement instead of thread and destroy
1118
them at the end of its execution.
1120
if (thd->derived_tables)
1124
Close all derived tables generated in queries like
1125
SELECT * FROM (SELECT * FROM t1)
1127
for (table= thd->derived_tables ; table ; table= next)
1130
free_tmp_table(thd, table);
1132
thd->derived_tables= 0;
1136
Mark all temporary tables used by this statement as free for reuse.
1138
mark_temp_tables_as_free_for_reuse(thd);
1140
Let us commit transaction for statement. Since in 5.0 we only have
1141
one statement transaction and don't allow several nested statement
1142
transactions this call will do nothing if we are inside of stored
1143
function or trigger (i.e. statement transaction is already active and
1144
does not belong to statement for which we do close_thread_tables()).
1145
TODO: This should be fixed in later releases.
1147
if (!(thd->state_flags & Open_tables_state::BACKUPS_AVAIL))
1149
thd->main_da.can_overwrite_status= TRUE;
1150
ha_autocommit_or_rollback(thd, thd->is_error());
1151
thd->main_da.can_overwrite_status= FALSE;
1152
thd->transaction.stmt.reset();
1155
if (thd->locked_tables)
1158
/* Ensure we are calling ha_reset() for all used tables */
1159
mark_used_tables_as_free_for_reuse(thd, thd->open_tables);
1162
We are under simple LOCK TABLES so should not do anything else.
1170
For RBR we flush the pending event just before we unlock all the
1171
tables. This means that we are at the end of a topmost
1172
statement, so we ensure that the STMT_END_F flag is set on the
1173
pending event. For statements that are *inside* stored
1174
functions, the pending event will not be flushed: that will be
1175
handled either before writing a query log event (inside
1176
binlog_query()) or when preparing a pending event.
1178
thd->binlog_flush_pending_rows_event(TRUE);
1179
mysql_unlock_tables(thd, thd->lock);
1183
Note that we need to hold LOCK_open while changing the
1184
open_tables list. Another thread may work on it.
1185
(See: remove_table_from_cache(), mysql_wait_completed_table())
1186
Closing a MERGE child before the parent would be fatal if the
1187
other thread tries to abort the MERGE lock in between.
1189
if (thd->open_tables)
1190
close_open_tables(thd);
1196
/* move one table to free list */
1198
bool close_thread_table(THD *thd, TABLE **table_ptr)
1200
bool found_old_table= 0;
1201
TABLE *table= *table_ptr;
1202
DBUG_ENTER("close_thread_table");
1203
DBUG_ASSERT(table->key_read == 0);
1204
DBUG_ASSERT(!table->file || table->file->inited == handler::NONE);
1205
DBUG_PRINT("tcache", ("table: '%s'.'%s' 0x%lx", table->s->db.str,
1206
table->s->table_name.str, (long) table));
1208
*table_ptr=table->next;
1210
if (table->needs_reopen_or_name_lock() ||
1211
thd->version != refresh_version || !table->db_stat)
1213
VOID(hash_delete(&open_cache,(uchar*) table));
1219
Open placeholders have TABLE::db_stat set to 0, so they should be
1220
handled by the first alternative.
1222
DBUG_ASSERT(!table->open_placeholder);
1224
/* Free memory and reset for next loop */
1225
table->file->ha_reset();
1229
table->next=unused_tables; /* Link in last */
1230
table->prev=unused_tables->prev;
1231
unused_tables->prev=table;
1232
table->prev->next=table;
1235
unused_tables=table->next=table->prev=table;
1237
DBUG_RETURN(found_old_table);
1241
/* close_temporary_tables' internal, 4 is due to uint4korr definition */
1242
static inline uint tmpkeyval(THD *thd, TABLE *table)
1244
return uint4korr(table->s->table_cache_key.str + table->s->table_cache_key.length - 4);
1249
Close all temporary tables created by 'CREATE TEMPORARY TABLE' for thread
1250
creates one DROP TEMPORARY TABLE binlog event for each pseudo-thread
1253
void close_temporary_tables(THD *thd)
1258
/* Assume thd->options has OPTION_QUOTE_SHOW_CREATE */
1259
bool was_quote_show= TRUE;
1261
if (!thd->temporary_tables)
1264
if (!mysql_bin_log.is_open() || thd->current_stmt_binlog_row_based)
1267
for (table= thd->temporary_tables; table; table= tmp_next)
1269
tmp_next= table->next;
1270
close_temporary(table, 1, 1);
1272
thd->temporary_tables= 0;
1276
/* Better add "if exists", in case a RESET MASTER has been done */
1277
const char stub[]= "DROP /*!40005 TEMPORARY */ TABLE IF EXISTS ";
1278
uint stub_len= sizeof(stub) - 1;
1280
String s_query= String(buf, sizeof(buf), system_charset_info);
1281
bool found_user_tables= FALSE;
1283
memcpy(buf, stub, stub_len);
1286
Insertion sort of temp tables by pseudo_thread_id to build ordered list
1287
of sublists of equal pseudo_thread_id
1290
for (prev_table= thd->temporary_tables, table= prev_table->next;
1292
prev_table= table, table= table->next)
1294
TABLE *prev_sorted /* same as for prev_table */, *sorted;
1295
if (is_user_table(table))
1297
if (!found_user_tables)
1298
found_user_tables= true;
1299
for (prev_sorted= NULL, sorted= thd->temporary_tables; sorted != table;
1300
prev_sorted= sorted, sorted= sorted->next)
1302
if (!is_user_table(sorted) ||
1303
tmpkeyval(thd, sorted) > tmpkeyval(thd, table))
1305
/* move into the sorted part of the list from the unsorted */
1306
prev_table->next= table->next;
1307
table->next= sorted;
1310
prev_sorted->next= table;
1314
thd->temporary_tables= table;
1323
/* We always quote db,table names though it is slight overkill */
1324
if (found_user_tables &&
1325
!(was_quote_show= test(thd->options & OPTION_QUOTE_SHOW_CREATE)))
1327
thd->options |= OPTION_QUOTE_SHOW_CREATE;
1330
/* scan sorted tmps to generate sequence of DROP */
1331
for (table= thd->temporary_tables; table; table= next)
1333
if (is_user_table(table))
1335
my_thread_id save_pseudo_thread_id= thd->variables.pseudo_thread_id;
1336
/* Set pseudo_thread_id to be that of the processed table */
1337
thd->variables.pseudo_thread_id= tmpkeyval(thd, table);
1339
Loop forward through all tables within the sublist of
1340
common pseudo_thread_id to create single DROP query.
1342
for (s_query.length(stub_len);
1343
table && is_user_table(table) &&
1344
tmpkeyval(thd, table) == thd->variables.pseudo_thread_id;
1348
We are going to add 4 ` around the db/table names and possible more
1349
due to special characters in the names
1351
append_identifier(thd, &s_query, table->s->db.str, strlen(table->s->db.str));
1352
s_query.append('.');
1353
append_identifier(thd, &s_query, table->s->table_name.str,
1354
strlen(table->s->table_name.str));
1355
s_query.append(',');
1357
close_temporary(table, 1, 1);
1360
CHARSET_INFO *cs_save= thd->variables.character_set_client;
1361
thd->variables.character_set_client= system_charset_info;
1362
Query_log_event qinfo(thd, s_query.ptr(),
1363
s_query.length() - 1 /* to remove trailing ',' */,
1365
thd->variables.character_set_client= cs_save;
1367
Imagine the thread had created a temp table, then was doing a
1368
SELECT, and the SELECT was killed. Then it's not clever to
1369
mark the statement above as "killed", because it's not really
1370
a statement updating data, and there are 99.99% chances it
1371
will succeed on slave. If a real update (one updating a
1372
persistent table) was killed on the master, then this real
1373
update will be logged with error_code=killed, rightfully
1374
causing the slave to stop.
1376
qinfo.error_code= 0;
1377
mysql_bin_log.write(&qinfo);
1378
thd->variables.pseudo_thread_id= save_pseudo_thread_id;
1383
close_temporary(table, 1, 1);
1386
if (!was_quote_show)
1387
thd->options&= ~OPTION_QUOTE_SHOW_CREATE; /* restore option */
1388
thd->temporary_tables=0;
401
1392
Find table in list.
405
table Pointer to table list
406
offset Offset to which list in table structure to use
407
db_name Data base name
408
table_name Table name
411
This is called by find_table_in_global_list().
415
# 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.
418
TableList *find_table_in_list(TableList *table,
419
TableList *TableList::*link,
421
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)
423
1415
for (; table; table= table->*link )
425
if ((table->table == 0 || table->table->getShare()->getType() == message::Table::STANDARD) &&
426
strcasecmp(table->getSchemaName(), db_name) == 0 &&
427
strcasecmp(table->getTableName(), table_name) == 0)
1417
if ((table->table == 0 || table->table->s->tmp_table == NO_TMP_TABLE) &&
1418
strcmp(table->db, db_name) == 0 &&
1419
strcmp(table->table_name, table_name) == 0)
512
1510
(exclude_from_table_unique_test) or prelocking placeholder.
514
1512
table_list= res->next_global;
520
void Open_tables_state::doGetTableNames(const SchemaIdentifier &schema_identifier,
521
std::set<std::string>& set_of_names)
523
for (Table *table= getTemporaryTables() ; table ; table= table->getNext())
525
if (schema_identifier.compare(table->getShare()->getSchemaName()))
527
set_of_names.insert(table->getShare()->getTableName());
532
void Open_tables_state::doGetTableNames(CachedDirectory &,
533
const SchemaIdentifier &schema_identifier,
534
std::set<std::string> &set_of_names)
536
doGetTableNames(schema_identifier, set_of_names);
539
void Open_tables_state::doGetTableIdentifiers(const SchemaIdentifier &schema_identifier,
540
TableIdentifier::vector &set_of_identifiers)
542
for (Table *table= getTemporaryTables() ; table ; table= table->getNext())
544
if (schema_identifier.compare(table->getShare()->getSchemaName()))
546
set_of_identifiers.push_back(TableIdentifier(table->getShare()->getSchemaName(),
547
table->getShare()->getTableName(),
548
table->getShare()->getPath()));
553
void Open_tables_state::doGetTableIdentifiers(CachedDirectory &,
554
const SchemaIdentifier &schema_identifier,
555
TableIdentifier::vector &set_of_identifiers)
557
doGetTableIdentifiers(schema_identifier, set_of_identifiers);
560
bool Open_tables_state::doDoesTableExist(const TableIdentifier &identifier)
562
for (Table *table= getTemporaryTables() ; table ; table= table->getNext())
564
if (table->getShare()->getType() == message::Table::TEMPORARY)
566
if (identifier.getKey() == table->getShare()->getCacheKey())
576
int Open_tables_state::doGetTableDefinition(const TableIdentifier &identifier,
577
message::Table &table_proto)
579
for (Table *table= getTemporaryTables() ; table ; table= table->getNext())
581
if (table->getShare()->getType() == message::Table::TEMPORARY)
583
if (identifier.getKey() == table->getShare()->getCacheKey())
585
table_proto.CopyFrom(*(table->getShare()->getTableProto()));
595
Table *Open_tables_state::find_temporary_table(const TableIdentifier &identifier)
597
for (Table *table= temporary_tables ; table ; table= table->getNext())
599
if (identifier.getKey() == table->getShare()->getCacheKey())
603
return NULL; // Not a temporary table
1514
("found same copy of table or table which we should skip"));
1521
Issue correct error message in case we found 2 duplicate tables which
1522
prevent some update operation
1525
update_non_unique_table_error()
1526
update table which we try to update
1527
operation name of update operation
1528
duplicate duplicate table which we found
1531
here we hide view underlying tables if we have them
1534
void update_non_unique_table_error(TABLE_LIST *update,
1535
const char *operation,
1536
TABLE_LIST *duplicate)
1538
my_error(ER_UPDATE_TABLE_USED, MYF(0), update->alias);
1542
TABLE *find_temporary_table(THD *thd, const char *db, const char *table_name)
1544
TABLE_LIST table_list;
1546
table_list.db= (char*) db;
1547
table_list.table_name= (char*) table_name;
1548
return find_temporary_table(thd, &table_list);
1552
TABLE *find_temporary_table(THD *thd, TABLE_LIST *table_list)
1554
char key[MAX_DBKEY_LENGTH];
1557
DBUG_ENTER("find_temporary_table");
1558
DBUG_PRINT("enter", ("table: '%s'.'%s'",
1559
table_list->db, table_list->table_name));
1561
key_length= create_table_def_key(thd, key, table_list, 1);
1562
for (table=thd->temporary_tables ; table ; table= table->next)
1564
if (table->s->table_cache_key.length == key_length &&
1565
!memcmp(table->s->table_cache_key.str, key, key_length))
1568
("Found table. server_id: %u pseudo_thread_id: %lu",
1569
(uint) thd->server_id,
1570
(ulong) thd->variables.pseudo_thread_id));
1574
DBUG_RETURN(0); // Not a temporary table
608
1579
Drop a temporary table.
610
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.
611
1582
If the table is found:
612
- if the table is being used by some outer statement, fail.
613
- if the table is in session->locked_tables, unlock it and
614
remove it from the list of locked tables. Currently only transactional
615
temporary tables are present in the locked_tables list.
616
- Close the temporary table, remove its .FRM
617
- 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
619
1590
This function is used to drop user temporary tables, as well as
620
1591
internal tables created in CREATE TEMPORARY TABLE ... SELECT
621
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
622
1593
is redundant when the table is internal, as long as we
623
1594
link both internal and user temporary tables into the same
624
session->temporary_tables list, it's impossible to tell here whether
1595
thd->temporary_tables list, it's impossible to tell here whether
625
1596
we're dealing with an internal or a user temporary table.
627
1598
@retval 0 the table was found and dropped successfully.
628
1599
@retval 1 the table was not found in the list of temporary tables
630
1601
@retval -1 the table is in use by a outer query
633
int Open_tables_state::drop_temporary_table(const drizzled::TableIdentifier &identifier)
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));
637
if (not (table= find_temporary_table(identifier)))
1611
if (!(table= find_temporary_table(thd, table_list)))
640
1614
/* Table might be in use by some outer statement. */
641
if (table->query_id && table->query_id != getQueryId())
643
my_error(ER_CANT_REOPEN_TABLE, MYF(0), table->getAlias());
647
close_temporary_table(table);
1615
if (table->query_id && table->query_id != thd->query_id)
1617
my_error(ER_CANT_REOPEN_TABLE, MYF(0), table->alias);
1622
If LOCK TABLES list is not empty and contains this table,
1623
unlock the table and remove the table from this list.
1625
mysql_lock_remove(thd, thd->locked_tables, table, FALSE);
1626
close_temporary_table(thd, table, 1, 1);
1631
unlink from thd->temporary tables and close temporary table
1634
void close_temporary_table(THD *thd, TABLE *table,
1635
bool free_share, bool delete_table)
1637
DBUG_ENTER("close_temporary_table");
1638
DBUG_PRINT("tmptable", ("closing table: '%s'.'%s' 0x%lx alias: '%s'",
1639
table->s->db.str, table->s->table_name.str,
1640
(long) table, table->alias));
1644
table->prev->next= table->next;
1645
if (table->prev->next)
1646
table->next->prev= table->prev;
1650
/* removing the item from the list */
1651
DBUG_ASSERT(table == thd->temporary_tables);
1653
slave must reset its temporary list pointer to zero to exclude
1654
passing non-zero value to end_slave via rli->save_temporary_tables
1655
when no temp tables opened, see an invariant below.
1657
thd->temporary_tables= table->next;
1658
if (thd->temporary_tables)
1659
table->next->prev= 0;
1661
if (thd->slave_thread)
1663
/* natural invariant of temporary_tables */
1664
DBUG_ASSERT(slave_open_temp_tables || !thd->temporary_tables);
1665
slave_open_temp_tables--;
1667
close_temporary(table, free_share, delete_table);
1673
Close and delete a temporary table
1676
This dosn't unlink table from thd->temporary
1677
If this is needed, use close_temporary_table()
1680
void close_temporary(TABLE *table, bool free_share, bool delete_table)
1682
handlerton *table_type= table->s->db_type();
1683
DBUG_ENTER("close_temporary");
1684
DBUG_PRINT("tmptable", ("closing table: '%s'.'%s'",
1685
table->s->db.str, table->s->table_name.str));
1687
free_io_cache(table);
1690
Check that temporary table has not been created with
1691
frm_only because it has then not been created in any storage engine
1694
rm_temporary_table(table_type, table->s->path.str,
1695
table->s->tmp_table == TMP_TABLE_FRM_FILE_ONLY);
1698
free_table_share(table->s);
1699
my_free((char*) table,MYF(0));
1706
Used by ALTER TABLE when the table is a temporary one. It changes something
1707
only if the ALTER contained a RENAME clause (otherwise, table_name is the old
1709
Prepares a table cache key, which is the concatenation of db, table_name and
1710
thd->slave_proxy_id, separated by '\0'.
1713
bool rename_temporary_table(THD* thd, TABLE *table, const char *db,
1714
const char *table_name)
1718
TABLE_SHARE *share= table->s;
1719
TABLE_LIST table_list;
1720
DBUG_ENTER("rename_temporary_table");
1722
if (!(key=(char*) alloc_root(&share->mem_root, MAX_DBKEY_LENGTH)))
1723
DBUG_RETURN(1); /* purecov: inspected */
1725
table_list.db= (char*) db;
1726
table_list.table_name= (char*) table_name;
1727
key_length= create_table_def_key(thd, key, &table_list, 1);
1728
share->set_table_cache_key(key, key_length);
1733
/* move table first in unused links */
1735
static void relink_unused(TABLE *table)
1737
if (table != unused_tables)
1739
table->prev->next=table->next; /* Remove from unused list */
1740
table->next->prev=table->prev;
1741
table->next=unused_tables; /* Link in unused tables */
1742
table->prev=unused_tables->prev;
1743
unused_tables->prev->next=table;
1744
unused_tables->prev=table;
1745
unused_tables=table;
654
Remove all instances of table from thread's open list and
657
@param session Thread context
658
@param find Table to remove
660
@note because we risk the chance of deleting the share, we can't assume that it will exist past, this should be modified once we can use a TableShare::shared_ptr here.
1752
Remove all instances of table from thread's open list and
1755
@param thd Thread context
1756
@param find Table to remove
1757
@param unlock TRUE - free all locks on tables removed that are
1758
done with LOCK TABLES
1761
@note When unlock parameter is FALSE or current thread doesn't have
1762
any tables locked with LOCK TABLES, tables are assumed to be
1763
not locked (for example already unlocked).
663
void Session::unlink_open_table(Table *find)
1766
void unlink_open_table(THD *thd, TABLE *find, bool unlock)
665
const TableIdentifier::Key find_key(find->getShare()->getCacheKey());
667
safe_mutex_assert_owner(table::Cache::singleton().mutex().native_handle());
1768
char key[MAX_DBKEY_LENGTH];
1769
uint key_length= find->s->table_cache_key.length;
1770
TABLE *list, **prev;
1771
DBUG_ENTER("unlink_open_table");
1773
safe_mutex_assert_owner(&LOCK_open);
1775
memcpy(key, find->s->table_cache_key.str, key_length);
670
Note that we need to hold table::Cache::singleton().mutex() while changing the
1777
Note that we need to hold LOCK_open while changing the
671
1778
open_tables list. Another thread may work on it.
672
(See: table::Cache::singleton().removeTable(), mysql_wait_completed_table())
1779
(See: remove_table_from_cache(), mysql_wait_completed_table())
673
1780
Closing a MERGE child before the parent would be fatal if the
674
1781
other thread tries to abort the MERGE lock in between.
676
for (prev= &open_tables; *prev; )
1783
for (prev= &thd->open_tables; *prev; )
680
if (list->getShare()->getCacheKey() == find_key)
1787
if (list->s->table_cache_key.length == key_length &&
1788
!memcmp(list->s->table_cache_key.str, key, key_length))
1790
if (unlock && thd->locked_tables)
1791
mysql_lock_remove(thd, thd->locked_tables, list, TRUE);
682
1793
/* Remove table from open_tables list. */
683
*prev= list->getNext();
685
1795
/* Close table. */
686
table::remove_table(static_cast<table::Concurrent *>(list));
1796
VOID(hash_delete(&open_cache,(uchar*) list)); // Close table
690
1800
/* Step to next entry in open_tables list. */
691
prev= list->getNextPtr();
695
1805
// Notify any 'refresh' threads
696
locking::broadcast_refresh();
1806
broadcast_refresh();
701
Auxiliary routine which closes and drops open table.
703
@param session Thread handle
704
@param table Table object for table to be dropped
705
@param db_name Name of database for this table
706
@param table_name Name of this table
708
@note This routine assumes that table to be closed is open only
709
by calling thread so we needn't wait until other threads
710
will close the table. Also unless called under implicit or
711
explicit LOCK TABLES mode it assumes that table to be
712
dropped is already unlocked. In the former case it will
713
also remove lock on the table. But one should not rely on
714
this behaviour as it may change in future.
715
Currently, however, this function is never called for a
716
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.
719
void Session::drop_open_table(Table *table, const TableIdentifier &identifier)
1830
void drop_open_table(THD *thd, TABLE *table, const char *db_name,
1831
const char *table_name)
721
if (table->getShare()->getType())
723
close_temporary_table(table);
1833
if (table->s->tmp_table)
1834
close_temporary_table(thd, table, 1, 1);
727
boost_unique_lock_t scoped_lock(table::Cache::singleton().mutex()); /* Close and drop a table (AUX routine) */
1837
handlerton *table_type= table->s->db_type();
1838
VOID(pthread_mutex_lock(&LOCK_open));
729
1840
unlink_open_table() also tells threads waiting for refresh or close
730
1841
that something has happened.
732
unlink_open_table(table);
733
plugin::StorageEngine::dropTable(*this, identifier);
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));
739
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
743
session Thread Cursor
744
mutex mutex that is currently hold that is associated with condition
745
Will be unlocked on return
746
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
749
void Session::wait_for_condition(boost::mutex &mutex, boost::condition_variable_any &cond)
1861
void wait_for_condition(THD *thd, pthread_mutex_t *mutex, pthread_cond_t *cond)
751
1863
/* Wait until the current table is up to date */
752
const char *saved_proc_info;
753
mysys_var->current_mutex= &mutex;
754
mysys_var->current_cond= &cond;
755
saved_proc_info= get_proc_info();
756
set_proc_info("Waiting for table");
759
We must unlock mutex first to avoid deadlock becasue conditions are
760
sent to this thread by doing locks in the following order:
761
lock(mysys_var->mutex)
762
lock(mysys_var->current_mutex)
764
One by effect of this that one can only use wait_for_condition with
765
condition variables that are guranteed to not disapper (freed) even if this
768
boost_unique_lock_t scopedLock(mutex, boost::adopt_lock_t());
771
cond.wait(scopedLock);
774
boost_unique_lock_t mysys_scopedLock(mysys_var->mutex);
775
mysys_var->current_mutex= 0;
776
mysys_var->current_cond= 0;
777
set_proc_info(saved_proc_info);
782
Create and insert into table cache placeholder for table
783
which will prevent its opening (or creation) (a.k.a lock
786
@param session Thread context
787
@param key Table cache key for name to be locked
788
@param key_length Table cache key length
790
@return Pointer to Table object used for name locking or 0 in
794
table::Placeholder *Session::table_cache_insert_placeholder(const drizzled::TableIdentifier &arg)
796
safe_mutex_assert_owner(table::Cache::singleton().mutex().native_handle());
1864
const char *proc_info;
1865
thd->mysys_var->current_mutex= mutex;
1866
thd->mysys_var->current_cond= cond;
1867
proc_info=thd->proc_info;
1868
thd_proc_info(thd, "Waiting for table");
1869
DBUG_ENTER("wait_for_condition");
1871
(void) pthread_cond_wait(cond, mutex);
1874
We must unlock mutex first to avoid deadlock becasue conditions are
1875
sent to this thread by doing locks in the following order:
1876
lock(mysys_var->mutex)
1877
lock(mysys_var->current_mutex)
1879
One by effect of this that one can only use wait_for_condition with
1880
condition variables that are guranteed to not disapper (freed) even if this
1884
pthread_mutex_unlock(mutex);
1885
pthread_mutex_lock(&thd->mysys_var->mutex);
1886
thd->mysys_var->current_mutex= 0;
1887
thd->mysys_var->current_cond= 0;
1888
thd_proc_info(thd, proc_info);
1889
pthread_mutex_unlock(&thd->mysys_var->mutex);
1895
Exclusively name-lock a table that is already write-locked by the
1898
@param thd current thread context
1899
@param tables table list containing one table to open.
1901
@return FALSE on success, TRUE otherwise.
1904
bool name_lock_locked_table(THD *thd, TABLE_LIST *tables)
1906
DBUG_ENTER("name_lock_locked_table");
1908
/* Under LOCK TABLES we must only accept write locked tables. */
1909
tables->table= find_locked_table(thd, tables->db, tables->table_name);
1912
my_error(ER_TABLE_NOT_LOCKED, MYF(0), tables->alias);
1913
else if (tables->table->reginfo.lock_type < TL_WRITE_LOW_PRIORITY)
1914
my_error(ER_TABLE_NOT_LOCKED_FOR_WRITE, MYF(0), tables->alias);
1918
Ensures that table is opened only by this thread and that no
1919
other statement will open this table.
1921
wait_while_table_is_used(thd, tables->table, HA_EXTRA_FORCE_REOPEN);
1930
Open table which is already name-locked by this thread.
1933
reopen_name_locked_table()
1935
table_list TABLE_LIST object for table to be open, TABLE_LIST::table
1936
member should point to TABLE object which was used for
1938
link_in TRUE - if TABLE object for table to be opened should be
1939
linked into THD::open_tables list.
1940
FALSE - placeholder used for name-locking is already in
1941
this list so we only need to preserve TABLE::next
1945
This function assumes that its caller already acquired LOCK_open mutex.
1952
bool reopen_name_locked_table(THD* thd, TABLE_LIST* table_list, bool link_in)
1954
TABLE *table= table_list->table;
1956
char *table_name= table_list->table_name;
1958
DBUG_ENTER("reopen_name_locked_table");
1960
safe_mutex_assert_owner(&LOCK_open);
1962
if (thd->killed || !table)
1967
if (open_unireg_entry(thd, table, table_list, table_name,
1968
table->s->table_cache_key.str,
1969
table->s->table_cache_key.length, thd->mem_root, 0))
1971
intern_close_table(table);
1973
If there was an error during opening of table (for example if it
1974
does not exist) '*table' object can be wiped out. To be able
1975
properly release name-lock in this case we should restore this
1976
object to its original state.
1984
We want to prevent other connections from opening this table until end
1985
of statement as it is likely that modifications of table's metadata are
1986
not yet finished (for example CREATE TRIGGER have to change .TRG file,
1987
or we might want to drop table if CREATE TABLE ... SELECT fails).
1988
This also allows us to assume that no other connection will sneak in
1989
before we will get table-level lock on this table.
1992
table->in_use = thd;
1997
table->next= thd->open_tables;
1998
thd->open_tables= table;
2003
TABLE object should be already in THD::open_tables list so we just
2004
need to set TABLE::next correctly.
2006
table->next= orig_table.next;
2009
table->tablenr=thd->current_tablenr++;
2010
table->used_fields=0;
2011
table->const_table=0;
2012
table->null_row= table->maybe_null= table->force_index= 0;
2013
table->status=STATUS_NO_RECORD;
2019
Create and insert into table cache placeholder for table
2020
which will prevent its opening (or creation) (a.k.a lock
2023
@param thd Thread context
2024
@param key Table cache key for name to be locked
2025
@param key_length Table cache key length
2027
@return Pointer to TABLE object used for name locking or 0 in
2031
TABLE *table_cache_insert_placeholder(THD *thd, const char *key,
2037
DBUG_ENTER("table_cache_insert_placeholder");
2039
safe_mutex_assert_owner(&LOCK_open);
799
2042
Create a table entry with the right key and with an old refresh version
2043
Note that we must use my_multi_malloc() here as this is freed by the
801
TableIdentifier identifier(arg.getSchemaName(), arg.getTableName(), message::Table::INTERNAL);
802
table::Placeholder *table= new table::Placeholder(this, identifier);
804
if (not table::Cache::singleton().insert(table))
2046
if (!my_multi_malloc(MYF(MY_WME | MY_ZEROFILL),
2047
&table, sizeof(*table),
2048
&share, sizeof(*share),
2049
&key_buff, key_length,
2054
share->set_table_cache_key(key_buff, key, key_length);
2055
share->tmp_table= INTERNAL_TMP_TABLE; // for intern_close_table
2057
table->locked_by_name=1;
2059
if (my_hash_insert(&open_cache, (uchar*)table))
2061
my_free((uchar*) table, MYF(0));
816
Obtain an exclusive name lock on the table if it is not cached
819
@param session Thread context
820
@param db Name of database
821
@param table_name Name of table
822
@param[out] table Out parameter which is either:
823
- set to NULL if table cache contains record for
825
- set to point to the Table instance used for
828
@note This function takes into account all records for table in table
829
cache, even placeholders used for name-locking. This means that
830
'table' parameter can be set to NULL for some situations when
831
table does not really exist.
833
@retval true Error occured (OOM)
834
@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.
836
bool Session::lock_table_name_if_not_cached(const TableIdentifier &identifier, Table **table)
2091
bool lock_table_name_if_not_cached(THD *thd, const char *db,
2092
const char *table_name, TABLE **table)
838
const TableIdentifier::Key &key(identifier.getKey());
840
boost_unique_lock_t scope_lock(table::Cache::singleton().mutex()); /* Obtain a name lock even though table is not in cache (like for create table) */
842
table::CacheMap::iterator iter;
844
iter= table::getCache().find(key);
846
if (iter != table::getCache().end())
2094
char key[MAX_DBKEY_LENGTH];
2096
DBUG_ENTER("lock_table_name_if_not_cached");
2098
key_length= (uint)(strmov(strmov(key, db) + 1, table_name) - key) + 1;
2099
VOID(pthread_mutex_lock(&LOCK_open));
2101
if (hash_search(&open_cache, (uchar *)key, key_length))
2103
VOID(pthread_mutex_unlock(&LOCK_open));
2104
DBUG_PRINT("info", ("Table is cached, name-lock is not obtained"));
852
if (not (*table= table_cache_insert_placeholder(identifier)))
856
(*table)->open_placeholder= true;
857
(*table)->setNext(open_tables);
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);
868
session Thread context.
869
table_list Open first table in list.
870
refresh INOUT Pointer to memory that will be set to 1 if
871
we need to close all tables and reopen them.
872
If this is a NULL pointer, then the table is not
873
put in the thread-open-list.
874
flags Bitmap of flags to modify how open works:
875
DRIZZLE_LOCK_IGNORE_FLUSH - Open table even if
876
someone has done a flush or namelock on it.
877
No version number checking is done.
878
DRIZZLE_OPEN_TEMPORARY_ONLY - Open only temporary
879
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.
882
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.
884
If table list element for the table to be opened has "create" flag
885
set and table does not exist, this function will automatically insert
886
a placeholder for exclusive name lock into the open tables cache and
887
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.
890
NULL Open failed. If refresh is set then one should close
891
all other tables and retry the open.
892
# 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.
896
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)
899
const char *alias= table_list->alias;
2221
register TABLE *table;
2222
char key[MAX_DBKEY_LENGTH];
2223
unsigned int key_length;
2224
char *alias= table_list->alias;
2225
HASH_SEARCH_STATE state;
2226
DBUG_ENTER("open_table");
901
/* Parsing of partitioning information from .frm needs session->lex set up. */
902
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);
904
2231
/* find a unused table in the open table cache */
908
2235
/* an open table operation needs a lot of the stack space */
909
if (check_stack_overrun(this, STACK_MIN_SIZE_FOR_OPEN, (unsigned char *)&alias))
915
TableIdentifier identifier(table_list->getSchemaName(), table_list->getTableName());
916
const TableIdentifier::Key &key(identifier.getKey());
917
table::CacheRange ppp;
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);
920
2246
Unless requested otherwise, try to resolve this table in the list
921
2247
of temporary tables of this thread. In MySQL temporary tables
922
2248
are always thread-local and "shadow" possible base tables with the
923
2249
same name. This block implements the behaviour.
924
TODO -> move this block into a separate function.
2250
TODO: move this block into a separate function.
927
for (table= getTemporaryTables(); table ; table=table->getNext())
929
if (table->getShare()->getCacheKey() == key)
932
We're trying to use the same temporary table twice in a query.
933
Right now we don't support this because a temporary table
934
is always represented by only one Table object in Session, and
935
it can not be cloned. Emit an error for an unsupported behaviour.
939
my_error(ER_CANT_REOPEN_TABLE, MYF(0), table->getAlias());
942
table->query_id= getQueryId();
950
if (flags & DRIZZLE_OPEN_TEMPORARY_ONLY)
952
my_error(ER_NO_SUCH_TABLE, MYF(0), table_list->getSchemaName(), table_list->getTableName());
957
If it's the first table from a list of tables used in a query,
958
remember refresh_version (the version of open_cache state).
959
If the version changes while we're opening the remaining tables,
960
we will have to back off, close all the tables opened-so-far,
961
and try to reopen them.
963
Note-> refresh_version is currently changed only during FLUSH TABLES.
967
version= refresh_version;
969
else if ((version != refresh_version) &&
970
! (flags & DRIZZLE_LOCK_IGNORE_FLUSH))
972
/* Someone did a refresh while thread was opening tables */
980
Before we test the global cache, we test our local session cache.
984
assert(false); /* Not implemented yet */
988
Non pre-locked/LOCK TABLES mode, and the table is not temporary:
989
this is the normal use case.
991
- try to find the table in the table cache.
992
- if one of the discovered Table instances is name-locked
993
(table->getShare()->version == 0) back off -- we have to wait
994
until no one holds a name lock on the table.
995
- if there is no such Table in the name cache, read the table definition
996
and insert it into the cache.
997
We perform all of the above under table::Cache::singleton().mutex() which currently protects
998
the open cache (also known as table cache) and table definitions stored
1003
table::Cache::singleton().mutex().lock(); /* Lock for FLUSH TABLES for open table */
1006
Actually try to find the table in the open_cache.
1007
The cache may contain several "Table" instances for the same
1008
physical table. The instances that are currently "in use" by
1009
some thread have their "in_use" member != NULL.
1010
There is no good reason for having more than one entry in the
1011
hash for the same physical table, except that we use this as
1012
an implicit "pending locks queue" - see
1013
wait_for_locked_table_names for details.
1015
ppp= table::getCache().equal_range(key);
1018
for (table::CacheMap::const_iterator iter= ppp.first;
1019
iter != ppp.second; ++iter, table= NULL)
1021
table= (*iter).second;
1023
if (not table->in_use)
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))
1026
Here we flush tables marked for flush.
1027
Normally, table->getShare()->version contains the value of
1028
refresh_version from the moment when this table was
1029
(re-)opened and added to the cache.
1030
If since then we did (or just started) FLUSH TABLES
1031
statement, refresh_version has been increased.
1032
For "name-locked" Table instances, table->getShare()->version is set
1033
to 0 (see lock_table_name for details).
1034
In case there is a pending FLUSH TABLES or a name lock, we
1035
need to back off and re-start opening tables.
1036
If we do not back off now, we may dead lock in case of lock
1037
order mismatch with some other thread:
1038
c1-> name lock t1; -- sort of exclusive lock
1039
c2-> open t2; -- sort of shared lock
1040
c1-> name lock t2; -- blocks
1041
c2-> open t1; -- blocks
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.
1043
if (table->needs_reopen_or_name_lock())
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)
1045
if (flags & DRIZZLE_LOCK_IGNORE_FLUSH)
1047
/* Force close at once after usage */
1048
version= table->getShare()->getVersion();
1052
/* Avoid self-deadlocks by detecting self-dependencies. */
1053
if (table->open_placeholder && table->in_use == this)
1055
table::Cache::singleton().mutex().unlock();
1056
my_error(ER_UPDATE_TABLE_USED, MYF(0), table->getShare()->getTableName());
1061
Back off, part 1: mark the table as "unused" for the
1062
purpose of name-locking by setting table->db_stat to 0. Do
1063
that only for the tables in this thread that have an old
1064
table->getShare()->version (this is an optimization (?)).
1065
table->db_stat == 0 signals wait_for_locked_table_names
1066
that the tables in question are not used any more. See
1067
table_is_used call for details.
1069
close_old_data_files(false, false);
1072
Back-off part 2: try to avoid "busy waiting" on the table:
1073
if the table is in use by some other thread, we suspend
1074
and wait till the operation is complete: when any
1075
operation that juggles with table->getShare()->version completes,
1076
it broadcasts COND_refresh condition variable.
1077
If 'old' table we met is in use by current thread we return
1078
without waiting since in this situation it's this thread
1079
which is responsible for broadcasting on COND_refresh
1080
(and this was done already in Session::close_old_data_files()).
1081
Good example of such situation is when we have statement
1082
that needs two instances of table and FLUSH TABLES comes
1083
after we open first instance but before we open second
1086
if (table->in_use != this)
1088
/* wait_for_conditionwill unlock table::Cache::singleton().mutex() for us */
1089
wait_for_condition(table::Cache::singleton().mutex(), COND_refresh);
1093
table::Cache::singleton().mutex().unlock();
1096
There is a refresh in progress for this table.
1097
Signal the caller that it has to try again.
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);
1106
table::getUnused().unlink(static_cast<table::Concurrent *>(table));
1107
table->in_use= this;
1111
/* Insert a new Table instance into the open cache */
1113
/* Free cache if too big */
1114
table::getUnused().cull();
1116
if (table_list->isCreate())
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 */
1118
TableIdentifier lock_table_identifier(table_list->getSchemaName(), table_list->getTableName(), message::Table::STANDARD);
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.
1120
if (not plugin::StorageEngine::doesTableExist(*this, lock_table_identifier))
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))
1123
Table to be created, so we need to create placeholder in table-cache.
1125
if (!(table= table_cache_insert_placeholder(lock_table_identifier)))
2342
best_distance= distance;
2344
if (best_distance == 0 && !check_if_used)
1127
table::Cache::singleton().mutex().unlock();
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.
1131
Link placeholder to the open tables list so it will be automatically
1132
removed once tables are closed. Also mark it so it won't be ignored
1133
by other trying to take name-lock.
1135
table->open_placeholder= true;
1136
table->setNext(open_tables);
1138
table::Cache::singleton().mutex().unlock();
1142
/* Table exists. Let us try to open it. */
1145
/* make a new table */
1147
table::Concurrent *new_table= new table::Concurrent;
1149
if (new_table == NULL)
1151
table::Cache::singleton().mutex().unlock();
1155
error= new_table->open_unireg_entry(this, alias, identifier);
1159
table::Cache::singleton().mutex().unlock();
1162
(void)table::Cache::singleton().insert(new_table);
1166
table::Cache::singleton().mutex().unlock();
2361
table->query_id= thd->query_id;
2362
DBUG_PRINT("info",("Using locked table"));
2366
No table in the locked tables list. In case of explicit LOCK TABLES
2367
this can happen if a user did not include the able into the list.
2368
In case of pre-locked mode locked tables list is generated automatically,
2369
so we may only end up here if the table did not exist when
2370
locked tables list was created.
2372
my_error(ER_TABLE_NOT_LOCKED, MYF(0), alias);
2377
Non pre-locked/LOCK TABLES mode, and the table is not temporary:
2378
this is the normal use case.
2380
- try to find the table in the table cache.
2381
- if one of the discovered TABLE instances is name-locked
2382
(table->s->version == 0) or some thread has started FLUSH TABLES
2383
(refresh_version > table->s->version), back off -- we have to wait
2384
until no one holds a name lock on the table.
2385
- if there is no such TABLE in the name cache, read the table definition
2386
and insert it into the cache.
2387
We perform all of the above under LOCK_open which currently protects
2388
the open cache (also known as table cache) and table definitions stored
2392
VOID(pthread_mutex_lock(&LOCK_open));
2395
If it's the first table from a list of tables used in a query,
2396
remember refresh_version (the version of open_cache state).
2397
If the version changes while we're opening the remaining tables,
2398
we will have to back off, close all the tables opened-so-far,
2399
and try to reopen them.
2400
Note: refresh_version is currently changed only during FLUSH TABLES.
2402
if (!thd->open_tables)
2403
thd->version=refresh_version;
2404
else if ((thd->version != refresh_version) &&
2405
! (flags & MYSQL_LOCK_IGNORE_FLUSH))
2407
/* Someone did a refresh while thread was opening tables */
1170
table->setNext(open_tables); /* Link into simple list */
1173
table->reginfo.lock_type= TL_READ; /* Assume read */
1176
assert(table->getShare()->getTableCount() > 0 || table->getShare()->getType() != message::Table::STANDARD);
2410
VOID(pthread_mutex_unlock(&LOCK_open));
2415
In order for the back off and re-start process to work properly,
2416
handler tables having old versions (due to FLUSH TABLES or pending
2417
name-lock) MUST be closed. This is specially important if a name-lock
2418
is pending for any table of the handler_tables list, otherwise a
2421
if (thd->handler_tables)
2422
mysql_ha_flush(thd);
2425
Actually try to find the table in the open_cache.
2426
The cache may contain several "TABLE" instances for the same
2427
physical table. The instances that are currently "in use" by
2428
some thread have their "in_use" member != NULL.
2429
There is no good reason for having more than one entry in the
2430
hash for the same physical table, except that we use this as
2431
an implicit "pending locks queue" - see
2432
wait_for_locked_table_names for details.
2434
for (table= (TABLE*) hash_first(&open_cache, (uchar*) key, key_length,
2436
table && table->in_use ;
2437
table= (TABLE*) hash_next(&open_cache, (uchar*) key, key_length,
2440
DBUG_PRINT("tcache", ("in_use table: '%s'.'%s' 0x%lx", table->s->db.str,
2441
table->s->table_name.str, (long) table));
2443
Here we flush tables marked for flush.
2444
Normally, table->s->version contains the value of
2445
refresh_version from the moment when this table was
2446
(re-)opened and added to the cache.
2447
If since then we did (or just started) FLUSH TABLES
2448
statement, refresh_version has been increased.
2449
For "name-locked" TABLE instances, table->s->version is set
2450
to 0 (see lock_table_name for details).
2451
In case there is a pending FLUSH TABLES or a name lock, we
2452
need to back off and re-start opening tables.
2453
If we do not back off now, we may dead lock in case of lock
2454
order mismatch with some other thread:
2455
c1: name lock t1; -- sort of exclusive lock
2456
c2: open t2; -- sort of shared lock
2457
c1: name lock t2; -- blocks
2458
c2: open t1; -- blocks
2460
if (table->needs_reopen_or_name_lock())
2463
("Found table '%s.%s' with different refresh version",
2464
table_list->db, table_list->table_name));
2466
if (flags & MYSQL_LOCK_IGNORE_FLUSH)
2468
/* Force close at once after usage */
2469
thd->version= table->s->version;
2473
/* Avoid self-deadlocks by detecting self-dependencies. */
2474
if (table->open_placeholder && table->in_use == thd)
2476
VOID(pthread_mutex_unlock(&LOCK_open));
2477
my_error(ER_UPDATE_TABLE_USED, MYF(0), table->s->table_name.str);
2482
Back off, part 1: mark the table as "unused" for the
2483
purpose of name-locking by setting table->db_stat to 0. Do
2484
that only for the tables in this thread that have an old
2485
table->s->version (this is an optimization (?)).
2486
table->db_stat == 0 signals wait_for_locked_table_names
2487
that the tables in question are not used any more. See
2488
table_is_used call for details.
2490
Notice that HANDLER tables were already taken care of by
2491
the earlier call to mysql_ha_flush() in this same critical
2494
close_old_data_files(thd,thd->open_tables,0,0);
2496
Back-off part 2: try to avoid "busy waiting" on the table:
2497
if the table is in use by some other thread, we suspend
2498
and wait till the operation is complete: when any
2499
operation that juggles with table->s->version completes,
2500
it broadcasts COND_refresh condition variable.
2501
If 'old' table we met is in use by current thread we return
2502
without waiting since in this situation it's this thread
2503
which is responsible for broadcasting on COND_refresh
2504
(and this was done already in close_old_data_files()).
2505
Good example of such situation is when we have statement
2506
that needs two instances of table and FLUSH TABLES comes
2507
after we open first instance but before we open second
2510
if (table->in_use != thd)
2512
/* wait_for_conditionwill unlock LOCK_open for us */
2513
wait_for_condition(thd, &LOCK_open, &COND_refresh);
2517
VOID(pthread_mutex_unlock(&LOCK_open));
2520
There is a refresh in progress for this table.
2521
Signal the caller that it has to try again.
2530
DBUG_PRINT("tcache", ("unused table: '%s'.'%s' 0x%lx", table->s->db.str,
2531
table->s->table_name.str, (long) table));
2532
/* Unlink the table from "unused_tables" list. */
2533
if (table == unused_tables)
2535
unused_tables=unused_tables->next; // Remove from link
2536
if (table == unused_tables)
2539
table->prev->next=table->next; /* Remove from unused list */
2540
table->next->prev=table->prev;
2545
/* Insert a new TABLE instance into the open cache */
2547
DBUG_PRINT("tcache", ("opening new table"));
2548
/* Free cache if too big */
2549
while (open_cache.records > table_cache_size && unused_tables)
2550
VOID(hash_delete(&open_cache,(uchar*) unused_tables)); /* purecov: tested */
2552
if (table_list->create)
2556
if (check_if_table_exists(thd, table_list, &exists))
2558
VOID(pthread_mutex_unlock(&LOCK_open));
2565
Table to be created, so we need to create placeholder in table-cache.
2567
if (!(table= table_cache_insert_placeholder(thd, key, key_length)))
2569
VOID(pthread_mutex_unlock(&LOCK_open));
2573
Link placeholder to the open tables list so it will be automatically
2574
removed once tables are closed. Also mark it so it won't be ignored
2575
by other trying to take name-lock.
2577
table->open_placeholder= 1;
2578
table->next= thd->open_tables;
2579
thd->open_tables= table;
2580
VOID(pthread_mutex_unlock(&LOCK_open));
2583
/* Table exists. Let us try to open it. */
2586
/* make a new table */
2587
if (!(table=(TABLE*) my_malloc(sizeof(*table),MYF(MY_WME))))
2589
VOID(pthread_mutex_unlock(&LOCK_open));
2593
error= open_unireg_entry(thd, table, table_list, alias, key, key_length,
2594
mem_root, (flags & OPEN_VIEW_NO_PARSE));
2595
/* Combine the follow two */
2598
my_free((uchar*)table, MYF(0));
2599
VOID(pthread_mutex_unlock(&LOCK_open));
2604
my_free((uchar*)table, MYF(0));
2605
VOID(pthread_mutex_unlock(&LOCK_open));
2606
DBUG_RETURN(0); // VIEW
2608
DBUG_PRINT("info", ("inserting table '%s'.'%s' 0x%lx into the cache",
2609
table->s->db.str, table->s->table_name.str,
2611
VOID(my_hash_insert(&open_cache,(uchar*) table));
2614
check_unused(); // Debugging call
2616
VOID(pthread_mutex_unlock(&LOCK_open));
2619
table->next=thd->open_tables; /* Link into simple list */
2620
thd->open_tables=table;
2622
table->reginfo.lock_type=TL_READ; /* Assume read */
2625
DBUG_ASSERT(table->s->ref_count > 0 || table->s->tmp_table != NO_TMP_TABLE);
2627
if (thd->lex->need_correct_ident())
2628
table->alias_name_used= my_strcasecmp(table_alias_charset,
2629
table->s->table_name.str, alias);
1178
2630
/* Fix alias if table name changes */
1179
if (strcmp(table->getAlias(), alias))
2631
if (strcmp(table->alias, alias))
1181
table->setAlias(alias);
2633
uint length=(uint) strlen(alias)+1;
2634
table->alias= (char*) my_realloc((char*) table->alias, length,
2636
memcpy((char*) table->alias, alias, length);
1184
2638
/* These variables are also set in reopen_table() */
1185
table->tablenr= current_tablenr++;
1186
table->used_fields= 0;
1187
table->const_table= 0;
1188
table->null_row= false;
1189
table->maybe_null= false;
1190
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;
1191
2643
table->status=STATUS_NO_RECORD;
1192
table->insert_values.clear();
2644
table->insert_values= 0;
2645
table->fulltext_searched= 0;
2646
table->file->ft_handler= 0;
1193
2647
/* Catch wrong handling of the auto_increment_field_not_null. */
1194
assert(!table->auto_increment_field_not_null);
1195
table->auto_increment_field_not_null= false;
2648
DBUG_ASSERT(!table->auto_increment_field_not_null);
2649
table->auto_increment_field_not_null= FALSE;
1196
2650
if (table->timestamp_field)
1198
2651
table->timestamp_field_type= table->timestamp_field->get_auto_set_type();
1200
2652
table->pos_in_table_list= table_list;
1201
2653
table->clear_column_bitmaps();
1202
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))
2675
Reopen an table because the definition has changed.
2682
The data file for the table is already closed and the share is released
2683
The table has a 'dummy' share that mainly contains database and table name.
2687
1 error. The old table object is not changed.
2690
bool reopen_table(TABLE *table)
2696
TABLE_LIST table_list;
2697
THD *thd= table->in_use;
2698
DBUG_ENTER("reopen_table");
2699
DBUG_PRINT("tcache", ("table: '%s'.'%s' 0x%lx", table->s->db.str,
2700
table->s->table_name.str, (long) table));
2702
DBUG_ASSERT(table->s->ref_count == 0);
2703
DBUG_ASSERT(!table->sort.io_cache);
2707
sql_print_error("Table %s had a open data handler in reopen_table",
2710
bzero((char*) &table_list, sizeof(TABLE_LIST));
2711
table_list.db= table->s->db.str;
2712
table_list.table_name= table->s->table_name.str;
2713
table_list.table= table;
2715
if (wait_for_locked_table_names(thd, &table_list))
2716
DBUG_RETURN(1); // Thread was killed
2718
if (open_unireg_entry(thd, &tmp, &table_list,
2720
table->s->table_cache_key.str,
2721
table->s->table_cache_key.length,
2725
/* This list copies variables set by open_table */
2726
tmp.tablenr= table->tablenr;
2727
tmp.used_fields= table->used_fields;
2728
tmp.const_table= table->const_table;
2729
tmp.null_row= table->null_row;
2730
tmp.maybe_null= table->maybe_null;
2731
tmp.status= table->status;
2733
tmp.s->table_map_id= table->s->table_map_id;
2737
tmp.reginfo.lock_type=table->reginfo.lock_type;
2739
/* Replace table in open list */
2740
tmp.next= table->next;
2741
tmp.prev= table->prev;
2744
VOID(closefrm(table, 1)); // close file, free everything
2747
table->default_column_bitmaps();
2748
table->file->change_table_ptr(table, table->s);
2750
DBUG_ASSERT(table->alias != 0);
2751
for (field=table->field ; *field ; field++)
2753
(*field)->table= (*field)->orig_table= table;
2754
(*field)->table_name= &table->alias;
2756
for (key=0 ; key < table->s->keys ; key++)
2758
for (part=0 ; part < table->key_info[key].usable_key_parts ; part++)
2759
table->key_info[key].key_part[part].field->table= table;
2762
Do not attach MERGE children here. The children might be reopened
2763
after the parent. Attach children after reopening all tables that
2764
require reopen. See for example reopen_tables().
2767
broadcast_refresh();
1209
Close all instances of a table open by this thread and replace
1210
them with exclusive name-locks.
1212
@param session Thread context
1213
@param db Database name for the table to be closed
1214
@param table_name Name of the table to be closed
1216
@note This function assumes that if we are not under LOCK TABLES,
1217
then there is only one table open and locked. This means that
1218
the function probably has to be adjusted before it can be used
1219
anywhere outside ALTER Table.
1221
@note Must not use TableShare::table_name/db of the table being closed,
1222
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.
1225
void Session::close_data_files_and_morph_locks(const TableIdentifier &identifier)
2792
void close_data_files_and_morph_locks(THD *thd, const char *db,
2793
const char *table_name)
1227
safe_mutex_assert_owner(table::Cache::singleton().mutex().native_handle()); /* Adjust locks at the end of ALTER TABLEL */
2796
DBUG_ENTER("close_data_files_and_morph_locks");
2798
safe_mutex_assert_owner(&LOCK_open);
1232
2803
If we are not under LOCK TABLES we should have only one table
1233
2804
open and locked so it makes sense to remove the lock at once.
2806
mysql_unlock_tables(thd, thd->lock);
1240
2811
Note that open table list may contain a name-lock placeholder
1241
for target table name if we process ALTER Table ... RENAME.
2812
for target table name if we process ALTER TABLE ... RENAME.
1242
2813
So loop below makes sense even if we are not under LOCK TABLES.
1244
for (Table *table= open_tables; table ; table=table->getNext())
2815
for (table=thd->open_tables; table ; table=table->next)
1246
if (table->getShare()->getCacheKey() == identifier.getKey())
2817
if (!strcmp(table->s->table_name.str, table_name) &&
2818
!strcmp(table->s->db.str, db))
1248
table->open_placeholder= true;
2820
if (thd->locked_tables)
2822
mysql_lock_remove(thd, thd->locked_tables, table, TRUE);
2824
table->open_placeholder= 1;
1249
2825
close_handle_and_leave_table_as_lock(table);
1256
Reopen all tables with closed data files.
1258
@param session Thread context
1259
@param get_locks Should we get locks after reopening tables ?
1260
@param mark_share_as_old Mark share as old to protect from a impending
1263
@note Since this function can't properly handle prelocking and
1264
create placeholders it should be used in very special
1265
situations like FLUSH TABLES or ALTER Table. In general
1266
case one should just repeat open_tables()/lock_tables()
1267
combination when one needs tables to be reopened (for
1268
example see openTablesLock()).
1270
@note One should have lock on table::Cache::singleton().mutex() when calling this.
1272
@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.
1275
bool Session::reopen_tables(bool get_locks, bool)
2852
bool reopen_tables(THD *thd, bool get_locks, bool mark_share_as_old)
1277
Table *table,*next,**prev;
1278
Table **tables,**tables_ptr; // For locks
2854
TABLE *table,*next,**prev;
2855
TABLE **tables,**tables_ptr; // For locks
1279
2856
bool error=0, not_used;
1280
const uint32_t flags= DRIZZLE_LOCK_NOTIFY_IF_NEED_REOPEN |
1281
DRIZZLE_LOCK_IGNORE_GLOBAL_READ_LOCK |
1282
DRIZZLE_LOCK_IGNORE_FLUSH;
1284
if (open_tables == NULL)
1287
safe_mutex_assert_owner(table::Cache::singleton().mutex().native_handle());
2857
const uint flags= MYSQL_LOCK_NOTIFY_IF_NEED_REOPEN |
2858
MYSQL_LOCK_IGNORE_GLOBAL_READ_LOCK |
2859
MYSQL_LOCK_IGNORE_FLUSH;
2861
DBUG_ENTER("reopen_tables");
2863
if (!thd->open_tables)
2866
safe_mutex_assert_owner(&LOCK_open);
1291
2870
The ptr is checked later
1292
2871
Do not handle locks of MERGE children.
1296
for (table= open_tables; table ; table=table->getNext())
2874
for (table= thd->open_tables; table ; table=table->next)
1300
tables= new Table *[opens];
2876
DBUG_PRINT("tcache", ("open tables to lock: %u", opens));
2877
tables= (TABLE**) my_alloca(sizeof(TABLE*)*opens);
1304
tables= &open_tables;
2880
tables= &thd->open_tables;
1306
2881
tables_ptr =tables;
1309
for (table= open_tables; table ; table=next)
2883
prev= &thd->open_tables;
2884
for (table=thd->open_tables; table ; table=next)
1311
next= table->getNext();
1313
my_error(ER_CANT_REOPEN_TABLE, MYF(0), table->getAlias());
1314
table::remove_table(static_cast<table::Concurrent *>(table));
2886
uint db_stat=table->db_stat;
2888
if (!tables || (!db_stat && reopen_table(table)))
2890
my_error(ER_CANT_REOPEN_TABLE, MYF(0), table->alias);
2891
VOID(hash_delete(&open_cache,(uchar*) table));
2898
/* Do not handle locks of MERGE children. */
2899
if (get_locks && !db_stat)
2900
*tables_ptr++= table; // need new lock on this
2901
if (mark_share_as_old)
2903
table->s->version=0;
2904
table->open_placeholder= 0;
2909
DBUG_PRINT("tcache", ("open tables to lock: %u",
2910
(uint) (tables_ptr - tables)));
1318
2911
if (tables != tables_ptr) // Should we get back old locks
1320
DrizzleLock *local_lock;
1322
2915
We should always get these locks. Anyway, we must not go into
1323
wait_for_tables() as it tries to acquire table::Cache::singleton().mutex(), which is
2916
wait_for_tables() as it tries to acquire LOCK_open, which is
1324
2917
already locked.
1326
some_tables_deleted= false;
1328
if ((local_lock= lockTables(tables, (uint32_t) (tables_ptr - tables),
2919
thd->some_tables_deleted=0;
2920
if ((lock= mysql_lock_tables(thd, tables, (uint) (tables_ptr - tables),
2923
thd->locked_tables=mysql_lock_merge(thd->locked_tables,lock);
3912
6608
On INSERT or UPDATE fields are checked to be from the same table,
3913
6609
thus we safely can take table from the first field.
3915
table= (*ptr)->getTable();
3916
table->auto_increment_field_not_null= false;
6611
table= (*ptr)->table;
6612
table->auto_increment_field_not_null= FALSE;
3918
while ((field = *ptr++) && ! session->is_error())
6614
while ((field = *ptr++) && ! thd->is_error())
3921
table= field->getTable();
6617
table= field->table;
3922
6618
if (field == table->next_number_field)
3923
table->auto_increment_field_not_null= true;
6619
table->auto_increment_field_not_null= TRUE;
3924
6620
if (value->save_in_field(field, 0) < 0)
6623
DBUG_RETURN(thd->is_error());
6627
table->auto_increment_field_not_null= FALSE;
6632
my_bool mysql_rm_tmp_tables(void)
6635
char filePath[FN_REFLEN], *tmpdir, filePathCopy[FN_REFLEN];
6640
DBUG_ENTER("mysql_rm_tmp_tables");
6642
if (!(thd= new THD))
6644
thd->thread_stack= (char*) &thd;
6645
thd->store_globals();
6647
for (i=0; i<=mysql_tmpdir_list.max; i++)
6649
tmpdir=mysql_tmpdir_list.list[i];
6650
/* See if the directory exists */
6651
if (!(dirp = my_dir(tmpdir,MYF(MY_WME | MY_DONT_SORT))))
6654
/* Remove all SQLxxx tables from directory */
6656
for (idx=0 ; idx < (uint) dirp->number_off_files ; idx++)
3927
table->auto_increment_field_not_null= false;
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)));
3933
return(session->is_error());
3937
bool drizzle_rm_tmp_tables()
3941
assert(drizzle_tmpdir.size());
3943
if (!(session= new Session(plugin::Listen::getNullClient())))
3945
session->thread_stack= (char*) &session;
3946
session->storeGlobals();
3948
plugin::StorageEngine::removeLostTemporaryTables(*session, drizzle_tmpdir.c_str());
6700
my_pthread_setspecific_ptr(THR_THD, 0);
3957
6706
/*****************************************************************************
3958
unireg support functions
3959
*****************************************************************************/
6707
unireg support functions
6708
*****************************************************************************/
6711
Invalidate any cache entries that are for some DB
6714
remove_db_from_cache()
6715
db Database name. This will be in lower case if
6716
lower_case_table_name is set
6719
We can't use hash_delete when looping hash_elements. We mark them first
6720
and afterwards delete those marked unused.
6723
void remove_db_from_cache(const char *db)
6725
for (uint idx=0 ; idx < open_cache.records ; idx++)
6727
TABLE *table=(TABLE*) hash_element(&open_cache,idx);
6728
if (!strcmp(table->s->db.str, db))
6730
table->s->version= 0L; /* Free when thread is ready */
6732
relink_unused(table);
6735
while (unused_tables && !unused_tables->s->version)
6736
VOID(hash_delete(&open_cache,(uchar*) unused_tables));
6741
free all unused tables
6744
This is called by 'handle_manager' when one wants to periodicly flush
6745
all not used tables.
6750
(void) pthread_mutex_lock(&LOCK_open);
6751
while (unused_tables)
6752
hash_delete(&open_cache,(uchar*) unused_tables);
6753
(void) pthread_mutex_unlock(&LOCK_open);
6758
Mark all entries with the table as deleted to force an reopen of the table
6760
The table will be closed (not stored in cache) by the current thread when
6761
close_thread_tables() is called.
6767
0 This thread now have exclusive access to this table and no other thread
6768
can access the table until close_thread_tables() is called.
6769
1 Table is in use by another thread
6772
bool remove_table_from_cache(THD *thd, const char *db, const char *table_name,
6775
char key[MAX_DBKEY_LENGTH];
6779
bool result= 0, signalled= 0;
6780
DBUG_ENTER("remove_table_from_cache");
6781
DBUG_PRINT("enter", ("table: '%s'.'%s' flags: %u", db, table_name, flags));
6783
key_length=(uint) (strmov(strmov(key,db)+1,table_name)-key)+1;
6786
HASH_SEARCH_STATE state;
6787
result= signalled= 0;
6789
for (table= (TABLE*) hash_first(&open_cache, (uchar*) key, key_length,
6792
table= (TABLE*) hash_next(&open_cache, (uchar*) key, key_length,
6796
DBUG_PRINT("tcache", ("found table: '%s'.'%s' 0x%lx", table->s->db.str,
6797
table->s->table_name.str, (long) table));
6799
table->s->version=0L; /* Free when thread is ready */
6800
if (!(in_use=table->in_use))
6802
DBUG_PRINT("info",("Table was not in use"));
6803
relink_unused(table);
6805
else if (in_use != thd)
6807
DBUG_PRINT("info", ("Table was in use by other thread"));
6809
Mark that table is going to be deleted from cache. This will
6810
force threads that are in mysql_lock_tables() (but not yet
6811
in thr_multi_lock()) to abort it's locks, close all tables and retry
6813
in_use->some_tables_deleted= 1;
6814
if (table->is_name_opened())
6816
DBUG_PRINT("info", ("Found another active instance of the table"));
6819
/* Kill delayed insert threads */
6820
if ((in_use->system_thread & SYSTEM_THREAD_DELAYED_INSERT) &&
6823
in_use->killed= THD::KILL_CONNECTION;
6824
pthread_mutex_lock(&in_use->mysys_var->mutex);
6825
if (in_use->mysys_var->current_cond)
6827
pthread_mutex_lock(in_use->mysys_var->current_mutex);
6829
pthread_cond_broadcast(in_use->mysys_var->current_cond);
6830
pthread_mutex_unlock(in_use->mysys_var->current_mutex);
6832
pthread_mutex_unlock(&in_use->mysys_var->mutex);
6835
Now we must abort all tables locks used by this thread
6836
as the thread may be waiting to get a lock for another table.
6837
Note that we need to hold LOCK_open while going through the
6838
list. So that the other thread cannot change it. The other
6839
thread must also hold LOCK_open whenever changing the
6840
open_tables list. Aborting the MERGE lock after a child was
6841
closed and before the parent is closed would be fatal.
6843
for (TABLE *thd_table= in_use->open_tables;
6845
thd_table= thd_table->next)
6847
/* Do not handle locks of MERGE children. */
6848
if (thd_table->db_stat) // If table is open
6849
signalled|= mysql_lock_abort_for_thread(thd, thd_table);
6854
DBUG_PRINT("info", ("Table was in use by current thread. db_stat: %u",
6856
result= result || (flags & RTFC_OWNED_BY_THD_FLAG);
6859
while (unused_tables && !unused_tables->s->version)
6860
VOID(hash_delete(&open_cache,(uchar*) unused_tables));
6862
DBUG_PRINT("info", ("Removing table from table_def_cache"));
6863
/* Remove table from table definition cache if it's not in use */
6864
if ((share= (TABLE_SHARE*) hash_search(&table_def_cache,(uchar*) key,
6867
DBUG_PRINT("info", ("share version: %lu ref_count: %u",
6868
share->version, share->ref_count));
6869
share->version= 0; // Mark for delete
6870
if (share->ref_count == 0)
6872
pthread_mutex_lock(&share->mutex);
6873
VOID(hash_delete(&table_def_cache, (uchar*) share));
6877
if (result && (flags & RTFC_WAIT_OTHER_THREAD_FLAG))
6880
Signal any thread waiting for tables to be freed to
6883
broadcast_refresh();
6884
DBUG_PRINT("info", ("Waiting for refresh signal"));
6885
if (!(flags & RTFC_CHECK_KILLED_FLAG) || !thd->killed)
6888
if (likely(signalled))
6889
(void) pthread_cond_wait(&COND_refresh, &LOCK_open);
6892
struct timespec abstime;
6894
It can happen that another thread has opened the
6895
table but has not yet locked any table at all. Since
6896
it can be locked waiting for a table that our thread
6897
has done LOCK TABLE x WRITE on previously, we need to
6898
ensure that the thread actually hears our signal
6899
before we go to sleep. Thus we wait for a short time
6900
and then we retry another loop in the
6901
remove_table_from_cache routine.
6903
set_timespec(abstime, 10);
6904
pthread_cond_timedwait(&COND_refresh, &LOCK_open, &abstime);
6912
DBUG_RETURN(result);
6916
bool is_equal(const LEX_STRING *a, const LEX_STRING *b)
6918
return a->length == b->length && !strncmp(a->str, b->str, a->length);
6923
Open and lock system tables for read.
6926
open_system_tables_for_read()
6928
table_list List of tables to open.
6929
backup Pointer to Open_tables_state instance where
6930
information about currently open tables will be
6931
saved, and from which will be restored when we will
6932
end work with system tables.
6935
Thanks to restrictions which we put on opening and locking of
6936
system tables for writing, we can open and lock them for reading
6937
even when we already have some other tables open and locked. One
6938
must call close_system_tables() to close systems tables opened
6947
open_system_tables_for_read(THD *thd, TABLE_LIST *table_list,
6948
Open_tables_state *backup)
6950
DBUG_ENTER("open_system_tables_for_read");
6952
thd->reset_n_backup_open_tables_state(backup);
6956
for (TABLE_LIST *tables= table_list; tables; tables= tables->next_global)
6958
TABLE *table= open_table(thd, tables, thd->mem_root, ¬_used,
6959
MYSQL_LOCK_IGNORE_FLUSH);
6963
DBUG_ASSERT(table->s->table_category == TABLE_CATEGORY_SYSTEM);
6965
table->use_all_columns();
6966
table->reginfo.lock_type= tables->lock_type;
6967
tables->table= table;
6972
TABLE **list= (TABLE**) thd->alloc(sizeof(TABLE*) * count);
6974
for (TABLE_LIST *tables= table_list; tables; tables= tables->next_global)
6975
*(ptr++)= tables->table;
6977
thd->lock= mysql_lock_tables(thd, list, count,
6978
MYSQL_LOCK_IGNORE_FLUSH, ¬_used);
6984
close_system_tables(thd, backup);
6991
Close system tables, opened with open_system_tables_for_read().
6994
close_system_tables()
6996
backup Pointer to Open_tables_state instance which holds
6997
information about tables which were open before we
6998
decided to access system tables.
7002
close_system_tables(THD *thd, Open_tables_state *backup)
7004
close_thread_tables(thd);
7005
thd->restore_backup_open_tables_state(backup);
7010
Open and lock one system table for update.
7013
open_system_table_for_update()
7015
one_table Table to open.
7018
Table opened with this call should closed using close_thread_tables().
7022
# Pointer to TABLE object of system table
7026
open_system_table_for_update(THD *thd, TABLE_LIST *one_table)
7028
DBUG_ENTER("open_system_table_for_update");
7030
TABLE *table= open_ltable(thd, one_table, one_table->lock_type, 0);
7033
DBUG_ASSERT(table->s->table_category == TABLE_CATEGORY_SYSTEM);
7034
table->use_all_columns();
3965
7041
@} (end of group Data_Dictionary)
3968
void kill_drizzle(void)
3970
pthread_kill(signal_thread, SIGTERM);
3971
shutdown_in_progress= 1; // Safety if kill didn't work
3974
} /* namespace drizzled */