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/transaction_services.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/timestamp.h>
49
#include <drizzled/field/null.h>
50
#include "drizzled/sql_table.h"
51
#include "drizzled/global_charset_info.h"
52
#include "drizzled/pthread_globals.h"
53
#include "drizzled/internal/iocache.h"
54
#include "drizzled/drizzled.h"
55
#include "drizzled/plugin/authorization.h"
56
#include "drizzled/table/temporary.h"
57
#include "drizzled/table/placeholder.h"
58
#include "drizzled/table/unused.h"
49
extern drizzled::TransactionServices transaction_services;
52
@defgroup Data_Dictionary Data Dictionary
55
Table *unused_tables; /* Used by mysql_test */
56
HASH open_cache; /* Used by mysql_test */
57
static HASH table_def_cache;
58
static pthread_mutex_t LOCK_table_share;
59
static bool table_def_inited= 0;
61
static int open_unireg_entry(Session *session, Table *entry, TableList *table_list,
63
char *cache_key, uint32_t cache_key_length);
64
extern "C" void free_cache_entry(void *entry);
65
static void close_old_data_files(Session *session, Table *table, bool morph_locks,
69
extern "C" unsigned char *table_cache_key(const unsigned char *record, size_t *length,
72
Table *entry=(Table*) record;
73
*length= entry->s->table_cache_key.length;
74
return (unsigned char*) entry->s->table_cache_key.str;
65
extern bool volatile shutdown_in_progress;
67
78
bool table_cache_init(void)
80
return hash_init(&open_cache, &my_charset_bin,
81
(size_t) table_cache_size+16,
82
0, 0, table_cache_key,
86
void table_cache_free(void)
90
close_cached_tables(NULL, NULL, false, false, false);
91
if (!open_cache.records) // Safety first
92
hash_free(&open_cache);
72
96
uint32_t cached_open_tables(void)
74
return table::getCache().size();
77
void table_cache_free(void)
79
refresh_version++; // Force close of open tables
81
table::getUnused().clear();
82
table::getCache().clear();
86
Close cursor handle, but leave the table in the table cache
98
return open_cache.records;
102
Create a table cache key
105
create_table_def_key()
106
key Create key here (must be of size MAX_DBKEY_LENGTH)
107
table_list Table definition
110
The table cache_key is created from:
114
if the table is a tmp table, we add the following to make each tmp table
117
4 bytes for master thread id
118
4 bytes pseudo thread id
124
uint32_t create_table_def_key(char *key, TableList *table_list)
128
key_pos= strcpy(key_pos, table_list->db) + strlen(table_list->db);
129
key_pos= strcpy(key_pos+1, table_list->table_name) +
130
strlen(table_list->table_name);
131
key_length= (uint32_t)(key_pos-key)+1;
138
/*****************************************************************************
139
Functions to handle table definition cach (TableShare)
140
*****************************************************************************/
142
extern "C" unsigned char *table_def_key(const unsigned char *record, size_t *length,
145
TableShare *entry=(TableShare*) record;
146
*length= entry->table_cache_key.length;
147
return (unsigned char*) entry->table_cache_key.str;
151
static void table_def_free_entry(TableShare *share)
153
share->free_table_share();
157
bool table_def_init(void)
160
pthread_mutex_init(&LOCK_table_share, MY_MUTEX_INIT_FAST);
162
return hash_init(&table_def_cache, &my_charset_bin, (size_t)table_def_size,
164
(hash_free_key) table_def_free_entry, 0);
168
void table_def_free(void)
170
if (table_def_inited)
173
pthread_mutex_destroy(&LOCK_table_share);
174
hash_free(&table_def_cache);
179
uint32_t cached_table_definitions(void)
181
return table_def_cache.records;
186
Get TableShare for a table.
189
session Thread handle
190
table_list Table that should be opened
192
key_length Length of key
193
error out: Error code from open_table_def()
196
Get a table definition from the table definition cache.
197
If it doesn't exist, create a new from the table definition file.
200
We must have wrlock on LOCK_open when we come here
201
(To be changed later)
208
TableShare *get_table_share(Session *session, TableList *table_list, char *key,
209
uint32_t key_length, uint32_t, int *error)
215
/* Read table definition from cache */
216
if ((share= (TableShare*) hash_search(&table_def_cache,(unsigned char*) key,
220
if (!(share= alloc_table_share(table_list, key, key_length)))
226
Lock mutex to be able to read table definition from file without
229
(void) pthread_mutex_lock(&share->mutex);
231
if (my_hash_insert(&table_def_cache, (unsigned char*) share))
233
share->free_table_share();
234
return(0); // return error
236
if (open_table_def(session, share))
238
*error= share->error;
239
(void) hash_delete(&table_def_cache, (unsigned char*) share);
242
share->ref_count++; // Mark in use
243
(void) pthread_mutex_unlock(&share->mutex);
248
We found an existing table definition. Return it if we didn't get
249
an error when reading the table definition from file.
252
/* We must do a lock to ensure that the structure is initialized */
253
(void) pthread_mutex_lock(&share->mutex);
256
/* Table definition contained an error */
257
share->open_table_error(share->error, share->open_errno, share->errarg);
258
(void) pthread_mutex_unlock(&share->mutex);
264
(void) pthread_mutex_unlock(&share->mutex);
271
Get a table share. If it didn't exist, try creating it from engine
273
For arguments and return values, see get_table_from_share()
277
*get_table_share_with_create(Session *session, TableList *table_list,
278
char *key, uint32_t key_length,
279
uint32_t db_flags, int *error)
283
share= get_table_share(session, table_list, key, key_length, db_flags, error);
285
If share is not NULL, we found an existing share.
287
If share is NULL, and there is no error, we're inside
288
pre-locking, which silences 'ER_NO_SUCH_TABLE' errors
289
with the intention to silently drop non-existing tables
290
from the pre-locking list. In this case we still need to try
291
auto-discover before returning a NULL share.
293
If share is NULL and the error is ER_NO_SUCH_TABLE, this is
294
the same as above, only that the error was not silenced by
295
pre-locking. Once again, we need to try to auto-discover
298
Finally, if share is still NULL, it's a real error and we need
301
@todo Rework alternative ways to deal with ER_NO_SUCH Table.
303
if (share || (session->is_error() && (session->main_da.sql_errno() != ER_NO_SUCH_TABLE)))
312
Mark that we are not using table share anymore.
315
release_table_share()
319
If ref_count goes to zero and (we have done a refresh or if we have
320
already too many open table shares) then delete the definition.
322
If type == RELEASE_WAIT_FOR_DROP then don't return until we get a signal
323
that the table is deleted or the thread is killed.
326
void release_table_share(TableShare *share)
328
bool to_be_deleted= false;
330
safe_mutex_assert_owner(&LOCK_open);
332
pthread_mutex_lock(&share->mutex);
333
if (!--share->ref_count)
338
hash_delete(&table_def_cache, (unsigned char*) share);
341
pthread_mutex_unlock(&share->mutex);
346
Check if table definition exits in cache
349
get_cached_table_share()
351
table_name Table name
355
# TableShare for table
358
TableShare *get_cached_table_share(const char *db, const char *table_name)
360
char key[NAME_LEN*2+2];
361
TableList table_list;
363
safe_mutex_assert_owner(&LOCK_open);
365
table_list.db= (char*) db;
366
table_list.table_name= (char*) table_name;
367
key_length= create_table_def_key(key, &table_list);
368
return (TableShare*) hash_search(&table_def_cache,(unsigned char*) key, key_length);
373
Close file handle, but leave the table in the table cache
89
376
close_handle_and_leave_table_as_lock()
93
380
By leaving the table in the table cache, it disallows any other thread
96
session->getKilled() will be set if we run out of memory
383
session->killed will be set if we run out of memory
98
385
If closing a MERGE child, the calling function has to take care for
99
386
closing the parent too, if necessary.
103
390
void close_handle_and_leave_table_as_lock(Table *table)
392
TableShare *share, *old_share= table->s;
394
MEM_ROOT *mem_root= &table->mem_root;
105
396
assert(table->db_stat);
106
assert(table->getShare()->getType() == message::Table::STANDARD);
109
399
Make a local copy of the table share and free the current one.
110
400
This has to be done to ensure that the table share is removed from
111
401
the table defintion cache as soon as the last instance is removed
113
TableIdentifier identifier(table->getShare()->getSchemaName(), table->getShare()->getTableName(), message::Table::INTERNAL);
114
const TableIdentifier::Key &key(identifier.getKey());
115
TableShare *share= new TableShare(identifier.getType(),
117
const_cast<char *>(key.vector()), static_cast<uint32_t>(table->getShare()->getCacheKeySize()));
119
table->cursor->close();
120
table->db_stat= 0; // Mark cursor closed
121
TableShare::release(table->getMutableShare());
122
table->setShare(share);
403
if (multi_alloc_root(mem_root,
404
&share, sizeof(*share),
405
&key_buff, old_share->table_cache_key.length,
408
memset(share, 0, sizeof(*share));
409
share->set_table_cache_key(key_buff, old_share->table_cache_key.str,
410
old_share->table_cache_key.length);
411
share->tmp_table= INTERNAL_TMP_TABLE; // for intern_close_table()
414
table->file->close();
415
table->db_stat= 0; // Mark file closed
416
release_table_share(table->s);
418
table->file->change_table_ptr(table, table->s);
424
Create a list for all open tables matching SQL expression
428
wild SQL like expression
431
One gets only a list of tables for which one has any kind of privilege.
432
db and table names are allocated in result struct, so one doesn't need
433
a lock on LOCK_open when traversing the return list.
436
NULL Error (Probably OOM)
437
# Pointer to list of names of open tables.
440
OPEN_TableList *list_open_tables(const char *db, const char *wild)
443
OPEN_TableList **start_list, *open_list;
444
TableList table_list;
446
pthread_mutex_lock(&LOCK_open); /* List all open tables */
447
memset(&table_list, 0, sizeof(table_list));
448
start_list= &open_list;
451
for (uint32_t idx=0 ; result == 0 && idx < open_cache.records; idx++)
453
OPEN_TableList *table;
454
Table *entry=(Table*) hash_element(&open_cache,idx);
455
TableShare *share= entry->s;
457
if (db && my_strcasecmp(system_charset_info, db, share->db.str))
459
if (wild && wild_compare(share->table_name.str, wild, 0))
462
/* Check if user has SELECT privilege for any column in the table */
463
table_list.db= share->db.str;
464
table_list.table_name= share->table_name.str;
466
/* need to check if we haven't already listed it */
467
for (table= open_list ; table ; table=table->next)
469
if (!strcmp(table->table, share->table_name.str) &&
470
!strcmp(table->db, share->db.str))
474
if (entry->locked_by_name)
481
if (!(*start_list = (OPEN_TableList *)
482
sql_alloc(sizeof(**start_list)+share->table_cache_key.length)))
484
open_list=0; // Out of memory
487
strcpy((*start_list)->table=
488
strcpy(((*start_list)->db= (char*) ((*start_list)+1)),
489
share->db.str)+share->db.length+1,
490
share->table_name.str);
491
(*start_list)->in_use= entry->in_use ? 1 : 0;
492
(*start_list)->locked= entry->locked_by_name ? 1 : 0;
493
start_list= &(*start_list)->next;
496
pthread_mutex_unlock(&LOCK_open);
126
500
/*****************************************************************************
127
501
* Functions to free open table cache
128
502
****************************************************************************/
131
void Table::intern_close_table()
505
void intern_close_table(Table *table)
132
506
{ // Free all structures
134
if (cursor) // Not true if name lock
507
free_io_cache(table);
508
if (table->file) // Not true if name lock
509
table->closefrm(true); // close file
513
Remove table from the open table cache
517
entry Table to remove
520
We need to have a lock on LOCK_open when calling this
523
void free_cache_entry(void *entry)
525
Table *table= static_cast<Table *>(entry);
526
intern_close_table(table);
136
delete_table(true); // close cursor
529
table->next->prev=table->prev; /* remove from used chain */
530
table->prev->next=table->next;
531
if (table == unused_tables)
533
unused_tables=unused_tables->next;
534
if (table == unused_tables)
140
542
/* Free resources allocated by filesort() and read_record() */
142
void Table::free_io_cache()
544
void free_io_cache(Table *table)
546
if (table->sort.io_cache)
146
sort.io_cache->close_cached_file();
147
delete sort.io_cache;
548
close_cached_file(table->sort.io_cache);
549
delete table->sort.io_cache;
550
table->sort.io_cache= 0;
165
567
and tables must be NULL.
168
bool Session::close_cached_tables(TableList *tables, bool wait_for_refresh, bool wait_for_placeholders)
570
bool close_cached_tables(Session *session, TableList *tables, bool have_lock,
571
bool wait_for_refresh, bool wait_for_placeholders)
171
Session *session= this;
574
assert(session || (!wait_for_refresh && !tables));
577
pthread_mutex_lock(&LOCK_open); /* Optionally lock for remove tables from open_cahe if not in use */
174
table::Cache::singleton().mutex().lock(); /* Optionally lock for remove tables from open_cahe if not in use */
178
refresh_version++; // Force close of open tables
180
table::getUnused().clear();
182
if (wait_for_refresh)
185
Other threads could wait in a loop in open_and_lock_tables(),
186
trying to lock one or more of our tables.
188
If they wait for the locks in thr_multi_lock(), their lock
189
request is aborted. They loop in open_and_lock_tables() and
190
enter open_table(). Here they notice the table is refreshed and
191
wait for COND_refresh. Then they loop again in
192
openTablesLock() and this time open_table() succeeds. At
193
this moment, if we (the FLUSH TABLES thread) are scheduled and
194
on another FLUSH TABLES enter close_cached_tables(), they could
195
awake while we sleep below, waiting for others threads (us) to
196
close their open tables. If this happens, the other threads
197
would find the tables unlocked. They would get the locks, one
198
after the other, and could do their destructive work. This is an
199
issue if we have LOCK TABLES in effect.
201
The problem is that the other threads passed all checks in
202
open_table() before we refresh the table.
204
The fix for this problem is to set some_tables_deleted for all
205
threads with open tables. These threads can still get their
206
locks, but will immediately release them again after checking
207
this variable. They will then loop in openTablesLock()
208
again. There they will wait until we update all tables version
211
Setting some_tables_deleted is done by table::Cache::singleton().removeTable()
214
In other words (reviewer suggestion): You need this setting of
215
some_tables_deleted for the case when table was opened and all
216
related checks were passed before incrementing refresh_version
217
(which you already have) but attempt to lock the table happened
218
after the call to Session::close_old_data_files() i.e. after removal of
219
current thread locks.
221
for (table::CacheMap::const_iterator iter= table::getCache().begin();
222
iter != table::getCache().end();
225
Table *table= (*iter).second;
227
table->in_use->some_tables_deleted= false;
234
for (TableList *table= tables; table; table= table->next_local)
236
TableIdentifier identifier(table->getSchemaName(), table->getTableName());
237
if (table::Cache::singleton().removeTable(session, identifier,
238
RTFC_OWNED_BY_Session_FLAG))
244
wait_for_refresh= false; // Nothing to wait for
580
refresh_version++; // Force close of open tables
581
while (unused_tables)
584
if (hash_delete(&open_cache,(unsigned char*) unused_tables))
585
printf("Warning: Couldn't delete open table from hash\n");
587
hash_delete(&open_cache,(unsigned char*) unused_tables);
247
590
if (wait_for_refresh)
250
If there is any table that has a lower refresh_version, wait until
251
this is closed (or this thread is killed) before returning
593
Other threads could wait in a loop in open_and_lock_tables(),
594
trying to lock one or more of our tables.
596
If they wait for the locks in thr_multi_lock(), their lock
597
request is aborted. They loop in open_and_lock_tables() and
598
enter open_table(). Here they notice the table is refreshed and
599
wait for COND_refresh. Then they loop again in
600
open_and_lock_tables() and this time open_table() succeeds. At
601
this moment, if we (the FLUSH TABLES thread) are scheduled and
602
on another FLUSH TABLES enter close_cached_tables(), they could
603
awake while we sleep below, waiting for others threads (us) to
604
close their open tables. If this happens, the other threads
605
would find the tables unlocked. They would get the locks, one
606
after the other, and could do their destructive work. This is an
607
issue if we have LOCK TABLES in effect.
609
The problem is that the other threads passed all checks in
610
open_table() before we refresh the table.
612
The fix for this problem is to set some_tables_deleted for all
613
threads with open tables. These threads can still get their
614
locks, but will immediately release them again after checking
615
this variable. They will then loop in open_and_lock_tables()
616
again. There they will wait until we update all tables version
619
Setting some_tables_deleted is done by remove_table_from_cache()
622
In other words (reviewer suggestion): You need this setting of
623
some_tables_deleted for the case when table was opened and all
624
related checks were passed before incrementing refresh_version
625
(which you already have) but attempt to lock the table happened
626
after the call to close_old_data_files() i.e. after removal of
627
current thread locks.
253
session->mysys_var->current_mutex= &table::Cache::singleton().mutex();
254
session->mysys_var->current_cond= &COND_refresh;
255
session->set_proc_info("Flushing tables");
257
session->close_old_data_files();
260
/* Wait until all threads has closed all the tables we had locked */
261
while (found && ! session->getKilled())
264
for (table::CacheMap::const_iterator iter= table::getCache().begin();
265
iter != table::getCache().end();
629
for (uint32_t idx=0 ; idx < open_cache.records ; idx++)
631
Table *table=(Table*) hash_element(&open_cache,idx);
633
table->in_use->some_tables_deleted= 1;
640
for (TableList *table= tables; table; table= table->next_local)
642
if (remove_table_from_cache(session, table->db, table->table_name,
643
RTFC_OWNED_BY_Session_FLAG))
647
wait_for_refresh=0; // Nothing to wait for
650
if (wait_for_refresh)
653
If there is any table that has a lower refresh_version, wait until
654
this is closed (or this thread is killed) before returning
656
session->mysys_var->current_mutex= &LOCK_open;
657
session->mysys_var->current_cond= &COND_refresh;
658
session->set_proc_info("Flushing tables");
660
close_old_data_files(session,session->open_tables,1,1);
663
/* Wait until all threads has closed all the tables we had locked */
664
while (found && ! session->killed)
667
for (uint32_t idx=0 ; idx < open_cache.records ; idx++)
669
Table *table=(Table*) hash_element(&open_cache,idx);
670
/* Avoid a self-deadlock. */
671
if (table->in_use == session)
674
Note that we wait here only for tables which are actually open, and
675
not for placeholders with Table::open_placeholder set. Waiting for
676
latter will cause deadlock in the following scenario, for example:
678
conn1: lock table t1 write;
679
conn2: lock table t2 write;
683
It also does not make sense to wait for those of placeholders that
684
are employed by CREATE TABLE as in this case table simply does not
687
if (table->needs_reopen_or_name_lock() && (table->db_stat ||
688
(table->open_placeholder && wait_for_placeholders)))
268
Table *table= (*iter).second;
269
/* Avoid a self-deadlock. */
270
if (table->in_use == session)
273
Note that we wait here only for tables which are actually open, and
274
not for placeholders with Table::open_placeholder set. Waiting for
275
latter will cause deadlock in the following scenario, for example:
277
conn1-> lock table t1 write;
278
conn2-> lock table t2 write;
279
conn1-> flush tables;
280
conn2-> flush tables;
282
It also does not make sense to wait for those of placeholders that
283
are employed by CREATE TABLE as in this case table simply does not
286
if (table->needs_reopen_or_name_lock() && (table->db_stat ||
287
(table->open_placeholder && wait_for_placeholders)))
290
boost_unique_lock_t scoped(table::Cache::singleton().mutex(), boost::adopt_lock_t());
291
COND_refresh.wait(scoped);
691
pthread_cond_wait(&COND_refresh,&LOCK_open);
697
No other thread has the locked tables open; reopen them and get the
698
old locks. This should always succeed (unless some external process
699
has removed the tables)
701
session->in_lock_tables=1;
702
result=reopen_tables(session,1,1);
703
session->in_lock_tables=0;
704
/* Set version for table */
705
for (Table *table=session->open_tables; table ; table= table->next)
298
No other thread has the locked tables open; reopen them and get the
299
old locks. This should always succeed (unless some external process
300
has removed the tables)
708
Preserve the version (0) of write locked tables so that a impending
709
global read lock won't sneak in.
302
result= session->reopen_tables(true, true);
304
/* Set version for table */
305
for (Table *table= session->open_tables; table ; table= table->getNext())
308
Preserve the version (0) of write locked tables so that a impending
309
global read lock won't sneak in.
311
if (table->reginfo.lock_type < TL_WRITE_ALLOW_WRITE)
312
table->getMutableShare()->refreshVersion();
711
if (table->reginfo.lock_type < TL_WRITE_ALLOW_WRITE)
712
table->s->version= refresh_version;
316
table::Cache::singleton().mutex().unlock();
716
pthread_mutex_unlock(&LOCK_open);
319
717
if (wait_for_refresh)
321
boost_unique_lock_t scopedLock(session->mysys_var->mutex);
719
pthread_mutex_lock(&session->mysys_var->mutex);
322
720
session->mysys_var->current_mutex= 0;
323
721
session->mysys_var->current_cond= 0;
324
722
session->set_proc_info(0);
723
pthread_mutex_unlock(&session->mysys_var->mutex);
630
999
@retval -1 the table is in use by a outer query
633
int Open_tables_state::drop_temporary_table(const drizzled::TableIdentifier &identifier)
1002
int drop_temporary_table(Session *session, TableList *table_list)
637
if (not (table= find_temporary_table(identifier)))
1006
if (!(table= find_temporary_table(session, table_list)))
640
1009
/* Table might be in use by some outer statement. */
641
if (table->query_id && table->query_id != getQueryId())
643
my_error(ER_CANT_REOPEN_TABLE, MYF(0), table->getAlias());
647
close_temporary_table(table);
1010
if (table->query_id && table->query_id != session->query_id)
1012
my_error(ER_CANT_REOPEN_TABLE, MYF(0), table->alias);
1017
If LOCK TABLES list is not empty and contains this table,
1018
unlock the table and remove the table from this list.
1020
mysql_lock_remove(session, session->locked_tables, table, false);
1021
close_temporary_table(session, table, 1, 1);
1026
unlink from session->temporary tables and close temporary table
1029
void close_temporary_table(Session *session, Table *table,
1030
bool free_share, bool delete_table)
1034
table->prev->next= table->next;
1035
if (table->prev->next)
1036
table->next->prev= table->prev;
1040
/* removing the item from the list */
1041
assert(table == session->temporary_tables);
1043
slave must reset its temporary list pointer to zero to exclude
1044
passing non-zero value to end_slave via rli->save_temporary_tables
1045
when no temp tables opened, see an invariant below.
1047
session->temporary_tables= table->next;
1048
if (session->temporary_tables)
1049
table->next->prev= 0;
1051
close_temporary(table, free_share, delete_table);
1056
Close and delete a temporary table
1059
This dosn't unlink table from session->temporary
1060
If this is needed, use close_temporary_table()
1063
void close_temporary(Table *table, bool free_share, bool delete_table)
1065
StorageEngine *table_type= table->s->db_type();
1067
free_io_cache(table);
1068
table->closefrm(false);
1071
rm_temporary_table(table_type, table->s->path.str);
1075
table->s->free_table_share();
1076
free((char*) table);
1082
Used by ALTER Table when the table is a temporary one. It changes something
1083
only if the ALTER contained a RENAME clause (otherwise, table_name is the old
1085
Prepares a table cache key, which is the concatenation of db, table_name and
1086
session->slave_proxy_id, separated by '\0'.
1089
bool rename_temporary_table(Table *table, const char *db, const char *table_name)
1092
uint32_t key_length;
1093
TableShare *share= table->s;
1094
TableList table_list;
1096
if (!(key=(char*) alloc_root(&share->mem_root, MAX_DBKEY_LENGTH)))
1097
return true; /* purecov: inspected */
1099
table_list.db= (char*) db;
1100
table_list.table_name= (char*) table_name;
1101
key_length= create_table_def_key(key, &table_list);
1102
share->set_table_cache_key(key, key_length);
1108
/* move table first in unused links */
1110
static void relink_unused(Table *table)
1112
if (table != unused_tables)
1114
table->prev->next=table->next; /* Remove from unused list */
1115
table->next->prev=table->prev;
1116
table->next=unused_tables; /* Link in unused tables */
1117
table->prev=unused_tables->prev;
1118
unused_tables->prev->next=table;
1119
unused_tables->prev=table;
1120
unused_tables=table;
742
1226
wait_for_condition()
743
session Thread Cursor
1227
session Thread handler
744
1228
mutex mutex that is currently hold that is associated with condition
745
1229
Will be unlocked on return
746
1230
cond Condition to wait for
749
void Session::wait_for_condition(boost::mutex &mutex, boost::condition_variable_any &cond)
1233
void wait_for_condition(Session *session, pthread_mutex_t *mutex, pthread_cond_t *cond)
751
1235
/* Wait until the current table is up to date */
752
const char *saved_proc_info;
753
mysys_var->current_mutex= &mutex;
754
mysys_var->current_cond= &cond;
755
saved_proc_info= get_proc_info();
756
set_proc_info("Waiting for table");
759
We must unlock mutex first to avoid deadlock becasue conditions are
760
sent to this thread by doing locks in the following order:
761
lock(mysys_var->mutex)
762
lock(mysys_var->current_mutex)
764
One by effect of this that one can only use wait_for_condition with
765
condition variables that are guranteed to not disapper (freed) even if this
768
boost_unique_lock_t scopedLock(mutex, boost::adopt_lock_t());
771
cond.wait(scopedLock);
774
boost_unique_lock_t mysys_scopedLock(mysys_var->mutex);
775
mysys_var->current_mutex= 0;
776
mysys_var->current_cond= 0;
777
set_proc_info(saved_proc_info);
1236
const char *proc_info;
1237
session->mysys_var->current_mutex= mutex;
1238
session->mysys_var->current_cond= cond;
1239
proc_info=session->get_proc_info();
1240
session->set_proc_info("Waiting for table");
1241
if (!session->killed)
1242
(void) pthread_cond_wait(cond, mutex);
1245
We must unlock mutex first to avoid deadlock becasue conditions are
1246
sent to this thread by doing locks in the following order:
1247
lock(mysys_var->mutex)
1248
lock(mysys_var->current_mutex)
1250
One by effect of this that one can only use wait_for_condition with
1251
condition variables that are guranteed to not disapper (freed) even if this
1255
pthread_mutex_unlock(mutex);
1256
pthread_mutex_lock(&session->mysys_var->mutex);
1257
session->mysys_var->current_mutex= 0;
1258
session->mysys_var->current_cond= 0;
1259
session->set_proc_info(proc_info);
1260
pthread_mutex_unlock(&session->mysys_var->mutex);
1265
Exclusively name-lock a table that is already write-locked by the
1268
@param session current thread context
1269
@param tables table list containing one table to open.
1271
@return false on success, true otherwise.
1274
bool name_lock_locked_table(Session *session, TableList *tables)
1276
/* Under LOCK TABLES we must only accept write locked tables. */
1277
tables->table= find_locked_table(session, tables->db, tables->table_name);
1280
my_error(ER_TABLE_NOT_LOCKED, MYF(0), tables->alias);
1281
else if (tables->table->reginfo.lock_type <= TL_WRITE_DEFAULT)
1282
my_error(ER_TABLE_NOT_LOCKED_FOR_WRITE, MYF(0), tables->alias);
1286
Ensures that table is opened only by this thread and that no
1287
other statement will open this table.
1289
wait_while_table_is_used(session, tables->table, HA_EXTRA_FORCE_REOPEN);
1298
Open table which is already name-locked by this thread.
1301
reopen_name_locked_table()
1302
session Thread handle
1303
table_list TableList object for table to be open, TableList::table
1304
member should point to Table object which was used for
1306
link_in true - if Table object for table to be opened should be
1307
linked into Session::open_tables list.
1308
false - placeholder used for name-locking is already in
1309
this list so we only need to preserve Table::next
1313
This function assumes that its caller already acquired LOCK_open mutex.
1320
bool reopen_name_locked_table(Session* session, TableList* table_list, bool link_in)
1322
Table *table= table_list->table;
1324
char *table_name= table_list->table_name;
1327
safe_mutex_assert_owner(&LOCK_open);
1329
if (session->killed || !table)
1334
if (open_unireg_entry(session, table, table_list, table_name,
1335
table->s->table_cache_key.str,
1336
table->s->table_cache_key.length))
1338
intern_close_table(table);
1340
If there was an error during opening of table (for example if it
1341
does not exist) '*table' object can be wiped out. To be able
1342
properly release name-lock in this case we should restore this
1343
object to its original state.
1351
We want to prevent other connections from opening this table until end
1352
of statement as it is likely that modifications of table's metadata are
1353
not yet finished (for example CREATE TRIGGER have to change .TRG file,
1354
or we might want to drop table if CREATE TABLE ... SELECT fails).
1355
This also allows us to assume that no other connection will sneak in
1356
before we will get table-level lock on this table.
1359
table->in_use = session;
1363
table->next= session->open_tables;
1364
session->open_tables= table;
1369
Table object should be already in Session::open_tables list so we just
1370
need to set Table::next correctly.
1372
table->next= orig_table.next;
1375
table->tablenr=session->current_tablenr++;
1376
table->used_fields=0;
1377
table->const_table=0;
1378
table->null_row= false;
1379
table->maybe_null= false;
1380
table->force_index= false;
1381
table->status=STATUS_NO_RECORD;
937
1564
if (table->query_id)
939
my_error(ER_CANT_REOPEN_TABLE, MYF(0), table->getAlias());
1566
my_error(ER_CANT_REOPEN_TABLE, MYF(0), table->alias);
942
table->query_id= getQueryId();
1569
table->query_id= session->query_id;
1574
if (flags & DRIZZLE_OPEN_TEMPORARY_ONLY)
950
if (flags & DRIZZLE_OPEN_TEMPORARY_ONLY)
952
my_error(ER_NO_SUCH_TABLE, MYF(0), table_list->getSchemaName(), table_list->getTableName());
957
If it's the first table from a list of tables used in a query,
958
remember refresh_version (the version of open_cache state).
959
If the version changes while we're opening the remaining tables,
960
we will have to back off, close all the tables opened-so-far,
961
and try to reopen them.
963
Note-> refresh_version is currently changed only during FLUSH TABLES.
967
version= refresh_version;
969
else if ((version != refresh_version) &&
970
! (flags & DRIZZLE_LOCK_IGNORE_FLUSH))
972
/* Someone did a refresh while thread was opening tables */
980
Before we test the global cache, we test our local session cache.
984
assert(false); /* Not implemented yet */
988
Non pre-locked/LOCK TABLES mode, and the table is not temporary:
989
this is the normal use case.
991
- try to find the table in the table cache.
992
- if one of the discovered Table instances is name-locked
993
(table->getShare()->version == 0) back off -- we have to wait
994
until no one holds a name lock on the table.
995
- if there is no such Table in the name cache, read the table definition
996
and insert it into the cache.
997
We perform all of the above under table::Cache::singleton().mutex() which currently protects
998
the open cache (also known as table cache) and table definitions stored
1003
table::Cache::singleton().mutex().lock(); /* Lock for FLUSH TABLES for open table */
1006
Actually try to find the table in the open_cache.
1007
The cache may contain several "Table" instances for the same
1008
physical table. The instances that are currently "in use" by
1009
some thread have their "in_use" member != NULL.
1010
There is no good reason for having more than one entry in the
1011
hash for the same physical table, except that we use this as
1012
an implicit "pending locks queue" - see
1013
wait_for_locked_table_names for details.
1015
ppp= table::getCache().equal_range(key);
1018
for (table::CacheMap::const_iterator iter= ppp.first;
1019
iter != ppp.second; ++iter, table= NULL)
1576
my_error(ER_NO_SUCH_TABLE, MYF(0), table_list->db, table_list->table_name);
1581
The table is not temporary - if we're in pre-locked or LOCK TABLES
1582
mode, let's try to find the requested table in the list of pre-opened
1583
and locked tables. If the table is not there, return an error - we can't
1584
open not pre-opened tables in pre-locked/LOCK TABLES mode.
1585
TODO: move this block into a separate function.
1587
if (session->locked_tables)
1588
{ // Using table locks
1589
Table *best_table= 0;
1590
int best_distance= INT_MIN;
1591
bool check_if_used= false;
1592
for (table=session->open_tables; table ; table=table->next)
1594
if (table->s->table_cache_key.length == key_length &&
1595
!memcmp(table->s->table_cache_key.str, key, key_length))
1021
table= (*iter).second;
1023
if (not table->in_use)
1597
if (check_if_used && table->query_id &&
1598
table->query_id != session->query_id)
1601
If we are in stored function or trigger we should ensure that
1602
we won't change table that is already used by calling statement.
1603
So if we are opening table for writing, we should check that it
1604
is not already open by some calling stamement.
1606
my_error(ER_CANT_UPDATE_USED_TABLE_IN_SF_OR_TRG, MYF(0),
1607
table->s->table_name.str);
1026
Here we flush tables marked for flush.
1027
Normally, table->getShare()->version contains the value of
1028
refresh_version from the moment when this table was
1029
(re-)opened and added to the cache.
1030
If since then we did (or just started) FLUSH TABLES
1031
statement, refresh_version has been increased.
1032
For "name-locked" Table instances, table->getShare()->version is set
1033
to 0 (see lock_table_name for details).
1034
In case there is a pending FLUSH TABLES or a name lock, we
1035
need to back off and re-start opening tables.
1036
If we do not back off now, we may dead lock in case of lock
1037
order mismatch with some other thread:
1038
c1-> name lock t1; -- sort of exclusive lock
1039
c2-> open t2; -- sort of shared lock
1040
c1-> name lock t2; -- blocks
1041
c2-> open t1; -- blocks
1611
When looking for a usable Table, ignore MERGE children, as they
1612
belong to their parent and cannot be used explicitly.
1043
if (table->needs_reopen_or_name_lock())
1045
if (flags & DRIZZLE_LOCK_IGNORE_FLUSH)
1047
/* Force close at once after usage */
1048
version= table->getShare()->getVersion();
1052
/* Avoid self-deadlocks by detecting self-dependencies. */
1053
if (table->open_placeholder && table->in_use == this)
1055
table::Cache::singleton().mutex().unlock();
1056
my_error(ER_UPDATE_TABLE_USED, MYF(0), table->getShare()->getTableName());
1061
Back off, part 1: mark the table as "unused" for the
1062
purpose of name-locking by setting table->db_stat to 0. Do
1063
that only for the tables in this thread that have an old
1064
table->getShare()->version (this is an optimization (?)).
1065
table->db_stat == 0 signals wait_for_locked_table_names
1066
that the tables in question are not used any more. See
1067
table_is_used call for details.
1069
close_old_data_files(false, false);
1072
Back-off part 2: try to avoid "busy waiting" on the table:
1073
if the table is in use by some other thread, we suspend
1074
and wait till the operation is complete: when any
1075
operation that juggles with table->getShare()->version completes,
1076
it broadcasts COND_refresh condition variable.
1077
If 'old' table we met is in use by current thread we return
1078
without waiting since in this situation it's this thread
1079
which is responsible for broadcasting on COND_refresh
1080
(and this was done already in Session::close_old_data_files()).
1081
Good example of such situation is when we have statement
1082
that needs two instances of table and FLUSH TABLES comes
1083
after we open first instance but before we open second
1086
if (table->in_use != this)
1088
/* wait_for_conditionwill unlock table::Cache::singleton().mutex() for us */
1089
wait_for_condition(table::Cache::singleton().mutex(), COND_refresh);
1093
table::Cache::singleton().mutex().unlock();
1096
There is a refresh in progress for this table.
1097
Signal the caller that it has to try again.
1106
table::getUnused().unlink(static_cast<table::Concurrent *>(table));
1107
table->in_use= this;
1111
/* Insert a new Table instance into the open cache */
1113
/* Free cache if too big */
1114
table::getUnused().cull();
1116
if (table_list->isCreate())
1118
TableIdentifier lock_table_identifier(table_list->getSchemaName(), table_list->getTableName(), message::Table::STANDARD);
1120
if (not plugin::StorageEngine::doesTableExist(*this, lock_table_identifier))
1123
Table to be created, so we need to create placeholder in table-cache.
1125
if (!(table= table_cache_insert_placeholder(lock_table_identifier)))
1614
if (!my_strcasecmp(system_charset_info, table->alias, alias) &&
1615
table->query_id != session->query_id) /* skip tables already used */
1617
int distance= ((int) table->reginfo.lock_type -
1618
(int) table_list->lock_type);
1620
Find a table that either has the exact lock type requested,
1621
or has the best suitable lock. In case there is no locked
1622
table that has an equal or higher lock than requested,
1623
we us the closest matching lock to be able to produce an error
1624
message about wrong lock mode on the table. The best_table
1625
is changed if bd < 0 <= d or bd < d < 0 or 0 <= d < bd.
1627
distance < 0 - No suitable lock found
1628
distance > 0 - we have lock mode higher then we require
1629
distance == 0 - we have lock mode exactly which we need
1631
if ((best_distance < 0 && distance > best_distance) || (distance >= 0 && distance < best_distance))
1633
best_distance= distance;
1635
if (best_distance == 0 && !check_if_used)
1127
table::Cache::singleton().mutex().unlock();
1638
If we have found perfect match and we don't need to check that
1639
table is not used by one of calling statements (assuming that
1640
we are inside of function or trigger) we can finish iterating
1641
through open tables list.
1131
Link placeholder to the open tables list so it will be automatically
1132
removed once tables are closed. Also mark it so it won't be ignored
1133
by other trying to take name-lock.
1135
table->open_placeholder= true;
1136
table->setNext(open_tables);
1138
table::Cache::singleton().mutex().unlock();
1142
/* Table exists. Let us try to open it. */
1145
/* make a new table */
1147
table::Concurrent *new_table= new table::Concurrent;
1149
if (new_table == NULL)
1151
table::Cache::singleton().mutex().unlock();
1155
error= new_table->open_unireg_entry(this, alias, identifier);
1159
table::Cache::singleton().mutex().unlock();
1162
(void)table::Cache::singleton().insert(new_table);
1166
table::Cache::singleton().mutex().unlock();
1652
table->query_id= session->query_id;
1656
No table in the locked tables list. In case of explicit LOCK TABLES
1657
this can happen if a user did not include the able into the list.
1658
In case of pre-locked mode locked tables list is generated automatically,
1659
so we may only end up here if the table did not exist when
1660
locked tables list was created.
1662
my_error(ER_TABLE_NOT_LOCKED, MYF(0), alias);
1667
If it's the first table from a list of tables used in a query,
1668
remember refresh_version (the version of open_cache state).
1669
If the version changes while we're opening the remaining tables,
1670
we will have to back off, close all the tables opened-so-far,
1671
and try to reopen them.
1673
Note-> refresh_version is currently changed only during FLUSH TABLES.
1675
if (!session->open_tables)
1676
session->version=refresh_version;
1677
else if ((session->version != refresh_version) &&
1678
! (flags & DRIZZLE_LOCK_IGNORE_FLUSH))
1680
/* Someone did a refresh while thread was opening tables */
1170
table->setNext(open_tables); /* Link into simple list */
1173
table->reginfo.lock_type= TL_READ; /* Assume read */
1176
assert(table->getShare()->getTableCount() > 0 || table->getShare()->getType() != message::Table::STANDARD);
1683
pthread_mutex_unlock(&LOCK_open);
1689
Before we test the global cache, we test our local session cache.
1691
if (session->cached_table)
1693
assert(false); /* Not implemented yet */
1697
Non pre-locked/LOCK TABLES mode, and the table is not temporary:
1698
this is the normal use case.
1700
- try to find the table in the table cache.
1701
- if one of the discovered Table instances is name-locked
1702
(table->s->version == 0) back off -- we have to wait
1703
until no one holds a name lock on the table.
1704
- if there is no such Table in the name cache, read the table definition
1705
and insert it into the cache.
1706
We perform all of the above under LOCK_open which currently protects
1707
the open cache (also known as table cache) and table definitions stored
1711
pthread_mutex_lock(&LOCK_open); /* Lock for FLUSH TABLES for open table */
1714
Actually try to find the table in the open_cache.
1715
The cache may contain several "Table" instances for the same
1716
physical table. The instances that are currently "in use" by
1717
some thread have their "in_use" member != NULL.
1718
There is no good reason for having more than one entry in the
1719
hash for the same physical table, except that we use this as
1720
an implicit "pending locks queue" - see
1721
wait_for_locked_table_names for details.
1723
for (table= (Table*) hash_first(&open_cache, (unsigned char*) key, key_length,
1725
table && table->in_use ;
1726
table= (Table*) hash_next(&open_cache, (unsigned char*) key, key_length,
1730
Here we flush tables marked for flush.
1731
Normally, table->s->version contains the value of
1732
refresh_version from the moment when this table was
1733
(re-)opened and added to the cache.
1734
If since then we did (or just started) FLUSH TABLES
1735
statement, refresh_version has been increased.
1736
For "name-locked" Table instances, table->s->version is set
1737
to 0 (see lock_table_name for details).
1738
In case there is a pending FLUSH TABLES or a name lock, we
1739
need to back off and re-start opening tables.
1740
If we do not back off now, we may dead lock in case of lock
1741
order mismatch with some other thread:
1742
c1: name lock t1; -- sort of exclusive lock
1743
c2: open t2; -- sort of shared lock
1744
c1: name lock t2; -- blocks
1745
c2: open t1; -- blocks
1747
if (table->needs_reopen_or_name_lock())
1749
if (flags & DRIZZLE_LOCK_IGNORE_FLUSH)
1751
/* Force close at once after usage */
1752
session->version= table->s->version;
1756
/* Avoid self-deadlocks by detecting self-dependencies. */
1757
if (table->open_placeholder && table->in_use == session)
1759
pthread_mutex_unlock(&LOCK_open);
1760
my_error(ER_UPDATE_TABLE_USED, MYF(0), table->s->table_name.str);
1765
Back off, part 1: mark the table as "unused" for the
1766
purpose of name-locking by setting table->db_stat to 0. Do
1767
that only for the tables in this thread that have an old
1768
table->s->version (this is an optimization (?)).
1769
table->db_stat == 0 signals wait_for_locked_table_names
1770
that the tables in question are not used any more. See
1771
table_is_used call for details.
1773
Notice that HANDLER tables were already taken care of by
1774
the earlier call to mysql_ha_flush() in this same critical
1777
close_old_data_files(session,session->open_tables,0,0);
1779
Back-off part 2: try to avoid "busy waiting" on the table:
1780
if the table is in use by some other thread, we suspend
1781
and wait till the operation is complete: when any
1782
operation that juggles with table->s->version completes,
1783
it broadcasts COND_refresh condition variable.
1784
If 'old' table we met is in use by current thread we return
1785
without waiting since in this situation it's this thread
1786
which is responsible for broadcasting on COND_refresh
1787
(and this was done already in close_old_data_files()).
1788
Good example of such situation is when we have statement
1789
that needs two instances of table and FLUSH TABLES comes
1790
after we open first instance but before we open second
1793
if (table->in_use != session)
1795
/* wait_for_conditionwill unlock LOCK_open for us */
1796
wait_for_condition(session, &LOCK_open, &COND_refresh);
1800
pthread_mutex_unlock(&LOCK_open);
1803
There is a refresh in progress for this table.
1804
Signal the caller that it has to try again.
1813
/* Unlink the table from "unused_tables" list. */
1814
if (table == unused_tables)
1816
unused_tables=unused_tables->next; // Remove from link
1817
if (table == unused_tables)
1818
unused_tables= NULL;
1820
table->prev->next=table->next; /* Remove from unused list */
1821
table->next->prev=table->prev;
1822
table->in_use= session;
1826
/* Insert a new Table instance into the open cache */
1828
/* Free cache if too big */
1829
while (open_cache.records > table_cache_size && unused_tables)
1830
hash_delete(&open_cache,(unsigned char*) unused_tables); /* purecov: tested */
1832
if (table_list->create)
1834
if (ha_table_exists_in_engine(session, table_list->db,
1835
table_list->table_name)
1836
!= HA_ERR_TABLE_EXIST)
1839
Table to be created, so we need to create placeholder in table-cache.
1841
if (!(table= table_cache_insert_placeholder(session, key, key_length)))
1843
pthread_mutex_unlock(&LOCK_open);
1847
Link placeholder to the open tables list so it will be automatically
1848
removed once tables are closed. Also mark it so it won't be ignored
1849
by other trying to take name-lock.
1851
table->open_placeholder= true;
1852
table->next= session->open_tables;
1853
session->open_tables= table;
1854
pthread_mutex_unlock(&LOCK_open);
1857
/* Table exists. Let us try to open it. */
1860
/* make a new table */
1864
pthread_mutex_unlock(&LOCK_open);
1868
error= open_unireg_entry(session, table, table_list, alias, key, key_length);
1872
pthread_mutex_unlock(&LOCK_open);
1875
my_hash_insert(&open_cache, (unsigned char*) table);
1878
pthread_mutex_unlock(&LOCK_open);
1881
table->next=session->open_tables; /* Link into simple list */
1882
session->open_tables=table;
1884
table->reginfo.lock_type= TL_READ; /* Assume read */
1887
assert(table->s->ref_count > 0 || table->s->tmp_table != NO_TMP_TABLE);
1889
if (session->lex->need_correct_ident())
1890
table->alias_name_used= my_strcasecmp(table_alias_charset,
1891
table->s->table_name.str, alias);
1178
1892
/* Fix alias if table name changes */
1179
if (strcmp(table->getAlias(), alias))
1893
if (strcmp(table->alias, alias))
1181
table->setAlias(alias);
1895
uint32_t length=(uint32_t) strlen(alias)+1;
1896
table->alias= (char*) realloc((char*) table->alias, length);
1897
memcpy((void*) table->alias, alias, length);
1184
1900
/* These variables are also set in reopen_table() */
1185
table->tablenr= current_tablenr++;
1901
table->tablenr=session->current_tablenr++;
1186
1902
table->used_fields= 0;
1187
1903
table->const_table= 0;
1188
1904
table->null_row= false;
1189
1905
table->maybe_null= false;
1190
1906
table->force_index= false;
1191
1907
table->status=STATUS_NO_RECORD;
1192
table->insert_values.clear();
1908
table->insert_values= 0;
1193
1909
/* Catch wrong handling of the auto_increment_field_not_null. */
1194
1910
assert(!table->auto_increment_field_not_null);
1195
1911
table->auto_increment_field_not_null= false;
1196
1912
if (table->timestamp_field)
1198
1913
table->timestamp_field_type= table->timestamp_field->get_auto_set_type();
1200
1914
table->pos_in_table_list= table_list;
1201
1915
table->clear_column_bitmaps();
1202
1916
assert(table->key_read == 0);
1551
2434
other threads trying to get the lock.
1554
void abort_locked_tables(Session *session, const drizzled::TableIdentifier &identifier)
2437
void abort_locked_tables(Session *session,const char *db, const char *table_name)
1557
for (table= session->open_tables; table ; table= table->getNext())
2440
for (table= session->open_tables; table ; table= table->next)
1559
if (table->getShare()->getCacheKey() == identifier.getKey())
2442
if (!strcmp(table->s->table_name.str, table_name) &&
2443
!strcmp(table->s->db.str, db))
1561
2445
/* If MERGE child, forward lock handling to parent. */
1562
session->abortLock(table);
2446
mysql_lock_abort(session, table, true);
2453
Load a table definition from file and open unireg table
2457
session Thread handle
2458
entry Store open table definition here
2459
table_list TableList with db, table_name
2461
cache_key Key for share_cache
2462
cache_key_length length of cache_key
2465
Extra argument for open is taken from session->open_options
2466
One must have a lock on LOCK_open when calling this function
2473
static int open_unireg_entry(Session *session, Table *entry, TableList *table_list,
2475
char *cache_key, uint32_t cache_key_length)
2479
uint32_t discover_retry_count= 0;
2481
safe_mutex_assert_owner(&LOCK_open);
2483
if (!(share= get_table_share_with_create(session, table_list, cache_key,
2485
table_list->i_s_requested_object,
2489
while ((error= open_table_from_share(session, share, alias,
2490
(uint32_t) (HA_OPEN_KEYFILE |
2495
session->open_options, entry, OTM_OPEN)))
2497
if (error == 7) // Table def changed
2499
share->version= 0; // Mark share as old
2500
if (discover_retry_count++) // Retry once
2505
Here we should wait until all threads has released the table.
2506
For now we do one retry. This may cause a deadlock if there
2507
is other threads waiting for other tables used by this thread.
2509
Proper fix would be to if the second retry failed:
2510
- Mark that table def changed
2511
- Return from open table
2512
- Close all tables used by this thread
2513
- Start waiting that the share is released
2514
- Retry by opening all tables again
2519
To avoid deadlock, only wait for release if no one else is
2522
if (share->ref_count != 1)
2524
/* Free share and wait until it's released by all threads */
2525
release_table_share(share);
2526
if (!session->killed)
2528
drizzle_reset_errors(session, 1); // Clear warnings
2529
session->clear_error(); // Clear error message
2534
if (!entry->s || !entry->s->crashed)
2536
// Code below is for repairing a crashed file
2537
if ((error= lock_table_name(session, table_list, true)))
2541
if (wait_for_locked_table_names(session, table_list))
2543
unlock_table_name(table_list);
2547
pthread_mutex_unlock(&LOCK_open);
2548
session->clear_error(); // Clear error message
2550
if (open_table_from_share(session, share, alias,
2551
(uint32_t) (HA_OPEN_KEYFILE | HA_OPEN_RNDFILE |
2555
ha_open_options | HA_OPEN_FOR_REPAIR,
2556
entry, OTM_OPEN) || ! entry->file ||
2557
(entry->file->is_crashed() && entry->file->ha_check_and_repair(session)))
2559
/* Give right error message */
2560
session->clear_error();
2561
my_error(ER_NOT_KEYFILE, MYF(0), share->table_name.str, my_errno);
2562
errmsg_printf(ERRMSG_LVL_ERROR, _("Couldn't repair table: %s.%s"), share->db.str,
2563
share->table_name.str);
2565
entry->closefrm(false);
2569
session->clear_error(); // Clear error message
2570
pthread_mutex_lock(&LOCK_open);
2571
unlock_table_name(table_list);
2579
If we are here, there was no fatal error (but error may be still
2582
if (unlikely(entry->file->implicit_emptied))
2584
entry->file->implicit_emptied= 0;
2587
uint32_t query_buf_size= 20 + share->db.length + share->table_name.length +1;
2588
if ((query= (char*) malloc(query_buf_size)))
2591
"this DELETE FROM is needed even with row-based binlogging"
2593
We inherited this from MySQL. TODO: fix it to issue a propper truncate
2594
of the table (though that may not be completely right sematics).
2597
end+= sprintf(query, "DELETE FROM `%s`.`%s`", share->db.str,
2598
share->table_name.str);
2599
transaction_services.rawStatement(session, query, (size_t)(end - query));
2604
errmsg_printf(ERRMSG_LVL_ERROR, _("When opening HEAP table, could not allocate memory "
2605
"to write 'DELETE FROM `%s`.`%s`' to replication"),
2606
table_list->db, table_list->table_name);
2607
my_error(ER_OUTOFMEMORY, MYF(0), query_buf_size);
2608
entry->closefrm(false);
2616
release_table_share(share);
1570
2623
Open all tables in list
1574
session - thread Cursor
2627
session - thread handler
1575
2628
start - list of tables in/out
1576
2629
counter - number of opened tables will be return using this parameter
1577
2630
flags - bitmap of flags to modify how the tables will be open:
1837
Table *Open_tables_state::open_temporary_table(const TableIdentifier &identifier,
3124
Table *open_temporary_table(Session *session, const char *path, const char *db,
3125
const char *table_name, bool link_in_list,
3126
open_table_mode open_mode)
1840
assert(identifier.isTmp());
1843
table::Temporary *new_tmp_table= new table::Temporary(identifier.getType(),
1845
const_cast<char *>(const_cast<TableIdentifier&>(identifier).getPath().c_str()),
1846
static_cast<uint32_t>(identifier.getPath().length()));
1847
if (not new_tmp_table)
3130
char cache_key[MAX_DBKEY_LENGTH], *saved_cache_key, *tmp_path;
3131
uint32_t key_length, path_length;
3132
TableList table_list;
3134
table_list.db= (char*) db;
3135
table_list.table_name= (char*) table_name;
3136
/* Create the cache_key for temporary tables */
3137
key_length= create_table_def_key(cache_key, &table_list);
3138
path_length= strlen(path);
3140
if (!(tmp_table= (Table*) malloc(sizeof(*tmp_table) + sizeof(*share) +
3141
path_length + 1 + key_length)))
3144
share= (TableShare*) (tmp_table+1);
3145
tmp_path= (char*) (share+1);
3146
saved_cache_key= strcpy(tmp_path, path)+path_length+1;
3147
memcpy(saved_cache_key, cache_key, key_length);
3149
share->init(saved_cache_key, key_length, strchr(saved_cache_key, '\0')+1, tmp_path);
1851
3152
First open the share, and then open the table from the share we just opened.
1853
if (new_tmp_table->getMutableShare()->open_table_def(*static_cast<Session *>(this), identifier) ||
1854
new_tmp_table->getMutableShare()->open_table_from_share(static_cast<Session *>(this), identifier, identifier.getTableName().c_str(),
1855
(uint32_t) (HA_OPEN_KEYFILE | HA_OPEN_RNDFILE |
3154
if (open_table_def(session, share) ||
3155
open_table_from_share(session, share, table_name,
3156
(open_mode == OTM_ALTER) ? 0 :
3157
(uint32_t) (HA_OPEN_KEYFILE | HA_OPEN_RNDFILE |
3159
(open_mode == OTM_ALTER) ?
3160
(EXTRA_RECORD | OPEN_FRM_FILE_ONLY)
3163
tmp_table, open_mode))
1860
3165
/* No need to lock share->mutex as this is not needed for tmp tables */
1861
delete new_tmp_table->getMutableShare();
1862
delete new_tmp_table;
1867
new_tmp_table->reginfo.lock_type= TL_WRITE; // Simulate locked
3166
share->free_table_share();
3167
free((char*) tmp_table);
3171
tmp_table->reginfo.lock_type= TL_WRITE; // Simulate locked
3172
if (open_mode == OTM_ALTER)
3175
Temporary table has been created with frm_only
3176
and has not been created in any storage engine
3178
share->tmp_table= TMP_TABLE_FRM_FILE_ONLY;
3181
share->tmp_table= (tmp_table->file->has_transactions() ?
3182
TRANSACTIONAL_TMP_TABLE : NON_TRANSACTIONAL_TMP_TABLE);
1869
3184
if (link_in_list)
1871
3186
/* growing temp list at the head */
1872
new_tmp_table->setNext(this->temporary_tables);
1873
if (new_tmp_table->getNext())
1875
new_tmp_table->getNext()->setPrev(new_tmp_table);
1877
this->temporary_tables= new_tmp_table;
1878
this->temporary_tables->setPrev(0);
1880
new_tmp_table->pos_in_table_list= 0;
1882
return new_tmp_table;
3187
tmp_table->next= session->temporary_tables;
3188
if (tmp_table->next)
3189
tmp_table->next->prev= tmp_table;
3190
session->temporary_tables= tmp_table;
3191
session->temporary_tables->prev= 0;
3193
tmp_table->pos_in_table_list= 0;
3199
bool rm_temporary_table(StorageEngine *base, char *path)
3204
if(delete_table_proto_file(path))
3205
error=1; /* purecov: inspected */
3207
file= get_new_handler((TableShare*) 0, current_session->mem_root, base);
3208
if (file && file->ha_delete_table(path))
3211
errmsg_printf(ERRMSG_LVL_WARN, _("Could not remove temporary table: '%s', error: %d"),
3958
5525
unireg support functions
3959
5526
*****************************************************************************/
5529
Invalidate any cache entries that are for some DB
5532
remove_db_from_cache()
5533
db Database name. This will be in lower case if
5534
lower_case_table_name is set
5537
We can't use hash_delete when looping hash_elements. We mark them first
5538
and afterwards delete those marked unused.
5541
void remove_db_from_cache(const char *db)
5543
for (uint32_t idx=0 ; idx < open_cache.records ; idx++)
5545
Table *table=(Table*) hash_element(&open_cache,idx);
5546
if (!strcmp(table->s->db.str, db))
5548
table->s->version= 0L; /* Free when thread is ready */
5550
relink_unused(table);
5553
while (unused_tables && !unused_tables->s->version)
5554
hash_delete(&open_cache,(unsigned char*) unused_tables);
5559
Mark all entries with the table as deleted to force an reopen of the table
5561
The table will be closed (not stored in cache) by the current thread when
5562
close_thread_tables() is called.
5568
0 This thread now have exclusive access to this table and no other thread
5569
can access the table until close_thread_tables() is called.
5570
1 Table is in use by another thread
5573
bool remove_table_from_cache(Session *session, const char *db, const char *table_name,
5576
char key[MAX_DBKEY_LENGTH];
5578
uint32_t key_length;
5581
bool result= 0, signalled= 0;
5583
key_pos= strcpy(key_pos, db) + strlen(db);
5584
key_pos= strcpy(key_pos+1, table_name) + strlen(table_name);
5585
key_length= (uint32_t) (key_pos-key)+1;
5589
HASH_SEARCH_STATE state;
5590
result= signalled= 0;
5592
for (table= (Table*) hash_first(&open_cache, (unsigned char*) key, key_length,
5595
table= (Table*) hash_next(&open_cache, (unsigned char*) key, key_length,
5600
table->s->version=0L; /* Free when thread is ready */
5601
if (!(in_use=table->in_use))
5603
relink_unused(table);
5605
else if (in_use != session)
5608
Mark that table is going to be deleted from cache. This will
5609
force threads that are in mysql_lock_tables() (but not yet
5610
in thr_multi_lock()) to abort it's locks, close all tables and retry
5612
in_use->some_tables_deleted= 1;
5613
if (table->is_name_opened())
5618
Now we must abort all tables locks used by this thread
5619
as the thread may be waiting to get a lock for another table.
5620
Note that we need to hold LOCK_open while going through the
5621
list. So that the other thread cannot change it. The other
5622
thread must also hold LOCK_open whenever changing the
5623
open_tables list. Aborting the MERGE lock after a child was
5624
closed and before the parent is closed would be fatal.
5626
for (Table *session_table= in_use->open_tables;
5628
session_table= session_table->next)
5630
/* Do not handle locks of MERGE children. */
5631
if (session_table->db_stat) // If table is open
5632
signalled|= mysql_lock_abort_for_thread(session, session_table);
5636
result= result || (flags & RTFC_OWNED_BY_Session_FLAG);
5638
while (unused_tables && !unused_tables->s->version)
5639
hash_delete(&open_cache,(unsigned char*) unused_tables);
5641
/* Remove table from table definition cache if it's not in use */
5642
if ((share= (TableShare*) hash_search(&table_def_cache,(unsigned char*) key,
5645
share->version= 0; // Mark for delete
5646
if (share->ref_count == 0)
5648
pthread_mutex_lock(&share->mutex);
5649
hash_delete(&table_def_cache, (unsigned char*) share);
5653
if (result && (flags & RTFC_WAIT_OTHER_THREAD_FLAG))
5656
Signal any thread waiting for tables to be freed to
5659
broadcast_refresh();
5660
if (!(flags & RTFC_CHECK_KILLED_FLAG) || !session->killed)
5663
if (likely(signalled))
5664
(void) pthread_cond_wait(&COND_refresh, &LOCK_open);
5667
struct timespec abstime;
5669
It can happen that another thread has opened the
5670
table but has not yet locked any table at all. Since
5671
it can be locked waiting for a table that our thread
5672
has done LOCK Table x WRITE on previously, we need to
5673
ensure that the thread actually hears our signal
5674
before we go to sleep. Thus we wait for a short time
5675
and then we retry another loop in the
5676
remove_table_from_cache routine.
5678
set_timespec(abstime, 10);
5679
pthread_cond_timedwait(&COND_refresh, &LOCK_open, &abstime);
5691
bool is_equal(const LEX_STRING *a, const LEX_STRING *b)
5693
return a->length == b->length && !strncmp(a->str, b->str, a->length);
3965
5696
@} (end of group Data_Dictionary)