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/epoch.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>
59
#include <drizzled/plugin/storage_engine.h>
60
#include <drizzled/session.h>
62
#include <drizzled/refresh_version.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
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;
69
extern bool volatile shutdown_in_progress;
71
56
bool table_cache_init(void)
76
uint32_t cached_open_tables(void)
78
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;
81
63
void table_cache_free(void)
83
refresh_version++; // Force close of open tables
85
table::getUnused().clear();
86
table::getCache().clear();
90
Close cursor handle, but leave the table in the table cache
93
close_handle_and_leave_table_as_lock()
97
By leaving the table in the table cache, it disallows any other thread
100
session->getKilled() will be set if we run out of memory
102
If closing a MERGE child, the calling function has to take care for
103
closing the parent too, if necessary.
107
void close_handle_and_leave_table_as_lock(Table *table)
67
close_cached_tables(NULL, NULL, false, false, false);
68
if (!open_cache.records) // Safety first
69
hash_free(&open_cache);
74
uint cached_open_tables(void)
76
return open_cache.records;
80
Create a table cache key
83
create_table_def_key()
85
key Create key here (must be of size MAX_DBKEY_LENGTH)
86
table_list Table definition
87
tmp_table Set if table is a tmp table
90
The table cache_key is created from:
94
if the table is a tmp table, we add the following to make each tmp table
97
4 bytes for master thread id
98
4 bytes pseudo thread id
104
uint create_table_def_key(THD *thd, char *key, TABLE_LIST *table_list,
107
uint key_length= (uint) (strmov(strmov(key, table_list->db)+1,
108
table_list->table_name)-key)+1;
111
int4store(key + key_length, thd->server_id);
112
int4store(key + key_length + 4, thd->variables.pseudo_thread_id);
113
key_length+= TMP_TABLE_KEY_EXTRA;
120
/*****************************************************************************
121
Functions to handle table definition cach (TABLE_SHARE)
122
*****************************************************************************/
124
extern "C" uchar *table_def_key(const uchar *record, size_t *length,
125
bool not_used __attribute__((unused)))
127
TABLE_SHARE *entry=(TABLE_SHARE*) record;
128
*length= entry->table_cache_key.length;
129
return (uchar*) entry->table_cache_key.str;
133
static void table_def_free_entry(TABLE_SHARE *share)
137
/* remove from old_unused_share list */
138
pthread_mutex_lock(&LOCK_table_share);
139
*share->prev= share->next;
140
share->next->prev= share->prev;
141
pthread_mutex_unlock(&LOCK_table_share);
143
free_table_share(share);
148
bool table_def_init(void)
151
pthread_mutex_init(&LOCK_table_share, MY_MUTEX_INIT_FAST);
152
oldest_unused_share= &end_of_unused_share;
153
end_of_unused_share.prev= &oldest_unused_share;
155
return hash_init(&table_def_cache, &my_charset_bin, table_def_size,
157
(hash_free_key) table_def_free_entry, 0) != 0;
161
void table_def_free(void)
163
if (table_def_inited)
166
pthread_mutex_destroy(&LOCK_table_share);
167
hash_free(&table_def_cache);
173
uint cached_table_definitions(void)
175
return table_def_cache.records;
180
Get TABLE_SHARE for a table.
184
table_list Table that should be opened
186
key_length Length of key
187
db_flags Flags to open_table_def():
189
error out: Error code from open_table_def()
192
Get a table definition from the table definition cache.
193
If it doesn't exist, create a new from the table definition file.
196
We must have wrlock on LOCK_open when we come here
197
(To be changed later)
204
TABLE_SHARE *get_table_share(THD *thd, TABLE_LIST *table_list, char *key,
205
uint key_length, uint db_flags, int *error)
211
/* Read table definition from cache */
212
if ((share= (TABLE_SHARE*) hash_search(&table_def_cache,(uchar*) key,
216
if (!(share= alloc_table_share(table_list, key, key_length)))
222
Lock mutex to be able to read table definition from file without
225
(void) pthread_mutex_lock(&share->mutex);
228
We assign a new table id under the protection of the LOCK_open and
229
the share's own mutex. We do this insted of creating a new mutex
230
and using it for the sole purpose of serializing accesses to a
231
static variable, we assign the table id here. We assign it to the
232
share before inserting it into the table_def_cache to be really
233
sure that it cannot be read from the cache without having a table
236
CAVEAT. This means that the table cannot be used for
237
binlogging/replication purposes, unless get_table_share() has been
238
called directly or indirectly.
240
assign_new_table_id(share);
242
if (my_hash_insert(&table_def_cache, (uchar*) share))
244
free_table_share(share);
245
return(0); // return error
247
if (open_table_def(thd, share, db_flags))
249
*error= share->error;
250
(void) hash_delete(&table_def_cache, (uchar*) share);
253
share->ref_count++; // Mark in use
254
(void) pthread_mutex_unlock(&share->mutex);
259
We found an existing table definition. Return it if we didn't get
260
an error when reading the table definition from file.
263
/* We must do a lock to ensure that the structure is initialized */
264
(void) pthread_mutex_lock(&share->mutex);
267
/* Table definition contained an error */
268
open_table_error(share, share->error, share->open_errno, share->errarg);
269
(void) pthread_mutex_unlock(&share->mutex);
273
if (!share->ref_count++ && share->prev)
276
Share was not used before and it was in the old_unused_share list
277
Unlink share from this list
279
pthread_mutex_lock(&LOCK_table_share);
280
*share->prev= share->next;
281
share->next->prev= share->prev;
284
pthread_mutex_unlock(&LOCK_table_share);
286
(void) pthread_mutex_unlock(&share->mutex);
288
/* Free cache if too big */
289
while (table_def_cache.records > table_def_size &&
290
oldest_unused_share->next)
292
pthread_mutex_lock(&oldest_unused_share->mutex);
293
VOID(hash_delete(&table_def_cache, (uchar*) oldest_unused_share));
301
Get a table share. If it didn't exist, try creating it from engine
303
For arguments and return values, see get_table_from_share()
307
*get_table_share_with_create(THD *thd, TABLE_LIST *table_list,
308
char *key, uint key_length,
309
uint db_flags, int *error)
314
share= get_table_share(thd, table_list, key, key_length, db_flags, error);
316
If share is not NULL, we found an existing share.
318
If share is NULL, and there is no error, we're inside
319
pre-locking, which silences 'ER_NO_SUCH_TABLE' errors
320
with the intention to silently drop non-existing tables
321
from the pre-locking list. In this case we still need to try
322
auto-discover before returning a NULL share.
324
If share is NULL and the error is ER_NO_SUCH_TABLE, this is
325
the same as above, only that the error was not silenced by
326
pre-locking. Once again, we need to try to auto-discover
329
Finally, if share is still NULL, it's a real error and we need
332
@todo Rework alternative ways to deal with ER_NO_SUCH TABLE.
334
if (share || (thd->is_error() && (thd->main_da.sql_errno() != ER_NO_SUCH_TABLE)))
338
/* Table didn't exist. Check if some engine can provide it */
339
if ((tmp= ha_create_table_from_engine(thd, table_list->db,
340
table_list->table_name)) < 0)
343
No such table in any engine.
344
Hide "Table doesn't exist" errors if the table belongs to a view.
345
The check for thd->is_error() is necessary to not push an
346
unwanted error in case of pre-locking, which silences
347
"no such table" errors.
348
@todo Rework the alternative ways to deal with ER_NO_SUCH TABLE.
350
if (thd->is_error() && table_list->belong_to_view)
353
my_error(ER_VIEW_INVALID, MYF(0), "", "");
359
/* Give right error message */
361
my_printf_error(ER_UNKNOWN_ERROR,
362
"Failed to open '%-.64s', error while "
363
"unpacking from engine",
364
MYF(0), table_list->table_name);
367
/* Table existed in engine. Let's open it */
368
mysql_reset_errors(thd, 1); // Clear warnings
369
thd->clear_error(); // Clear error message
370
return(get_table_share(thd, table_list, key, key_length,
376
Mark that we are not using table share anymore.
379
release_table_share()
381
release_type How the release should be done:
383
- Release without checking
384
RELEASE_WAIT_FOR_DROP
385
- Don't return until we get a signal that the
386
table is deleted or the thread is killed.
389
If ref_count goes to zero and (we have done a refresh or if we have
390
already too many open table shares) then delete the definition.
392
If type == RELEASE_WAIT_FOR_DROP then don't return until we get a signal
393
that the table is deleted or the thread is killed.
396
void release_table_share(TABLE_SHARE *share,
397
enum release_type type __attribute__((__unused__)))
399
bool to_be_deleted= 0;
401
safe_mutex_assert_owner(&LOCK_open);
403
pthread_mutex_lock(&share->mutex);
404
if (!--share->ref_count)
406
if (share->version != refresh_version)
410
/* Link share last in used_table_share list */
411
assert(share->next == 0);
412
pthread_mutex_lock(&LOCK_table_share);
413
share->prev= end_of_unused_share.prev;
414
*end_of_unused_share.prev= share;
415
end_of_unused_share.prev= &share->next;
416
share->next= &end_of_unused_share;
417
pthread_mutex_unlock(&LOCK_table_share);
419
to_be_deleted= (table_def_cache.records > table_def_size);
425
hash_delete(&table_def_cache, (uchar*) share);
428
pthread_mutex_unlock(&share->mutex);
434
Check if table definition exits in cache
437
get_cached_table_share()
439
table_name Table name
443
# TABLE_SHARE for table
446
TABLE_SHARE *get_cached_table_share(const char *db, const char *table_name)
448
char key[NAME_LEN*2+2];
449
TABLE_LIST table_list;
451
safe_mutex_assert_owner(&LOCK_open);
453
table_list.db= (char*) db;
454
table_list.table_name= (char*) table_name;
455
key_length= create_table_def_key((THD*) 0, key, &table_list, 0);
456
return (TABLE_SHARE*) hash_search(&table_def_cache,(uchar*) key, key_length);
461
Close file handle, but leave the table in the table cache
464
close_handle_and_leave_table_as_lock()
468
By leaving the table in the table cache, it disallows any other thread
471
thd->killed will be set if we run out of memory
473
If closing a MERGE child, the calling function has to take care for
474
closing the parent too, if necessary.
478
void close_handle_and_leave_table_as_lock(TABLE *table)
480
TABLE_SHARE *share, *old_share= table->s;
482
MEM_ROOT *mem_root= &table->mem_root;
109
484
assert(table->db_stat);
110
assert(table->getShare()->getType() == message::Table::STANDARD);
113
487
Make a local copy of the table share and free the current one.
114
488
This has to be done to ensure that the table share is removed from
115
489
the table defintion cache as soon as the last instance is removed
117
identifier::Table identifier(table->getShare()->getSchemaName(), table->getShare()->getTableName(), message::Table::INTERNAL);
118
const identifier::Table::Key &key(identifier.getKey());
119
TableShare *share= new TableShare(identifier.getType(),
121
const_cast<char *>(key.vector()), static_cast<uint32_t>(table->getShare()->getCacheKeySize()));
123
table->cursor->close();
124
table->db_stat= 0; // Mark cursor closed
125
table::instance::release(table->getMutableShare());
126
table->setShare(share);
491
if (multi_alloc_root(mem_root,
492
&share, sizeof(*share),
493
&key_buff, old_share->table_cache_key.length,
496
bzero((char*) share, sizeof(*share));
497
share->set_table_cache_key(key_buff, old_share->table_cache_key.str,
498
old_share->table_cache_key.length);
499
share->tmp_table= INTERNAL_TMP_TABLE; // for intern_close_table()
502
table->file->close();
503
table->db_stat= 0; // Mark file closed
504
release_table_share(table->s, RELEASE_NORMAL);
506
table->file->change_table_ptr(table, table->s);
514
Create a list for all open tables matching SQL expression
519
wild SQL like expression
522
One gets only a list of tables for which one has any kind of privilege.
523
db and table names are allocated in result struct, so one doesn't need
524
a lock on LOCK_open when traversing the return list.
527
NULL Error (Probably OOM)
528
# Pointer to list of names of open tables.
531
OPEN_TABLE_LIST *list_open_tables(THD *thd __attribute__((__unused__)),
532
const char *db, const char *wild)
535
OPEN_TABLE_LIST **start_list, *open_list;
536
TABLE_LIST table_list;
538
VOID(pthread_mutex_lock(&LOCK_open));
539
bzero((char*) &table_list,sizeof(table_list));
540
start_list= &open_list;
543
for (uint idx=0 ; result == 0 && idx < open_cache.records; idx++)
545
OPEN_TABLE_LIST *table;
546
TABLE *entry=(TABLE*) hash_element(&open_cache,idx);
547
TABLE_SHARE *share= entry->s;
549
if (db && my_strcasecmp(system_charset_info, db, share->db.str))
551
if (wild && wild_compare(share->table_name.str, wild, 0))
554
/* Check if user has SELECT privilege for any column in the table */
555
table_list.db= share->db.str;
556
table_list.table_name= share->table_name.str;
558
/* need to check if we haven't already listed it */
559
for (table= open_list ; table ; table=table->next)
561
if (!strcmp(table->table, share->table_name.str) &&
562
!strcmp(table->db, share->db.str))
566
if (entry->locked_by_name)
573
if (!(*start_list = (OPEN_TABLE_LIST *)
574
sql_alloc(sizeof(**start_list)+share->table_cache_key.length)))
576
open_list=0; // Out of memory
579
strmov((*start_list)->table=
580
strmov(((*start_list)->db= (char*) ((*start_list)+1)),
582
share->table_name.str);
583
(*start_list)->in_use= entry->in_use ? 1 : 0;
584
(*start_list)->locked= entry->locked_by_name ? 1 : 0;
585
start_list= &(*start_list)->next;
588
VOID(pthread_mutex_unlock(&LOCK_open));
130
592
/*****************************************************************************
131
593
* Functions to free open table cache
132
594
****************************************************************************/
135
void Table::intern_close_table()
597
void intern_close_table(TABLE *table)
136
598
{ // Free all structures
138
if (cursor) // Not true if name lock
599
free_io_cache(table);
600
if (table->file) // Not true if name lock
601
VOID(closefrm(table, 1)); // close file
606
Remove table from the open table cache
610
table Table to remove
613
We need to have a lock on LOCK_open when calling this
616
static void free_cache_entry(TABLE *table)
618
intern_close_table(table);
140
delete_table(true); // close cursor
621
table->next->prev=table->prev; /* remove from used chain */
622
table->prev->next=table->next;
623
if (table == unused_tables)
625
unused_tables=unused_tables->next;
626
if (table == unused_tables)
630
my_free((uchar*) table,MYF(0));
144
634
/* Free resources allocated by filesort() and read_record() */
146
void Table::free_io_cache()
636
void free_io_cache(TABLE *table)
638
if (table->sort.io_cache)
150
sort.io_cache->close_cached_file();
151
safe_delete(sort.io_cache);
640
close_cached_file(table->sort.io_cache);
641
my_free((uchar*) table->sort.io_cache,MYF(0));
642
table->sort.io_cache=0;
157
649
Close all tables which aren't in use by any thread
159
@param session Thread context (may be NULL)
651
@param thd Thread context
160
652
@param tables List of tables to remove from the cache
161
@param have_lock If table::Cache::singleton().mutex() is locked
653
@param have_lock If LOCK_open is locked
162
654
@param wait_for_refresh Wait for a impending flush
163
655
@param wait_for_placeholders Wait for tables being reopened so that the GRL
164
won't proceed while write-locked tables are being reopened by other
167
@remark Session can be NULL, but then wait_for_refresh must be false
168
and tables must be NULL.
171
bool Session::close_cached_tables(TableList *tables, bool wait_for_refresh, bool wait_for_placeholders)
656
won't proceed while write-locked tables are being reopened by other
659
@remark THD can be NULL, but then wait_for_refresh must be false
660
and tables must be NULL.
663
bool close_cached_tables(THD *thd, TABLE_LIST *tables, bool have_lock,
664
bool wait_for_refresh, bool wait_for_placeholders)
667
assert(thd || (!wait_for_refresh && !tables));
670
VOID(pthread_mutex_lock(&LOCK_open));
673
refresh_version++; // Force close of open tables
674
while (unused_tables)
677
if (hash_delete(&open_cache,(uchar*) unused_tables))
678
printf("Warning: Couldn't delete open table from hash\n");
680
VOID(hash_delete(&open_cache,(uchar*) unused_tables));
683
/* Free table shares */
684
while (oldest_unused_share->next)
686
pthread_mutex_lock(&oldest_unused_share->mutex);
687
VOID(hash_delete(&table_def_cache, (uchar*) oldest_unused_share));
689
if (wait_for_refresh)
692
Other threads could wait in a loop in open_and_lock_tables(),
693
trying to lock one or more of our tables.
695
If they wait for the locks in thr_multi_lock(), their lock
696
request is aborted. They loop in open_and_lock_tables() and
697
enter open_table(). Here they notice the table is refreshed and
698
wait for COND_refresh. Then they loop again in
699
open_and_lock_tables() and this time open_table() succeeds. At
700
this moment, if we (the FLUSH TABLES thread) are scheduled and
701
on another FLUSH TABLES enter close_cached_tables(), they could
702
awake while we sleep below, waiting for others threads (us) to
703
close their open tables. If this happens, the other threads
704
would find the tables unlocked. They would get the locks, one
705
after the other, and could do their destructive work. This is an
706
issue if we have LOCK TABLES in effect.
708
The problem is that the other threads passed all checks in
709
open_table() before we refresh the table.
711
The fix for this problem is to set some_tables_deleted for all
712
threads with open tables. These threads can still get their
713
locks, but will immediately release them again after checking
714
this variable. They will then loop in open_and_lock_tables()
715
again. There they will wait until we update all tables version
718
Setting some_tables_deleted is done by remove_table_from_cache()
721
In other words (reviewer suggestion): You need this setting of
722
some_tables_deleted for the case when table was opened and all
723
related checks were passed before incrementing refresh_version
724
(which you already have) but attempt to lock the table happened
725
after the call to close_old_data_files() i.e. after removal of
726
current thread locks.
728
for (uint idx=0 ; idx < open_cache.records ; idx++)
730
TABLE *table=(TABLE*) hash_element(&open_cache,idx);
732
table->in_use->some_tables_deleted= 1;
739
for (TABLE_LIST *table= tables; table; table= table->next_local)
741
if (remove_table_from_cache(thd, table->db, table->table_name,
742
RTFC_OWNED_BY_THD_FLAG))
746
wait_for_refresh=0; // Nothing to wait for
749
if (wait_for_refresh)
752
If there is any table that has a lower refresh_version, wait until
753
this is closed (or this thread is killed) before returning
755
thd->mysys_var->current_mutex= &LOCK_open;
756
thd->mysys_var->current_cond= &COND_refresh;
757
thd_proc_info(thd, "Flushing tables");
759
close_old_data_files(thd,thd->open_tables,1,1);
763
/* Wait until all threads has closed all the tables we had locked */
764
while (found && ! thd->killed)
767
for (uint idx=0 ; idx < open_cache.records ; idx++)
769
TABLE *table=(TABLE*) hash_element(&open_cache,idx);
770
/* Avoid a self-deadlock. */
771
if (table->in_use == thd)
774
Note that we wait here only for tables which are actually open, and
775
not for placeholders with TABLE::open_placeholder set. Waiting for
776
latter will cause deadlock in the following scenario, for example:
778
conn1: lock table t1 write;
779
conn2: lock table t2 write;
783
It also does not make sense to wait for those of placeholders that
784
are employed by CREATE TABLE as in this case table simply does not
787
if (table->needs_reopen_or_name_lock() && (table->db_stat ||
788
(table->open_placeholder && wait_for_placeholders)))
791
pthread_cond_wait(&COND_refresh,&LOCK_open);
797
No other thread has the locked tables open; reopen them and get the
798
old locks. This should always succeed (unless some external process
799
has removed the tables)
801
thd->in_lock_tables=1;
802
result=reopen_tables(thd,1,1);
803
thd->in_lock_tables=0;
804
/* Set version for table */
805
for (TABLE *table=thd->open_tables; table ; table= table->next)
808
Preserve the version (0) of write locked tables so that a impending
809
global read lock won't sneak in.
811
if (table->reginfo.lock_type < TL_WRITE_ALLOW_WRITE)
812
table->s->version= refresh_version;
816
VOID(pthread_mutex_unlock(&LOCK_open));
817
if (wait_for_refresh)
819
pthread_mutex_lock(&thd->mysys_var->mutex);
820
thd->mysys_var->current_mutex= 0;
821
thd->mysys_var->current_cond= 0;
822
thd_proc_info(thd, 0);
823
pthread_mutex_unlock(&thd->mysys_var->mutex);
830
Close all tables which match specified connection string or
831
if specified string is NULL, then any table with a connection string.
834
bool close_cached_connection_tables(THD *thd, bool if_wait_for_refresh,
835
LEX_STRING *connection, bool have_lock)
838
TABLE_LIST tmp, *tables= NULL;
173
839
bool result= false;
174
Session *session= this;
177
boost::mutex::scoped_lock scopedLock(table::Cache::singleton().mutex()); /* Optionally lock for remove tables from open_cahe if not in use */
181
refresh_version++; // Force close of open tables
183
table::getUnused().clear();
185
if (wait_for_refresh)
188
Other threads could wait in a loop in open_and_lock_tables(),
189
trying to lock one or more of our tables.
191
If they wait for the locks in thr_multi_lock(), their lock
192
request is aborted. They loop in open_and_lock_tables() and
193
enter open_table(). Here they notice the table is refreshed and
194
wait for COND_refresh. Then they loop again in
195
openTablesLock() and this time open_table() succeeds. At
196
this moment, if we (the FLUSH TABLES thread) are scheduled and
197
on another FLUSH TABLES enter close_cached_tables(), they could
198
awake while we sleep below, waiting for others threads (us) to
199
close their open tables. If this happens, the other threads
200
would find the tables unlocked. They would get the locks, one
201
after the other, and could do their destructive work. This is an
202
issue if we have LOCK TABLES in effect.
204
The problem is that the other threads passed all checks in
205
open_table() before we refresh the table.
207
The fix for this problem is to set some_tables_deleted for all
208
threads with open tables. These threads can still get their
209
locks, but will immediately release them again after checking
210
this variable. They will then loop in openTablesLock()
211
again. There they will wait until we update all tables version
214
Setting some_tables_deleted is done by table::Cache::singleton().removeTable()
217
In other words (reviewer suggestion): You need this setting of
218
some_tables_deleted for the case when table was opened and all
219
related checks were passed before incrementing refresh_version
220
(which you already have) but attempt to lock the table happened
221
after the call to Session::close_old_data_files() i.e. after removal of
222
current thread locks.
224
for (table::CacheMap::const_iterator iter= table::getCache().begin();
225
iter != table::getCache().end();
228
Table *table= (*iter).second;
230
table->in_use->some_tables_deleted= false;
237
for (TableList *table= tables; table; table= table->next_local)
239
identifier::Table identifier(table->getSchemaName(), table->getTableName());
240
if (table::Cache::singleton().removeTable(session, identifier,
241
RTFC_OWNED_BY_Session_FLAG))
247
wait_for_refresh= false; // Nothing to wait for
250
if (wait_for_refresh)
253
If there is any table that has a lower refresh_version, wait until
254
this is closed (or this thread is killed) before returning
256
session->mysys_var->current_mutex= &table::Cache::singleton().mutex();
257
session->mysys_var->current_cond= &COND_refresh;
258
session->set_proc_info("Flushing tables");
260
session->close_old_data_files();
263
/* Wait until all threads has closed all the tables we had locked */
264
while (found && ! session->getKilled())
267
for (table::CacheMap::const_iterator iter= table::getCache().begin();
268
iter != table::getCache().end();
271
Table *table= (*iter).second;
272
/* Avoid a self-deadlock. */
273
if (table->in_use == session)
276
Note that we wait here only for tables which are actually open, and
277
not for placeholders with Table::open_placeholder set. Waiting for
278
latter will cause deadlock in the following scenario, for example:
280
conn1-> lock table t1 write;
281
conn2-> lock table t2 write;
282
conn1-> flush tables;
283
conn2-> flush tables;
285
It also does not make sense to wait for those of placeholders that
286
are employed by CREATE TABLE as in this case table simply does not
289
if (table->needs_reopen_or_name_lock() && (table->db_stat ||
290
(table->open_placeholder && wait_for_placeholders)))
293
COND_refresh.wait(scopedLock);
299
No other thread has the locked tables open; reopen them and get the
300
old locks. This should always succeed (unless some external process
301
has removed the tables)
303
result= session->reopen_tables();
305
/* Set version for table */
306
for (Table *table= session->open_tables; table ; table= table->getNext())
309
Preserve the version (0) of write locked tables so that a impending
310
global read lock won't sneak in.
312
if (table->reginfo.lock_type < TL_WRITE_ALLOW_WRITE)
313
table->getMutableShare()->refreshVersion();
318
if (wait_for_refresh)
320
boost_unique_lock_t scopedLock(session->mysys_var->mutex);
321
session->mysys_var->current_mutex= 0;
322
session->mysys_var->current_cond= 0;
323
session->set_proc_info(0);
842
bzero(&tmp, sizeof(TABLE_LIST));
845
VOID(pthread_mutex_lock(&LOCK_open));
847
for (idx= 0; idx < table_def_cache.records; idx++)
849
TABLE_SHARE *share= (TABLE_SHARE *) hash_element(&table_def_cache, idx);
851
/* Ignore if table is not open or does not have a connect_string */
852
if (!share->connect_string.length || !share->ref_count)
855
/* Compare the connection string */
857
(connection->length > share->connect_string.length ||
858
(connection->length < share->connect_string.length &&
859
(share->connect_string.str[connection->length] != '/' &&
860
share->connect_string.str[connection->length] != '\\')) ||
861
strncasecmp(connection->str, share->connect_string.str,
862
connection->length)))
865
/* close_cached_tables() only uses these elements */
866
tmp.db= share->db.str;
867
tmp.table_name= share->table_name.str;
868
tmp.next_local= tables;
870
tables= (TABLE_LIST *) memdup_root(thd->mem_root, (char*)&tmp,
875
result= close_cached_tables(thd, tables, true, false, false);
878
VOID(pthread_mutex_unlock(&LOCK_open));
880
if (if_wait_for_refresh)
882
pthread_mutex_lock(&thd->mysys_var->mutex);
883
thd->mysys_var->current_mutex= 0;
884
thd->mysys_var->current_cond= 0;
886
pthread_mutex_unlock(&thd->mysys_var->mutex);
331
move one table to free list
334
bool Session::free_cached_table(boost::mutex::scoped_lock &scopedLock)
336
bool found_old_table= false;
340
table::Concurrent *table= static_cast<table::Concurrent *>(open_tables);
342
safe_mutex_assert_owner(table::Cache::singleton().mutex().native_handle());
343
assert(table->key_read == 0);
344
assert(!table->cursor || table->cursor->inited == Cursor::NONE);
346
open_tables= table->getNext();
348
if (table->needs_reopen_or_name_lock() ||
349
version != refresh_version || !table->db_stat)
351
table::remove_table(table);
352
found_old_table= true;
357
Open placeholders have Table::db_stat set to 0, so they should be
358
handled by the first alternative.
360
assert(not table->open_placeholder);
362
/* Free memory and reset for next loop */
363
table->cursor->ha_reset();
366
table::getUnused().link(table);
369
return found_old_table;
894
Mark all temporary tables which were used by the current statement or
895
substatement as free for reuse, but only if the query_id can be cleared.
897
@param thd thread context
899
@remark For temp tables associated with a open SQL HANDLER the query_id
900
is not reset until the HANDLER is closed.
903
static void mark_temp_tables_as_free_for_reuse(THD *thd)
905
for (TABLE *table= thd->temporary_tables ; table ; table= table->next)
907
if ((table->query_id == thd->query_id) && ! table->open_by_handler)
910
table->file->ha_reset();
917
Mark all tables in the list which were used by current substatement
921
mark_used_tables_as_free_for_reuse()
923
table - head of the list of tables
926
Marks all tables in the list which were used by current substatement
927
(they are marked by its query_id) as free for reuse.
930
The reason we reset query_id is that it's not enough to just test
931
if table->query_id != thd->query_id to know if a table is in use.
934
SELECT f1_that_uses_t1() FROM t1;
935
In f1_that_uses_t1() we will see one instance of t1 where query_id is
936
set to query_id of original query.
939
static void mark_used_tables_as_free_for_reuse(THD *thd, TABLE *table)
941
for (; table ; table= table->next)
943
if (table->query_id == thd->query_id)
946
table->file->ha_reset();
374
953
Auxiliary function to close all tables in the open_tables list.
376
@param session Thread context.
955
@param thd Thread context.
378
957
@remark It should not ordinarily be called directly.
381
void Session::close_open_tables()
960
static void close_open_tables(THD *thd)
383
bool found_old_table= false;
385
safe_mutex_assert_not_owner(table::Cache::singleton().mutex().native_handle());
387
boost_unique_lock_t scoped_lock(table::Cache::singleton().mutex()); /* Close all open tables on Session */
391
found_old_table|= free_cached_table(scoped_lock);
393
some_tables_deleted= false;
962
bool found_old_table= 0;
964
safe_mutex_assert_not_owner(&LOCK_open);
966
VOID(pthread_mutex_lock(&LOCK_open));
968
while (thd->open_tables)
969
found_old_table|= close_thread_table(thd, &thd->open_tables);
970
thd->some_tables_deleted= 0;
972
/* Free tables to hold down open files */
973
while (open_cache.records > table_cache_size && unused_tables)
974
VOID(hash_delete(&open_cache,(uchar*) unused_tables)); /* purecov: tested */
395
975
if (found_old_table)
397
977
/* Tell threads waiting for refresh that something has happened */
398
locking::broadcast_refresh();
981
VOID(pthread_mutex_unlock(&LOCK_open));
986
Close all tables used by the current substatement, or all tables
987
used by this thread if we are on the upper level.
990
close_thread_tables()
994
Unlocks tables and frees derived tables.
995
Put all normal tables used by thread in free list.
997
It will only close/mark as free for reuse tables opened by this
998
substatement, it will also check if we are closing tables after
999
execution of complete query (i.e. we are on upper level) and will
1000
leave prelocked mode if needed.
1003
void close_thread_tables(THD *thd)
1008
We are assuming here that thd->derived_tables contains ONLY derived
1009
tables for this substatement. i.e. instead of approach which uses
1010
query_id matching for determining which of the derived tables belong
1011
to this substatement we rely on the ability of substatements to
1012
save/restore thd->derived_tables during their execution.
1014
TODO: Probably even better approach is to simply associate list of
1015
derived tables with (sub-)statement instead of thread and destroy
1016
them at the end of its execution.
1018
if (thd->derived_tables)
1022
Close all derived tables generated in queries like
1023
SELECT * FROM (SELECT * FROM t1)
1025
for (table= thd->derived_tables ; table ; table= next)
1028
free_tmp_table(thd, table);
1030
thd->derived_tables= 0;
1034
Mark all temporary tables used by this statement as free for reuse.
1036
mark_temp_tables_as_free_for_reuse(thd);
1038
Let us commit transaction for statement. Since in 5.0 we only have
1039
one statement transaction and don't allow several nested statement
1040
transactions this call will do nothing if we are inside of stored
1041
function or trigger (i.e. statement transaction is already active and
1042
does not belong to statement for which we do close_thread_tables()).
1043
TODO: This should be fixed in later releases.
1045
if (!(thd->state_flags & Open_tables_state::BACKUPS_AVAIL))
1047
thd->main_da.can_overwrite_status= true;
1048
ha_autocommit_or_rollback(thd, thd->is_error());
1049
thd->main_da.can_overwrite_status= false;
1050
thd->transaction.stmt.reset();
1053
if (thd->locked_tables)
1056
/* Ensure we are calling ha_reset() for all used tables */
1057
mark_used_tables_as_free_for_reuse(thd, thd->open_tables);
1060
We are under simple LOCK TABLES so should not do anything else.
1068
For RBR we flush the pending event just before we unlock all the
1069
tables. This means that we are at the end of a topmost
1070
statement, so we ensure that the STMT_END_F flag is set on the
1071
pending event. For statements that are *inside* stored
1072
functions, the pending event will not be flushed: that will be
1073
handled either before writing a query log event (inside
1074
binlog_query()) or when preparing a pending event.
1076
thd->binlog_flush_pending_rows_event(true);
1077
mysql_unlock_tables(thd, thd->lock);
1081
Note that we need to hold LOCK_open while changing the
1082
open_tables list. Another thread may work on it.
1083
(See: remove_table_from_cache(), mysql_wait_completed_table())
1084
Closing a MERGE child before the parent would be fatal if the
1085
other thread tries to abort the MERGE lock in between.
1087
if (thd->open_tables)
1088
close_open_tables(thd);
1094
/* move one table to free list */
1096
bool close_thread_table(THD *thd, TABLE **table_ptr)
1098
bool found_old_table= 0;
1099
TABLE *table= *table_ptr;
1101
assert(table->key_read == 0);
1102
assert(!table->file || table->file->inited == handler::NONE);
1104
*table_ptr=table->next;
1106
if (table->needs_reopen_or_name_lock() ||
1107
thd->version != refresh_version || !table->db_stat)
1109
VOID(hash_delete(&open_cache,(uchar*) table));
1115
Open placeholders have TABLE::db_stat set to 0, so they should be
1116
handled by the first alternative.
1118
assert(!table->open_placeholder);
1120
/* Free memory and reset for next loop */
1121
table->file->ha_reset();
1125
table->next=unused_tables; /* Link in last */
1126
table->prev=unused_tables->prev;
1127
unused_tables->prev=table;
1128
table->prev->next=table;
1131
unused_tables=table->next=table->prev=table;
1133
return(found_old_table);
1137
/* close_temporary_tables' internal, 4 is due to uint4korr definition */
1138
static inline uint tmpkeyval(THD *thd __attribute__((__unused__)),
1141
return uint4korr(table->s->table_cache_key.str + table->s->table_cache_key.length - 4);
1146
Close all temporary tables created by 'CREATE TEMPORARY TABLE' for thread
1147
creates one DROP TEMPORARY TABLE binlog event for each pseudo-thread
1150
void close_temporary_tables(THD *thd)
1155
/* Assume thd->options has OPTION_QUOTE_SHOW_CREATE */
1156
bool was_quote_show= true;
1158
if (!thd->temporary_tables)
1161
if (!mysql_bin_log.is_open() || thd->current_stmt_binlog_row_based)
1164
for (table= thd->temporary_tables; table; table= tmp_next)
1166
tmp_next= table->next;
1167
close_temporary(table, 1, 1);
1169
thd->temporary_tables= 0;
1173
/* Better add "if exists", in case a RESET MASTER has been done */
1174
const char stub[]= "DROP /*!40005 TEMPORARY */ TABLE IF EXISTS ";
1175
uint stub_len= sizeof(stub) - 1;
1177
String s_query= String(buf, sizeof(buf), system_charset_info);
1178
bool found_user_tables= false;
1180
memcpy(buf, stub, stub_len);
1183
Insertion sort of temp tables by pseudo_thread_id to build ordered list
1184
of sublists of equal pseudo_thread_id
1187
for (prev_table= thd->temporary_tables, table= prev_table->next;
1189
prev_table= table, table= table->next)
1191
TABLE *prev_sorted /* same as for prev_table */, *sorted;
1192
if (is_user_table(table))
1194
if (!found_user_tables)
1195
found_user_tables= true;
1196
for (prev_sorted= NULL, sorted= thd->temporary_tables; sorted != table;
1197
prev_sorted= sorted, sorted= sorted->next)
1199
if (!is_user_table(sorted) ||
1200
tmpkeyval(thd, sorted) > tmpkeyval(thd, table))
1202
/* move into the sorted part of the list from the unsorted */
1203
prev_table->next= table->next;
1204
table->next= sorted;
1207
prev_sorted->next= table;
1211
thd->temporary_tables= table;
1220
/* We always quote db,table names though it is slight overkill */
1221
if (found_user_tables &&
1222
!(was_quote_show= test(thd->options & OPTION_QUOTE_SHOW_CREATE)))
1224
thd->options |= OPTION_QUOTE_SHOW_CREATE;
1227
/* scan sorted tmps to generate sequence of DROP */
1228
for (table= thd->temporary_tables; table; table= next)
1230
if (is_user_table(table))
1232
my_thread_id save_pseudo_thread_id= thd->variables.pseudo_thread_id;
1233
/* Set pseudo_thread_id to be that of the processed table */
1234
thd->variables.pseudo_thread_id= tmpkeyval(thd, table);
1236
Loop forward through all tables within the sublist of
1237
common pseudo_thread_id to create single DROP query.
1239
for (s_query.length(stub_len);
1240
table && is_user_table(table) &&
1241
tmpkeyval(thd, table) == thd->variables.pseudo_thread_id;
1245
We are going to add 4 ` around the db/table names and possible more
1246
due to special characters in the names
1248
append_identifier(thd, &s_query, table->s->db.str, strlen(table->s->db.str));
1249
s_query.append('.');
1250
append_identifier(thd, &s_query, table->s->table_name.str,
1251
strlen(table->s->table_name.str));
1252
s_query.append(',');
1254
close_temporary(table, 1, 1);
1257
CHARSET_INFO *cs_save= thd->variables.character_set_client;
1258
thd->variables.character_set_client= system_charset_info;
1259
Query_log_event qinfo(thd, s_query.ptr(),
1260
s_query.length() - 1 /* to remove trailing ',' */,
1262
thd->variables.character_set_client= cs_save;
1264
Imagine the thread had created a temp table, then was doing a
1265
SELECT, and the SELECT was killed. Then it's not clever to
1266
mark the statement above as "killed", because it's not really
1267
a statement updating data, and there are 99.99% chances it
1268
will succeed on slave. If a real update (one updating a
1269
persistent table) was killed on the master, then this real
1270
update will be logged with error_code=killed, rightfully
1271
causing the slave to stop.
1273
qinfo.error_code= 0;
1274
mysql_bin_log.write(&qinfo);
1275
thd->variables.pseudo_thread_id= save_pseudo_thread_id;
1280
close_temporary(table, 1, 1);
1283
if (!was_quote_show)
1284
thd->options&= ~OPTION_QUOTE_SHOW_CREATE; /* restore option */
1285
thd->temporary_tables=0;
403
1289
Find table in list.
407
table Pointer to table list
408
offset Offset to which list in table structure to use
409
db_name Data base name
410
table_name Table name
413
This is called by find_table_in_global_list().
417
# Pointer to found table.
1292
find_table_in_list()
1293
table Pointer to table list
1294
offset Offset to which list in table structure to use
1295
db_name Data base name
1296
table_name Table name
1299
This is called by find_table_in_local_list() and
1300
find_table_in_global_list().
1303
NULL Table not found
1304
# Pointer to found table.
420
TableList *find_table_in_list(TableList *table,
421
TableList *TableList::*link,
423
const char *table_name)
1307
TABLE_LIST *find_table_in_list(TABLE_LIST *table,
1308
TABLE_LIST *TABLE_LIST::*link,
1309
const char *db_name,
1310
const char *table_name)
425
1312
for (; table; table= table->*link )
427
if ((table->table == 0 || table->table->getShare()->getType() == message::Table::STANDARD) and
428
my_strcasecmp(system_charset_info, table->getSchemaName(), db_name) == 0 and
429
my_strcasecmp(system_charset_info, table->getTableName(), table_name) == 0)
1314
if ((table->table == 0 || table->table->s->tmp_table == NO_TMP_TABLE) &&
1315
strcmp(table->db, db_name) == 0 &&
1316
strcmp(table->table_name, table_name) == 0)
524
void Open_tables_state::doGetTableNames(const identifier::Schema &schema_identifier,
525
std::set<std::string>& set_of_names)
527
for (Table *table= getTemporaryTables() ; table ; table= table->getNext())
529
if (schema_identifier.compare(table->getShare()->getSchemaName()))
531
set_of_names.insert(table->getShare()->getTableName());
536
void Open_tables_state::doGetTableNames(CachedDirectory &,
537
const identifier::Schema &schema_identifier,
538
std::set<std::string> &set_of_names)
540
doGetTableNames(schema_identifier, set_of_names);
543
void Open_tables_state::doGetTableIdentifiers(const identifier::Schema &schema_identifier,
544
identifier::Table::vector &set_of_identifiers)
546
for (Table *table= getTemporaryTables() ; table ; table= table->getNext())
548
if (schema_identifier.compare(table->getShare()->getSchemaName()))
550
set_of_identifiers.push_back(identifier::Table(table->getShare()->getSchemaName(),
551
table->getShare()->getTableName(),
552
table->getShare()->getPath()));
557
void Open_tables_state::doGetTableIdentifiers(CachedDirectory &,
558
const identifier::Schema &schema_identifier,
559
identifier::Table::vector &set_of_identifiers)
561
doGetTableIdentifiers(schema_identifier, set_of_identifiers);
564
bool Open_tables_state::doDoesTableExist(const identifier::Table &identifier)
566
for (Table *table= getTemporaryTables() ; table ; table= table->getNext())
568
if (table->getShare()->getType() == message::Table::TEMPORARY)
570
if (identifier.getKey() == table->getShare()->getCacheKey())
580
int Open_tables_state::doGetTableDefinition(const identifier::Table &identifier,
581
message::Table &table_proto)
583
for (Table *table= getTemporaryTables() ; table ; table= table->getNext())
585
if (table->getShare()->getType() == message::Table::TEMPORARY)
587
if (identifier.getKey() == table->getShare()->getCacheKey())
589
table_proto.CopyFrom(*(table->getShare()->getTableMessage()));
599
Table *Open_tables_state::find_temporary_table(const identifier::Table &identifier)
601
for (Table *table= temporary_tables ; table ; table= table->getNext())
603
if (identifier.getKey() == table->getShare()->getCacheKey())
607
return NULL; // Not a temporary table
1413
Issue correct error message in case we found 2 duplicate tables which
1414
prevent some update operation
1417
update_non_unique_table_error()
1418
update table which we try to update
1419
operation name of update operation
1420
duplicate duplicate table which we found
1423
here we hide view underlying tables if we have them
1426
void update_non_unique_table_error(TABLE_LIST *update,
1427
const char *operation __attribute__((__unused__)),
1428
TABLE_LIST *duplicate __attribute__((__unused__)))
1430
my_error(ER_UPDATE_TABLE_USED, MYF(0), update->alias);
1434
TABLE *find_temporary_table(THD *thd, const char *db, const char *table_name)
1436
TABLE_LIST table_list;
1438
table_list.db= (char*) db;
1439
table_list.table_name= (char*) table_name;
1440
return find_temporary_table(thd, &table_list);
1444
TABLE *find_temporary_table(THD *thd, TABLE_LIST *table_list)
1446
char key[MAX_DBKEY_LENGTH];
1450
key_length= create_table_def_key(thd, key, table_list, 1);
1451
for (table=thd->temporary_tables ; table ; table= table->next)
1453
if (table->s->table_cache_key.length == key_length &&
1454
!memcmp(table->s->table_cache_key.str, key, key_length))
1457
return(0); // Not a temporary table
612
1462
Drop a temporary table.
614
Try to locate the table in the list of session->temporary_tables.
1464
Try to locate the table in the list of thd->temporary_tables.
615
1465
If the table is found:
616
- if the table is being used by some outer statement, fail.
617
- if the table is in session->locked_tables, unlock it and
618
remove it from the list of locked tables. Currently only transactional
619
temporary tables are present in the locked_tables list.
620
- Close the temporary table, remove its .FRM
621
- remove the table from the list of temporary tables
1466
- if the table is being used by some outer statement, fail.
1467
- if the table is in thd->locked_tables, unlock it and
1468
remove it from the list of locked tables. Currently only transactional
1469
temporary tables are present in the locked_tables list.
1470
- Close the temporary table, remove its .FRM
1471
- remove the table from the list of temporary tables
623
1473
This function is used to drop user temporary tables, as well as
624
1474
internal tables created in CREATE TEMPORARY TABLE ... SELECT
625
or ALTER Table. Even though part of the work done by this function
1475
or ALTER TABLE. Even though part of the work done by this function
626
1476
is redundant when the table is internal, as long as we
627
1477
link both internal and user temporary tables into the same
628
session->temporary_tables list, it's impossible to tell here whether
1478
thd->temporary_tables list, it's impossible to tell here whether
629
1479
we're dealing with an internal or a user temporary table.
631
1481
@retval 0 the table was found and dropped successfully.
632
1482
@retval 1 the table was not found in the list of temporary tables
634
1484
@retval -1 the table is in use by a outer query
637
int Open_tables_state::drop_temporary_table(const drizzled::identifier::Table &identifier)
1487
int drop_temporary_table(THD *thd, TABLE_LIST *table_list)
641
if (not (table= find_temporary_table(identifier)))
1491
if (!(table= find_temporary_table(thd, table_list)))
644
1494
/* Table might be in use by some outer statement. */
645
if (table->query_id && table->query_id != getQueryId())
647
my_error(ER_CANT_REOPEN_TABLE, MYF(0), table->getAlias());
651
close_temporary_table(table);
1495
if (table->query_id && table->query_id != thd->query_id)
1497
my_error(ER_CANT_REOPEN_TABLE, MYF(0), table->alias);
1502
If LOCK TABLES list is not empty and contains this table,
1503
unlock the table and remove the table from this list.
1505
mysql_lock_remove(thd, thd->locked_tables, table, false);
1506
close_temporary_table(thd, table, 1, 1);
1511
unlink from thd->temporary tables and close temporary table
1514
void close_temporary_table(THD *thd, TABLE *table,
1515
bool free_share, bool delete_table)
1519
table->prev->next= table->next;
1520
if (table->prev->next)
1521
table->next->prev= table->prev;
1525
/* removing the item from the list */
1526
assert(table == thd->temporary_tables);
1528
slave must reset its temporary list pointer to zero to exclude
1529
passing non-zero value to end_slave via rli->save_temporary_tables
1530
when no temp tables opened, see an invariant below.
1532
thd->temporary_tables= table->next;
1533
if (thd->temporary_tables)
1534
table->next->prev= 0;
1536
if (thd->slave_thread)
1538
/* natural invariant of temporary_tables */
1539
assert(slave_open_temp_tables || !thd->temporary_tables);
1540
slave_open_temp_tables--;
1542
close_temporary(table, free_share, delete_table);
1548
Close and delete a temporary table
1551
This dosn't unlink table from thd->temporary
1552
If this is needed, use close_temporary_table()
1555
void close_temporary(TABLE *table, bool free_share, bool delete_table)
1557
handlerton *table_type= table->s->db_type();
1559
free_io_cache(table);
1562
Check that temporary table has not been created with
1563
frm_only because it has then not been created in any storage engine
1566
rm_temporary_table(table_type, table->s->path.str,
1567
table->s->tmp_table == TMP_TABLE_FRM_FILE_ONLY);
1570
free_table_share(table->s);
1571
my_free((char*) table,MYF(0));
1578
Used by ALTER TABLE when the table is a temporary one. It changes something
1579
only if the ALTER contained a RENAME clause (otherwise, table_name is the old
1581
Prepares a table cache key, which is the concatenation of db, table_name and
1582
thd->slave_proxy_id, separated by '\0'.
1585
bool rename_temporary_table(THD* thd, TABLE *table, const char *db,
1586
const char *table_name)
1590
TABLE_SHARE *share= table->s;
1591
TABLE_LIST table_list;
1593
if (!(key=(char*) alloc_root(&share->mem_root, MAX_DBKEY_LENGTH)))
1594
return(1); /* purecov: inspected */
1596
table_list.db= (char*) db;
1597
table_list.table_name= (char*) table_name;
1598
key_length= create_table_def_key(thd, key, &table_list, 1);
1599
share->set_table_cache_key(key, key_length);
1604
/* move table first in unused links */
1606
static void relink_unused(TABLE *table)
1608
if (table != unused_tables)
1610
table->prev->next=table->next; /* Remove from unused list */
1611
table->next->prev=table->prev;
1612
table->next=unused_tables; /* Link in unused tables */
1613
table->prev=unused_tables->prev;
1614
unused_tables->prev->next=table;
1615
unused_tables->prev=table;
1616
unused_tables=table;
658
Remove all instances of table from thread's open list and
661
@param session Thread context
662
@param find Table to remove
664
@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.
1622
Remove all instances of table from thread's open list and
1625
@param thd Thread context
1626
@param find Table to remove
1627
@param unlock true - free all locks on tables removed that are
1628
done with LOCK TABLES
1631
@note When unlock parameter is false or current thread doesn't have
1632
any tables locked with LOCK TABLES, tables are assumed to be
1633
not locked (for example already unlocked).
667
void Session::unlink_open_table(Table *find)
1636
void unlink_open_table(THD *thd, TABLE *find, bool unlock)
669
const identifier::Table::Key find_key(find->getShare()->getCacheKey());
671
safe_mutex_assert_owner(table::Cache::singleton().mutex().native_handle());
1638
char key[MAX_DBKEY_LENGTH];
1639
uint key_length= find->s->table_cache_key.length;
1640
TABLE *list, **prev;
1642
safe_mutex_assert_owner(&LOCK_open);
1644
memcpy(key, find->s->table_cache_key.str, key_length);
674
Note that we need to hold table::Cache::singleton().mutex() while changing the
1646
Note that we need to hold LOCK_open while changing the
675
1647
open_tables list. Another thread may work on it.
676
(See: table::Cache::singleton().removeTable(), wait_completed_table())
1648
(See: remove_table_from_cache(), mysql_wait_completed_table())
677
1649
Closing a MERGE child before the parent would be fatal if the
678
1650
other thread tries to abort the MERGE lock in between.
680
for (prev= &open_tables; *prev; )
1652
for (prev= &thd->open_tables; *prev; )
684
if (list->getShare()->getCacheKey() == find_key)
1656
if (list->s->table_cache_key.length == key_length &&
1657
!memcmp(list->s->table_cache_key.str, key, key_length))
1659
if (unlock && thd->locked_tables)
1660
mysql_lock_remove(thd, thd->locked_tables, list, true);
686
1662
/* Remove table from open_tables list. */
687
*prev= list->getNext();
689
1664
/* Close table. */
690
table::remove_table(static_cast<table::Concurrent *>(list));
1665
VOID(hash_delete(&open_cache,(uchar*) list)); // Close table
694
1669
/* Step to next entry in open_tables list. */
695
prev= list->getNextPtr();
699
1674
// Notify any 'refresh' threads
700
locking::broadcast_refresh();
1675
broadcast_refresh();
705
Auxiliary routine which closes and drops open table.
707
@param session Thread handle
708
@param table Table object for table to be dropped
709
@param db_name Name of database for this table
710
@param table_name Name of this table
712
@note This routine assumes that table to be closed is open only
713
by calling thread so we needn't wait until other threads
714
will close the table. Also unless called under implicit or
715
explicit LOCK TABLES mode it assumes that table to be
716
dropped is already unlocked. In the former case it will
717
also remove lock on the table. But one should not rely on
718
this behaviour as it may change in future.
719
Currently, however, this function is never called for a
720
table that was locked with LOCK TABLES.
1681
Auxiliary routine which closes and drops open table.
1683
@param thd Thread handle
1684
@param table TABLE object for table to be dropped
1685
@param db_name Name of database for this table
1686
@param table_name Name of this table
1688
@note This routine assumes that table to be closed is open only
1689
by calling thread so we needn't wait until other threads
1690
will close the table. Also unless called under implicit or
1691
explicit LOCK TABLES mode it assumes that table to be
1692
dropped is already unlocked. In the former case it will
1693
also remove lock on the table. But one should not rely on
1694
this behaviour as it may change in future.
1695
Currently, however, this function is never called for a
1696
table that was locked with LOCK TABLES.
723
void Session::drop_open_table(Table *table, const identifier::Table &identifier)
1699
void drop_open_table(THD *thd, TABLE *table, const char *db_name,
1700
const char *table_name)
725
if (table->getShare()->getType())
727
close_temporary_table(table);
1702
if (table->s->tmp_table)
1703
close_temporary_table(thd, table, 1, 1);
731
boost_unique_lock_t scoped_lock(table::Cache::singleton().mutex()); /* Close and drop a table (AUX routine) */
1706
handlerton *table_type= table->s->db_type();
1707
VOID(pthread_mutex_lock(&LOCK_open));
733
1709
unlink_open_table() also tells threads waiting for refresh or close
734
1710
that something has happened.
736
unlink_open_table(table);
737
(void)plugin::StorageEngine::dropTable(*this, identifier);
1712
unlink_open_table(thd, table, false);
1713
quick_rm_table(table_type, db_name, table_name, 0);
1714
VOID(pthread_mutex_unlock(&LOCK_open));
743
Wait for condition but allow the user to send a kill to mysqld
1720
Wait for condition but allow the user to send a kill to mysqld
747
session Thread Cursor
748
mutex mutex that is currently hold that is associated with condition
749
Will be unlocked on return
750
cond Condition to wait for
1723
wait_for_condition()
1725
mutex mutex that is currently hold that is associated with condition
1726
Will be unlocked on return
1727
cond Condition to wait for
753
void Session::wait_for_condition(boost::mutex &mutex, boost::condition_variable_any &cond)
1730
void wait_for_condition(THD *thd, pthread_mutex_t *mutex, pthread_cond_t *cond)
755
1732
/* Wait until the current table is up to date */
756
const char *saved_proc_info;
757
mysys_var->current_mutex= &mutex;
758
mysys_var->current_cond= &cond;
759
saved_proc_info= get_proc_info();
760
set_proc_info("Waiting for table");
763
We must unlock mutex first to avoid deadlock becasue conditions are
764
sent to this thread by doing locks in the following order:
765
lock(mysys_var->mutex)
766
lock(mysys_var->current_mutex)
768
One by effect of this that one can only use wait_for_condition with
769
condition variables that are guranteed to not disapper (freed) even if this
772
boost_unique_lock_t scopedLock(mutex, boost::adopt_lock_t());
775
cond.wait(scopedLock);
778
boost_unique_lock_t mysys_scopedLock(mysys_var->mutex);
779
mysys_var->current_mutex= 0;
780
mysys_var->current_cond= 0;
781
set_proc_info(saved_proc_info);
786
Create and insert into table cache placeholder for table
787
which will prevent its opening (or creation) (a.k.a lock
790
@param session Thread context
791
@param key Table cache key for name to be locked
792
@param key_length Table cache key length
794
@return Pointer to Table object used for name locking or 0 in
798
table::Placeholder *Session::table_cache_insert_placeholder(const drizzled::identifier::Table &arg)
800
safe_mutex_assert_owner(table::Cache::singleton().mutex().native_handle());
1733
const char *proc_info;
1734
thd->mysys_var->current_mutex= mutex;
1735
thd->mysys_var->current_cond= cond;
1736
proc_info=thd->proc_info;
1737
thd_proc_info(thd, "Waiting for table");
1739
(void) pthread_cond_wait(cond, mutex);
1742
We must unlock mutex first to avoid deadlock becasue conditions are
1743
sent to this thread by doing locks in the following order:
1744
lock(mysys_var->mutex)
1745
lock(mysys_var->current_mutex)
1747
One by effect of this that one can only use wait_for_condition with
1748
condition variables that are guranteed to not disapper (freed) even if this
1752
pthread_mutex_unlock(mutex);
1753
pthread_mutex_lock(&thd->mysys_var->mutex);
1754
thd->mysys_var->current_mutex= 0;
1755
thd->mysys_var->current_cond= 0;
1756
thd_proc_info(thd, proc_info);
1757
pthread_mutex_unlock(&thd->mysys_var->mutex);
1763
Exclusively name-lock a table that is already write-locked by the
1766
@param thd current thread context
1767
@param tables table list containing one table to open.
1769
@return false on success, true otherwise.
1772
bool name_lock_locked_table(THD *thd, TABLE_LIST *tables)
1774
/* Under LOCK TABLES we must only accept write locked tables. */
1775
tables->table= find_locked_table(thd, tables->db, tables->table_name);
1778
my_error(ER_TABLE_NOT_LOCKED, MYF(0), tables->alias);
1779
else if (tables->table->reginfo.lock_type < TL_WRITE_LOW_PRIORITY)
1780
my_error(ER_TABLE_NOT_LOCKED_FOR_WRITE, MYF(0), tables->alias);
1784
Ensures that table is opened only by this thread and that no
1785
other statement will open this table.
1787
wait_while_table_is_used(thd, tables->table, HA_EXTRA_FORCE_REOPEN);
1796
Open table which is already name-locked by this thread.
1799
reopen_name_locked_table()
1801
table_list TABLE_LIST object for table to be open, TABLE_LIST::table
1802
member should point to TABLE object which was used for
1804
link_in true - if TABLE object for table to be opened should be
1805
linked into THD::open_tables list.
1806
false - placeholder used for name-locking is already in
1807
this list so we only need to preserve TABLE::next
1811
This function assumes that its caller already acquired LOCK_open mutex.
1818
bool reopen_name_locked_table(THD* thd, TABLE_LIST* table_list, bool link_in)
1820
TABLE *table= table_list->table;
1822
char *table_name= table_list->table_name;
1825
safe_mutex_assert_owner(&LOCK_open);
1827
if (thd->killed || !table)
1832
if (open_unireg_entry(thd, table, table_list, table_name,
1833
table->s->table_cache_key.str,
1834
table->s->table_cache_key.length, thd->mem_root, 0))
1836
intern_close_table(table);
1838
If there was an error during opening of table (for example if it
1839
does not exist) '*table' object can be wiped out. To be able
1840
properly release name-lock in this case we should restore this
1841
object to its original state.
1849
We want to prevent other connections from opening this table until end
1850
of statement as it is likely that modifications of table's metadata are
1851
not yet finished (for example CREATE TRIGGER have to change .TRG file,
1852
or we might want to drop table if CREATE TABLE ... SELECT fails).
1853
This also allows us to assume that no other connection will sneak in
1854
before we will get table-level lock on this table.
1857
table->in_use = thd;
1861
table->next= thd->open_tables;
1862
thd->open_tables= table;
1867
TABLE object should be already in THD::open_tables list so we just
1868
need to set TABLE::next correctly.
1870
table->next= orig_table.next;
1873
table->tablenr=thd->current_tablenr++;
1874
table->used_fields=0;
1875
table->const_table=0;
1876
table->null_row= table->maybe_null= table->force_index= 0;
1877
table->status=STATUS_NO_RECORD;
1883
Create and insert into table cache placeholder for table
1884
which will prevent its opening (or creation) (a.k.a lock
1887
@param thd Thread context
1888
@param key Table cache key for name to be locked
1889
@param key_length Table cache key length
1891
@return Pointer to TABLE object used for name locking or 0 in
1895
TABLE *table_cache_insert_placeholder(THD *thd, const char *key,
1902
safe_mutex_assert_owner(&LOCK_open);
803
1905
Create a table entry with the right key and with an old refresh version
1906
Note that we must use my_multi_malloc() here as this is freed by the
805
identifier::Table identifier(arg.getSchemaName(), arg.getTableName(), message::Table::INTERNAL);
806
table::Placeholder *table= new table::Placeholder(this, identifier);
808
if (not table::Cache::singleton().insert(table))
1909
if (!my_multi_malloc(MYF(MY_WME | MY_ZEROFILL),
1910
&table, sizeof(*table),
1911
&share, sizeof(*share),
1912
&key_buff, key_length,
1917
share->set_table_cache_key(key_buff, key, key_length);
1918
share->tmp_table= INTERNAL_TMP_TABLE; // for intern_close_table
1920
table->locked_by_name=1;
1922
if (my_hash_insert(&open_cache, (uchar*)table))
1924
my_free((uchar*) table, MYF(0));
820
Obtain an exclusive name lock on the table if it is not cached
823
@param session Thread context
824
@param db Name of database
825
@param table_name Name of table
826
@param[out] table Out parameter which is either:
827
- set to NULL if table cache contains record for
829
- set to point to the Table instance used for
832
@note This function takes into account all records for table in table
833
cache, even placeholders used for name-locking. This means that
834
'table' parameter can be set to NULL for some situations when
835
table does not really exist.
837
@retval true Error occured (OOM)
838
@retval false Success. 'table' parameter set according to above rules.
1933
Obtain an exclusive name lock on the table if it is not cached
1936
@param thd Thread context
1937
@param db Name of database
1938
@param table_name Name of table
1939
@param[out] table Out parameter which is either:
1940
- set to NULL if table cache contains record for
1942
- set to point to the TABLE instance used for
1945
@note This function takes into account all records for table in table
1946
cache, even placeholders used for name-locking. This means that
1947
'table' parameter can be set to NULL for some situations when
1948
table does not really exist.
1950
@retval true Error occured (OOM)
1951
@retval false Success. 'table' parameter set according to above rules.
840
bool Session::lock_table_name_if_not_cached(const identifier::Table &identifier, Table **table)
1954
bool lock_table_name_if_not_cached(THD *thd, const char *db,
1955
const char *table_name, TABLE **table)
842
const identifier::Table::Key &key(identifier.getKey());
844
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) */
846
table::CacheMap::iterator iter;
848
iter= table::getCache().find(key);
850
if (iter != table::getCache().end())
1957
char key[MAX_DBKEY_LENGTH];
1960
key_length= (uint)(strmov(strmov(key, db) + 1, table_name) - key) + 1;
1961
VOID(pthread_mutex_lock(&LOCK_open));
1963
if (hash_search(&open_cache, (uchar *)key, key_length))
1965
VOID(pthread_mutex_unlock(&LOCK_open));
856
if (not (*table= table_cache_insert_placeholder(identifier)))
860
(*table)->open_placeholder= true;
861
(*table)->setNext(open_tables);
1969
if (!(*table= table_cache_insert_placeholder(thd, key, key_length)))
1971
VOID(pthread_mutex_unlock(&LOCK_open));
1974
(*table)->open_placeholder= 1;
1975
(*table)->next= thd->open_tables;
1976
thd->open_tables= *table;
1977
VOID(pthread_mutex_unlock(&LOCK_open));
1983
Check that table exists in table definition cache, on disk
1984
or in some storage engine.
1986
@param thd Thread context
1987
@param table Table list element
1988
@param[out] exists Out parameter which is set to true if table
1989
exists and to false otherwise.
1991
@note This function assumes that caller owns LOCK_open mutex.
1992
It also assumes that the fact that there are no name-locks
1993
on the table was checked beforehand.
1995
@note If there is no .FRM file for the table but it exists in one
1996
of engines (e.g. it was created on another node of NDB cluster)
1997
this function will fetch and create proper .FRM file for it.
1999
@retval true Some error occured
2000
@retval false No error. 'exists' out parameter set accordingly.
2003
bool check_if_table_exists(THD *thd, TABLE_LIST *table, bool *exists)
2005
char path[FN_REFLEN];
2008
safe_mutex_assert_owner(&LOCK_open);
2012
if (get_cached_table_share(table->db, table->table_name))
2015
build_table_filename(path, sizeof(path) - 1, table->db, table->table_name,
2018
if (!access(path, F_OK))
2021
/* .FRM file doesn't exist. Check if some engine can provide it. */
2023
rc= ha_create_table_from_engine(thd, table->db, table->table_name);
2027
/* Table does not exists in engines as well. */
2033
/* Table exists in some engine and .FRM for it was created. */
2038
my_printf_error(ER_UNKNOWN_ERROR, "Failed to open '%-.64s', error while "
2039
"unpacking from engine", MYF(0), table->table_name);
872
session Thread context.
873
table_list Open first table in list.
874
refresh INOUT Pointer to memory that will be set to 1 if
875
we need to close all tables and reopen them.
876
If this is a NULL pointer, then the table is not
877
put in the thread-open-list.
878
flags Bitmap of flags to modify how open works:
879
DRIZZLE_LOCK_IGNORE_FLUSH - Open table even if
880
someone has done a flush or namelock on it.
881
No version number checking is done.
882
DRIZZLE_OPEN_TEMPORARY_ONLY - Open only temporary
883
table not the base table or view.
2051
table_list Open first table in list.
2052
refresh INOUT Pointer to memory that will be set to 1 if
2053
we need to close all tables and reopen them.
2054
If this is a NULL pointer, then the table is not
2055
put in the thread-open-list.
2056
flags Bitmap of flags to modify how open works:
2057
MYSQL_LOCK_IGNORE_FLUSH - Open table even if
2058
someone has done a flush or namelock on it.
2059
No version number checking is done.
2060
MYSQL_OPEN_TEMPORARY_ONLY - Open only temporary
2061
table not the base table or view.
886
Uses a cache of open tables to find a table not in use.
2064
Uses a cache of open tables to find a table not in use.
888
If table list element for the table to be opened has "create" flag
889
set and table does not exist, this function will automatically insert
890
a placeholder for exclusive name lock into the open tables cache and
891
will return the Table instance that corresponds to this placeholder.
2066
If table list element for the table to be opened has "create" flag
2067
set and table does not exist, this function will automatically insert
2068
a placeholder for exclusive name lock into the open tables cache and
2069
will return the TABLE instance that corresponds to this placeholder.
894
NULL Open failed. If refresh is set then one should close
895
all other tables and retry the open.
896
# Success. Pointer to Table object for open table.
2072
NULL Open failed. If refresh is set then one should close
2073
all other tables and retry the open.
2074
# Success. Pointer to TABLE object for open table.
900
Table *Session::openTable(TableList *table_list, bool *refresh, uint32_t flags)
2078
TABLE *open_table(THD *thd, TABLE_LIST *table_list, MEM_ROOT *mem_root,
2079
bool *refresh, uint flags)
903
const char *alias= table_list->alias;
2081
register TABLE *table;
2082
char key[MAX_DBKEY_LENGTH];
2083
unsigned int key_length;
2084
char *alias= table_list->alias;
2085
HASH_SEARCH_STATE state;
905
/* Parsing of partitioning information from .frm needs session->lex set up. */
906
assert(lex->is_lex_started);
2087
/* Parsing of partitioning information from .frm needs thd->lex set up. */
2088
assert(thd->lex->is_lex_started);
908
2090
/* find a unused table in the open table cache */
912
2094
/* an open table operation needs a lot of the stack space */
913
if (check_stack_overrun(this, STACK_MIN_SIZE_FOR_OPEN, (unsigned char *)&alias))
919
identifier::Table identifier(table_list->getSchemaName(), table_list->getTableName());
920
const identifier::Table::Key &key(identifier.getKey());
921
table::CacheRange ppp;
2095
if (check_stack_overrun(thd, STACK_MIN_SIZE_FOR_OPEN, (uchar *)&alias))
2101
key_length= (create_table_def_key(thd, key, table_list, 1) -
2102
TMP_TABLE_KEY_EXTRA);
924
2105
Unless requested otherwise, try to resolve this table in the list
925
2106
of temporary tables of this thread. In MySQL temporary tables
926
2107
are always thread-local and "shadow" possible base tables with the
927
2108
same name. This block implements the behaviour.
928
TODO -> move this block into a separate function.
2109
TODO: move this block into a separate function.
931
for (table= getTemporaryTables(); table ; table=table->getNext())
933
if (table->getShare()->getCacheKey() == key)
936
We're trying to use the same temporary table twice in a query.
937
Right now we don't support this because a temporary table
938
is always represented by only one Table object in Session, and
939
it can not be cloned. Emit an error for an unsupported behaviour.
943
my_error(ER_CANT_REOPEN_TABLE, MYF(0), table->getAlias());
946
table->query_id= getQueryId();
954
if (flags & DRIZZLE_OPEN_TEMPORARY_ONLY)
956
my_error(ER_TABLE_UNKNOWN, identifier);
961
If it's the first table from a list of tables used in a query,
962
remember refresh_version (the version of open_cache state).
963
If the version changes while we're opening the remaining tables,
964
we will have to back off, close all the tables opened-so-far,
965
and try to reopen them.
967
Note-> refresh_version is currently changed only during FLUSH TABLES.
971
version= refresh_version;
973
else if ((version != refresh_version) &&
974
! (flags & DRIZZLE_LOCK_IGNORE_FLUSH))
976
/* Someone did a refresh while thread was opening tables */
984
Before we test the global cache, we test our local session cache.
988
assert(false); /* Not implemented yet */
992
Non pre-locked/LOCK TABLES mode, and the table is not temporary:
993
this is the normal use case.
995
- try to find the table in the table cache.
996
- if one of the discovered Table instances is name-locked
997
(table->getShare()->version == 0) back off -- we have to wait
998
until no one holds a name lock on the table.
999
- if there is no such Table in the name cache, read the table definition
1000
and insert it into the cache.
1001
We perform all of the above under table::Cache::singleton().mutex() which currently protects
1002
the open cache (also known as table cache) and table definitions stored
1007
boost::mutex::scoped_lock scopedLock(table::Cache::singleton().mutex());
1010
Actually try to find the table in the open_cache.
1011
The cache may contain several "Table" instances for the same
1012
physical table. The instances that are currently "in use" by
1013
some thread have their "in_use" member != NULL.
1014
There is no good reason for having more than one entry in the
1015
hash for the same physical table, except that we use this as
1016
an implicit "pending locks queue" - see
1017
wait_for_locked_table_names for details.
1019
ppp= table::getCache().equal_range(key);
1022
for (table::CacheMap::const_iterator iter= ppp.first;
1023
iter != ppp.second; ++iter, table= NULL)
1025
table= (*iter).second;
1027
if (not table->in_use)
2112
for (table= thd->temporary_tables; table ; table=table->next)
2114
if (table->s->table_cache_key.length == key_length +
2115
TMP_TABLE_KEY_EXTRA &&
2116
!memcmp(table->s->table_cache_key.str, key,
2117
key_length + TMP_TABLE_KEY_EXTRA))
1030
Here we flush tables marked for flush.
1031
Normally, table->getShare()->version contains the value of
1032
refresh_version from the moment when this table was
1033
(re-)opened and added to the cache.
1034
If since then we did (or just started) FLUSH TABLES
1035
statement, refresh_version has been increased.
1036
For "name-locked" Table instances, table->getShare()->version is set
1037
to 0 (see lock_table_name for details).
1038
In case there is a pending FLUSH TABLES or a name lock, we
1039
need to back off and re-start opening tables.
1040
If we do not back off now, we may dead lock in case of lock
1041
order mismatch with some other thread:
1042
c1-> name lock t1; -- sort of exclusive lock
1043
c2-> open t2; -- sort of shared lock
1044
c1-> name lock t2; -- blocks
1045
c2-> open t1; -- blocks
2120
We're trying to use the same temporary table twice in a query.
2121
Right now we don't support this because a temporary table
2122
is always represented by only one TABLE object in THD, and
2123
it can not be cloned. Emit an error for an unsupported behaviour.
1047
if (table->needs_reopen_or_name_lock())
2125
if (table->query_id)
2127
my_error(ER_CANT_REOPEN_TABLE, MYF(0), table->alias);
2130
table->query_id= thd->query_id;
2131
thd->thread_specific_used= true;
2137
if (flags & MYSQL_OPEN_TEMPORARY_ONLY)
2139
my_error(ER_NO_SUCH_TABLE, MYF(0), table_list->db, table_list->table_name);
2144
The table is not temporary - if we're in pre-locked or LOCK TABLES
2145
mode, let's try to find the requested table in the list of pre-opened
2146
and locked tables. If the table is not there, return an error - we can't
2147
open not pre-opened tables in pre-locked/LOCK TABLES mode.
2148
TODO: move this block into a separate function.
2150
if (thd->locked_tables)
2151
{ // Using table locks
2152
TABLE *best_table= 0;
2153
int best_distance= INT_MIN;
2154
bool check_if_used= false;
2155
for (table=thd->open_tables; table ; table=table->next)
2157
if (table->s->table_cache_key.length == key_length &&
2158
!memcmp(table->s->table_cache_key.str, key, key_length))
2160
if (check_if_used && table->query_id &&
2161
table->query_id != thd->query_id)
1049
if (flags & DRIZZLE_LOCK_IGNORE_FLUSH)
1051
/* Force close at once after usage */
1052
version= table->getShare()->getVersion();
1056
/* Avoid self-deadlocks by detecting self-dependencies. */
1057
if (table->open_placeholder && table->in_use == this)
1059
my_error(ER_UPDATE_TABLE_USED, MYF(0), table->getShare()->getTableName());
1064
Back off, part 1: mark the table as "unused" for the
1065
purpose of name-locking by setting table->db_stat to 0. Do
1066
that only for the tables in this thread that have an old
1067
table->getShare()->version (this is an optimization (?)).
1068
table->db_stat == 0 signals wait_for_locked_table_names
1069
that the tables in question are not used any more. See
1070
table_is_used call for details.
1072
close_old_data_files(false, false);
1075
Back-off part 2: try to avoid "busy waiting" on the table:
1076
if the table is in use by some other thread, we suspend
1077
and wait till the operation is complete: when any
1078
operation that juggles with table->getShare()->version completes,
1079
it broadcasts COND_refresh condition variable.
1080
If 'old' table we met is in use by current thread we return
1081
without waiting since in this situation it's this thread
1082
which is responsible for broadcasting on COND_refresh
1083
(and this was done already in Session::close_old_data_files()).
1084
Good example of such situation is when we have statement
1085
that needs two instances of table and FLUSH TABLES comes
1086
after we open first instance but before we open second
1089
if (table->in_use != this)
1091
/* wait_for_conditionwill unlock table::Cache::singleton().mutex() for us */
1092
wait_for_condition(table::Cache::singleton().mutex(), COND_refresh);
1093
scopedLock.release();
1097
scopedLock.unlock();
1101
There is a refresh in progress for this table.
1102
Signal the caller that it has to try again.
2164
If we are in stored function or trigger we should ensure that
2165
we won't change table that is already used by calling statement.
2166
So if we are opening table for writing, we should check that it
2167
is not already open by some calling stamement.
2169
my_error(ER_CANT_UPDATE_USED_TABLE_IN_SF_OR_TRG, MYF(0),
2170
table->s->table_name.str);
1113
table::getUnused().unlink(static_cast<table::Concurrent *>(table));
1114
table->in_use= this;
1118
/* Insert a new Table instance into the open cache */
1120
/* Free cache if too big */
1121
table::getUnused().cull();
1123
if (table_list->isCreate())
2174
When looking for a usable TABLE, ignore MERGE children, as they
2175
belong to their parent and cannot be used explicitly.
2177
if (!my_strcasecmp(system_charset_info, table->alias, alias) &&
2178
table->query_id != thd->query_id) /* skip tables already used */
1125
identifier::Table lock_table_identifier(table_list->getSchemaName(), table_list->getTableName(), message::Table::STANDARD);
2180
int distance= ((int) table->reginfo.lock_type -
2181
(int) table_list->lock_type);
2183
Find a table that either has the exact lock type requested,
2184
or has the best suitable lock. In case there is no locked
2185
table that has an equal or higher lock than requested,
2186
we us the closest matching lock to be able to produce an error
2187
message about wrong lock mode on the table. The best_table
2188
is changed if bd < 0 <= d or bd < d < 0 or 0 <= d < bd.
1127
if (not plugin::StorageEngine::doesTableExist(*this, lock_table_identifier))
2190
distance < 0 - No suitable lock found
2191
distance > 0 - we have lock mode higher then we require
2192
distance == 0 - we have lock mode exactly which we need
2194
if ((best_distance < 0 && distance > best_distance) || (distance >= 0 && distance < best_distance))
1130
Table to be created, so we need to create placeholder in table-cache.
1132
if (!(table= table_cache_insert_placeholder(lock_table_identifier)))
2196
best_distance= distance;
2198
if (best_distance == 0 && !check_if_used)
2201
If we have found perfect match and we don't need to check that
2202
table is not used by one of calling statements (assuming that
2203
we are inside of function or trigger) we can finish iterating
2204
through open tables list.
1137
Link placeholder to the open tables list so it will be automatically
1138
removed once tables are closed. Also mark it so it won't be ignored
1139
by other trying to take name-lock.
1141
table->open_placeholder= true;
1142
table->setNext(open_tables);
1147
/* Table exists. Let us try to open it. */
1150
/* make a new table */
1152
table::Concurrent *new_table= new table::Concurrent;
1154
if (new_table == NULL)
1159
error= new_table->open_unireg_entry(this, alias, identifier);
1165
(void)table::Cache::singleton().insert(new_table);
2215
table->query_id= thd->query_id;
2219
No table in the locked tables list. In case of explicit LOCK TABLES
2220
this can happen if a user did not include the able into the list.
2221
In case of pre-locked mode locked tables list is generated automatically,
2222
so we may only end up here if the table did not exist when
2223
locked tables list was created.
2225
my_error(ER_TABLE_NOT_LOCKED, MYF(0), alias);
2230
Non pre-locked/LOCK TABLES mode, and the table is not temporary:
2231
this is the normal use case.
2233
- try to find the table in the table cache.
2234
- if one of the discovered TABLE instances is name-locked
2235
(table->s->version == 0) or some thread has started FLUSH TABLES
2236
(refresh_version > table->s->version), back off -- we have to wait
2237
until no one holds a name lock on the table.
2238
- if there is no such TABLE in the name cache, read the table definition
2239
and insert it into the cache.
2240
We perform all of the above under LOCK_open which currently protects
2241
the open cache (also known as table cache) and table definitions stored
2245
VOID(pthread_mutex_lock(&LOCK_open));
2248
If it's the first table from a list of tables used in a query,
2249
remember refresh_version (the version of open_cache state).
2250
If the version changes while we're opening the remaining tables,
2251
we will have to back off, close all the tables opened-so-far,
2252
and try to reopen them.
2253
Note: refresh_version is currently changed only during FLUSH TABLES.
2255
if (!thd->open_tables)
2256
thd->version=refresh_version;
2257
else if ((thd->version != refresh_version) &&
2258
! (flags & MYSQL_LOCK_IGNORE_FLUSH))
2260
/* Someone did a refresh while thread was opening tables */
1172
table->setNext(open_tables); /* Link into simple list */
1175
table->reginfo.lock_type= TL_READ; /* Assume read */
1178
assert(table->getShare()->getTableCount() > 0 || table->getShare()->getType() != message::Table::STANDARD);
2263
VOID(pthread_mutex_unlock(&LOCK_open));
2268
In order for the back off and re-start process to work properly,
2269
handler tables having old versions (due to FLUSH TABLES or pending
2270
name-lock) MUST be closed. This is specially important if a name-lock
2271
is pending for any table of the handler_tables list, otherwise a
2274
if (thd->handler_tables)
2275
mysql_ha_flush(thd);
2278
Actually try to find the table in the open_cache.
2279
The cache may contain several "TABLE" instances for the same
2280
physical table. The instances that are currently "in use" by
2281
some thread have their "in_use" member != NULL.
2282
There is no good reason for having more than one entry in the
2283
hash for the same physical table, except that we use this as
2284
an implicit "pending locks queue" - see
2285
wait_for_locked_table_names for details.
2287
for (table= (TABLE*) hash_first(&open_cache, (uchar*) key, key_length,
2289
table && table->in_use ;
2290
table= (TABLE*) hash_next(&open_cache, (uchar*) key, key_length,
2294
Here we flush tables marked for flush.
2295
Normally, table->s->version contains the value of
2296
refresh_version from the moment when this table was
2297
(re-)opened and added to the cache.
2298
If since then we did (or just started) FLUSH TABLES
2299
statement, refresh_version has been increased.
2300
For "name-locked" TABLE instances, table->s->version is set
2301
to 0 (see lock_table_name for details).
2302
In case there is a pending FLUSH TABLES or a name lock, we
2303
need to back off and re-start opening tables.
2304
If we do not back off now, we may dead lock in case of lock
2305
order mismatch with some other thread:
2306
c1: name lock t1; -- sort of exclusive lock
2307
c2: open t2; -- sort of shared lock
2308
c1: name lock t2; -- blocks
2309
c2: open t1; -- blocks
2311
if (table->needs_reopen_or_name_lock())
2313
if (flags & MYSQL_LOCK_IGNORE_FLUSH)
2315
/* Force close at once after usage */
2316
thd->version= table->s->version;
2320
/* Avoid self-deadlocks by detecting self-dependencies. */
2321
if (table->open_placeholder && table->in_use == thd)
2323
VOID(pthread_mutex_unlock(&LOCK_open));
2324
my_error(ER_UPDATE_TABLE_USED, MYF(0), table->s->table_name.str);
2329
Back off, part 1: mark the table as "unused" for the
2330
purpose of name-locking by setting table->db_stat to 0. Do
2331
that only for the tables in this thread that have an old
2332
table->s->version (this is an optimization (?)).
2333
table->db_stat == 0 signals wait_for_locked_table_names
2334
that the tables in question are not used any more. See
2335
table_is_used call for details.
2337
Notice that HANDLER tables were already taken care of by
2338
the earlier call to mysql_ha_flush() in this same critical
2341
close_old_data_files(thd,thd->open_tables,0,0);
2343
Back-off part 2: try to avoid "busy waiting" on the table:
2344
if the table is in use by some other thread, we suspend
2345
and wait till the operation is complete: when any
2346
operation that juggles with table->s->version completes,
2347
it broadcasts COND_refresh condition variable.
2348
If 'old' table we met is in use by current thread we return
2349
without waiting since in this situation it's this thread
2350
which is responsible for broadcasting on COND_refresh
2351
(and this was done already in close_old_data_files()).
2352
Good example of such situation is when we have statement
2353
that needs two instances of table and FLUSH TABLES comes
2354
after we open first instance but before we open second
2357
if (table->in_use != thd)
2359
/* wait_for_conditionwill unlock LOCK_open for us */
2360
wait_for_condition(thd, &LOCK_open, &COND_refresh);
2364
VOID(pthread_mutex_unlock(&LOCK_open));
2367
There is a refresh in progress for this table.
2368
Signal the caller that it has to try again.
2377
/* Unlink the table from "unused_tables" list. */
2378
if (table == unused_tables)
2380
unused_tables=unused_tables->next; // Remove from link
2381
if (table == unused_tables)
2384
table->prev->next=table->next; /* Remove from unused list */
2385
table->next->prev=table->prev;
2390
/* Insert a new TABLE instance into the open cache */
2392
/* Free cache if too big */
2393
while (open_cache.records > table_cache_size && unused_tables)
2394
VOID(hash_delete(&open_cache,(uchar*) unused_tables)); /* purecov: tested */
2396
if (table_list->create)
2400
if (check_if_table_exists(thd, table_list, &exists))
2402
VOID(pthread_mutex_unlock(&LOCK_open));
2409
Table to be created, so we need to create placeholder in table-cache.
2411
if (!(table= table_cache_insert_placeholder(thd, key, key_length)))
2413
VOID(pthread_mutex_unlock(&LOCK_open));
2417
Link placeholder to the open tables list so it will be automatically
2418
removed once tables are closed. Also mark it so it won't be ignored
2419
by other trying to take name-lock.
2421
table->open_placeholder= 1;
2422
table->next= thd->open_tables;
2423
thd->open_tables= table;
2424
VOID(pthread_mutex_unlock(&LOCK_open));
2427
/* Table exists. Let us try to open it. */
2430
/* make a new table */
2431
if (!(table=(TABLE*) my_malloc(sizeof(*table),MYF(MY_WME))))
2433
VOID(pthread_mutex_unlock(&LOCK_open));
2437
error= open_unireg_entry(thd, table, table_list, alias, key, key_length,
2438
mem_root, (flags & OPEN_VIEW_NO_PARSE));
2439
/* Combine the follow two */
2442
my_free((uchar*)table, MYF(0));
2443
VOID(pthread_mutex_unlock(&LOCK_open));
2448
my_free((uchar*)table, MYF(0));
2449
VOID(pthread_mutex_unlock(&LOCK_open));
2452
VOID(my_hash_insert(&open_cache,(uchar*) table));
2455
VOID(pthread_mutex_unlock(&LOCK_open));
2458
table->next=thd->open_tables; /* Link into simple list */
2459
thd->open_tables=table;
2461
table->reginfo.lock_type=TL_READ; /* Assume read */
2464
assert(table->s->ref_count > 0 || table->s->tmp_table != NO_TMP_TABLE);
2466
if (thd->lex->need_correct_ident())
2467
table->alias_name_used= my_strcasecmp(table_alias_charset,
2468
table->s->table_name.str, alias);
1180
2469
/* Fix alias if table name changes */
1181
if (strcmp(table->getAlias(), alias))
2470
if (strcmp(table->alias, alias))
1183
table->setAlias(alias);
2472
uint length=(uint) strlen(alias)+1;
2473
table->alias= (char*) my_realloc((char*) table->alias, length,
2475
memcpy((char*) table->alias, alias, length);
1186
2477
/* These variables are also set in reopen_table() */
1187
table->tablenr= current_tablenr++;
1188
table->used_fields= 0;
1189
table->const_table= 0;
1190
table->null_row= false;
1191
table->maybe_null= false;
1192
table->force_index= false;
2478
table->tablenr=thd->current_tablenr++;
2479
table->used_fields=0;
2480
table->const_table=0;
2481
table->null_row= table->maybe_null= table->force_index= 0;
1193
2482
table->status=STATUS_NO_RECORD;
1194
table->insert_values.clear();
2483
table->insert_values= 0;
1195
2484
/* Catch wrong handling of the auto_increment_field_not_null. */
1196
2485
assert(!table->auto_increment_field_not_null);
1197
2486
table->auto_increment_field_not_null= false;
1198
2487
if (table->timestamp_field)
1200
2488
table->timestamp_field_type= table->timestamp_field->get_auto_set_type();
1202
2489
table->pos_in_table_list= table_list;
1203
2490
table->clear_column_bitmaps();
1204
2491
assert(table->key_read == 0);
2496
TABLE *find_locked_table(THD *thd, const char *db,const char *table_name)
2498
char key[MAX_DBKEY_LENGTH];
2499
uint key_length=(uint) (strmov(strmov(key,db)+1,table_name)-key)+1;
2501
for (TABLE *table=thd->open_tables; table ; table=table->next)
2503
if (table->s->table_cache_key.length == key_length &&
2504
!memcmp(table->s->table_cache_key.str, key, key_length))
2512
Reopen an table because the definition has changed.
2519
The data file for the table is already closed and the share is released
2520
The table has a 'dummy' share that mainly contains database and table name.
2524
1 error. The old table object is not changed.
2527
bool reopen_table(TABLE *table)
2533
TABLE_LIST table_list;
2534
THD *thd= table->in_use;
2536
assert(table->s->ref_count == 0);
2537
assert(!table->sort.io_cache);
2541
sql_print_error("Table %s had a open data handler in reopen_table",
2544
bzero((char*) &table_list, sizeof(TABLE_LIST));
2545
table_list.db= table->s->db.str;
2546
table_list.table_name= table->s->table_name.str;
2547
table_list.table= table;
2549
if (wait_for_locked_table_names(thd, &table_list))
2550
return(1); // Thread was killed
2552
if (open_unireg_entry(thd, &tmp, &table_list,
2554
table->s->table_cache_key.str,
2555
table->s->table_cache_key.length,
2559
/* This list copies variables set by open_table */
2560
tmp.tablenr= table->tablenr;
2561
tmp.used_fields= table->used_fields;
2562
tmp.const_table= table->const_table;
2563
tmp.null_row= table->null_row;
2564
tmp.maybe_null= table->maybe_null;
2565
tmp.status= table->status;
2567
tmp.s->table_map_id= table->s->table_map_id;
2571
tmp.reginfo.lock_type=table->reginfo.lock_type;
2573
/* Replace table in open list */
2574
tmp.next= table->next;
2575
tmp.prev= table->prev;
2578
VOID(closefrm(table, 1)); // close file, free everything
2581
table->default_column_bitmaps();
2582
table->file->change_table_ptr(table, table->s);
2584
assert(table->alias != 0);
2585
for (field=table->field ; *field ; field++)
2587
(*field)->table= (*field)->orig_table= table;
2588
(*field)->table_name= &table->alias;
2590
for (key=0 ; key < table->s->keys ; key++)
2592
for (part=0 ; part < table->key_info[key].usable_key_parts ; part++)
2593
table->key_info[key].key_part[part].field->table= table;
2596
Do not attach MERGE children here. The children might be reopened
2597
after the parent. Attach children after reopening all tables that
2598
require reopen. See for example reopen_tables().
2601
broadcast_refresh();
1211
Close all instances of a table open by this thread and replace
1212
them with exclusive name-locks.
1214
@param session Thread context
1215
@param db Database name for the table to be closed
1216
@param table_name Name of the table to be closed
1218
@note This function assumes that if we are not under LOCK TABLES,
1219
then there is only one table open and locked. This means that
1220
the function probably has to be adjusted before it can be used
1221
anywhere outside ALTER Table.
1223
@note Must not use TableShare::table_name/db of the table being closed,
1224
the strings are used in a loop even after the share may be freed.
2610
Close all instances of a table open by this thread and replace
2611
them with exclusive name-locks.
2613
@param thd Thread context
2614
@param db Database name for the table to be closed
2615
@param table_name Name of the table to be closed
2617
@note This function assumes that if we are not under LOCK TABLES,
2618
then there is only one table open and locked. This means that
2619
the function probably has to be adjusted before it can be used
2620
anywhere outside ALTER TABLE.
2622
@note Must not use TABLE_SHARE::table_name/db of the table being closed,
2623
the strings are used in a loop even after the share may be freed.
1227
void Session::close_data_files_and_morph_locks(const identifier::Table &identifier)
2626
void close_data_files_and_morph_locks(THD *thd, const char *db,
2627
const char *table_name)
1229
safe_mutex_assert_owner(table::Cache::singleton().mutex().native_handle()); /* Adjust locks at the end of ALTER TABLEL */
2631
safe_mutex_assert_owner(&LOCK_open);
1234
2636
If we are not under LOCK TABLES we should have only one table
1235
2637
open and locked so it makes sense to remove the lock at once.
2639
mysql_unlock_tables(thd, thd->lock);
1242
2644
Note that open table list may contain a name-lock placeholder
1243
for target table name if we process ALTER Table ... RENAME.
2645
for target table name if we process ALTER TABLE ... RENAME.
1244
2646
So loop below makes sense even if we are not under LOCK TABLES.
1246
for (Table *table= open_tables; table ; table=table->getNext())
2648
for (table=thd->open_tables; table ; table=table->next)
1248
if (table->getShare()->getCacheKey() == identifier.getKey())
2650
if (!strcmp(table->s->table_name.str, table_name) &&
2651
!strcmp(table->s->db.str, db))
1250
table->open_placeholder= true;
2653
if (thd->locked_tables)
2655
mysql_lock_remove(thd, thd->locked_tables, table, true);
2657
table->open_placeholder= 1;
1251
2658
close_handle_and_leave_table_as_lock(table);
1258
Reopen all tables with closed data files.
1260
@param session Thread context
1261
@param get_locks Should we get locks after reopening tables ?
1262
@param mark_share_as_old Mark share as old to protect from a impending
1265
@note Since this function can't properly handle prelocking and
1266
create placeholders it should be used in very special
1267
situations like FLUSH TABLES or ALTER Table. In general
1268
case one should just repeat open_tables()/lock_tables()
1269
combination when one needs tables to be reopened (for
1270
example see openTablesLock()).
1272
@note One should have lock on table::Cache::singleton().mutex() when calling this.
1274
@return false in case of success, true - otherwise.
2666
Reopen all tables with closed data files.
2668
@param thd Thread context
2669
@param get_locks Should we get locks after reopening tables ?
2670
@param mark_share_as_old Mark share as old to protect from a impending
2673
@note Since this function can't properly handle prelocking and
2674
create placeholders it should be used in very special
2675
situations like FLUSH TABLES or ALTER TABLE. In general
2676
case one should just repeat open_tables()/lock_tables()
2677
combination when one needs tables to be reopened (for
2678
example see open_and_lock_tables()).
2680
@note One should have lock on LOCK_open when calling this.
2682
@return false in case of success, true - otherwise.
1277
bool Session::reopen_tables()
2685
bool reopen_tables(THD *thd, bool get_locks, bool mark_share_as_old)
1279
Table *table,*next,**prev;
1280
Table **tables= 0; // For locks
1281
Table **tables_ptr= 0; // For locks
1283
const uint32_t flags= DRIZZLE_LOCK_NOTIFY_IF_NEED_REOPEN |
1284
DRIZZLE_LOCK_IGNORE_GLOBAL_READ_LOCK |
1285
DRIZZLE_LOCK_IGNORE_FLUSH;
1287
if (open_tables == NULL)
1290
safe_mutex_assert_owner(table::Cache::singleton().mutex().native_handle());
2687
TABLE *table,*next,**prev;
2688
TABLE **tables,**tables_ptr; // For locks
2689
bool error=0, not_used;
2690
const uint flags= MYSQL_LOCK_NOTIFY_IF_NEED_REOPEN |
2691
MYSQL_LOCK_IGNORE_GLOBAL_READ_LOCK |
2692
MYSQL_LOCK_IGNORE_FLUSH;
2694
if (!thd->open_tables)
2697
safe_mutex_assert_owner(&LOCK_open);
1293
2701
The ptr is checked later
1294
2702
Do not handle locks of MERGE children.
1298
for (table= open_tables; table ; table=table->getNext())
2705
for (table= thd->open_tables; table ; table=table->next)
1302
tables= new Table *[opens];
2707
tables= (TABLE**) my_alloca(sizeof(TABLE*)*opens);
2710
tables= &thd->open_tables;
1305
2711
tables_ptr =tables;
1308
for (table= open_tables; table ; table=next)
2713
prev= &thd->open_tables;
2714
for (table=thd->open_tables; table ; table=next)
1310
next= table->getNext();
1312
my_error(ER_CANT_REOPEN_TABLE, MYF(0), table->getAlias());
1313
table::remove_table(static_cast<table::Concurrent *>(table));
2716
uint db_stat=table->db_stat;
2718
if (!tables || (!db_stat && reopen_table(table)))
2720
my_error(ER_CANT_REOPEN_TABLE, MYF(0), table->alias);
2721
VOID(hash_delete(&open_cache,(uchar*) table));
2728
/* Do not handle locks of MERGE children. */
2729
if (get_locks && !db_stat)
2730
*tables_ptr++= table; // need new lock on this
2731
if (mark_share_as_old)
2733
table->s->version=0;
2734
table->open_placeholder= 0;
1318
2739
if (tables != tables_ptr) // Should we get back old locks
1320
DrizzleLock *local_lock;
1322
2743
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
2744
wait_for_tables() as it tries to acquire LOCK_open, which is
1324
2745
already locked.
1326
some_tables_deleted= false;
1328
if ((local_lock= lockTables(tables, (uint32_t) (tables_ptr - tables), flags)))
2747
thd->some_tables_deleted=0;
2748
if ((lock= mysql_lock_tables(thd, tables, (uint) (tables_ptr - tables),
2751
thd->locked_tables=mysql_lock_merge(thd->locked_tables,lock);
1640
3373
result= -1; // Fatal error
1643
if (tables->lock_type != TL_UNLOCK)
3376
if (tables->lock_type != TL_UNLOCK && ! thd->locked_tables)
1645
3378
if (tables->lock_type == TL_WRITE_DEFAULT)
1646
tables->table->reginfo.lock_type= update_lock_default;
1647
else if (tables->table->getShare()->getType() == message::Table::STANDARD)
3379
tables->table->reginfo.lock_type= thd->update_lock_default;
3380
else if (tables->table->s->tmp_table == NO_TMP_TABLE)
1648
3381
tables->table->reginfo.lock_type= tables->lock_type;
3385
thd_proc_info(thd, 0);
3386
free_root(&new_frm_mem, MYF(0)); // Free pre-alloced block
1654
3388
if (result && tables)
1657
3391
Some functions determine success as (tables->table != NULL).
1658
tables->table is in session->open_tables.
3392
tables->table is in thd->open_tables. It won't go lost. If the
3393
error happens on a MERGE child, clear the parents TABLE reference.
3395
if (tables->parent_l)
3396
tables->parent_l->table= NULL;
1660
3397
tables->table= NULL;
1663
3399
return(result);
3404
Check that lock is ok for tables; Call start stmt if ok
3407
check_lock_and_start_stmt()
3409
table_list Table to check
3410
lock_type Lock used for table
3417
static bool check_lock_and_start_stmt(THD *thd, TABLE *table,
3418
thr_lock_type lock_type)
3422
if ((int) lock_type >= (int) TL_WRITE_ALLOW_READ &&
3423
(int) table->reginfo.lock_type < (int) TL_WRITE_ALLOW_READ)
3425
my_error(ER_TABLE_NOT_LOCKED_FOR_WRITE, MYF(0),table->alias);
3428
if ((error=table->file->start_stmt(thd, lock_type)))
3430
table->file->print_error(error,MYF(0));
3438
@brief Open and lock one table
3440
@param[in] thd thread handle
3441
@param[in] table_l table to open is first table in this list
3442
@param[in] lock_type lock to use for table
3445
@retval != NULL OK, opened table returned
3449
If ok, the following are also set:
3450
table_list->lock_type lock_type
3451
table_list->table table
3454
If table_l is a list, not a single table, the list is temporarily
3458
This function is meant as a replacement for open_ltable() when
3459
MERGE tables can be opened. open_ltable() cannot open MERGE tables.
3461
There may be more differences between open_n_lock_single_table() and
3462
open_ltable(). One known difference is that open_ltable() does
3463
neither call decide_logging_format() nor handle some other logging
3464
and locking issues because it does not call lock_tables().
3467
TABLE *open_n_lock_single_table(THD *thd, TABLE_LIST *table_l,
3468
thr_lock_type lock_type)
3470
TABLE_LIST *save_next_global;
3472
/* Remember old 'next' pointer. */
3473
save_next_global= table_l->next_global;
3475
table_l->next_global= NULL;
3477
/* Set requested lock type. */
3478
table_l->lock_type= lock_type;
3479
/* Allow to open real tables only. */
3480
table_l->required_type= FRMTYPE_TABLE;
3482
/* Open the table. */
3483
if (simple_open_n_lock_tables(thd, table_l))
3484
table_l->table= NULL; /* Just to be sure. */
3487
table_l->next_global= save_next_global;
3489
return(table_l->table);
1668
3494
Open and lock one table
1672
session Thread Cursor
1673
table_list Table to open is first table in this list
1674
lock_type Lock to use for open
1675
lock_flags Flags passed to mysql_lock_table
3499
table_list Table to open is first table in this list
3500
lock_type Lock to use for open
3501
lock_flags Flags passed to mysql_lock_table
1678
This function don't do anything like SP/SF/views/triggers analysis done
1679
in open_tables(). It is intended for opening of only one concrete table.
1680
And used only in special contexts.
3504
This function don't do anything like SP/SF/views/triggers analysis done
3505
in open_tables(). It is intended for opening of only one concrete table.
3506
And used only in special contexts.
1686
If ok, the following are also set:
1687
table_list->lock_type lock_type
1688
table_list->table table
3512
If ok, the following are also set:
3513
table_list->lock_type lock_type
3514
table_list->table table
1691
Table *Session::openTableLock(TableList *table_list, thr_lock_type lock_type)
3517
TABLE *open_ltable(THD *thd, TABLE_LIST *table_list, thr_lock_type lock_type,
1696
set_proc_info("Opening table");
1698
while (!(table= openTable(table_list, &refresh)) && refresh) ;
3523
thd_proc_info(thd, "Opening table");
3524
thd->current_tablenr= 0;
3525
/* open_ltable can be used only for BASIC TABLEs */
3526
table_list->required_type= FRMTYPE_TABLE;
3527
while (!(table= open_table(thd, table_list, thd->mem_root, &refresh, 0)) &&
1702
3533
table_list->lock_type= lock_type;
1703
3534
table_list->table= table;
1705
assert(lock == 0); // You must lock everything at once
1706
if ((table->reginfo.lock_type= lock_type) != TL_UNLOCK)
1708
if (not (lock= lockTables(&table_list->table, 1, 0)))
3535
if (thd->locked_tables)
3537
if (check_lock_and_start_stmt(thd, table, lock_type))
3542
assert(thd->lock == 0); // You must lock everything at once
3543
if ((table->reginfo.lock_type= lock_type) != TL_UNLOCK)
3544
if (! (thd->lock= mysql_lock_tables(thd, &table_list->table, 1,
3545
lock_flags, &refresh)))
3550
thd_proc_info(thd, 0);
3556
Open all tables in list, locks them and optionally process derived tables.
3559
open_and_lock_tables_derived()
3560
thd - thread handler
3561
tables - list of tables for open&locking
3562
derived - if to handle derived tables
3569
The lock will automaticaly be freed by close_thread_tables()
3572
There are two convenience functions:
3573
- simple_open_n_lock_tables(thd, tables) without derived handling
3574
- open_and_lock_tables(thd, tables) with derived handling
3575
Both inline functions call open_and_lock_tables_derived() with
3576
the third argument set appropriately.
3579
int open_and_lock_tables_derived(THD *thd, TABLE_LIST *tables, bool derived)
3586
if (open_tables(thd, &tables, &counter, 0))
3589
if (!lock_tables(thd, tables, counter, &need_reopen))
3593
close_tables_for_reopen(thd, &tables);
3596
(mysql_handle_derived(thd->lex, &mysql_derived_prepare) ||
3597
(thd->fill_derived_tables() &&
3598
mysql_handle_derived(thd->lex, &mysql_derived_filling))))
3599
return(true); /* purecov: inspected */
3605
Open all tables in list and process derived tables
3608
open_normal_and_derived_tables
3609
thd - thread handler
3610
tables - list of tables for open
3611
flags - bitmap of flags to modify how the tables will be open:
3612
MYSQL_LOCK_IGNORE_FLUSH - open table even if someone has
3613
done a flush or namelock on it.
3620
This is to be used on prepare stage when you don't read any
3621
data from the tables.
3624
bool open_normal_and_derived_tables(THD *thd, TABLE_LIST *tables, uint flags)
3627
assert(!thd->fill_derived_tables());
3628
if (open_tables(thd, &tables, &counter, flags) ||
3629
mysql_handle_derived(thd->lex, &mysql_derived_prepare))
3630
return(true); /* purecov: inspected */
3636
Decide on logging format to use for the statement.
3638
Compute the capabilities vector for the involved storage engines
3639
and mask out the flags for the binary log. Right now, the binlog
3640
flags only include the capabilities of the storage engines, so this
3643
We now have three alternatives that prevent the statement from
3646
1. If there are no capabilities left (all flags are clear) it is
3647
not possible to log the statement at all, so we roll back the
3648
statement and report an error.
3650
2. Statement mode is set, but the capabilities indicate that
3651
statement format is not possible.
3653
3. Row mode is set, but the capabilities indicate that row
3654
format is not possible.
3656
4. Statement is unsafe, but the capabilities indicate that row
3657
format is not possible.
3659
If we are in MIXED mode, we then decide what logging format to use:
3661
1. If the statement is unsafe, row-based logging is used.
3663
2. If statement-based logging is not possible, row-based logging is
3666
3. Otherwise, statement-based logging is used.
3668
@param thd Client thread
3669
@param tables Tables involved in the query
3672
int decide_logging_format(THD *thd, TABLE_LIST *tables)
3674
if (mysql_bin_log.is_open() && (thd->options & OPTION_BIN_LOG))
3676
handler::Table_flags flags_some_set= handler::Table_flags();
3677
handler::Table_flags flags_all_set= ~handler::Table_flags();
3678
my_bool multi_engine= false;
3679
void* prev_ht= NULL;
3680
for (TABLE_LIST *table= tables; table; table= table->next_global)
3682
if (!table->placeholder() && table->lock_type >= TL_WRITE_ALLOW_WRITE)
3684
uint64_t const flags= table->table->file->ha_table_flags();
3685
if (prev_ht && prev_ht != table->table->file->ht)
3687
prev_ht= table->table->file->ht;
3688
flags_all_set &= flags;
3689
flags_some_set |= flags;
3694
if (flags_all_set == 0)
3696
my_error((error= ER_BINLOG_LOGGING_IMPOSSIBLE), MYF(0),
3697
"Statement cannot be logged to the binary log in"
3698
" row-based nor statement-based format");
3700
else if (thd->variables.binlog_format == BINLOG_FORMAT_STMT &&
3701
(flags_all_set & HA_BINLOG_STMT_CAPABLE) == 0)
3703
my_error((error= ER_BINLOG_LOGGING_IMPOSSIBLE), MYF(0),
3704
"Statement-based format required for this statement,"
3705
" but not allowed by this combination of engines");
3707
else if ((thd->variables.binlog_format == BINLOG_FORMAT_ROW ||
3708
thd->lex->is_stmt_unsafe()) &&
3709
(flags_all_set & HA_BINLOG_ROW_CAPABLE) == 0)
3711
my_error((error= ER_BINLOG_LOGGING_IMPOSSIBLE), MYF(0),
3712
"Row-based format required for this statement,"
3713
" but not allowed by this combination of engines");
3717
If more than one engine is involved in the statement and at
3718
least one is doing it's own logging (is *self-logging*), the
3719
statement cannot be logged atomically, so we generate an error
3720
rather than allowing the binlog to become corrupt.
3723
(flags_some_set & HA_HAS_OWN_BINLOGGING))
3725
error= ER_BINLOG_LOGGING_IMPOSSIBLE;
3726
my_error(error, MYF(0),
3727
"Statement cannot be written atomically since more"
3728
" than one engine involved and at least one engine"
3729
" is self-logging");
3736
We switch to row-based format if we are in mixed mode and one of
3737
the following are true:
3739
1. If the statement is unsafe
3740
2. If statement format cannot be used
3742
Observe that point to cannot be decided before the tables
3743
involved in a statement has been checked, i.e., we cannot put
3744
this code in reset_current_stmt_binlog_row_based(), it has to be
3747
if (thd->lex->is_stmt_unsafe() ||
3748
(flags_all_set & HA_BINLOG_STMT_CAPABLE) == 0)
3750
thd->set_current_stmt_binlog_row_based_if_mixed();
1719
3758
Lock all tables in list
1723
session Thread Cursor
1724
tables Tables to lock
1725
count Number of opened tables
1726
need_reopen Out parameter which if true indicates that some
1727
tables were dropped or altered during this call
1728
and therefore invoker should reopen tables and
1729
try to lock them once again (in this case
1730
lock_tables() will also return error).
3763
tables Tables to lock
3764
count Number of opened tables
3765
need_reopen Out parameter which if true indicates that some
3766
tables were dropped or altered during this call
3767
and therefore invoker should reopen tables and
3768
try to lock them once again (in this case
3769
lock_tables() will also return error).
1733
You can't call lock_tables twice, as this would break the dead-lock-free
1734
handling thr_lock gives us. You most always get all needed locks at
3772
You can't call lock_tables twice, as this would break the dead-lock-free
3773
handling thr_lock gives us. You most always get all needed locks at
1737
If query for which we are calling this function marked as requring
1738
prelocking, this function will do implicit LOCK TABLES and change
1739
session::prelocked_mode accordingly.
3776
If query for which we are calling this function marked as requring
3777
prelocking, this function will do implicit LOCK TABLES and change
3778
thd::prelocked_mode accordingly.
1746
int Session::lock_tables(TableList *tables, uint32_t count, bool *need_reopen)
3785
int lock_tables(THD *thd, TABLE_LIST *tables, uint count, bool *need_reopen)
1749
Session *session= this;
1752
3790
We can't meet statement requiring prelocking if we already