43
44
#include <drizzled/replication_services.h>
44
45
#include <drizzled/check_stack_overrun.h>
45
46
#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>
47
#include <drizzled/listen.h>
48
#include <mysys/cached_directory.h>
63
50
using namespace std;
68
extern bool volatile shutdown_in_progress;
52
extern drizzled::ReplicationServices replication_services;
55
@defgroup Data_Dictionary Data Dictionary
58
Table *unused_tables; /* Used by mysql_test */
59
HASH open_cache; /* Used by mysql_test */
60
static int open_unireg_entry(Session *session, Table *entry, TableList *table_list,
62
char *cache_key, uint32_t cache_key_length);
65
void free_cache_entry(void *entry);
66
unsigned char *table_cache_key(const unsigned char *record,
69
unsigned char *table_def_key(const unsigned char *record,
76
unsigned char *table_cache_key(const unsigned char *record,
80
Table *entry=(Table*) record;
81
*length= entry->s->table_cache_key.length;
82
return (unsigned char*) entry->s->table_cache_key.str;
70
86
bool table_cache_init(void)
88
return hash_init(&open_cache, &my_charset_bin,
89
(size_t) table_cache_size+16,
90
0, 0, table_cache_key,
94
void table_cache_free(void)
96
close_cached_tables(NULL, NULL, false, false);
97
if (!open_cache.records) // Safety first
98
hash_free(&open_cache);
75
101
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();
103
return open_cache.records;
89
Close cursor handle, but leave the table in the table cache
108
Close file handle, but leave the table in the table cache
92
111
close_handle_and_leave_table_as_lock()
96
115
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
118
session->killed will be set if we run out of memory
101
120
If closing a MERGE child, the calling function has to take care for
102
121
closing the parent too, if necessary.
106
125
void close_handle_and_leave_table_as_lock(Table *table)
127
TableShare *share, *old_share= table->s;
129
MEM_ROOT *mem_root= &table->mem_root;
108
131
assert(table->db_stat);
109
assert(table->getShare()->getType() == message::Table::STANDARD);
112
134
Make a local copy of the table share and free the current one.
113
135
This has to be done to ensure that the table share is removed from
114
136
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);
138
if (multi_alloc_root(mem_root,
139
&share, sizeof(*share),
140
&key_buff, old_share->table_cache_key.length,
143
memset(share, 0, sizeof(*share));
144
share->set_table_cache_key(key_buff, old_share->table_cache_key.str,
145
old_share->table_cache_key.length);
146
share->tmp_table= INTERNAL_TMP_TABLE; // for intern_close_table()
149
table->file->close();
150
table->db_stat= 0; // Mark file closed
151
TableShare::release(table->s);
153
table->file->change_table_ptr(table, table->s);
159
Create a list for all open tables matching SQL expression
163
wild SQL like expression
166
One gets only a list of tables for which one has any kind of privilege.
167
db and table names are allocated in result struct, so one doesn't need
168
a lock on LOCK_open when traversing the return list.
174
bool list_open_tables(const char *db, const char *wild, bool(*func)(Table *table, open_table_list_st& open_list), Table *display)
176
vector<open_table_list_st> open_list;
177
vector<open_table_list_st>::iterator it;
178
open_table_list_st table;
180
/* What we really need is an optimization for knowing unique tables */
182
open_list.reserve(sizeof(open_table_list_st) * (open_cache.records % 2));
184
open_list.reserve(sizeof(open_table_list_st) * open_cache.records);
186
pthread_mutex_lock(&LOCK_open); /* List all open tables */
188
for (uint32_t idx= 0; idx < open_cache.records; idx++)
191
Table *entry=(Table*) hash_element(&open_cache,idx);
193
if (db && my_strcasecmp(system_charset_info, db, entry->s->db.str))
195
if (wild && wild_compare(entry->s->table_name.str, wild, 0))
198
for (it= open_list.begin(); it < open_list.end(); it++)
200
if (!(*it).table.compare(entry->s->table_name.str) &&
201
!(*it).db.compare(entry->s->db.str))
205
if (entry->locked_by_name)
217
table.db= entry->s->db.str;
218
table.table= entry->s->table_name.str;
219
open_list.push_back(table);
221
pthread_mutex_unlock(&LOCK_open);
223
for (it= open_list.begin(); it < open_list.end(); it++)
225
if (func(display, *it))
129
232
/*****************************************************************************
130
233
* Functions to free open table cache
131
234
****************************************************************************/
134
void Table::intern_close_table()
237
void intern_close_table(Table *table)
135
238
{ // Free all structures
137
if (cursor) // Not true if name lock
239
free_io_cache(table);
240
if (table->file) // Not true if name lock
241
table->closefrm(true); // close file
245
Remove table from the open table cache
249
entry Table to remove
252
We need to have a lock on LOCK_open when calling this
255
void free_cache_entry(void *entry)
257
Table *table= static_cast<Table *>(entry);
258
intern_close_table(table);
139
delete_table(true); // close cursor
261
table->next->prev=table->prev; /* remove from used chain */
262
table->prev->next=table->next;
263
if (table == unused_tables)
265
unused_tables=unused_tables->next;
266
if (table == unused_tables)
143
273
/* Free resources allocated by filesort() and read_record() */
145
void Table::free_io_cache()
275
void free_io_cache(Table *table)
277
if (table->sort.io_cache)
149
sort.io_cache->close_cached_file();
150
delete sort.io_cache;
279
close_cached_file(table->sort.io_cache);
280
delete table->sort.io_cache;
281
table->sort.io_cache= 0;
168
298
and tables must be NULL.
171
bool Session::close_cached_tables(TableList *tables, bool wait_for_refresh, bool wait_for_placeholders)
301
bool close_cached_tables(Session *session, TableList *tables,
302
bool wait_for_refresh, bool wait_for_placeholders)
173
304
bool result= false;
174
Session *session= this;
177
boost::mutex::scoped_lock scopedLock(table::Cache::singleton().mutex()); /* Optionally lock for remove tables from open_cahe if not in use */
181
refresh_version++; // Force close of open tables
183
table::getUnused().clear();
185
if (wait_for_refresh)
305
assert(session || (!wait_for_refresh && !tables));
307
pthread_mutex_lock(&LOCK_open); /* Optionally lock for remove tables from open_cahe if not in use */
311
refresh_version++; // Force close of open tables
312
while (unused_tables)
315
if (hash_delete(&open_cache,(unsigned char*) unused_tables))
316
printf("Warning: Couldn't delete open table from hash\n");
318
hash_delete(&open_cache,(unsigned char*) unused_tables);
321
if (wait_for_refresh)
324
Other threads could wait in a loop in open_and_lock_tables(),
325
trying to lock one or more of our tables.
327
If they wait for the locks in thr_multi_lock(), their lock
328
request is aborted. They loop in open_and_lock_tables() and
329
enter open_table(). Here they notice the table is refreshed and
330
wait for COND_refresh. Then they loop again in
331
open_and_lock_tables() and this time open_table() succeeds. At
332
this moment, if we (the FLUSH TABLES thread) are scheduled and
333
on another FLUSH TABLES enter close_cached_tables(), they could
334
awake while we sleep below, waiting for others threads (us) to
335
close their open tables. If this happens, the other threads
336
would find the tables unlocked. They would get the locks, one
337
after the other, and could do their destructive work. This is an
338
issue if we have LOCK TABLES in effect.
340
The problem is that the other threads passed all checks in
341
open_table() before we refresh the table.
343
The fix for this problem is to set some_tables_deleted for all
344
threads with open tables. These threads can still get their
345
locks, but will immediately release them again after checking
346
this variable. They will then loop in open_and_lock_tables()
347
again. There they will wait until we update all tables version
350
Setting some_tables_deleted is done by remove_table_from_cache()
353
In other words (reviewer suggestion): You need this setting of
354
some_tables_deleted for the case when table was opened and all
355
related checks were passed before incrementing refresh_version
356
(which you already have) but attempt to lock the table happened
357
after the call to Session::close_old_data_files() i.e. after removal of
358
current thread locks.
360
for (uint32_t idx=0 ; idx < open_cache.records ; idx++)
362
Table *table=(Table*) hash_element(&open_cache,idx);
364
table->in_use->some_tables_deleted= false;
371
for (TableList *table= tables; table; table= table->next_local)
373
if (remove_table_from_cache(session, table->db, table->table_name,
374
RTFC_OWNED_BY_Session_FLAG))
378
wait_for_refresh= false; // Nothing to wait for
381
if (wait_for_refresh)
385
If there is any table that has a lower refresh_version, wait until
386
this is closed (or this thread is killed) before returning
388
session->mysys_var->current_mutex= &LOCK_open;
389
session->mysys_var->current_cond= &COND_refresh;
390
session->set_proc_info("Flushing tables");
392
session->close_old_data_files();
395
/* Wait until all threads has closed all the tables we had locked */
396
while (found && ! session->killed)
399
for (uint32_t idx=0 ; idx < open_cache.records ; idx++)
401
Table *table=(Table*) hash_element(&open_cache,idx);
402
/* Avoid a self-deadlock. */
403
if (table->in_use == session)
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.
406
Note that we wait here only for tables which are actually open, and
407
not for placeholders with Table::open_placeholder set. Waiting for
408
latter will cause deadlock in the following scenario, for example:
410
conn1: lock table t1 write;
411
conn2: lock table t2 write;
415
It also does not make sense to wait for those of placeholders that
416
are employed by CREATE TABLE as in this case table simply does not
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))
419
if (table->needs_reopen_or_name_lock() && (table->db_stat ||
420
(table->open_placeholder && wait_for_placeholders)))
423
pthread_cond_wait(&COND_refresh,&LOCK_open);
247
wait_for_refresh= false; // Nothing to wait for
429
No other thread has the locked tables open; reopen them and get the
430
old locks. This should always succeed (unless some external process
431
has removed the tables)
433
result= session->reopen_tables(true, true);
250
if (wait_for_refresh)
435
/* Set version for table */
436
for (Table *table=session->open_tables; table ; table= table->next)
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();
439
Preserve the version (0) of write locked tables so that a impending
440
global read lock won't sneak in.
442
if (table->reginfo.lock_type < TL_WRITE_ALLOW_WRITE)
443
table->s->version= refresh_version;
447
pthread_mutex_unlock(&LOCK_open);
318
449
if (wait_for_refresh)
320
boost_unique_lock_t scopedLock(session->mysys_var->mutex);
453
pthread_mutex_lock(&session->mysys_var->mutex);
321
454
session->mysys_var->current_mutex= 0;
322
455
session->mysys_var->current_cond= 0;
323
456
session->set_proc_info(0);
457
pthread_mutex_unlock(&session->mysys_var->mutex);
524
void Open_tables_state::doGetTableNames(const identifier::Schema &schema_identifier,
525
std::set<std::string>& set_of_names)
527
for (Table *table= getTemporaryTables() ; table ; table= table->getNext())
529
if (schema_identifier.compare(table->getShare()->getSchemaName()))
531
set_of_names.insert(table->getShare()->getTableName());
536
void Open_tables_state::doGetTableNames(CachedDirectory &,
537
const identifier::Schema &schema_identifier,
538
std::set<std::string> &set_of_names)
540
doGetTableNames(schema_identifier, set_of_names);
543
void Open_tables_state::doGetTableIdentifiers(const identifier::Schema &schema_identifier,
544
identifier::Table::vector &set_of_identifiers)
546
for (Table *table= getTemporaryTables() ; table ; table= table->getNext())
548
if (schema_identifier.compare(table->getShare()->getSchemaName()))
550
set_of_identifiers.push_back(identifier::Table(table->getShare()->getSchemaName(),
551
table->getShare()->getTableName(),
552
table->getShare()->getPath()));
557
void Open_tables_state::doGetTableIdentifiers(CachedDirectory &,
558
const identifier::Schema &schema_identifier,
559
identifier::Table::vector &set_of_identifiers)
561
doGetTableIdentifiers(schema_identifier, set_of_identifiers);
564
bool Open_tables_state::doDoesTableExist(const identifier::Table &identifier)
566
for (Table *table= getTemporaryTables() ; table ; table= table->getNext())
568
if (table->getShare()->getType() == message::Table::TEMPORARY)
570
if (identifier.getKey() == table->getShare()->getCacheKey())
580
int Open_tables_state::doGetTableDefinition(const identifier::Table &identifier,
581
message::Table &table_proto)
583
for (Table *table= getTemporaryTables() ; table ; table= table->getNext())
585
if (table->getShare()->getType() == message::Table::TEMPORARY)
587
if (identifier.getKey() == table->getShare()->getCacheKey())
589
table_proto.CopyFrom(*(table->getShare()->getTableMessage()));
599
Table *Open_tables_state::find_temporary_table(const identifier::Table &identifier)
601
for (Table *table= temporary_tables ; table ; table= table->getNext())
603
if (identifier.getKey() == table->getShare()->getCacheKey())
663
Table *Session::find_temporary_table(const char *new_db, const char *table_name)
665
char key[MAX_DBKEY_LENGTH];
669
key_length= TableShare::createKey(key, new_db, table_name);
671
for (table= temporary_tables ; table ; table= table->next)
673
if (table->s->table_cache_key.length == key_length &&
674
!memcmp(table->s->table_cache_key.str, key, key_length))
607
677
return NULL; // Not a temporary table
680
Table *Session::find_temporary_table(TableList *table_list)
682
return find_temporary_table(table_list->db, table_list->table_name);
612
687
Drop a temporary table.
634
709
@retval -1 the table is in use by a outer query
637
int Open_tables_state::drop_temporary_table(const drizzled::identifier::Table &identifier)
712
int Session::drop_temporary_table(TableList *table_list)
641
if (not (table= find_temporary_table(identifier)))
716
if (!(table= find_temporary_table(table_list)))
644
719
/* Table might be in use by some outer statement. */
645
if (table->query_id && table->query_id != getQueryId())
720
if (table->query_id && table->query_id != query_id)
647
my_error(ER_CANT_REOPEN_TABLE, MYF(0), table->getAlias());
722
my_error(ER_CANT_REOPEN_TABLE, MYF(0), table->alias);
651
close_temporary_table(table);
726
close_temporary_table(table, true, true);
732
unlink from session->temporary tables and close temporary table
735
void Session::close_temporary_table(Table *table,
736
bool free_share, bool delete_table)
740
table->prev->next= table->next;
741
if (table->prev->next)
742
table->next->prev= table->prev;
746
/* removing the item from the list */
747
assert(table == temporary_tables);
749
slave must reset its temporary list pointer to zero to exclude
750
passing non-zero value to end_slave via rli->save_temporary_tables
751
when no temp tables opened, see an invariant below.
753
temporary_tables= table->next;
754
if (temporary_tables)
755
table->next->prev= NULL;
757
close_temporary(table, free_share, delete_table);
762
Close and delete a temporary table
765
This dosn't unlink table from session->temporary
766
If this is needed, use close_temporary_table()
769
void close_temporary(Table *table, bool free_share, bool delete_table)
771
StorageEngine *table_type= table->s->db_type();
773
free_io_cache(table);
774
table->closefrm(false);
777
rm_temporary_table(table_type, table->s->path.str);
781
table->s->free_table_share();
782
/* This makes me sad, but we're allocating it via malloc */
789
Used by ALTER Table when the table is a temporary one. It changes something
790
only if the ALTER contained a RENAME clause (otherwise, table_name is the old
792
Prepares a table cache key, which is the concatenation of db, table_name and
793
session->slave_proxy_id, separated by '\0'.
796
bool rename_temporary_table(Table *table, const char *db, const char *table_name)
800
TableShare *share= table->s;
802
if (!(key=(char*) alloc_root(&share->mem_root, MAX_DBKEY_LENGTH)))
803
return true; /* purecov: inspected */
805
key_length= TableShare::createKey(key, db, table_name);
806
share->set_table_cache_key(key, key_length);
812
/* move table first in unused links */
814
static void relink_unused(Table *table)
816
if (table != unused_tables)
818
table->prev->next=table->next; /* Remove from unused list */
819
table->next->prev=table->prev;
820
table->next=unused_tables; /* Link in unused tables */
821
table->prev=unused_tables->prev;
822
unused_tables->prev->next=table;
823
unused_tables->prev=table;
658
830
Remove all instances of table from thread's open list and
746
920
wait_for_condition()
747
session Thread Cursor
921
session Thread handler
748
922
mutex mutex that is currently hold that is associated with condition
749
923
Will be unlocked on return
750
924
cond Condition to wait for
753
void Session::wait_for_condition(boost::mutex &mutex, boost::condition_variable_any &cond)
927
void Session::wait_for_condition(pthread_mutex_t *mutex, pthread_cond_t *cond)
755
929
/* Wait until the current table is up to date */
756
930
const char *saved_proc_info;
757
mysys_var->current_mutex= &mutex;
758
mysys_var->current_cond= &cond;
931
mysys_var->current_mutex= mutex;
932
mysys_var->current_cond= cond;
759
933
saved_proc_info= get_proc_info();
760
934
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);
936
(void) pthread_cond_wait(cond, mutex);
939
We must unlock mutex first to avoid deadlock becasue conditions are
940
sent to this thread by doing locks in the following order:
941
lock(mysys_var->mutex)
942
lock(mysys_var->current_mutex)
944
One by effect of this that one can only use wait_for_condition with
945
condition variables that are guranteed to not disapper (freed) even if this
949
pthread_mutex_unlock(mutex);
950
pthread_mutex_lock(&mysys_var->mutex);
779
951
mysys_var->current_mutex= 0;
780
952
mysys_var->current_cond= 0;
781
953
set_proc_info(saved_proc_info);
954
pthread_mutex_unlock(&mysys_var->mutex);
959
Exclusively name-lock a table that is already write-locked by the
962
@param session current thread context
963
@param tables table list containing one table to open.
965
@return false on success, true otherwise.
968
bool name_lock_locked_table(Session *session, TableList *tables)
970
/* Under LOCK TABLES we must only accept write locked tables. */
971
tables->table= find_locked_table(session, tables->db, tables->table_name);
974
my_error(ER_TABLE_NOT_LOCKED, MYF(0), tables->alias);
975
else if (tables->table->reginfo.lock_type <= TL_WRITE_DEFAULT)
976
my_error(ER_TABLE_NOT_LOCKED_FOR_WRITE, MYF(0), tables->alias);
980
Ensures that table is opened only by this thread and that no
981
other statement will open this table.
983
wait_while_table_is_used(session, tables->table, HA_EXTRA_FORCE_REOPEN);
992
Open table which is already name-locked by this thread.
995
reopen_name_locked_table()
996
session Thread handle
997
table_list TableList object for table to be open, TableList::table
998
member should point to Table object which was used for
1000
link_in true - if Table object for table to be opened should be
1001
linked into Session::open_tables list.
1002
false - placeholder used for name-locking is already in
1003
this list so we only need to preserve Table::next
1007
This function assumes that its caller already acquired LOCK_open mutex.
1014
bool Session::reopen_name_locked_table(TableList* table_list, bool link_in)
1016
Table *table= table_list->table;
1018
char *table_name= table_list->table_name;
1021
safe_mutex_assert_owner(&LOCK_open);
1023
if (killed || !table)
1028
if (open_unireg_entry(this, table, table_list, table_name,
1029
table->s->table_cache_key.str,
1030
table->s->table_cache_key.length))
1032
intern_close_table(table);
1034
If there was an error during opening of table (for example if it
1035
does not exist) '*table' object can be wiped out. To be able
1036
properly release name-lock in this case we should restore this
1037
object to its original state.
1045
We want to prevent other connections from opening this table until end
1046
of statement as it is likely that modifications of table's metadata are
1047
not yet finished (for example CREATE TRIGGER have to change .TRG file,
1048
or we might want to drop table if CREATE TABLE ... SELECT fails).
1049
This also allows us to assume that no other connection will sneak in
1050
before we will get table-level lock on this table.
1053
table->in_use = this;
1057
table->next= open_tables;
1063
Table object should be already in Session::open_tables list so we just
1064
need to set Table::next correctly.
1066
table->next= orig_table.next;
1069
table->tablenr= current_tablenr++;
1070
table->used_fields= 0;
1071
table->const_table= 0;
1072
table->null_row= false;
1073
table->maybe_null= false;
1074
table->force_index= false;
1075
table->status= STATUS_NO_RECORD;
941
1258
if (table->query_id)
943
my_error(ER_CANT_REOPEN_TABLE, MYF(0), table->getAlias());
1260
my_error(ER_CANT_REOPEN_TABLE, MYF(0), table->alias);
946
table->query_id= getQueryId();
954
if (flags & DRIZZLE_OPEN_TEMPORARY_ONLY)
956
my_error(ER_TABLE_UNKNOWN, identifier);
1263
table->query_id= query_id;
1268
if (flags & DRIZZLE_OPEN_TEMPORARY_ONLY)
1270
my_error(ER_NO_SUCH_TABLE, MYF(0), table_list->db, table_list->table_name);
1275
If it's the first table from a list of tables used in a query,
1276
remember refresh_version (the version of open_cache state).
1277
If the version changes while we're opening the remaining tables,
1278
we will have to back off, close all the tables opened-so-far,
1279
and try to reopen them.
1281
Note-> refresh_version is currently changed only during FLUSH TABLES.
1284
version= refresh_version;
1285
else if ((version != refresh_version) &&
1286
! (flags & DRIZZLE_LOCK_IGNORE_FLUSH))
1288
/* Someone did a refresh while thread was opening tables */
1296
Before we test the global cache, we test our local session cache.
1300
assert(false); /* Not implemented yet */
1304
Non pre-locked/LOCK TABLES mode, and the table is not temporary:
1305
this is the normal use case.
1307
- try to find the table in the table cache.
1308
- if one of the discovered Table instances is name-locked
1309
(table->s->version == 0) back off -- we have to wait
1310
until no one holds a name lock on the table.
1311
- if there is no such Table in the name cache, read the table definition
1312
and insert it into the cache.
1313
We perform all of the above under LOCK_open which currently protects
1314
the open cache (also known as table cache) and table definitions stored
1318
pthread_mutex_lock(&LOCK_open); /* Lock for FLUSH TABLES for open table */
1321
Actually try to find the table in the open_cache.
1322
The cache may contain several "Table" instances for the same
1323
physical table. The instances that are currently "in use" by
1324
some thread have their "in_use" member != NULL.
1325
There is no good reason for having more than one entry in the
1326
hash for the same physical table, except that we use this as
1327
an implicit "pending locks queue" - see
1328
wait_for_locked_table_names for details.
1330
for (table= (Table*) hash_first(&open_cache, (unsigned char*) key, key_length,
1332
table && table->in_use ;
1333
table= (Table*) hash_next(&open_cache, (unsigned char*) key, key_length,
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.
1337
Here we flush tables marked for flush.
1338
Normally, table->s->version contains the value of
1339
refresh_version from the moment when this table was
1340
(re-)opened and added to the cache.
1341
If since then we did (or just started) FLUSH TABLES
1342
statement, refresh_version has been increased.
1343
For "name-locked" Table instances, table->s->version is set
1344
to 0 (see lock_table_name for details).
1345
In case there is a pending FLUSH TABLES or a name lock, we
1346
need to back off and re-start opening tables.
1347
If we do not back off now, we may dead lock in case of lock
1348
order mismatch with some other thread:
1349
c1: name lock t1; -- sort of exclusive lock
1350
c2: open t2; -- sort of shared lock
1351
c1: name lock t2; -- blocks
1352
c2: open t1; -- blocks
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 */
1354
if (table->needs_reopen_or_name_lock())
1356
if (flags & DRIZZLE_LOCK_IGNORE_FLUSH)
1358
/* Force close at once after usage */
1359
version= table->s->version;
1363
/* Avoid self-deadlocks by detecting self-dependencies. */
1364
if (table->open_placeholder && table->in_use == this)
1366
pthread_mutex_unlock(&LOCK_open);
1367
my_error(ER_UPDATE_TABLE_USED, MYF(0), table->s->table_name.str);
1372
Back off, part 1: mark the table as "unused" for the
1373
purpose of name-locking by setting table->db_stat to 0. Do
1374
that only for the tables in this thread that have an old
1375
table->s->version (this is an optimization (?)).
1376
table->db_stat == 0 signals wait_for_locked_table_names
1377
that the tables in question are not used any more. See
1378
table_is_used call for details.
1380
close_old_data_files(false, false);
1383
Back-off part 2: try to avoid "busy waiting" on the table:
1384
if the table is in use by some other thread, we suspend
1385
and wait till the operation is complete: when any
1386
operation that juggles with table->s->version completes,
1387
it broadcasts COND_refresh condition variable.
1388
If 'old' table we met is in use by current thread we return
1389
without waiting since in this situation it's this thread
1390
which is responsible for broadcasting on COND_refresh
1391
(and this was done already in Session::close_old_data_files()).
1392
Good example of such situation is when we have statement
1393
that needs two instances of table and FLUSH TABLES comes
1394
after we open first instance but before we open second
1397
if (table->in_use != this)
1399
/* wait_for_conditionwill unlock LOCK_open for us */
1400
wait_for_condition(&LOCK_open, &COND_refresh);
1404
pthread_mutex_unlock(&LOCK_open);
1407
There is a refresh in progress for this table.
1408
Signal the caller that it has to try again.
984
Before we test the global cache, we test our local session cache.
988
assert(false); /* Not implemented yet */
1417
/* Unlink the table from "unused_tables" list. */
1418
if (table == unused_tables)
1420
unused_tables=unused_tables->next; // Remove from link
1421
if (table == unused_tables)
1422
unused_tables= NULL;
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
1424
table->prev->next=table->next; /* Remove from unused list */
1425
table->next->prev=table->prev;
1426
table->in_use= this;
1430
/* Insert a new Table instance into the open cache */
1432
/* Free cache if too big */
1433
while (open_cache.records > table_cache_size && unused_tables)
1434
hash_delete(&open_cache,(unsigned char*) unused_tables); /* purecov: tested */
1436
if (table_list->create)
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)
1438
char path[FN_REFLEN];
1441
length= build_table_filename(path, sizeof(path),
1442
table_list->db, table_list->table_name,
1445
if (StorageEngine::getTableProto(path, NULL) != EEXIST)
1025
table= (*iter).second;
1027
if (not table->in_use)
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
1448
Table to be created, so we need to create placeholder in table-cache.
1047
if (table->needs_reopen_or_name_lock())
1450
if (!(table= table_cache_insert_placeholder(key, key_length)))
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.
1452
pthread_mutex_unlock(&LOCK_open);
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())
1125
identifier::Table lock_table_identifier(table_list->getSchemaName(), table_list->getTableName(), message::Table::STANDARD);
1127
if (not plugin::StorageEngine::doesTableExist(*this, lock_table_identifier))
1130
Table to be created, so we need to create placeholder in table-cache.
1132
if (!(table= table_cache_insert_placeholder(lock_table_identifier)))
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);
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);
1456
Link placeholder to the open tables list so it will be automatically
1457
removed once tables are closed. Also mark it so it won't be ignored
1458
by other trying to take name-lock.
1460
table->open_placeholder= true;
1461
table->next= open_tables;
1463
pthread_mutex_unlock(&LOCK_open);
1467
/* Table exists. Let us try to open it. */
1470
/* make a new table */
1471
table= (Table *)malloc(sizeof(Table));
1474
pthread_mutex_unlock(&LOCK_open);
1478
error= open_unireg_entry(this, table, table_list, alias, key, key_length);
1482
pthread_mutex_unlock(&LOCK_open);
1485
my_hash_insert(&open_cache, (unsigned char*) table);
1488
pthread_mutex_unlock(&LOCK_open);
1491
table->next= open_tables; /* Link into simple list */
1494
table->reginfo.lock_type= TL_READ; /* Assume read */
1497
assert(table->s->ref_count > 0 || table->s->tmp_table != NO_TMP_TABLE);
1499
if (lex->need_correct_ident())
1500
table->alias_name_used= my_strcasecmp(table_alias_charset,
1501
table->s->table_name.str, alias);
1180
1502
/* Fix alias if table name changes */
1181
if (strcmp(table->getAlias(), alias))
1503
if (strcmp(table->alias, alias))
1183
table->setAlias(alias);
1505
uint32_t length=(uint32_t) strlen(alias)+1;
1506
table->alias= (char*) realloc((char*) table->alias, length);
1507
memcpy((void*) table->alias, alias, length);
1186
1510
/* These variables are also set in reopen_table() */
1532
Table *find_locked_table(Session *session, const char *db,const char *table_name)
1534
char key[MAX_DBKEY_LENGTH];
1536
uint32_t key_length;
1538
key_pos= strcpy(key_pos, db) + strlen(db);
1539
key_pos= strcpy(key_pos+1, table_name) + strlen(table_name);
1540
key_length= (uint32_t)(key_pos-key)+1;
1542
for (Table *table=session->open_tables; table ; table=table->next)
1544
if (table->s->table_cache_key.length == key_length &&
1545
!memcmp(table->s->table_cache_key.str, key, key_length))
1553
Reopen an table because the definition has changed.
1560
The data file for the table is already closed and the share is released
1561
The table has a 'dummy' share that mainly contains database and table name.
1565
1 error. The old table object is not changed.
1568
bool reopen_table(Table *table)
1574
TableList table_list;
1575
Session *session= table->in_use;
1577
assert(table->s->ref_count == 0);
1578
assert(!table->sort.io_cache);
1582
errmsg_printf(ERRMSG_LVL_ERROR, _("Table %s had a open data handler in reopen_table"),
1585
table_list.db= table->s->db.str;
1586
table_list.table_name= table->s->table_name.str;
1587
table_list.table= table;
1589
if (wait_for_locked_table_names(session, &table_list))
1590
return true; // Thread was killed
1592
if (open_unireg_entry(session, &tmp, &table_list,
1594
table->s->table_cache_key.str,
1595
table->s->table_cache_key.length))
1598
/* This list copies variables set by open_table */
1599
tmp.tablenr= table->tablenr;
1600
tmp.used_fields= table->used_fields;
1601
tmp.const_table= table->const_table;
1602
tmp.null_row= table->null_row;
1603
tmp.maybe_null= table->maybe_null;
1604
tmp.status= table->status;
1607
tmp.in_use= session;
1608
tmp.reginfo.lock_type=table->reginfo.lock_type;
1610
/* Replace table in open list */
1611
tmp.next= table->next;
1612
tmp.prev= table->prev;
1615
table->closefrm(true); // close file, free everything
1618
table->default_column_bitmaps();
1619
table->file->change_table_ptr(table, table->s);
1621
assert(table->alias != 0);
1622
for (field=table->field ; *field ; field++)
1624
(*field)->table= (*field)->orig_table= table;
1625
(*field)->table_name= &table->alias;
1627
for (key=0 ; key < table->s->keys ; key++)
1629
for (part=0 ; part < table->key_info[key].usable_key_parts ; part++)
1630
table->key_info[key].key_part[part].field->table= table;
1633
broadcast_refresh();
1211
1642
Close all instances of a table open by this thread and replace
1212
1643
them with exclusive name-locks.
1515
2035
other threads trying to get the lock.
1518
void abort_locked_tables(Session *session, const drizzled::identifier::Table &identifier)
2038
void abort_locked_tables(Session *session,const char *db, const char *table_name)
1521
for (table= session->open_tables; table ; table= table->getNext())
2041
for (table= session->open_tables; table ; table= table->next)
1523
if (table->getShare()->getCacheKey() == identifier.getKey())
2043
if (!strcmp(table->s->table_name.str, table_name) &&
2044
!strcmp(table->s->db.str, db))
1525
2046
/* If MERGE child, forward lock handling to parent. */
1526
session->abortLock(table);
2047
mysql_lock_abort(session, table, true);
2054
Load a table definition from file and open unireg table
2058
session Thread handle
2059
entry Store open table definition here
2060
table_list TableList with db, table_name
2062
cache_key Key for share_cache
2063
cache_key_length length of cache_key
2066
Extra argument for open is taken from session->open_options
2067
One must have a lock on LOCK_open when calling this function
2074
static int open_unireg_entry(Session *session, Table *entry, TableList *table_list,
2076
char *cache_key, uint32_t cache_key_length)
2080
uint32_t discover_retry_count= 0;
2082
safe_mutex_assert_owner(&LOCK_open);
2084
if (!(share= TableShare::getShare(session, table_list, cache_key,
2086
table_list->i_s_requested_object,
2090
while ((error= open_table_from_share(session, share, alias,
2091
(uint32_t) (HA_OPEN_KEYFILE |
2096
session->open_options, entry, OTM_OPEN)))
2098
if (error == 7) // Table def changed
2100
share->version= 0; // Mark share as old
2101
if (discover_retry_count++) // Retry once
2106
Here we should wait until all threads has released the table.
2107
For now we do one retry. This may cause a deadlock if there
2108
is other threads waiting for other tables used by this thread.
2110
Proper fix would be to if the second retry failed:
2111
- Mark that table def changed
2112
- Return from open table
2113
- Close all tables used by this thread
2114
- Start waiting that the share is released
2115
- Retry by opening all tables again
2120
To avoid deadlock, only wait for release if no one else is
2123
if (share->ref_count != 1)
2125
/* Free share and wait until it's released by all threads */
2126
TableShare::release(share);
2128
if (!session->killed)
2130
drizzle_reset_errors(session, 1); // Clear warnings
2131
session->clear_error(); // Clear error message
2136
if (!entry->s || !entry->s->crashed)
2138
// Code below is for repairing a crashed file
2139
if ((error= lock_table_name(session, table_list, true)))
2143
if (wait_for_locked_table_names(session, table_list))
2145
unlock_table_name(table_list);
2149
pthread_mutex_unlock(&LOCK_open);
2150
session->clear_error(); // Clear error message
2152
if (open_table_from_share(session, share, alias,
2153
(uint32_t) (HA_OPEN_KEYFILE | HA_OPEN_RNDFILE |
2157
ha_open_options | HA_OPEN_FOR_REPAIR,
2158
entry, OTM_OPEN) || ! entry->file)
2160
/* Give right error message */
2161
session->clear_error();
2162
my_error(ER_NOT_KEYFILE, MYF(0), share->table_name.str, my_errno);
2163
errmsg_printf(ERRMSG_LVL_ERROR, _("Couldn't repair table: %s.%s"), share->db.str,
2164
share->table_name.str);
2166
entry->closefrm(false);
2170
session->clear_error(); // Clear error message
2171
pthread_mutex_lock(&LOCK_open);
2172
unlock_table_name(table_list);
2180
If we are here, there was no fatal error (but error may be still
2183
if (unlikely(entry->file->implicit_emptied))
2185
entry->file->implicit_emptied= 0;
2188
uint32_t query_buf_size= 20 + share->db.length + share->table_name.length +1;
2189
if ((query= (char*) malloc(query_buf_size)))
2192
"this DELETE FROM is needed even with row-based binlogging"
2194
We inherited this from MySQL. TODO: fix it to issue a propper truncate
2195
of the table (though that may not be completely right sematics).
2198
end+= sprintf(query, "DELETE FROM `%s`.`%s`", share->db.str,
2199
share->table_name.str);
2200
replication_services.rawStatement(session, query, (size_t)(end - query));
2205
errmsg_printf(ERRMSG_LVL_ERROR, _("When opening HEAP table, could not allocate memory "
2206
"to write 'DELETE FROM `%s`.`%s`' to replication"),
2207
table_list->db, table_list->table_name);
2208
my_error(ER_OUTOFMEMORY, MYF(0), query_buf_size);
2209
entry->closefrm(false);
2217
TableShare::release(share);
1535
2224
Open all tables in list
1539
session - thread Cursor
2228
session - thread handler
1540
2229
start - list of tables in/out
1541
2230
counter - number of opened tables will be return using this parameter
1542
2231
flags - bitmap of flags to modify how the tables will be open:
1802
Table *Open_tables_state::open_temporary_table(const identifier::Table &identifier,
2489
Table *open_temporary_table(Session *session, const char *path, const char *db,
2490
const char *table_name, bool link_in_list,
2491
open_table_mode open_mode)
1805
assert(identifier.isTmp());
1808
table::Temporary *new_tmp_table= new table::Temporary(identifier.getType(),
1810
const_cast<char *>(const_cast<identifier::Table&>(identifier).getPath().c_str()),
1811
static_cast<uint32_t>(identifier.getPath().length()));
1812
if (not new_tmp_table)
2495
char cache_key[MAX_DBKEY_LENGTH], *saved_cache_key, *tmp_path;
2496
uint32_t key_length, path_length;
2497
TableList table_list;
2499
table_list.db= (char*) db;
2500
table_list.table_name= (char*) table_name;
2501
/* Create the cache_key for temporary tables */
2502
key_length= table_list.create_table_def_key(cache_key);
2503
path_length= strlen(path);
2505
if (!(tmp_table= (Table*) malloc(sizeof(*tmp_table) + sizeof(*share) +
2506
path_length + 1 + key_length)))
2509
share= (TableShare*) (tmp_table+1);
2510
tmp_path= (char*) (share+1);
2511
saved_cache_key= strcpy(tmp_path, path)+path_length+1;
2512
memcpy(saved_cache_key, cache_key, key_length);
2514
share->init(saved_cache_key, key_length, strchr(saved_cache_key, '\0')+1, tmp_path);
1816
2517
First open the share, and then open the table from the share we just opened.
1818
if (new_tmp_table->getMutableShare()->open_table_def(*static_cast<Session *>(this), identifier) ||
1819
new_tmp_table->getMutableShare()->open_table_from_share(static_cast<Session *>(this), identifier, identifier.getTableName().c_str(),
1820
(uint32_t) (HA_OPEN_KEYFILE | HA_OPEN_RNDFILE |
2519
if (open_table_def(session, share) ||
2520
open_table_from_share(session, share, table_name,
2521
(open_mode == OTM_ALTER) ? 0 :
2522
(uint32_t) (HA_OPEN_KEYFILE | HA_OPEN_RNDFILE |
2524
(open_mode == OTM_ALTER) ?
2525
(EXTRA_RECORD | OPEN_FRM_FILE_ONLY)
2528
tmp_table, open_mode))
1825
2530
/* No need to lock share->mutex as this is not needed for tmp tables */
1826
delete new_tmp_table->getMutableShare();
1827
delete new_tmp_table;
2531
share->free_table_share();
2532
free((char*) tmp_table);
1832
new_tmp_table->reginfo.lock_type= TL_WRITE; // Simulate locked
2536
tmp_table->reginfo.lock_type= TL_WRITE; // Simulate locked
2537
if (open_mode == OTM_ALTER)
2540
Temporary table has been created with frm_only
2541
and has not been created in any storage engine
2543
share->tmp_table= TMP_TABLE_FRM_FILE_ONLY;
2546
share->tmp_table= (tmp_table->file->has_transactions() ?
2547
TRANSACTIONAL_TMP_TABLE : NON_TRANSACTIONAL_TMP_TABLE);
1834
2549
if (link_in_list)
1836
2551
/* growing temp list at the head */
1837
new_tmp_table->setNext(this->temporary_tables);
1838
if (new_tmp_table->getNext())
1840
new_tmp_table->getNext()->setPrev(new_tmp_table);
1842
this->temporary_tables= new_tmp_table;
1843
this->temporary_tables->setPrev(0);
1845
new_tmp_table->pos_in_table_list= 0;
1847
return new_tmp_table;
2552
tmp_table->next= session->temporary_tables;
2553
if (tmp_table->next)
2554
tmp_table->next->prev= tmp_table;
2555
session->temporary_tables= tmp_table;
2556
session->temporary_tables->prev= 0;
2558
tmp_table->pos_in_table_list= 0;
2564
bool rm_temporary_table(StorageEngine *base, char *path)
2570
if(delete_table_proto_file(path))
2571
error=1; /* purecov: inspected */
2573
if (base->deleteTable(current_session, path))
2576
errmsg_printf(ERRMSG_LVL_WARN, _("Could not remove temporary table: '%s', error: %d"),
3885
4718
On INSERT or UPDATE fields are checked to be from the same table,
3886
4719
thus we safely can take table from the first field.
3888
table= (*ptr)->getTable();
4721
table= (*ptr)->table;
3889
4722
table->auto_increment_field_not_null= false;
3892
4724
while ((field = *ptr++) && ! session->is_error())
3895
table= field->getTable();
4727
table= field->table;
3897
4728
if (field == table->next_number_field)
3898
4729
table->auto_increment_field_not_null= true;
3900
4730
if (value->save_in_field(field, 0) < 0)
4732
tbl_list.push_back(table);
4734
/* Update virtual fields*/
4735
session->abort_on_warning= false;
4736
if (tbl_list.head())
4738
List_iterator_fast<Table> t(tbl_list);
4739
Table *prev_table= 0;
4740
while ((table= t++))
3903
table->auto_increment_field_not_null= false;
4743
Do simple optimization to prevent unnecessary re-generating
4744
values for virtual fields
4746
if (table != prev_table)
4752
session->abort_on_warning= abort_on_warning_saved;
3909
4753
return(session->is_error());
4756
session->abort_on_warning= abort_on_warning_saved;
4758
table->auto_increment_field_not_null= false;
3913
bool drizzle_rm_tmp_tables()
4763
bool drizzle_rm_tmp_tables(ListenHandler &listen_handler)
3916
assert(drizzle_tmpdir.size());
3917
Session::shared_ptr session= Session::make_shared(plugin::Listen::getNullClient(), catalog::local());
3921
session->thread_stack= (char*) session.get();
3922
session->storeGlobals();
3924
plugin::StorageEngine::removeLostTemporaryTables(*session, drizzle_tmpdir.c_str());
4765
char filePath[FN_REFLEN], filePathCopy[FN_REFLEN];
4768
assert(drizzle_tmpdir);
4770
if (!(session= new Session(listen_handler.getTmpProtocol())))
4772
session->thread_stack= (char*) &session;
4773
session->store_globals();
4775
CachedDirectory dir(drizzle_tmpdir);
4779
my_errno= dir.getError();
4780
my_error(ER_CANT_READ_DIR, MYF(0), drizzle_tmpdir, my_errno);
4784
CachedDirectory::Entries files= dir.getEntries();
4785
CachedDirectory::Entries::iterator fileIter= files.begin();
4787
/* Remove all temp tables in the tmpdir */
4788
while (fileIter != files.end())
4790
CachedDirectory::Entry *entry= *fileIter;
4791
string prefix= entry->filename.substr(0, TMP_FILE_PREFIX_LENGTH);
4793
if (prefix == TMP_FILE_PREFIX)
4795
char *ext= fn_ext(entry->filename.c_str());
4796
uint32_t ext_len= strlen(ext);
4797
uint32_t filePath_len= snprintf(filePath, sizeof(filePath),
4798
"%s%c%s", drizzle_tmpdir, FN_LIBCHAR,
4799
entry->filename.c_str());
4801
if (ext_len && !memcmp(".dfe", ext, ext_len))
4804
/* We should cut file extention before deleting of table */
4805
memcpy(filePathCopy, filePath, filePath_len - ext_len);
4806
filePathCopy[filePath_len - ext_len]= 0;
4807
share.init(NULL, filePathCopy);
4808
if (!open_table_def(session, &share))
4810
share.db_type()->deleteTable(session, filePathCopy);
4812
share.free_table_share();
4815
File can be already deleted by tmp_table.file->delete_table().
4816
So we hide error messages which happnes during deleting of these
4819
my_delete(filePath, MYF(0));
3932
4833
unireg support functions
3933
4834
*****************************************************************************/
4837
Invalidate any cache entries that are for some DB
4840
remove_db_from_cache()
4841
db Database name. This will be in lower case if
4842
lower_case_table_name is set
4845
We can't use hash_delete when looping hash_elements. We mark them first
4846
and afterwards delete those marked unused.
4849
void remove_db_from_cache(const char *db)
4851
safe_mutex_assert_owner(&LOCK_open);
4853
for (uint32_t idx=0 ; idx < open_cache.records ; idx++)
4855
Table *table=(Table*) hash_element(&open_cache,idx);
4856
if (!strcmp(table->s->db.str, db))
4858
table->s->version= 0L; /* Free when thread is ready */
4860
relink_unused(table);
4863
while (unused_tables && !unused_tables->s->version)
4864
hash_delete(&open_cache,(unsigned char*) unused_tables);
4869
Mark all entries with the table as deleted to force an reopen of the table
4871
The table will be closed (not stored in cache) by the current thread when
4872
close_thread_tables() is called.
4878
0 This thread now have exclusive access to this table and no other thread
4879
can access the table until close_thread_tables() is called.
4880
1 Table is in use by another thread
4883
bool remove_table_from_cache(Session *session, const char *db, const char *table_name,
4886
char key[MAX_DBKEY_LENGTH];
4888
uint32_t key_length;
4891
bool signalled= false;
4893
key_pos= strcpy(key_pos, db) + strlen(db);
4894
key_pos= strcpy(key_pos+1, table_name) + strlen(table_name);
4895
key_length= (uint32_t) (key_pos-key)+1;
4899
HASH_SEARCH_STATE state;
4900
result= signalled= false;
4902
for (table= (Table*) hash_first(&open_cache, (unsigned char*) key, key_length,
4905
table= (Table*) hash_next(&open_cache, (unsigned char*) key, key_length,
4910
table->s->version=0L; /* Free when thread is ready */
4911
if (!(in_use=table->in_use))
4913
relink_unused(table);
4915
else if (in_use != session)
4918
Mark that table is going to be deleted from cache. This will
4919
force threads that are in mysql_lock_tables() (but not yet
4920
in thr_multi_lock()) to abort it's locks, close all tables and retry
4922
in_use->some_tables_deleted= true;
4923
if (table->is_name_opened())
4928
Now we must abort all tables locks used by this thread
4929
as the thread may be waiting to get a lock for another table.
4930
Note that we need to hold LOCK_open while going through the
4931
list. So that the other thread cannot change it. The other
4932
thread must also hold LOCK_open whenever changing the
4933
open_tables list. Aborting the MERGE lock after a child was
4934
closed and before the parent is closed would be fatal.
4936
for (Table *session_table= in_use->open_tables;
4938
session_table= session_table->next)
4940
/* Do not handle locks of MERGE children. */
4941
if (session_table->db_stat) // If table is open
4942
signalled|= mysql_lock_abort_for_thread(session, session_table);
4946
result= result || (flags & RTFC_OWNED_BY_Session_FLAG);
4948
while (unused_tables && !unused_tables->s->version)
4949
hash_delete(&open_cache,(unsigned char*) unused_tables);
4951
/* Remove table from table definition cache if it's not in use */
4952
TableShare::release(key, key_length);
4954
if (result && (flags & RTFC_WAIT_OTHER_THREAD_FLAG))
4957
Signal any thread waiting for tables to be freed to
4960
broadcast_refresh();
4961
if (!(flags & RTFC_CHECK_KILLED_FLAG) || !session->killed)
4964
if (likely(signalled))
4965
(void) pthread_cond_wait(&COND_refresh, &LOCK_open);
4968
struct timespec abstime;
4970
It can happen that another thread has opened the
4971
table but has not yet locked any table at all. Since
4972
it can be locked waiting for a table that our thread
4973
has done LOCK Table x WRITE on previously, we need to
4974
ensure that the thread actually hears our signal
4975
before we go to sleep. Thus we wait for a short time
4976
and then we retry another loop in the
4977
remove_table_from_cache routine.
4979
set_timespec(abstime, 10);
4980
pthread_cond_timedwait(&COND_refresh, &LOCK_open, &abstime);
4992
bool is_equal(const LEX_STRING *a, const LEX_STRING *b)
4994
return a->length == b->length && !strncmp(a->str, b->str, a->length);
3939
4997
@} (end of group Data_Dictionary)