33
#include "drizzled/internal/my_pthread.h"
34
#include "drizzled/internal/thread_var.h"
35
#include <mysys/my_pthread.h>
36
37
#include <drizzled/sql_select.h>
38
#include <mysys/my_dir.h>
37
39
#include <drizzled/error.h>
38
40
#include <drizzled/gettext.h>
39
41
#include <drizzled/nested_join.h>
40
42
#include <drizzled/sql_base.h>
41
43
#include <drizzled/show.h>
42
44
#include <drizzled/item/cmpfunc.h>
43
#include <drizzled/replication_services.h>
45
#include <drizzled/replicator.h>
44
46
#include <drizzled/check_stack_overrun.h>
45
47
#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"
61
#include <drizzled/refresh_version.h>
68
extern bool volatile shutdown_in_progress;
51
return true if the table was created explicitly.
53
inline bool is_user_table(Table * table)
55
const char *name= table->s->table_name.str;
56
return strncmp(name, TMP_FILE_PREFIX, TMP_FILE_PREFIX_LENGTH);
61
@defgroup Data_Dictionary Data Dictionary
64
Table *unused_tables; /* Used by mysql_test */
65
HASH open_cache; /* Used by mysql_test */
66
static HASH table_def_cache;
67
static TABLE_SHARE *oldest_unused_share, end_of_unused_share;
68
static pthread_mutex_t LOCK_table_share;
69
static bool table_def_inited= 0;
71
static int open_unireg_entry(Session *session, Table *entry, TableList *table_list,
73
char *cache_key, uint32_t cache_key_length);
74
static void free_cache_entry(Table *entry);
75
static void close_old_data_files(Session *session, Table *table, bool morph_locks,
79
extern "C" unsigned char *table_cache_key(const unsigned char *record, size_t *length,
80
bool not_used __attribute__((unused)))
82
Table *entry=(Table*) record;
83
*length= entry->s->table_cache_key.length;
84
return (unsigned char*) entry->s->table_cache_key.str;
70
88
bool table_cache_init(void)
90
return hash_init(&open_cache, &my_charset_bin, table_cache_size+16,
91
0, 0, table_cache_key,
92
(hash_free_key) free_cache_entry, 0);
95
void table_cache_free(void)
99
close_cached_tables(NULL, NULL, false, false, false);
100
if (!open_cache.records) // Safety first
101
hash_free(&open_cache);
75
106
uint32_t cached_open_tables(void)
77
return table::getCache().size();
80
void table_cache_free(void)
82
refresh_version++; // Force close of open tables
84
table::getUnused().clear();
85
table::getCache().clear();
89
Close cursor handle, but leave the table in the table cache
92
close_handle_and_leave_table_as_lock()
96
By leaving the table in the table cache, it disallows any other thread
99
session->getKilled() will be set if we run out of memory
101
If closing a MERGE child, the calling function has to take care for
102
closing the parent too, if necessary.
108
return open_cache.records;
112
Create a table cache key
115
create_table_def_key()
116
session Thread handler
117
key Create key here (must be of size MAX_DBKEY_LENGTH)
118
table_list Table definition
119
tmp_table Set if table is a tmp table
122
The table cache_key is created from:
126
if the table is a tmp table, we add the following to make each tmp table
129
4 bytes for master thread id
130
4 bytes pseudo thread id
136
uint32_t create_table_def_key(Session *session, char *key, TableList *table_list,
141
key_pos= strcpy(key_pos, table_list->db) + strlen(table_list->db);
142
key_pos= strcpy(key_pos+1, table_list->table_name) +
143
strlen(table_list->table_name);
144
key_length= (uint32_t)(key_pos-key)+1;
148
int4store(key + key_length, session->server_id);
149
int4store(key + key_length + 4, session->variables.pseudo_thread_id);
150
key_length+= TMP_TABLE_KEY_EXTRA;
157
/*****************************************************************************
158
Functions to handle table definition cach (TABLE_SHARE)
159
*****************************************************************************/
161
extern "C" unsigned char *table_def_key(const unsigned char *record, size_t *length,
162
bool not_used __attribute__((unused)))
164
TABLE_SHARE *entry=(TABLE_SHARE*) record;
165
*length= entry->table_cache_key.length;
166
return (unsigned char*) entry->table_cache_key.str;
170
static void table_def_free_entry(TABLE_SHARE *share)
174
/* remove from old_unused_share list */
175
pthread_mutex_lock(&LOCK_table_share);
176
*share->prev= share->next;
177
share->next->prev= share->prev;
178
pthread_mutex_unlock(&LOCK_table_share);
180
free_table_share(share);
185
bool table_def_init(void)
188
pthread_mutex_init(&LOCK_table_share, MY_MUTEX_INIT_FAST);
189
oldest_unused_share= &end_of_unused_share;
190
end_of_unused_share.prev= &oldest_unused_share;
192
return hash_init(&table_def_cache, &my_charset_bin, table_def_size,
194
(hash_free_key) table_def_free_entry, 0);
198
void table_def_free(void)
200
if (table_def_inited)
203
pthread_mutex_destroy(&LOCK_table_share);
204
hash_free(&table_def_cache);
210
uint32_t cached_table_definitions(void)
212
return table_def_cache.records;
217
Get TABLE_SHARE for a table.
220
session Thread handle
221
table_list Table that should be opened
223
key_length Length of key
224
db_flags Flags to open_table_def():
226
error out: Error code from open_table_def()
229
Get a table definition from the table definition cache.
230
If it doesn't exist, create a new from the table definition file.
233
We must have wrlock on LOCK_open when we come here
234
(To be changed later)
241
TABLE_SHARE *get_table_share(Session *session, TableList *table_list, char *key,
242
uint32_t key_length, uint32_t db_flags, int *error)
248
/* Read table definition from cache */
249
if ((share= (TABLE_SHARE*) hash_search(&table_def_cache,(unsigned char*) key,
253
if (!(share= alloc_table_share(table_list, key, key_length)))
259
Lock mutex to be able to read table definition from file without
262
(void) pthread_mutex_lock(&share->mutex);
265
We assign a new table id under the protection of the LOCK_open and
266
the share's own mutex. We do this insted of creating a new mutex
267
and using it for the sole purpose of serializing accesses to a
268
static variable, we assign the table id here. We assign it to the
269
share before inserting it into the table_def_cache to be really
270
sure that it cannot be read from the cache without having a table
273
CAVEAT. This means that the table cannot be used for
274
binlogging/replication purposes, unless get_table_share() has been
275
called directly or indirectly.
277
assign_new_table_id(share);
279
if (my_hash_insert(&table_def_cache, (unsigned char*) share))
281
free_table_share(share);
282
return(0); // return error
284
if (open_table_def(session, share, db_flags))
286
*error= share->error;
287
(void) hash_delete(&table_def_cache, (unsigned char*) share);
290
share->ref_count++; // Mark in use
291
(void) pthread_mutex_unlock(&share->mutex);
296
We found an existing table definition. Return it if we didn't get
297
an error when reading the table definition from file.
300
/* We must do a lock to ensure that the structure is initialized */
301
(void) pthread_mutex_lock(&share->mutex);
304
/* Table definition contained an error */
305
open_table_error(share, share->error, share->open_errno, share->errarg);
306
(void) pthread_mutex_unlock(&share->mutex);
310
if (!share->ref_count++ && share->prev)
313
Share was not used before and it was in the old_unused_share list
314
Unlink share from this list
316
pthread_mutex_lock(&LOCK_table_share);
317
*share->prev= share->next;
318
share->next->prev= share->prev;
321
pthread_mutex_unlock(&LOCK_table_share);
323
(void) pthread_mutex_unlock(&share->mutex);
325
/* Free cache if too big */
326
while (table_def_cache.records > table_def_size &&
327
oldest_unused_share->next)
329
pthread_mutex_lock(&oldest_unused_share->mutex);
330
hash_delete(&table_def_cache, (unsigned char*) oldest_unused_share);
338
Get a table share. If it didn't exist, try creating it from engine
340
For arguments and return values, see get_table_from_share()
344
*get_table_share_with_create(Session *session, TableList *table_list,
345
char *key, uint32_t key_length,
346
uint32_t db_flags, int *error)
350
share= get_table_share(session, table_list, key, key_length, db_flags, error);
352
If share is not NULL, we found an existing share.
354
If share is NULL, and there is no error, we're inside
355
pre-locking, which silences 'ER_NO_SUCH_TABLE' errors
356
with the intention to silently drop non-existing tables
357
from the pre-locking list. In this case we still need to try
358
auto-discover before returning a NULL share.
360
If share is NULL and the error is ER_NO_SUCH_TABLE, this is
361
the same as above, only that the error was not silenced by
362
pre-locking. Once again, we need to try to auto-discover
365
Finally, if share is still NULL, it's a real error and we need
368
@todo Rework alternative ways to deal with ER_NO_SUCH Table.
370
if (share || (session->is_error() && (session->main_da.sql_errno() != ER_NO_SUCH_TABLE)))
379
Mark that we are not using table share anymore.
382
release_table_share()
384
release_type How the release should be done:
386
- Release without checking
387
RELEASE_WAIT_FOR_DROP
388
- Don't return until we get a signal that the
389
table is deleted or the thread is killed.
392
If ref_count goes to zero and (we have done a refresh or if we have
393
already too many open table shares) then delete the definition.
395
If type == RELEASE_WAIT_FOR_DROP then don't return until we get a signal
396
that the table is deleted or the thread is killed.
399
void release_table_share(TABLE_SHARE *share,
400
enum release_type type __attribute__((unused)))
402
bool to_be_deleted= 0;
404
safe_mutex_assert_owner(&LOCK_open);
406
pthread_mutex_lock(&share->mutex);
407
if (!--share->ref_count)
409
if (share->version != refresh_version)
413
/* Link share last in used_table_share list */
414
assert(share->next == 0);
415
pthread_mutex_lock(&LOCK_table_share);
416
share->prev= end_of_unused_share.prev;
417
*end_of_unused_share.prev= share;
418
end_of_unused_share.prev= &share->next;
419
share->next= &end_of_unused_share;
420
pthread_mutex_unlock(&LOCK_table_share);
422
to_be_deleted= (table_def_cache.records > table_def_size);
428
hash_delete(&table_def_cache, (unsigned char*) share);
431
pthread_mutex_unlock(&share->mutex);
437
Check if table definition exits in cache
440
get_cached_table_share()
442
table_name Table name
446
# TABLE_SHARE for table
449
TABLE_SHARE *get_cached_table_share(const char *db, const char *table_name)
451
char key[NAME_LEN*2+2];
452
TableList table_list;
454
safe_mutex_assert_owner(&LOCK_open);
456
table_list.db= (char*) db;
457
table_list.table_name= (char*) table_name;
458
key_length= create_table_def_key((Session*) 0, key, &table_list, 0);
459
return (TABLE_SHARE*) hash_search(&table_def_cache,(unsigned char*) key, key_length);
464
Close file handle, but leave the table in the table cache
467
close_handle_and_leave_table_as_lock()
471
By leaving the table in the table cache, it disallows any other thread
474
session->killed will be set if we run out of memory
476
If closing a MERGE child, the calling function has to take care for
477
closing the parent too, if necessary.
106
481
void close_handle_and_leave_table_as_lock(Table *table)
483
TABLE_SHARE *share, *old_share= table->s;
485
MEM_ROOT *mem_root= &table->mem_root;
108
487
assert(table->db_stat);
109
assert(table->getShare()->getType() == message::Table::STANDARD);
112
490
Make a local copy of the table share and free the current one.
113
491
This has to be done to ensure that the table share is removed from
114
492
the table defintion cache as soon as the last instance is removed
116
identifier::Table identifier(table->getShare()->getSchemaName(), table->getShare()->getTableName(), message::Table::INTERNAL);
117
const identifier::Table::Key &key(identifier.getKey());
118
TableShare *share= new TableShare(identifier.getType(),
120
const_cast<char *>(key.vector()), static_cast<uint32_t>(table->getShare()->getCacheKeySize()));
122
table->cursor->close();
123
table->db_stat= 0; // Mark cursor closed
124
table::instance::release(table->getMutableShare());
125
table->setShare(share);
494
if (multi_alloc_root(mem_root,
495
&share, sizeof(*share),
496
&key_buff, old_share->table_cache_key.length,
499
memset(share, 0, sizeof(*share));
500
share->set_table_cache_key(key_buff, old_share->table_cache_key.str,
501
old_share->table_cache_key.length);
502
share->tmp_table= INTERNAL_TMP_TABLE; // for intern_close_table()
505
table->file->close();
506
table->db_stat= 0; // Mark file closed
507
release_table_share(table->s, RELEASE_NORMAL);
509
table->file->change_table_ptr(table, table->s);
517
Create a list for all open tables matching SQL expression
521
session Thread Session
522
wild SQL like expression
525
One gets only a list of tables for which one has any kind of privilege.
526
db and table names are allocated in result struct, so one doesn't need
527
a lock on LOCK_open when traversing the return list.
530
NULL Error (Probably OOM)
531
# Pointer to list of names of open tables.
534
OPEN_TableList *list_open_tables(Session *session __attribute__((unused)),
535
const char *db, const char *wild)
538
OPEN_TableList **start_list, *open_list;
539
TableList table_list;
541
pthread_mutex_lock(&LOCK_open);
542
memset(&table_list, 0, sizeof(table_list));
543
start_list= &open_list;
546
for (uint32_t idx=0 ; result == 0 && idx < open_cache.records; idx++)
548
OPEN_TableList *table;
549
Table *entry=(Table*) hash_element(&open_cache,idx);
550
TABLE_SHARE *share= entry->s;
552
if (db && my_strcasecmp(system_charset_info, db, share->db.str))
554
if (wild && wild_compare(share->table_name.str, wild, 0))
557
/* Check if user has SELECT privilege for any column in the table */
558
table_list.db= share->db.str;
559
table_list.table_name= share->table_name.str;
561
/* need to check if we haven't already listed it */
562
for (table= open_list ; table ; table=table->next)
564
if (!strcmp(table->table, share->table_name.str) &&
565
!strcmp(table->db, share->db.str))
569
if (entry->locked_by_name)
576
if (!(*start_list = (OPEN_TableList *)
577
sql_alloc(sizeof(**start_list)+share->table_cache_key.length)))
579
open_list=0; // Out of memory
582
strcpy((*start_list)->table=
583
strcpy(((*start_list)->db= (char*) ((*start_list)+1)),
584
share->db.str)+share->db.length+1,
585
share->table_name.str);
586
(*start_list)->in_use= entry->in_use ? 1 : 0;
587
(*start_list)->locked= entry->locked_by_name ? 1 : 0;
588
start_list= &(*start_list)->next;
591
pthread_mutex_unlock(&LOCK_open);
129
595
/*****************************************************************************
130
596
* Functions to free open table cache
131
597
****************************************************************************/
134
void Table::intern_close_table()
600
void intern_close_table(Table *table)
135
601
{ // Free all structures
137
if (cursor) // Not true if name lock
602
free_io_cache(table);
603
if (table->file) // Not true if name lock
604
closefrm(table, 1); // close file
609
Remove table from the open table cache
613
table Table to remove
616
We need to have a lock on LOCK_open when calling this
619
static void free_cache_entry(Table *table)
621
intern_close_table(table);
139
delete_table(true); // close cursor
624
table->next->prev=table->prev; /* remove from used chain */
625
table->prev->next=table->next;
626
if (table == unused_tables)
628
unused_tables=unused_tables->next;
629
if (table == unused_tables)
633
free((unsigned char*) table);
143
637
/* Free resources allocated by filesort() and read_record() */
145
void Table::free_io_cache()
639
void free_io_cache(Table *table)
641
if (table->sort.io_cache)
149
sort.io_cache->close_cached_file();
150
delete sort.io_cache;
643
close_cached_file(table->sort.io_cache);
644
free((unsigned char*) table->sort.io_cache);
645
table->sort.io_cache=0;
157
652
Close all tables which aren't in use by any thread
159
@param session Thread context (may be NULL)
654
@param session Thread context
160
655
@param tables List of tables to remove from the cache
161
@param have_lock If table::Cache::singleton().mutex() is locked
656
@param have_lock If LOCK_open is locked
162
657
@param wait_for_refresh Wait for a impending flush
163
658
@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
659
won't proceed while write-locked tables are being reopened by other
167
662
@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)
663
and tables must be NULL.
666
bool close_cached_tables(Session *session, TableList *tables, bool have_lock,
667
bool wait_for_refresh, bool wait_for_placeholders)
670
assert(session || (!wait_for_refresh && !tables));
673
pthread_mutex_lock(&LOCK_open);
676
refresh_version++; // Force close of open tables
677
while (unused_tables)
680
if (hash_delete(&open_cache,(unsigned char*) unused_tables))
681
printf("Warning: Couldn't delete open table from hash\n");
683
hash_delete(&open_cache,(unsigned char*) unused_tables);
686
/* Free table shares */
687
while (oldest_unused_share->next)
689
pthread_mutex_lock(&oldest_unused_share->mutex);
690
hash_delete(&table_def_cache, (unsigned char*) oldest_unused_share);
692
if (wait_for_refresh)
695
Other threads could wait in a loop in open_and_lock_tables(),
696
trying to lock one or more of our tables.
698
If they wait for the locks in thr_multi_lock(), their lock
699
request is aborted. They loop in open_and_lock_tables() and
700
enter open_table(). Here they notice the table is refreshed and
701
wait for COND_refresh. Then they loop again in
702
open_and_lock_tables() and this time open_table() succeeds. At
703
this moment, if we (the FLUSH TABLES thread) are scheduled and
704
on another FLUSH TABLES enter close_cached_tables(), they could
705
awake while we sleep below, waiting for others threads (us) to
706
close their open tables. If this happens, the other threads
707
would find the tables unlocked. They would get the locks, one
708
after the other, and could do their destructive work. This is an
709
issue if we have LOCK TABLES in effect.
711
The problem is that the other threads passed all checks in
712
open_table() before we refresh the table.
714
The fix for this problem is to set some_tables_deleted for all
715
threads with open tables. These threads can still get their
716
locks, but will immediately release them again after checking
717
this variable. They will then loop in open_and_lock_tables()
718
again. There they will wait until we update all tables version
721
Setting some_tables_deleted is done by remove_table_from_cache()
724
In other words (reviewer suggestion): You need this setting of
725
some_tables_deleted for the case when table was opened and all
726
related checks were passed before incrementing refresh_version
727
(which you already have) but attempt to lock the table happened
728
after the call to close_old_data_files() i.e. after removal of
729
current thread locks.
731
for (uint32_t idx=0 ; idx < open_cache.records ; idx++)
733
Table *table=(Table*) hash_element(&open_cache,idx);
735
table->in_use->some_tables_deleted= 1;
742
for (TableList *table= tables; table; table= table->next_local)
744
if (remove_table_from_cache(session, table->db, table->table_name,
745
RTFC_OWNED_BY_Session_FLAG))
749
wait_for_refresh=0; // Nothing to wait for
752
if (wait_for_refresh)
755
If there is any table that has a lower refresh_version, wait until
756
this is closed (or this thread is killed) before returning
758
session->mysys_var->current_mutex= &LOCK_open;
759
session->mysys_var->current_cond= &COND_refresh;
760
session->set_proc_info("Flushing tables");
762
close_old_data_files(session,session->open_tables,1,1);
763
mysql_ha_flush(session);
766
/* Wait until all threads has closed all the tables we had locked */
767
while (found && ! session->killed)
770
for (uint32_t idx=0 ; idx < open_cache.records ; idx++)
772
Table *table=(Table*) hash_element(&open_cache,idx);
773
/* Avoid a self-deadlock. */
774
if (table->in_use == session)
777
Note that we wait here only for tables which are actually open, and
778
not for placeholders with Table::open_placeholder set. Waiting for
779
latter will cause deadlock in the following scenario, for example:
781
conn1: lock table t1 write;
782
conn2: lock table t2 write;
786
It also does not make sense to wait for those of placeholders that
787
are employed by CREATE TABLE as in this case table simply does not
790
if (table->needs_reopen_or_name_lock() && (table->db_stat ||
791
(table->open_placeholder && wait_for_placeholders)))
794
pthread_cond_wait(&COND_refresh,&LOCK_open);
800
No other thread has the locked tables open; reopen them and get the
801
old locks. This should always succeed (unless some external process
802
has removed the tables)
804
session->in_lock_tables=1;
805
result=reopen_tables(session,1,1);
806
session->in_lock_tables=0;
807
/* Set version for table */
808
for (Table *table=session->open_tables; table ; table= table->next)
811
Preserve the version (0) of write locked tables so that a impending
812
global read lock won't sneak in.
814
if (table->reginfo.lock_type < TL_WRITE_ALLOW_WRITE)
815
table->s->version= refresh_version;
819
pthread_mutex_unlock(&LOCK_open);
820
if (wait_for_refresh)
822
pthread_mutex_lock(&session->mysys_var->mutex);
823
session->mysys_var->current_mutex= 0;
824
session->mysys_var->current_cond= 0;
825
session->set_proc_info(0);
826
pthread_mutex_unlock(&session->mysys_var->mutex);
833
Close all tables which match specified connection string or
834
if specified string is NULL, then any table with a connection string.
837
bool close_cached_connection_tables(Session *session, bool if_wait_for_refresh,
838
LEX_STRING *connection, bool have_lock)
841
TableList tmp, *tables= NULL;
173
842
bool result= false;
174
Session *session= this;
845
memset(&tmp, 0, sizeof(TableList));
848
pthread_mutex_lock(&LOCK_open);
850
for (idx= 0; idx < table_def_cache.records; idx++)
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();
852
TABLE_SHARE *share= (TABLE_SHARE *) hash_element(&table_def_cache, idx);
854
/* Ignore if table is not open or does not have a connect_string */
855
if (!share->connect_string.length || !share->ref_count)
858
/* Compare the connection string */
860
(connection->length > share->connect_string.length ||
861
(connection->length < share->connect_string.length &&
862
(share->connect_string.str[connection->length] != '/' &&
863
share->connect_string.str[connection->length] != '\\')) ||
864
strncasecmp(connection->str, share->connect_string.str,
865
connection->length)))
868
/* close_cached_tables() only uses these elements */
869
tmp.db= share->db.str;
870
tmp.table_name= share->table_name.str;
871
tmp.next_local= tables;
873
tables= (TableList *) memdup_root(session->mem_root, (char*)&tmp,
318
if (wait_for_refresh)
878
result= close_cached_tables(session, tables, true, false, false);
881
pthread_mutex_unlock(&LOCK_open);
883
if (if_wait_for_refresh)
320
boost_unique_lock_t scopedLock(session->mysys_var->mutex);
885
pthread_mutex_lock(&session->mysys_var->mutex);
321
886
session->mysys_var->current_mutex= 0;
322
887
session->mysys_var->current_cond= 0;
323
888
session->set_proc_info(0);
889
pthread_mutex_unlock(&session->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;
897
Mark all temporary tables which were used by the current statement or
898
substatement as free for reuse, but only if the query_id can be cleared.
900
@param session thread context
902
@remark For temp tables associated with a open SQL HANDLER the query_id
903
is not reset until the HANDLER is closed.
906
static void mark_temp_tables_as_free_for_reuse(Session *session)
908
for (Table *table= session->temporary_tables ; table ; table= table->next)
910
if ((table->query_id == session->query_id) && ! table->open_by_handler)
913
table->file->ha_reset();
920
Mark all tables in the list which were used by current substatement
924
mark_used_tables_as_free_for_reuse()
925
session - thread context
926
table - head of the list of tables
929
Marks all tables in the list which were used by current substatement
930
(they are marked by its query_id) as free for reuse.
933
The reason we reset query_id is that it's not enough to just test
934
if table->query_id != session->query_id to know if a table is in use.
937
SELECT f1_that_uses_t1() FROM t1;
938
In f1_that_uses_t1() we will see one instance of t1 where query_id is
939
set to query_id of original query.
942
static void mark_used_tables_as_free_for_reuse(Session *session, Table *table)
944
for (; table ; table= table->next)
946
if (table->query_id == session->query_id)
949
table->file->ha_reset();
378
960
@remark It should not ordinarily be called directly.
381
void Session::close_open_tables()
963
static void close_open_tables(Session *session)
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;
965
bool found_old_table= 0;
967
safe_mutex_assert_not_owner(&LOCK_open);
969
pthread_mutex_lock(&LOCK_open);
971
while (session->open_tables)
972
found_old_table|= close_thread_table(session, &session->open_tables);
973
session->some_tables_deleted= 0;
975
/* Free tables to hold down open files */
976
while (open_cache.records > table_cache_size && unused_tables)
977
hash_delete(&open_cache,(unsigned char*) unused_tables); /* purecov: tested */
395
978
if (found_old_table)
397
980
/* Tell threads waiting for refresh that something has happened */
398
locking::broadcast_refresh();
984
pthread_mutex_unlock(&LOCK_open);
989
Close all tables used by the current substatement, or all tables
990
used by this thread if we are on the upper level.
993
close_thread_tables()
994
session Thread handler
997
Unlocks tables and frees derived tables.
998
Put all normal tables used by thread in free list.
1000
It will only close/mark as free for reuse tables opened by this
1001
substatement, it will also check if we are closing tables after
1002
execution of complete query (i.e. we are on upper level) and will
1003
leave prelocked mode if needed.
1006
void close_thread_tables(Session *session)
1011
We are assuming here that session->derived_tables contains ONLY derived
1012
tables for this substatement. i.e. instead of approach which uses
1013
query_id matching for determining which of the derived tables belong
1014
to this substatement we rely on the ability of substatements to
1015
save/restore session->derived_tables during their execution.
1017
TODO: Probably even better approach is to simply associate list of
1018
derived tables with (sub-)statement instead of thread and destroy
1019
them at the end of its execution.
1021
if (session->derived_tables)
1025
Close all derived tables generated in queries like
1026
SELECT * FROM (SELECT * FROM t1)
1028
for (table= session->derived_tables ; table ; table= next)
1031
table->free_tmp_table(session);
1033
session->derived_tables= 0;
1037
Mark all temporary tables used by this statement as free for reuse.
1039
mark_temp_tables_as_free_for_reuse(session);
1041
Let us commit transaction for statement. Since in 5.0 we only have
1042
one statement transaction and don't allow several nested statement
1043
transactions this call will do nothing if we are inside of stored
1044
function or trigger (i.e. statement transaction is already active and
1045
does not belong to statement for which we do close_thread_tables()).
1046
TODO: This should be fixed in later releases.
1048
if (!(session->state_flags & Open_tables_state::BACKUPS_AVAIL))
1050
session->main_da.can_overwrite_status= true;
1051
ha_autocommit_or_rollback(session, session->is_error());
1052
session->main_da.can_overwrite_status= false;
1053
session->transaction.stmt.reset();
1056
if (session->locked_tables)
1059
/* Ensure we are calling ha_reset() for all used tables */
1060
mark_used_tables_as_free_for_reuse(session, session->open_tables);
1063
We are under simple LOCK TABLES so should not do anything else.
1071
For RBR we flush the pending event just before we unlock all the
1072
tables. This means that we are at the end of a topmost
1073
statement, so we ensure that the STMT_END_F flag is set on the
1074
pending event. For statements that are *inside* stored
1075
functions, the pending event will not be flushed: that will be
1076
handled either before writing a query log event (inside
1077
binlog_query()) or when preparing a pending event.
1079
mysql_unlock_tables(session, session->lock);
1083
Note that we need to hold LOCK_open while changing the
1084
open_tables list. Another thread may work on it.
1085
(See: remove_table_from_cache(), mysql_wait_completed_table())
1086
Closing a MERGE child before the parent would be fatal if the
1087
other thread tries to abort the MERGE lock in between.
1089
if (session->open_tables)
1090
close_open_tables(session);
1096
/* move one table to free list */
1098
bool close_thread_table(Session *session, Table **table_ptr)
1100
bool found_old_table= 0;
1101
Table *table= *table_ptr;
1103
assert(table->key_read == 0);
1104
assert(!table->file || table->file->inited == handler::NONE);
1106
*table_ptr=table->next;
1108
if (table->needs_reopen_or_name_lock() ||
1109
session->version != refresh_version || !table->db_stat)
1111
hash_delete(&open_cache,(unsigned char*) table);
1117
Open placeholders have Table::db_stat set to 0, so they should be
1118
handled by the first alternative.
1120
assert(!table->open_placeholder);
1122
/* Free memory and reset for next loop */
1123
table->file->ha_reset();
1127
table->next=unused_tables; /* Link in last */
1128
table->prev=unused_tables->prev;
1129
unused_tables->prev=table;
1130
table->prev->next=table;
1133
unused_tables=table->next=table->prev=table;
1135
return(found_old_table);
1139
/* close_temporary_tables' internal, 4 is due to uint4korr definition */
1140
static inline uint32_t tmpkeyval(Session *session __attribute__((unused)),
1143
return uint4korr(table->s->table_cache_key.str + table->s->table_cache_key.length - 4);
1148
Close all temporary tables created by 'CREATE TEMPORARY TABLE' for thread
1149
creates one DROP TEMPORARY Table binlog event for each pseudo-thread
1152
void close_temporary_tables(Session *session)
1157
/* Assume session->options has OPTION_QUOTE_SHOW_CREATE */
1158
bool was_quote_show= true;
1160
if (!session->temporary_tables)
1163
if (!drizzle_bin_log.is_open() || true )
1166
for (table= session->temporary_tables; table; table= tmp_next)
1168
tmp_next= table->next;
1169
close_temporary(table, 1, 1);
1171
session->temporary_tables= 0;
1175
/* Better add "if exists", in case a RESET MASTER has been done */
1176
const char stub[]= "DROP /*!40005 TEMPORARY */ Table IF EXISTS ";
1177
uint32_t stub_len= sizeof(stub) - 1;
1179
String s_query= String(buf, sizeof(buf), system_charset_info);
1180
bool found_user_tables= false;
1182
memcpy(buf, stub, stub_len);
1185
Insertion sort of temp tables by pseudo_thread_id to build ordered list
1186
of sublists of equal pseudo_thread_id
1189
for (prev_table= session->temporary_tables, table= prev_table->next;
1191
prev_table= table, table= table->next)
1193
Table *prev_sorted /* same as for prev_table */, *sorted;
1194
if (is_user_table(table))
1196
if (!found_user_tables)
1197
found_user_tables= true;
1198
for (prev_sorted= NULL, sorted= session->temporary_tables; sorted != table;
1199
prev_sorted= sorted, sorted= sorted->next)
1201
if (!is_user_table(sorted) ||
1202
tmpkeyval(session, sorted) > tmpkeyval(session, table))
1204
/* move into the sorted part of the list from the unsorted */
1205
prev_table->next= table->next;
1206
table->next= sorted;
1209
prev_sorted->next= table;
1213
session->temporary_tables= table;
1222
/* We always quote db,table names though it is slight overkill */
1223
if (found_user_tables &&
1224
!(was_quote_show= test(session->options & OPTION_QUOTE_SHOW_CREATE)))
1226
session->options |= OPTION_QUOTE_SHOW_CREATE;
1229
/* scan sorted tmps to generate sequence of DROP */
1230
for (table= session->temporary_tables; table; table= next)
1232
if (is_user_table(table))
1234
my_thread_id save_pseudo_thread_id= session->variables.pseudo_thread_id;
1235
/* Set pseudo_thread_id to be that of the processed table */
1236
session->variables.pseudo_thread_id= tmpkeyval(session, table);
1238
Loop forward through all tables within the sublist of
1239
common pseudo_thread_id to create single DROP query.
1241
for (s_query.length(stub_len);
1242
table && is_user_table(table) &&
1243
tmpkeyval(session, table) == session->variables.pseudo_thread_id;
1247
We are going to add 4 ` around the db/table names and possible more
1248
due to special characters in the names
1250
append_identifier(session, &s_query, table->s->db.str, strlen(table->s->db.str));
1251
s_query.append('.');
1252
append_identifier(session, &s_query, table->s->table_name.str,
1253
strlen(table->s->table_name.str));
1254
s_query.append(',');
1256
close_temporary(table, 1, 1);
1258
session->clear_error();
1259
const CHARSET_INFO * const cs_save= session->variables.character_set_client;
1260
session->variables.character_set_client= system_charset_info;
1261
Query_log_event qinfo(session, s_query.ptr(),
1262
s_query.length() - 1 /* to remove trailing ',' */,
1264
session->variables.character_set_client= cs_save;
1266
Imagine the thread had created a temp table, then was doing a
1267
SELECT, and the SELECT was killed. Then it's not clever to
1268
mark the statement above as "killed", because it's not really
1269
a statement updating data, and there are 99.99% chances it
1270
will succeed on slave. If a real update (one updating a
1271
persistent table) was killed on the master, then this real
1272
update will be logged with error_code=killed, rightfully
1273
causing the slave to stop.
1275
qinfo.error_code= 0;
1276
drizzle_bin_log.write(&qinfo);
1277
session->variables.pseudo_thread_id= save_pseudo_thread_id;
1282
close_temporary(table, 1, 1);
1285
if (!was_quote_show)
1286
session->options&= ~OPTION_QUOTE_SHOW_CREATE; /* restore option */
1287
session->temporary_tables=0;
403
1291
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.
1294
find_table_in_list()
1295
table Pointer to table list
1296
offset Offset to which list in table structure to use
1297
db_name Data base name
1298
table_name Table name
1301
This is called by find_table_in_local_list() and
1302
find_table_in_global_list().
1305
NULL Table not found
1306
# Pointer to found table.
420
1309
TableList *find_table_in_list(TableList *table,
421
TableList *TableList::*link,
423
const char *table_name)
1310
TableList *TableList::*link,
1311
const char *db_name,
1312
const char *table_name)
425
1314
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)
1316
if ((table->table == 0 || table->table->s->tmp_table == NO_TMP_TABLE) &&
1317
strcmp(table->db, db_name) == 0 &&
1318
strcmp(table->table_name, table_name) == 0)
631
1483
@retval 0 the table was found and dropped successfully.
632
1484
@retval 1 the table was not found in the list of temporary tables
634
1486
@retval -1 the table is in use by a outer query
637
int Open_tables_state::drop_temporary_table(const drizzled::identifier::Table &identifier)
1489
int drop_temporary_table(Session *session, TableList *table_list)
641
if (not (table= find_temporary_table(identifier)))
1493
if (!(table= find_temporary_table(session, table_list)))
644
1496
/* 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);
1497
if (table->query_id && table->query_id != session->query_id)
1499
my_error(ER_CANT_REOPEN_TABLE, MYF(0), table->alias);
1504
If LOCK TABLES list is not empty and contains this table,
1505
unlock the table and remove the table from this list.
1507
mysql_lock_remove(session, session->locked_tables, table, false);
1508
close_temporary_table(session, table, 1, 1);
1513
unlink from session->temporary tables and close temporary table
1516
void close_temporary_table(Session *session, Table *table,
1517
bool free_share, bool delete_table)
1521
table->prev->next= table->next;
1522
if (table->prev->next)
1523
table->next->prev= table->prev;
1527
/* removing the item from the list */
1528
assert(table == session->temporary_tables);
1530
slave must reset its temporary list pointer to zero to exclude
1531
passing non-zero value to end_slave via rli->save_temporary_tables
1532
when no temp tables opened, see an invariant below.
1534
session->temporary_tables= table->next;
1535
if (session->temporary_tables)
1536
table->next->prev= 0;
1538
if (session->slave_thread)
1540
/* natural invariant of temporary_tables */
1541
assert(slave_open_temp_tables || !session->temporary_tables);
1542
slave_open_temp_tables--;
1544
close_temporary(table, free_share, delete_table);
1550
Close and delete a temporary table
1553
This dosn't unlink table from session->temporary
1554
If this is needed, use close_temporary_table()
1557
void close_temporary(Table *table, bool free_share, bool delete_table)
1559
handlerton *table_type= table->s->db_type();
1561
free_io_cache(table);
1565
rm_temporary_table(table_type, table->s->path.str);
1569
free_table_share(table->s);
1570
free((char*) table);
1577
Used by ALTER Table when the table is a temporary one. It changes something
1578
only if the ALTER contained a RENAME clause (otherwise, table_name is the old
1580
Prepares a table cache key, which is the concatenation of db, table_name and
1581
session->slave_proxy_id, separated by '\0'.
1584
bool rename_temporary_table(Session* session, Table *table, const char *db,
1585
const char *table_name)
1588
uint32_t key_length;
1589
TABLE_SHARE *share= table->s;
1590
TableList table_list;
1592
if (!(key=(char*) alloc_root(&share->mem_root, MAX_DBKEY_LENGTH)))
1593
return(1); /* purecov: inspected */
1595
table_list.db= (char*) db;
1596
table_list.table_name= (char*) table_name;
1597
key_length= create_table_def_key(session, key, &table_list, 1);
1598
share->set_table_cache_key(key, key_length);
1603
/* move table first in unused links */
1605
static void relink_unused(Table *table)
1607
if (table != unused_tables)
1609
table->prev->next=table->next; /* Remove from unused list */
1610
table->next->prev=table->prev;
1611
table->next=unused_tables; /* Link in unused tables */
1612
table->prev=unused_tables->prev;
1613
unused_tables->prev->next=table;
1614
unused_tables->prev=table;
1615
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.
1621
Remove all instances of table from thread's open list and
1624
@param session Thread context
1625
@param find Table to remove
1626
@param unlock true - free all locks on tables removed that are
1627
done with LOCK TABLES
1630
@note When unlock parameter is false or current thread doesn't have
1631
any tables locked with LOCK TABLES, tables are assumed to be
1632
not locked (for example already unlocked).
667
void Session::unlink_open_table(Table *find)
1635
void unlink_open_table(Session *session, 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());
1637
char key[MAX_DBKEY_LENGTH];
1638
uint32_t key_length= find->s->table_cache_key.length;
1639
Table *list, **prev;
1641
safe_mutex_assert_owner(&LOCK_open);
1643
memcpy(key, find->s->table_cache_key.str, key_length);
674
Note that we need to hold table::Cache::singleton().mutex() while changing the
1645
Note that we need to hold LOCK_open while changing the
675
1646
open_tables list. Another thread may work on it.
676
(See: table::Cache::singleton().removeTable(), wait_completed_table())
1647
(See: remove_table_from_cache(), mysql_wait_completed_table())
677
1648
Closing a MERGE child before the parent would be fatal if the
678
1649
other thread tries to abort the MERGE lock in between.
680
for (prev= &open_tables; *prev; )
1651
for (prev= &session->open_tables; *prev; )
684
if (list->getShare()->getCacheKey() == find_key)
1655
if (list->s->table_cache_key.length == key_length &&
1656
!memcmp(list->s->table_cache_key.str, key, key_length))
1658
if (unlock && session->locked_tables)
1659
mysql_lock_remove(session, session->locked_tables, list, true);
686
1661
/* Remove table from open_tables list. */
687
*prev= list->getNext();
689
1663
/* Close table. */
690
table::remove_table(static_cast<table::Concurrent *>(list));
1664
hash_delete(&open_cache,(unsigned char*) list); // Close table
694
1668
/* Step to next entry in open_tables list. */
695
prev= list->getNextPtr();
699
1673
// Notify any 'refresh' threads
700
locking::broadcast_refresh();
1674
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.
1680
Auxiliary routine which closes and drops open table.
1682
@param session Thread handle
1683
@param table Table object for table to be dropped
1684
@param db_name Name of database for this table
1685
@param table_name Name of this table
1687
@note This routine assumes that table to be closed is open only
1688
by calling thread so we needn't wait until other threads
1689
will close the table. Also unless called under implicit or
1690
explicit LOCK TABLES mode it assumes that table to be
1691
dropped is already unlocked. In the former case it will
1692
also remove lock on the table. But one should not rely on
1693
this behaviour as it may change in future.
1694
Currently, however, this function is never called for a
1695
table that was locked with LOCK TABLES.
723
void Session::drop_open_table(Table *table, const identifier::Table &identifier)
1698
void drop_open_table(Session *session, Table *table, const char *db_name,
1699
const char *table_name)
725
if (table->getShare()->getType())
727
close_temporary_table(table);
1701
if (table->s->tmp_table)
1702
close_temporary_table(session, table, 1, 1);
731
boost_unique_lock_t scoped_lock(table::Cache::singleton().mutex()); /* Close and drop a table (AUX routine) */
1705
handlerton *table_type= table->s->db_type();
1706
pthread_mutex_lock(&LOCK_open);
733
1708
unlink_open_table() also tells threads waiting for refresh or close
734
1709
that something has happened.
736
unlink_open_table(table);
737
(void)plugin::StorageEngine::dropTable(*this, identifier);
1711
unlink_open_table(session, table, false);
1712
quick_rm_table(table_type, db_name, table_name, 0);
1713
pthread_mutex_unlock(&LOCK_open);
743
Wait for condition but allow the user to send a kill to mysqld
1719
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
1722
wait_for_condition()
1723
session Thread handler
1724
mutex mutex that is currently hold that is associated with condition
1725
Will be unlocked on return
1726
cond Condition to wait for
753
void Session::wait_for_condition(boost::mutex &mutex, boost::condition_variable_any &cond)
1729
void wait_for_condition(Session *session, pthread_mutex_t *mutex, pthread_cond_t *cond)
755
1731
/* 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());
1732
const char *proc_info;
1733
session->mysys_var->current_mutex= mutex;
1734
session->mysys_var->current_cond= cond;
1735
proc_info=session->get_proc_info();
1736
session->set_proc_info("Waiting for table");
1737
if (!session->killed)
1738
(void) pthread_cond_wait(cond, mutex);
1741
We must unlock mutex first to avoid deadlock becasue conditions are
1742
sent to this thread by doing locks in the following order:
1743
lock(mysys_var->mutex)
1744
lock(mysys_var->current_mutex)
1746
One by effect of this that one can only use wait_for_condition with
1747
condition variables that are guranteed to not disapper (freed) even if this
1751
pthread_mutex_unlock(mutex);
1752
pthread_mutex_lock(&session->mysys_var->mutex);
1753
session->mysys_var->current_mutex= 0;
1754
session->mysys_var->current_cond= 0;
1755
session->set_proc_info(proc_info);
1756
pthread_mutex_unlock(&session->mysys_var->mutex);
1762
Exclusively name-lock a table that is already write-locked by the
1765
@param session current thread context
1766
@param tables table list containing one table to open.
1768
@return false on success, true otherwise.
1771
bool name_lock_locked_table(Session *session, TableList *tables)
1773
/* Under LOCK TABLES we must only accept write locked tables. */
1774
tables->table= find_locked_table(session, tables->db, tables->table_name);
1777
my_error(ER_TABLE_NOT_LOCKED, MYF(0), tables->alias);
1778
else if (tables->table->reginfo.lock_type < TL_WRITE_LOW_PRIORITY)
1779
my_error(ER_TABLE_NOT_LOCKED_FOR_WRITE, MYF(0), tables->alias);
1783
Ensures that table is opened only by this thread and that no
1784
other statement will open this table.
1786
wait_while_table_is_used(session, tables->table, HA_EXTRA_FORCE_REOPEN);
1795
Open table which is already name-locked by this thread.
1798
reopen_name_locked_table()
1799
session Thread handle
1800
table_list TableList object for table to be open, TableList::table
1801
member should point to Table object which was used for
1803
link_in true - if Table object for table to be opened should be
1804
linked into Session::open_tables list.
1805
false - placeholder used for name-locking is already in
1806
this list so we only need to preserve Table::next
1810
This function assumes that its caller already acquired LOCK_open mutex.
1817
bool reopen_name_locked_table(Session* session, TableList* table_list, bool link_in)
1819
Table *table= table_list->table;
1821
char *table_name= table_list->table_name;
1824
safe_mutex_assert_owner(&LOCK_open);
1826
if (session->killed || !table)
1831
if (open_unireg_entry(session, table, table_list, table_name,
1832
table->s->table_cache_key.str,
1833
table->s->table_cache_key.length))
1835
intern_close_table(table);
1837
If there was an error during opening of table (for example if it
1838
does not exist) '*table' object can be wiped out. To be able
1839
properly release name-lock in this case we should restore this
1840
object to its original state.
1848
We want to prevent other connections from opening this table until end
1849
of statement as it is likely that modifications of table's metadata are
1850
not yet finished (for example CREATE TRIGGER have to change .TRG file,
1851
or we might want to drop table if CREATE TABLE ... SELECT fails).
1852
This also allows us to assume that no other connection will sneak in
1853
before we will get table-level lock on this table.
1856
table->in_use = session;
1860
table->next= session->open_tables;
1861
session->open_tables= table;
1866
Table object should be already in Session::open_tables list so we just
1867
need to set Table::next correctly.
1869
table->next= orig_table.next;
1872
table->tablenr=session->current_tablenr++;
1873
table->used_fields=0;
1874
table->const_table=0;
1875
table->null_row= false;
1876
table->maybe_null= false;
1877
table->force_index= false;
1878
table->status=STATUS_NO_RECORD;
1884
Create and insert into table cache placeholder for table
1885
which will prevent its opening (or creation) (a.k.a lock
1888
@param session Thread context
1889
@param key Table cache key for name to be locked
1890
@param key_length Table cache key length
1892
@return Pointer to Table object used for name locking or 0 in
1896
Table *table_cache_insert_placeholder(Session *session, const char *key,
1897
uint32_t key_length)
1903
safe_mutex_assert_owner(&LOCK_open);
803
1906
Create a table entry with the right key and with an old refresh version
1907
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))
1910
if (!my_multi_malloc(MYF(MY_WME | MY_ZEROFILL),
1911
&table, sizeof(*table),
1912
&share, sizeof(*share),
1913
&key_buff, key_length,
1918
share->set_table_cache_key(key_buff, key, key_length);
1919
share->tmp_table= INTERNAL_TMP_TABLE; // for intern_close_table
1920
table->in_use= session;
1921
table->locked_by_name=1;
1923
if (my_hash_insert(&open_cache, (unsigned char*)table))
1925
free((unsigned char*) table);
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.
1934
Obtain an exclusive name lock on the table if it is not cached
1937
@param session Thread context
1938
@param db Name of database
1939
@param table_name Name of table
1940
@param[out] table Out parameter which is either:
1941
- set to NULL if table cache contains record for
1943
- set to point to the Table instance used for
1946
@note This function takes into account all records for table in table
1947
cache, even placeholders used for name-locking. This means that
1948
'table' parameter can be set to NULL for some situations when
1949
table does not really exist.
1951
@retval true Error occured (OOM)
1952
@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)
1955
bool lock_table_name_if_not_cached(Session *session, const char *db,
1956
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())
1958
char key[MAX_DBKEY_LENGTH];
1960
uint32_t key_length;
1962
key_pos= strcpy(key_pos, db) + strlen(db);
1963
key_pos= strcpy(key_pos+1, table_name) + strlen(table_name);
1964
key_length= (uint32_t) (key_pos-key)+1;
1966
pthread_mutex_lock(&LOCK_open);
1968
if (hash_search(&open_cache, (unsigned char *)key, key_length))
1970
pthread_mutex_unlock(&LOCK_open);
856
if (not (*table= table_cache_insert_placeholder(identifier)))
1974
if (!(*table= table_cache_insert_placeholder(session, key, key_length)))
1976
pthread_mutex_unlock(&LOCK_open);
860
(*table)->open_placeholder= true;
861
(*table)->setNext(open_tables);
1979
(*table)->open_placeholder= 1;
1980
(*table)->next= session->open_tables;
1981
session->open_tables= *table;
1982
pthread_mutex_unlock(&LOCK_open);
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.
1991
session Thread context.
1992
table_list Open first table in list.
1993
refresh INOUT Pointer to memory that will be set to 1 if
1994
we need to close all tables and reopen them.
1995
If this is a NULL pointer, then the table is not
1996
put in the thread-open-list.
1997
flags Bitmap of flags to modify how open works:
1998
DRIZZLE_LOCK_IGNORE_FLUSH - Open table even if
1999
someone has done a flush or namelock on it.
2000
No version number checking is done.
2001
DRIZZLE_OPEN_TEMPORARY_ONLY - Open only temporary
2002
table not the base table or view.
886
Uses a cache of open tables to find a table not in use.
2005
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.
2007
If table list element for the table to be opened has "create" flag
2008
set and table does not exist, this function will automatically insert
2009
a placeholder for exclusive name lock into the open tables cache and
2010
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.
2013
NULL Open failed. If refresh is set then one should close
2014
all other tables and retry the open.
2015
# Success. Pointer to Table object for open table.
900
Table *Session::openTable(TableList *table_list, bool *refresh, uint32_t flags)
2019
Table *open_table(Session *session, TableList *table_list, bool *refresh, uint32_t flags)
903
const char *alias= table_list->alias;
2021
register Table *table;
2022
char key[MAX_DBKEY_LENGTH];
2023
unsigned int key_length;
2024
char *alias= table_list->alias;
2025
HASH_SEARCH_STATE state;
905
2027
/* Parsing of partitioning information from .frm needs session->lex set up. */
906
assert(lex->is_lex_started);
2028
assert(session->lex->is_lex_started);
908
2030
/* find a unused table in the open table cache */
912
2034
/* 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;
2035
if (check_stack_overrun(session, STACK_MIN_SIZE_FOR_OPEN, (unsigned char *)&alias))
2038
if (session->killed)
2041
key_length= (create_table_def_key(session, key, table_list, 1) -
2042
TMP_TABLE_KEY_EXTRA);
924
2045
Unless requested otherwise, try to resolve this table in the list
925
2046
of temporary tables of this thread. In MySQL temporary tables
926
2047
are always thread-local and "shadow" possible base tables with the
927
2048
same name. This block implements the behaviour.
928
TODO -> move this block into a separate function.
2049
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)
2052
for (table= session->temporary_tables; table ; table=table->next)
2054
if (table->s->table_cache_key.length == key_length +
2055
TMP_TABLE_KEY_EXTRA &&
2056
!memcmp(table->s->table_cache_key.str, key,
2057
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
2060
We're trying to use the same temporary table twice in a query.
2061
Right now we don't support this because a temporary table
2062
is always represented by only one Table object in Session, and
2063
it can not be cloned. Emit an error for an unsupported behaviour.
1047
if (table->needs_reopen_or_name_lock())
2065
if (table->query_id)
2067
my_error(ER_CANT_REOPEN_TABLE, MYF(0), table->alias);
2070
table->query_id= session->query_id;
2071
session->thread_specific_used= true;
2077
if (flags & DRIZZLE_OPEN_TEMPORARY_ONLY)
2079
my_error(ER_NO_SUCH_TABLE, MYF(0), table_list->db, table_list->table_name);
2084
The table is not temporary - if we're in pre-locked or LOCK TABLES
2085
mode, let's try to find the requested table in the list of pre-opened
2086
and locked tables. If the table is not there, return an error - we can't
2087
open not pre-opened tables in pre-locked/LOCK TABLES mode.
2088
TODO: move this block into a separate function.
2090
if (session->locked_tables)
2091
{ // Using table locks
2092
Table *best_table= 0;
2093
int best_distance= INT_MIN;
2094
bool check_if_used= false;
2095
for (table=session->open_tables; table ; table=table->next)
2097
if (table->s->table_cache_key.length == key_length &&
2098
!memcmp(table->s->table_cache_key.str, key, key_length))
2100
if (check_if_used && table->query_id &&
2101
table->query_id != session->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.
2104
If we are in stored function or trigger we should ensure that
2105
we won't change table that is already used by calling statement.
2106
So if we are opening table for writing, we should check that it
2107
is not already open by some calling stamement.
2109
my_error(ER_CANT_UPDATE_USED_TABLE_IN_SF_OR_TRG, MYF(0),
2110
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())
2114
When looking for a usable Table, ignore MERGE children, as they
2115
belong to their parent and cannot be used explicitly.
2117
if (!my_strcasecmp(system_charset_info, table->alias, alias) &&
2118
table->query_id != session->query_id) /* skip tables already used */
1125
identifier::Table lock_table_identifier(table_list->getSchemaName(), table_list->getTableName(), message::Table::STANDARD);
2120
int distance= ((int) table->reginfo.lock_type -
2121
(int) table_list->lock_type);
2123
Find a table that either has the exact lock type requested,
2124
or has the best suitable lock. In case there is no locked
2125
table that has an equal or higher lock than requested,
2126
we us the closest matching lock to be able to produce an error
2127
message about wrong lock mode on the table. The best_table
2128
is changed if bd < 0 <= d or bd < d < 0 or 0 <= d < bd.
1127
if (not plugin::StorageEngine::doesTableExist(*this, lock_table_identifier))
2130
distance < 0 - No suitable lock found
2131
distance > 0 - we have lock mode higher then we require
2132
distance == 0 - we have lock mode exactly which we need
2134
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)))
2136
best_distance= distance;
2138
if (best_distance == 0 && !check_if_used)
2141
If we have found perfect match and we don't need to check that
2142
table is not used by one of calling statements (assuming that
2143
we are inside of function or trigger) we can finish iterating
2144
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);
2155
table->query_id= session->query_id;
2159
No table in the locked tables list. In case of explicit LOCK TABLES
2160
this can happen if a user did not include the able into the list.
2161
In case of pre-locked mode locked tables list is generated automatically,
2162
so we may only end up here if the table did not exist when
2163
locked tables list was created.
2165
my_error(ER_TABLE_NOT_LOCKED, MYF(0), alias);
2170
Non pre-locked/LOCK TABLES mode, and the table is not temporary:
2171
this is the normal use case.
2173
- try to find the table in the table cache.
2174
- if one of the discovered Table instances is name-locked
2175
(table->s->version == 0) or some thread has started FLUSH TABLES
2176
(refresh_version > table->s->version), back off -- we have to wait
2177
until no one holds a name lock on the table.
2178
- if there is no such Table in the name cache, read the table definition
2179
and insert it into the cache.
2180
We perform all of the above under LOCK_open which currently protects
2181
the open cache (also known as table cache) and table definitions stored
2185
pthread_mutex_lock(&LOCK_open);
2188
If it's the first table from a list of tables used in a query,
2189
remember refresh_version (the version of open_cache state).
2190
If the version changes while we're opening the remaining tables,
2191
we will have to back off, close all the tables opened-so-far,
2192
and try to reopen them.
2193
Note: refresh_version is currently changed only during FLUSH TABLES.
2195
if (!session->open_tables)
2196
session->version=refresh_version;
2197
else if ((session->version != refresh_version) &&
2198
! (flags & DRIZZLE_LOCK_IGNORE_FLUSH))
2200
/* 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);
2203
pthread_mutex_unlock(&LOCK_open);
2208
In order for the back off and re-start process to work properly,
2209
handler tables having old versions (due to FLUSH TABLES or pending
2210
name-lock) MUST be closed. This is specially important if a name-lock
2211
is pending for any table of the handler_tables list, otherwise a
2214
if (session->handler_tables)
2215
mysql_ha_flush(session);
2218
Actually try to find the table in the open_cache.
2219
The cache may contain several "Table" instances for the same
2220
physical table. The instances that are currently "in use" by
2221
some thread have their "in_use" member != NULL.
2222
There is no good reason for having more than one entry in the
2223
hash for the same physical table, except that we use this as
2224
an implicit "pending locks queue" - see
2225
wait_for_locked_table_names for details.
2227
for (table= (Table*) hash_first(&open_cache, (unsigned char*) key, key_length,
2229
table && table->in_use ;
2230
table= (Table*) hash_next(&open_cache, (unsigned char*) key, key_length,
2234
Here we flush tables marked for flush.
2235
Normally, table->s->version contains the value of
2236
refresh_version from the moment when this table was
2237
(re-)opened and added to the cache.
2238
If since then we did (or just started) FLUSH TABLES
2239
statement, refresh_version has been increased.
2240
For "name-locked" Table instances, table->s->version is set
2241
to 0 (see lock_table_name for details).
2242
In case there is a pending FLUSH TABLES or a name lock, we
2243
need to back off and re-start opening tables.
2244
If we do not back off now, we may dead lock in case of lock
2245
order mismatch with some other thread:
2246
c1: name lock t1; -- sort of exclusive lock
2247
c2: open t2; -- sort of shared lock
2248
c1: name lock t2; -- blocks
2249
c2: open t1; -- blocks
2251
if (table->needs_reopen_or_name_lock())
2253
if (flags & DRIZZLE_LOCK_IGNORE_FLUSH)
2255
/* Force close at once after usage */
2256
session->version= table->s->version;
2260
/* Avoid self-deadlocks by detecting self-dependencies. */
2261
if (table->open_placeholder && table->in_use == session)
2263
pthread_mutex_unlock(&LOCK_open);
2264
my_error(ER_UPDATE_TABLE_USED, MYF(0), table->s->table_name.str);
2269
Back off, part 1: mark the table as "unused" for the
2270
purpose of name-locking by setting table->db_stat to 0. Do
2271
that only for the tables in this thread that have an old
2272
table->s->version (this is an optimization (?)).
2273
table->db_stat == 0 signals wait_for_locked_table_names
2274
that the tables in question are not used any more. See
2275
table_is_used call for details.
2277
Notice that HANDLER tables were already taken care of by
2278
the earlier call to mysql_ha_flush() in this same critical
2281
close_old_data_files(session,session->open_tables,0,0);
2283
Back-off part 2: try to avoid "busy waiting" on the table:
2284
if the table is in use by some other thread, we suspend
2285
and wait till the operation is complete: when any
2286
operation that juggles with table->s->version completes,
2287
it broadcasts COND_refresh condition variable.
2288
If 'old' table we met is in use by current thread we return
2289
without waiting since in this situation it's this thread
2290
which is responsible for broadcasting on COND_refresh
2291
(and this was done already in close_old_data_files()).
2292
Good example of such situation is when we have statement
2293
that needs two instances of table and FLUSH TABLES comes
2294
after we open first instance but before we open second
2297
if (table->in_use != session)
2299
/* wait_for_conditionwill unlock LOCK_open for us */
2300
wait_for_condition(session, &LOCK_open, &COND_refresh);
2304
pthread_mutex_unlock(&LOCK_open);
2307
There is a refresh in progress for this table.
2308
Signal the caller that it has to try again.
2317
/* Unlink the table from "unused_tables" list. */
2318
if (table == unused_tables)
2320
unused_tables=unused_tables->next; // Remove from link
2321
if (table == unused_tables)
2324
table->prev->next=table->next; /* Remove from unused list */
2325
table->next->prev=table->prev;
2326
table->in_use= session;
2330
/* Insert a new Table instance into the open cache */
2332
/* Free cache if too big */
2333
while (open_cache.records > table_cache_size && unused_tables)
2334
hash_delete(&open_cache,(unsigned char*) unused_tables); /* purecov: tested */
2336
if (table_list->create)
2338
if(ha_table_exists_in_engine(session, table_list->db,
2339
table_list->table_name)
2340
== HA_ERR_TABLE_EXIST)
2342
pthread_mutex_unlock(&LOCK_open);
2348
Table to be created, so we need to create placeholder in table-cache.
2350
if (!(table= table_cache_insert_placeholder(session, key, key_length)))
2352
pthread_mutex_unlock(&LOCK_open);
2356
Link placeholder to the open tables list so it will be automatically
2357
removed once tables are closed. Also mark it so it won't be ignored
2358
by other trying to take name-lock.
2360
table->open_placeholder= 1;
2361
table->next= session->open_tables;
2362
session->open_tables= table;
2363
pthread_mutex_unlock(&LOCK_open);
2366
/* Table exists. Let us try to open it. */
2369
/* make a new table */
2370
if ((table= new Table) == NULL)
2372
pthread_mutex_unlock(&LOCK_open);
2376
error= open_unireg_entry(session, table, table_list, alias, key, key_length);
2377
/* Combine the follow two */
2381
pthread_mutex_unlock(&LOCK_open);
2386
free((unsigned char*)table);
2387
pthread_mutex_unlock(&LOCK_open);
2390
my_hash_insert(&open_cache,(unsigned char*) table);
2393
pthread_mutex_unlock(&LOCK_open);
2396
table->next=session->open_tables; /* Link into simple list */
2397
session->open_tables=table;
2399
table->reginfo.lock_type=TL_READ; /* Assume read */
2402
assert(table->s->ref_count > 0 || table->s->tmp_table != NO_TMP_TABLE);
2404
if (session->lex->need_correct_ident())
2405
table->alias_name_used= my_strcasecmp(table_alias_charset,
2406
table->s->table_name.str, alias);
1180
2407
/* Fix alias if table name changes */
1181
if (strcmp(table->getAlias(), alias))
2408
if (strcmp(table->alias, alias))
1183
table->setAlias(alias);
2410
uint32_t length=(uint) strlen(alias)+1;
2411
table->alias= (char*) realloc((char*) table->alias, length);
2412
memcpy((void*) table->alias, alias, length);
1186
2414
/* These variables are also set in reopen_table() */
1187
table->tablenr= current_tablenr++;
1188
table->used_fields= 0;
1189
table->const_table= 0;
2415
table->tablenr=session->current_tablenr++;
2416
table->used_fields=0;
2417
table->const_table=0;
1190
2418
table->null_row= false;
1191
2419
table->maybe_null= false;
1192
2420
table->force_index= false;
1193
2421
table->status=STATUS_NO_RECORD;
1194
table->insert_values.clear();
2422
table->insert_values= 0;
1195
2423
/* Catch wrong handling of the auto_increment_field_not_null. */
1196
2424
assert(!table->auto_increment_field_not_null);
1197
2425
table->auto_increment_field_not_null= false;
1198
2426
if (table->timestamp_field)
1200
2427
table->timestamp_field_type= table->timestamp_field->get_auto_set_type();
1202
2428
table->pos_in_table_list= table_list;
1203
2429
table->clear_column_bitmaps();
1204
2430
assert(table->key_read == 0);
2435
Table *find_locked_table(Session *session, const char *db,const char *table_name)
2437
char key[MAX_DBKEY_LENGTH];
2439
uint32_t key_length;
2441
key_pos= strcpy(key_pos, db) + strlen(db);
2442
key_pos= strcpy(key_pos+1, table_name) + strlen(table_name);
2443
key_length= (uint32_t)(key_pos-key)+1;
2445
for (Table *table=session->open_tables; table ; table=table->next)
2447
if (table->s->table_cache_key.length == key_length &&
2448
!memcmp(table->s->table_cache_key.str, key, key_length))
2456
Reopen an table because the definition has changed.
2463
The data file for the table is already closed and the share is released
2464
The table has a 'dummy' share that mainly contains database and table name.
2468
1 error. The old table object is not changed.
2471
bool reopen_table(Table *table)
2477
TableList table_list;
2478
Session *session= table->in_use;
2480
assert(table->s->ref_count == 0);
2481
assert(!table->sort.io_cache);
2485
sql_print_error(_("Table %s had a open data handler in reopen_table"),
2488
memset(&table_list, 0, sizeof(TableList));
2489
table_list.db= table->s->db.str;
2490
table_list.table_name= table->s->table_name.str;
2491
table_list.table= table;
2493
if (wait_for_locked_table_names(session, &table_list))
2494
return(1); // Thread was killed
2496
if (open_unireg_entry(session, &tmp, &table_list,
2498
table->s->table_cache_key.str,
2499
table->s->table_cache_key.length))
2502
/* This list copies variables set by open_table */
2503
tmp.tablenr= table->tablenr;
2504
tmp.used_fields= table->used_fields;
2505
tmp.const_table= table->const_table;
2506
tmp.null_row= table->null_row;
2507
tmp.maybe_null= table->maybe_null;
2508
tmp.status= table->status;
2510
tmp.s->table_map_id= table->s->table_map_id;
2513
tmp.in_use= session;
2514
tmp.reginfo.lock_type=table->reginfo.lock_type;
2516
/* Replace table in open list */
2517
tmp.next= table->next;
2518
tmp.prev= table->prev;
2521
closefrm(table, 1); // close file, free everything
2524
table->default_column_bitmaps();
2525
table->file->change_table_ptr(table, table->s);
2527
assert(table->alias != 0);
2528
for (field=table->field ; *field ; field++)
2530
(*field)->table= (*field)->orig_table= table;
2531
(*field)->table_name= &table->alias;
2533
for (key=0 ; key < table->s->keys ; key++)
2535
for (part=0 ; part < table->key_info[key].usable_key_parts ; part++)
2536
table->key_info[key].key_part[part].field->table= table;
2539
Do not attach MERGE children here. The children might be reopened
2540
after the parent. Attach children after reopening all tables that
2541
require reopen. See for example reopen_tables().
2544
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.
2553
Close all instances of a table open by this thread and replace
2554
them with exclusive name-locks.
2556
@param session Thread context
2557
@param db Database name for the table to be closed
2558
@param table_name Name of the table to be closed
2560
@note This function assumes that if we are not under LOCK TABLES,
2561
then there is only one table open and locked. This means that
2562
the function probably has to be adjusted before it can be used
2563
anywhere outside ALTER Table.
2565
@note Must not use TABLE_SHARE::table_name/db of the table being closed,
2566
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)
2569
void close_data_files_and_morph_locks(Session *session, const char *db,
2570
const char *table_name)
1229
safe_mutex_assert_owner(table::Cache::singleton().mutex().native_handle()); /* Adjust locks at the end of ALTER TABLEL */
2574
safe_mutex_assert_owner(&LOCK_open);
1234
2579
If we are not under LOCK TABLES we should have only one table
1235
2580
open and locked so it makes sense to remove the lock at once.
2582
mysql_unlock_tables(session, session->lock);