33
#include "drizzled/internal/my_pthread.h"
34
#include "drizzled/internal/thread_var.h"
36
#include <drizzled/sql_select.h>
37
#include <drizzled/error.h>
38
#include <drizzled/gettext.h>
39
#include <drizzled/nested_join.h>
40
#include <drizzled/sql_base.h>
41
#include <drizzled/show.h>
42
#include <drizzled/item/cmpfunc.h>
43
#include <drizzled/replication_services.h>
44
#include <drizzled/check_stack_overrun.h>
45
#include <drizzled/lock.h>
46
#include <drizzled/plugin/listen.h>
47
#include "drizzled/cached_directory.h"
48
#include <drizzled/field/timestamp.h>
49
#include <drizzled/field/null.h>
50
#include "drizzled/sql_table.h"
51
#include "drizzled/global_charset_info.h"
52
#include "drizzled/pthread_globals.h"
53
#include "drizzled/internal/iocache.h"
54
#include "drizzled/drizzled.h"
55
#include "drizzled/plugin/authorization.h"
56
#include "drizzled/table_placeholder.h"
63
extern bool volatile shutdown_in_progress;
65
TableOpenCache &get_open_cache()
67
static TableOpenCache open_cache; /* Used by mysql_test */
35
#define FLAGSTR(S,F) ((S) & (F) ? #F " " : "")
38
return true if the table was created explicitly.
40
inline bool is_user_table(Table * table)
42
const char *name= table->s->table_name.str;
43
return strncmp(name, tmp_file_prefix, tmp_file_prefix_length);
48
@defgroup Data_Dictionary Data Dictionary
51
Table *unused_tables; /* Used by mysql_test */
52
HASH open_cache; /* Used by mysql_test */
53
static HASH table_def_cache;
54
static TABLE_SHARE *oldest_unused_share, end_of_unused_share;
55
static pthread_mutex_t LOCK_table_share;
56
static bool table_def_inited= 0;
58
static int open_unireg_entry(THD *thd, Table *entry, TableList *table_list,
60
char *cache_key, uint32_t cache_key_length);
72
61
static void free_cache_entry(Table *entry);
74
void remove_table(Table *arg)
76
TableOpenCacheRange ppp;
77
ppp= get_open_cache().equal_range(arg->getShare()->getCacheKey());
79
for (TableOpenCache::const_iterator iter= ppp.first;
80
iter != ppp.second; ++iter)
82
Table *found_table= (*iter).second;
84
if (found_table == arg)
86
free_cache_entry(arg);
87
get_open_cache().erase(iter);
93
static bool add_table(Table *arg)
95
TableOpenCache &open_cache(get_open_cache());
97
TableOpenCache::iterator returnable= open_cache.insert(make_pair(arg->getShare()->getCacheKey(), arg));
99
return not (returnable == open_cache.end());
103
Table *tables; /* Used by mysql_test */
105
Table *getTable() const
110
Table *setTable(Table *arg)
119
/* Free cache if too big */
120
while (cached_open_tables() > table_cache_size && getTable())
121
remove_table(getTable());
126
while (getTable() && not getTable()->getShare()->getVersion())
127
remove_table(getTable());
130
void link(Table *table)
134
table->setNext(getTable()); /* Link in last */
135
table->setPrev(getTable()->getPrev());
136
getTable()->setPrev(table);
137
table->getPrev()->setNext(table);
141
table->setPrev(setTable(table));
142
table->setNext(table->getPrev());
143
assert(table->getNext() == table && table->getPrev() == table);
148
void unlink(Table *table)
152
/* Unlink the table from "unused_tables" list. */
153
if (table == getTable())
155
setTable(getTable()->getNext()); // Remove from link
156
if (table == getTable())
161
/* move table first in unused links */
163
void relink(Table *table)
165
if (table != getTable())
169
table->setNext(getTable()); /* Link in unused tables */
170
table->setPrev(getTable()->getPrev());
171
getTable()->getPrev()->setNext(table);
172
getTable()->setPrev(table);
181
remove_table(getTable());
193
static UnusedTables unused_tables;
194
static int open_unireg_entry(Session *session,
197
TableIdentifier &identifier);
199
unsigned char *table_cache_key(const unsigned char *record,
204
static bool reopen_table(Table *table);
207
unsigned char *table_cache_key(const unsigned char *record,
62
static void close_old_data_files(THD *thd, Table *table, bool morph_locks,
66
extern "C" unsigned char *table_cache_key(const unsigned char *record, size_t *length,
67
bool not_used __attribute__((unused)))
211
69
Table *entry=(Table*) record;
212
*length= entry->getShare()->getCacheKey().size();
213
return (unsigned char*) &entry->getShare()->getCacheKey()[0];
70
*length= entry->s->table_cache_key.length;
71
return (unsigned char*) entry->s->table_cache_key.str;
216
75
bool table_cache_init(void)
77
return hash_init(&open_cache, &my_charset_bin, table_cache_size+16,
78
0, 0, table_cache_key,
79
(hash_free_key) free_cache_entry, 0);
82
void table_cache_free(void)
86
close_cached_tables(NULL, NULL, false, false, false);
87
if (!open_cache.records) // Safety first
88
hash_free(&open_cache);
221
93
uint32_t cached_open_tables(void)
223
return get_open_cache().size();
226
void table_cache_free(void)
228
refresh_version++; // Force close of open tables
230
unused_tables.clear();
231
get_open_cache().clear();
235
Close cursor handle, but leave the table in the table cache
238
close_handle_and_leave_table_as_lock()
242
By leaving the table in the table cache, it disallows any other thread
245
session->killed will be set if we run out of memory
247
If closing a MERGE child, the calling function has to take care for
248
closing the parent too, if necessary.
95
return open_cache.records;
99
Create a table cache key
102
create_table_def_key()
104
key Create key here (must be of size MAX_DBKEY_LENGTH)
105
table_list Table definition
106
tmp_table Set if table is a tmp table
109
The table cache_key is created from:
113
if the table is a tmp table, we add the following to make each tmp table
116
4 bytes for master thread id
117
4 bytes pseudo thread id
123
uint32_t create_table_def_key(THD *thd, char *key, TableList *table_list,
126
uint32_t key_length= (uint) (my_stpcpy(my_stpcpy(key, table_list->db)+1,
127
table_list->table_name)-key)+1;
130
int4store(key + key_length, thd->server_id);
131
int4store(key + key_length + 4, thd->variables.pseudo_thread_id);
132
key_length+= TMP_TABLE_KEY_EXTRA;
139
/*****************************************************************************
140
Functions to handle table definition cach (TABLE_SHARE)
141
*****************************************************************************/
143
extern "C" unsigned char *table_def_key(const unsigned char *record, size_t *length,
144
bool not_used __attribute__((unused)))
146
TABLE_SHARE *entry=(TABLE_SHARE*) record;
147
*length= entry->table_cache_key.length;
148
return (unsigned char*) entry->table_cache_key.str;
152
static void table_def_free_entry(TABLE_SHARE *share)
156
/* remove from old_unused_share list */
157
pthread_mutex_lock(&LOCK_table_share);
158
*share->prev= share->next;
159
share->next->prev= share->prev;
160
pthread_mutex_unlock(&LOCK_table_share);
162
free_table_share(share);
167
bool table_def_init(void)
170
pthread_mutex_init(&LOCK_table_share, MY_MUTEX_INIT_FAST);
171
oldest_unused_share= &end_of_unused_share;
172
end_of_unused_share.prev= &oldest_unused_share;
174
return hash_init(&table_def_cache, &my_charset_bin, table_def_size,
176
(hash_free_key) table_def_free_entry, 0);
180
void table_def_free(void)
182
if (table_def_inited)
185
pthread_mutex_destroy(&LOCK_table_share);
186
hash_free(&table_def_cache);
192
uint32_t cached_table_definitions(void)
194
return table_def_cache.records;
199
Get TABLE_SHARE for a table.
203
table_list Table that should be opened
205
key_length Length of key
206
db_flags Flags to open_table_def():
208
error out: Error code from open_table_def()
211
Get a table definition from the table definition cache.
212
If it doesn't exist, create a new from the table definition file.
215
We must have wrlock on LOCK_open when we come here
216
(To be changed later)
223
TABLE_SHARE *get_table_share(THD *thd, TableList *table_list, char *key,
224
uint32_t key_length, uint32_t db_flags, int *error)
230
/* Read table definition from cache */
231
if ((share= (TABLE_SHARE*) hash_search(&table_def_cache,(unsigned char*) key,
235
if (!(share= alloc_table_share(table_list, key, key_length)))
241
Lock mutex to be able to read table definition from file without
244
(void) pthread_mutex_lock(&share->mutex);
247
We assign a new table id under the protection of the LOCK_open and
248
the share's own mutex. We do this insted of creating a new mutex
249
and using it for the sole purpose of serializing accesses to a
250
static variable, we assign the table id here. We assign it to the
251
share before inserting it into the table_def_cache to be really
252
sure that it cannot be read from the cache without having a table
255
CAVEAT. This means that the table cannot be used for
256
binlogging/replication purposes, unless get_table_share() has been
257
called directly or indirectly.
259
assign_new_table_id(share);
261
if (my_hash_insert(&table_def_cache, (unsigned char*) share))
263
free_table_share(share);
264
return(0); // return error
266
if (open_table_def(thd, share, db_flags))
268
*error= share->error;
269
(void) hash_delete(&table_def_cache, (unsigned char*) share);
272
share->ref_count++; // Mark in use
273
(void) pthread_mutex_unlock(&share->mutex);
278
We found an existing table definition. Return it if we didn't get
279
an error when reading the table definition from file.
282
/* We must do a lock to ensure that the structure is initialized */
283
(void) pthread_mutex_lock(&share->mutex);
286
/* Table definition contained an error */
287
open_table_error(share, share->error, share->open_errno, share->errarg);
288
(void) pthread_mutex_unlock(&share->mutex);
292
if (!share->ref_count++ && share->prev)
295
Share was not used before and it was in the old_unused_share list
296
Unlink share from this list
298
pthread_mutex_lock(&LOCK_table_share);
299
*share->prev= share->next;
300
share->next->prev= share->prev;
303
pthread_mutex_unlock(&LOCK_table_share);
305
(void) pthread_mutex_unlock(&share->mutex);
307
/* Free cache if too big */
308
while (table_def_cache.records > table_def_size &&
309
oldest_unused_share->next)
311
pthread_mutex_lock(&oldest_unused_share->mutex);
312
hash_delete(&table_def_cache, (unsigned char*) oldest_unused_share);
320
Get a table share. If it didn't exist, try creating it from engine
322
For arguments and return values, see get_table_from_share()
326
*get_table_share_with_create(THD *thd, TableList *table_list,
327
char *key, uint32_t key_length,
328
uint32_t db_flags, int *error)
333
share= get_table_share(thd, table_list, key, key_length, db_flags, error);
335
If share is not NULL, we found an existing share.
337
If share is NULL, and there is no error, we're inside
338
pre-locking, which silences 'ER_NO_SUCH_TABLE' errors
339
with the intention to silently drop non-existing tables
340
from the pre-locking list. In this case we still need to try
341
auto-discover before returning a NULL share.
343
If share is NULL and the error is ER_NO_SUCH_TABLE, this is
344
the same as above, only that the error was not silenced by
345
pre-locking. Once again, we need to try to auto-discover
348
Finally, if share is still NULL, it's a real error and we need
351
@todo Rework alternative ways to deal with ER_NO_SUCH Table.
353
if (share || (thd->is_error() && (thd->main_da.sql_errno() != ER_NO_SUCH_TABLE)))
357
/* Table didn't exist. Check if some engine can provide it */
358
if ((tmp= ha_create_table_from_engine(thd, table_list->db,
359
table_list->table_name)) < 0)
364
/* Give right error message */
366
my_printf_error(ER_UNKNOWN_ERROR,
367
"Failed to open '%-.64s', error while "
368
"unpacking from engine",
369
MYF(0), table_list->table_name);
372
/* Table existed in engine. Let's open it */
373
drizzle_reset_errors(thd, 1); // Clear warnings
374
thd->clear_error(); // Clear error message
375
return(get_table_share(thd, table_list, key, key_length,
381
Mark that we are not using table share anymore.
384
release_table_share()
386
release_type How the release should be done:
388
- Release without checking
389
RELEASE_WAIT_FOR_DROP
390
- Don't return until we get a signal that the
391
table is deleted or the thread is killed.
394
If ref_count goes to zero and (we have done a refresh or if we have
395
already too many open table shares) then delete the definition.
397
If type == RELEASE_WAIT_FOR_DROP then don't return until we get a signal
398
that the table is deleted or the thread is killed.
401
void release_table_share(TABLE_SHARE *share,
402
enum release_type type __attribute__((unused)))
404
bool to_be_deleted= 0;
406
safe_mutex_assert_owner(&LOCK_open);
408
pthread_mutex_lock(&share->mutex);
409
if (!--share->ref_count)
411
if (share->version != refresh_version)
415
/* Link share last in used_table_share list */
416
assert(share->next == 0);
417
pthread_mutex_lock(&LOCK_table_share);
418
share->prev= end_of_unused_share.prev;
419
*end_of_unused_share.prev= share;
420
end_of_unused_share.prev= &share->next;
421
share->next= &end_of_unused_share;
422
pthread_mutex_unlock(&LOCK_table_share);
424
to_be_deleted= (table_def_cache.records > table_def_size);
430
hash_delete(&table_def_cache, (unsigned char*) share);
433
pthread_mutex_unlock(&share->mutex);
439
Check if table definition exits in cache
442
get_cached_table_share()
444
table_name Table name
448
# TABLE_SHARE for table
451
TABLE_SHARE *get_cached_table_share(const char *db, const char *table_name)
453
char key[NAME_LEN*2+2];
454
TableList table_list;
456
safe_mutex_assert_owner(&LOCK_open);
458
table_list.db= (char*) db;
459
table_list.table_name= (char*) table_name;
460
key_length= create_table_def_key((THD*) 0, key, &table_list, 0);
461
return (TABLE_SHARE*) hash_search(&table_def_cache,(unsigned char*) key, key_length);
466
Close file handle, but leave the table in the table cache
469
close_handle_and_leave_table_as_lock()
473
By leaving the table in the table cache, it disallows any other thread
476
thd->killed will be set if we run out of memory
478
If closing a MERGE child, the calling function has to take care for
479
closing the parent too, if necessary.
252
483
void close_handle_and_leave_table_as_lock(Table *table)
254
TableShare *share, *old_share= table->getMutableShare();
485
TABLE_SHARE *share, *old_share= table->s;
487
MEM_ROOT *mem_root= &table->mem_root;
255
489
assert(table->db_stat);
256
assert(table->getShare()->getType() == message::Table::STANDARD);
259
492
Make a local copy of the table share and free the current one.
260
493
This has to be done to ensure that the table share is removed from
261
494
the table defintion cache as soon as the last instance is removed
263
TableIdentifier identifier(table->getShare()->getSchemaName(), table->getShare()->getTableName(), message::Table::INTERNAL);
264
const TableIdentifier::Key &key(identifier.getKey());
265
share= new TableShare(identifier.getType(),
267
const_cast<char *>(&key[0]), static_cast<uint32_t>(old_share->getCacheKeySize()));
269
table->cursor->close();
270
table->db_stat= 0; // Mark cursor closed
271
TableShare::release(table->getMutableShare());
272
table->setShare(share);
273
table->cursor->change_table_ptr(table, table->getMutableShare());
496
if (multi_alloc_root(mem_root,
497
&share, sizeof(*share),
498
&key_buff, old_share->table_cache_key.length,
501
memset(share, 0, sizeof(*share));
502
share->set_table_cache_key(key_buff, old_share->table_cache_key.str,
503
old_share->table_cache_key.length);
504
share->tmp_table= INTERNAL_TMP_TABLE; // for intern_close_table()
507
table->file->close();
508
table->db_stat= 0; // Mark file closed
509
release_table_share(table->s, RELEASE_NORMAL);
511
table->file->change_table_ptr(table, table->s);
519
Create a list for all open tables matching SQL expression
524
wild SQL like expression
527
One gets only a list of tables for which one has any kind of privilege.
528
db and table names are allocated in result struct, so one doesn't need
529
a lock on LOCK_open when traversing the return list.
532
NULL Error (Probably OOM)
533
# Pointer to list of names of open tables.
536
OPEN_TableList *list_open_tables(THD *thd __attribute__((unused)),
537
const char *db, const char *wild)
540
OPEN_TableList **start_list, *open_list;
541
TableList table_list;
543
pthread_mutex_lock(&LOCK_open);
544
memset(&table_list, 0, sizeof(table_list));
545
start_list= &open_list;
548
for (uint32_t idx=0 ; result == 0 && idx < open_cache.records; idx++)
550
OPEN_TableList *table;
551
Table *entry=(Table*) hash_element(&open_cache,idx);
552
TABLE_SHARE *share= entry->s;
554
if (db && my_strcasecmp(system_charset_info, db, share->db.str))
556
if (wild && wild_compare(share->table_name.str, wild, 0))
559
/* Check if user has SELECT privilege for any column in the table */
560
table_list.db= share->db.str;
561
table_list.table_name= share->table_name.str;
563
/* need to check if we haven't already listed it */
564
for (table= open_list ; table ; table=table->next)
566
if (!strcmp(table->table, share->table_name.str) &&
567
!strcmp(table->db, share->db.str))
571
if (entry->locked_by_name)
578
if (!(*start_list = (OPEN_TableList *)
579
sql_alloc(sizeof(**start_list)+share->table_cache_key.length)))
581
open_list=0; // Out of memory
584
my_stpcpy((*start_list)->table=
585
my_stpcpy(((*start_list)->db= (char*) ((*start_list)+1)),
587
share->table_name.str);
588
(*start_list)->in_use= entry->in_use ? 1 : 0;
589
(*start_list)->locked= entry->locked_by_name ? 1 : 0;
590
start_list= &(*start_list)->next;
593
pthread_mutex_unlock(&LOCK_open);
277
597
/*****************************************************************************
278
598
* Functions to free open table cache
279
599
****************************************************************************/
282
void Table::intern_close_table()
602
void intern_close_table(Table *table)
283
603
{ // Free all structures
285
if (cursor) // Not true if name lock
287
delete_table(true); // close cursor
604
free_io_cache(table);
605
if (table->file) // Not true if name lock
606
closefrm(table, 1); // close file
292
611
Remove table from the open table cache
296
entry Table to remove
615
table Table to remove
299
We need to have a lock on LOCK_open when calling this
618
We need to have a lock on LOCK_open when calling this
302
void free_cache_entry(Table *table)
621
static void free_cache_entry(Table *table)
304
table->intern_close_table();
305
if (not table->in_use)
623
intern_close_table(table);
307
unused_tables.unlink(table);
626
table->next->prev=table->prev; /* remove from used chain */
627
table->prev->next=table->next;
628
if (table == unused_tables)
630
unused_tables=unused_tables->next;
631
if (table == unused_tables)
635
free((unsigned char*) table);
313
639
/* Free resources allocated by filesort() and read_record() */
315
void Table::free_io_cache()
641
void free_io_cache(Table *table)
643
if (table->sort.io_cache)
319
close_cached_file(sort.io_cache);
320
delete sort.io_cache;
645
close_cached_file(table->sort.io_cache);
646
free((unsigned char*) table->sort.io_cache);
647
table->sort.io_cache=0;
327
654
Close all tables which aren't in use by any thread
329
@param session Thread context (may be NULL)
656
@param thd Thread context
330
657
@param tables List of tables to remove from the cache
331
658
@param have_lock If LOCK_open is locked
332
659
@param wait_for_refresh Wait for a impending flush
333
660
@param wait_for_placeholders Wait for tables being reopened so that the GRL
334
won't proceed while write-locked tables are being reopened by other
661
won't proceed while write-locked tables are being reopened by other
337
@remark Session can be NULL, but then wait_for_refresh must be false
338
and tables must be NULL.
664
@remark THD can be NULL, but then wait_for_refresh must be false
665
and tables must be NULL.
341
bool Session::close_cached_tables(TableList *tables, bool wait_for_refresh, bool wait_for_placeholders)
668
bool close_cached_tables(THD *thd, TableList *tables, bool have_lock,
669
bool wait_for_refresh, bool wait_for_placeholders)
344
Session *session= this;
346
LOCK_open.lock(); /* Optionally lock for remove tables from open_cahe if not in use */
672
assert(thd || (!wait_for_refresh && !tables));
675
pthread_mutex_lock(&LOCK_open);
350
678
refresh_version++; // Force close of open tables
352
unused_tables.clear();
679
while (unused_tables)
682
if (hash_delete(&open_cache,(unsigned char*) unused_tables))
683
printf("Warning: Couldn't delete open table from hash\n");
685
hash_delete(&open_cache,(unsigned char*) unused_tables);
688
/* Free table shares */
689
while (oldest_unused_share->next)
691
pthread_mutex_lock(&oldest_unused_share->mutex);
692
hash_delete(&table_def_cache, (unsigned char*) oldest_unused_share);
354
694
if (wait_for_refresh)
469
803
old locks. This should always succeed (unless some external process
470
804
has removed the tables)
472
result= session->reopen_tables(true, true);
806
thd->in_lock_tables=1;
807
result=reopen_tables(thd,1,1);
808
thd->in_lock_tables=0;
474
809
/* Set version for table */
475
for (Table *table= session->open_tables; table ; table= table->getNext())
810
for (Table *table=thd->open_tables; table ; table= table->next)
478
813
Preserve the version (0) of write locked tables so that a impending
479
814
global read lock won't sneak in.
481
816
if (table->reginfo.lock_type < TL_WRITE_ALLOW_WRITE)
482
table->getMutableShare()->refreshVersion();
817
table->s->version= refresh_version;
821
pthread_mutex_unlock(&LOCK_open);
488
822
if (wait_for_refresh)
490
boost::mutex::scoped_lock scopedLock(session->mysys_var->mutex);
491
session->mysys_var->current_mutex= 0;
492
session->mysys_var->current_cond= 0;
493
session->set_proc_info(0);
501
move one table to free list
504
bool Session::free_cached_table()
506
bool found_old_table= false;
507
Table *table= open_tables;
509
safe_mutex_assert_owner(LOCK_open.native_handle());
824
pthread_mutex_lock(&thd->mysys_var->mutex);
825
thd->mysys_var->current_mutex= 0;
826
thd->mysys_var->current_cond= 0;
827
thd->set_proc_info(0);
828
pthread_mutex_unlock(&thd->mysys_var->mutex);
835
Close all tables which match specified connection string or
836
if specified string is NULL, then any table with a connection string.
839
bool close_cached_connection_tables(THD *thd, bool if_wait_for_refresh,
840
LEX_STRING *connection, bool have_lock)
843
TableList tmp, *tables= NULL;
847
memset(&tmp, 0, sizeof(TableList));
850
pthread_mutex_lock(&LOCK_open);
852
for (idx= 0; idx < table_def_cache.records; idx++)
854
TABLE_SHARE *share= (TABLE_SHARE *) hash_element(&table_def_cache, idx);
856
/* Ignore if table is not open or does not have a connect_string */
857
if (!share->connect_string.length || !share->ref_count)
860
/* Compare the connection string */
862
(connection->length > share->connect_string.length ||
863
(connection->length < share->connect_string.length &&
864
(share->connect_string.str[connection->length] != '/' &&
865
share->connect_string.str[connection->length] != '\\')) ||
866
strncasecmp(connection->str, share->connect_string.str,
867
connection->length)))
870
/* close_cached_tables() only uses these elements */
871
tmp.db= share->db.str;
872
tmp.table_name= share->table_name.str;
873
tmp.next_local= tables;
875
tables= (TableList *) memdup_root(thd->mem_root, (char*)&tmp,
880
result= close_cached_tables(thd, tables, true, false, false);
883
pthread_mutex_unlock(&LOCK_open);
885
if (if_wait_for_refresh)
887
pthread_mutex_lock(&thd->mysys_var->mutex);
888
thd->mysys_var->current_mutex= 0;
889
thd->mysys_var->current_cond= 0;
890
thd->set_proc_info(0);
891
pthread_mutex_unlock(&thd->mysys_var->mutex);
899
Mark all temporary tables which were used by the current statement or
900
substatement as free for reuse, but only if the query_id can be cleared.
902
@param thd thread context
904
@remark For temp tables associated with a open SQL HANDLER the query_id
905
is not reset until the HANDLER is closed.
908
static void mark_temp_tables_as_free_for_reuse(THD *thd)
910
for (Table *table= thd->temporary_tables ; table ; table= table->next)
912
if ((table->query_id == thd->query_id) && ! table->open_by_handler)
915
table->file->ha_reset();
922
Mark all tables in the list which were used by current substatement
926
mark_used_tables_as_free_for_reuse()
928
table - head of the list of tables
931
Marks all tables in the list which were used by current substatement
932
(they are marked by its query_id) as free for reuse.
935
The reason we reset query_id is that it's not enough to just test
936
if table->query_id != thd->query_id to know if a table is in use.
939
SELECT f1_that_uses_t1() FROM t1;
940
In f1_that_uses_t1() we will see one instance of t1 where query_id is
941
set to query_id of original query.
944
static void mark_used_tables_as_free_for_reuse(THD *thd, Table *table)
946
for (; table ; table= table->next)
948
if (table->query_id == thd->query_id)
951
table->file->ha_reset();
958
Auxiliary function to close all tables in the open_tables list.
960
@param thd Thread context.
962
@remark It should not ordinarily be called directly.
965
static void close_open_tables(THD *thd)
967
bool found_old_table= 0;
969
safe_mutex_assert_not_owner(&LOCK_open);
971
pthread_mutex_lock(&LOCK_open);
973
while (thd->open_tables)
974
found_old_table|= close_thread_table(thd, &thd->open_tables);
975
thd->some_tables_deleted= 0;
977
/* Free tables to hold down open files */
978
while (open_cache.records > table_cache_size && unused_tables)
979
hash_delete(&open_cache,(unsigned char*) unused_tables); /* purecov: tested */
982
/* Tell threads waiting for refresh that something has happened */
986
pthread_mutex_unlock(&LOCK_open);
991
Close all tables used by the current substatement, or all tables
992
used by this thread if we are on the upper level.
995
close_thread_tables()
999
Unlocks tables and frees derived tables.
1000
Put all normal tables used by thread in free list.
1002
It will only close/mark as free for reuse tables opened by this
1003
substatement, it will also check if we are closing tables after
1004
execution of complete query (i.e. we are on upper level) and will
1005
leave prelocked mode if needed.
1008
void close_thread_tables(THD *thd)
1013
We are assuming here that thd->derived_tables contains ONLY derived
1014
tables for this substatement. i.e. instead of approach which uses
1015
query_id matching for determining which of the derived tables belong
1016
to this substatement we rely on the ability of substatements to
1017
save/restore thd->derived_tables during their execution.
1019
TODO: Probably even better approach is to simply associate list of
1020
derived tables with (sub-)statement instead of thread and destroy
1021
them at the end of its execution.
1023
if (thd->derived_tables)
1027
Close all derived tables generated in queries like
1028
SELECT * FROM (SELECT * FROM t1)
1030
for (table= thd->derived_tables ; table ; table= next)
1033
table->free_tmp_table(thd);
1035
thd->derived_tables= 0;
1039
Mark all temporary tables used by this statement as free for reuse.
1041
mark_temp_tables_as_free_for_reuse(thd);
1043
Let us commit transaction for statement. Since in 5.0 we only have
1044
one statement transaction and don't allow several nested statement
1045
transactions this call will do nothing if we are inside of stored
1046
function or trigger (i.e. statement transaction is already active and
1047
does not belong to statement for which we do close_thread_tables()).
1048
TODO: This should be fixed in later releases.
1050
if (!(thd->state_flags & Open_tables_state::BACKUPS_AVAIL))
1052
thd->main_da.can_overwrite_status= true;
1053
ha_autocommit_or_rollback(thd, thd->is_error());
1054
thd->main_da.can_overwrite_status= false;
1055
thd->transaction.stmt.reset();
1058
if (thd->locked_tables)
1061
/* Ensure we are calling ha_reset() for all used tables */
1062
mark_used_tables_as_free_for_reuse(thd, thd->open_tables);
1065
We are under simple LOCK TABLES so should not do anything else.
1073
For RBR we flush the pending event just before we unlock all the
1074
tables. This means that we are at the end of a topmost
1075
statement, so we ensure that the STMT_END_F flag is set on the
1076
pending event. For statements that are *inside* stored
1077
functions, the pending event will not be flushed: that will be
1078
handled either before writing a query log event (inside
1079
binlog_query()) or when preparing a pending event.
1081
thd->binlog_flush_pending_rows_event(true);
1082
mysql_unlock_tables(thd, thd->lock);
1086
Note that we need to hold LOCK_open while changing the
1087
open_tables list. Another thread may work on it.
1088
(See: remove_table_from_cache(), mysql_wait_completed_table())
1089
Closing a MERGE child before the parent would be fatal if the
1090
other thread tries to abort the MERGE lock in between.
1092
if (thd->open_tables)
1093
close_open_tables(thd);
1099
/* move one table to free list */
1101
bool close_thread_table(THD *thd, Table **table_ptr)
1103
bool found_old_table= 0;
1104
Table *table= *table_ptr;
510
1106
assert(table->key_read == 0);
511
assert(!table->cursor || table->cursor->inited == Cursor::NONE);
1107
assert(!table->file || table->file->inited == handler::NONE);
513
open_tables= table->getNext();
1109
*table_ptr=table->next;
515
1111
if (table->needs_reopen_or_name_lock() ||
516
version != refresh_version || !table->db_stat)
1112
thd->version != refresh_version || !table->db_stat)
519
found_old_table= true;
1114
hash_delete(&open_cache,(unsigned char*) table);
524
1120
Open placeholders have Table::db_stat set to 0, so they should be
525
1121
handled by the first alternative.
527
assert(not table->open_placeholder);
1123
assert(!table->open_placeholder);
529
1125
/* Free memory and reset for next loop */
530
table->cursor->ha_reset();
531
table->in_use= false;
533
unused_tables.link(table);
1126
table->file->ha_reset();
1130
table->next=unused_tables; /* Link in last */
1131
table->prev=unused_tables->prev;
1132
unused_tables->prev=table;
1133
table->prev->next=table;
1136
unused_tables=table->next=table->prev=table;
536
return found_old_table;
541
Auxiliary function to close all tables in the open_tables list.
543
@param session Thread context.
545
@remark It should not ordinarily be called directly.
1138
return(found_old_table);
1142
/* close_temporary_tables' internal, 4 is due to uint4korr definition */
1143
static inline uint32_t tmpkeyval(THD *thd __attribute__((unused)),
1146
return uint4korr(table->s->table_cache_key.str + table->s->table_cache_key.length - 4);
1151
Close all temporary tables created by 'CREATE TEMPORARY TABLE' for thread
1152
creates one DROP TEMPORARY Table binlog event for each pseudo-thread
548
void Session::close_open_tables()
1155
void close_temporary_tables(THD *thd)
550
bool found_old_table= false;
552
safe_mutex_assert_not_owner(LOCK_open.native_handle());
554
boost::mutex::scoped_lock scoped_lock(LOCK_open); /* Close all open tables on Session */
558
found_old_table|= free_cached_table();
560
some_tables_deleted= false;
564
/* Tell threads waiting for refresh that something has happened */
1160
/* Assume thd->options has OPTION_QUOTE_SHOW_CREATE */
1161
bool was_quote_show= true;
1163
if (!thd->temporary_tables)
1166
if (!mysql_bin_log.is_open() || thd->current_stmt_binlog_row_based)
1169
for (table= thd->temporary_tables; table; table= tmp_next)
1171
tmp_next= table->next;
1172
close_temporary(table, 1, 1);
1174
thd->temporary_tables= 0;
1178
/* Better add "if exists", in case a RESET MASTER has been done */
1179
const char stub[]= "DROP /*!40005 TEMPORARY */ Table IF EXISTS ";
1180
uint32_t stub_len= sizeof(stub) - 1;
1182
String s_query= String(buf, sizeof(buf), system_charset_info);
1183
bool found_user_tables= false;
1185
memcpy(buf, stub, stub_len);
1188
Insertion sort of temp tables by pseudo_thread_id to build ordered list
1189
of sublists of equal pseudo_thread_id
1192
for (prev_table= thd->temporary_tables, table= prev_table->next;
1194
prev_table= table, table= table->next)
1196
Table *prev_sorted /* same as for prev_table */, *sorted;
1197
if (is_user_table(table))
1199
if (!found_user_tables)
1200
found_user_tables= true;
1201
for (prev_sorted= NULL, sorted= thd->temporary_tables; sorted != table;
1202
prev_sorted= sorted, sorted= sorted->next)
1204
if (!is_user_table(sorted) ||
1205
tmpkeyval(thd, sorted) > tmpkeyval(thd, table))
1207
/* move into the sorted part of the list from the unsorted */
1208
prev_table->next= table->next;
1209
table->next= sorted;
1212
prev_sorted->next= table;
1216
thd->temporary_tables= table;
1225
/* We always quote db,table names though it is slight overkill */
1226
if (found_user_tables &&
1227
!(was_quote_show= test(thd->options & OPTION_QUOTE_SHOW_CREATE)))
1229
thd->options |= OPTION_QUOTE_SHOW_CREATE;
1232
/* scan sorted tmps to generate sequence of DROP */
1233
for (table= thd->temporary_tables; table; table= next)
1235
if (is_user_table(table))
1237
my_thread_id save_pseudo_thread_id= thd->variables.pseudo_thread_id;
1238
/* Set pseudo_thread_id to be that of the processed table */
1239
thd->variables.pseudo_thread_id= tmpkeyval(thd, table);
1241
Loop forward through all tables within the sublist of
1242
common pseudo_thread_id to create single DROP query.
1244
for (s_query.length(stub_len);
1245
table && is_user_table(table) &&
1246
tmpkeyval(thd, table) == thd->variables.pseudo_thread_id;
1250
We are going to add 4 ` around the db/table names and possible more
1251
due to special characters in the names
1253
append_identifier(thd, &s_query, table->s->db.str, strlen(table->s->db.str));
1254
s_query.append('.');
1255
append_identifier(thd, &s_query, table->s->table_name.str,
1256
strlen(table->s->table_name.str));
1257
s_query.append(',');
1259
close_temporary(table, 1, 1);
1262
const CHARSET_INFO * const cs_save= thd->variables.character_set_client;
1263
thd->variables.character_set_client= system_charset_info;
1264
Query_log_event qinfo(thd, s_query.ptr(),
1265
s_query.length() - 1 /* to remove trailing ',' */,
1267
thd->variables.character_set_client= cs_save;
1269
Imagine the thread had created a temp table, then was doing a
1270
SELECT, and the SELECT was killed. Then it's not clever to
1271
mark the statement above as "killed", because it's not really
1272
a statement updating data, and there are 99.99% chances it
1273
will succeed on slave. If a real update (one updating a
1274
persistent table) was killed on the master, then this real
1275
update will be logged with error_code=killed, rightfully
1276
causing the slave to stop.
1278
qinfo.error_code= 0;
1279
mysql_bin_log.write(&qinfo);
1280
thd->variables.pseudo_thread_id= save_pseudo_thread_id;
1285
close_temporary(table, 1, 1);
1288
if (!was_quote_show)
1289
thd->options&= ~OPTION_QUOTE_SHOW_CREATE; /* restore option */
1290
thd->temporary_tables=0;
570
1294
Find table in list.
574
table Pointer to table list
575
offset Offset to which list in table structure to use
576
db_name Data base name
577
table_name Table name
580
This is called by find_table_in_global_list().
584
# Pointer to found table.
1297
find_table_in_list()
1298
table Pointer to table list
1299
offset Offset to which list in table structure to use
1300
db_name Data base name
1301
table_name Table name
1304
This is called by find_table_in_local_list() and
1305
find_table_in_global_list().
1308
NULL Table not found
1309
# Pointer to found table.
587
1312
TableList *find_table_in_list(TableList *table,
588
TableList *TableList::*link,
590
const char *table_name)
1313
TableList *TableList::*link,
1314
const char *db_name,
1315
const char *table_name)
592
1317
for (; table; table= table->*link )
594
if ((table->table == 0 || table->table->getShare()->getType() == message::Table::STANDARD) &&
595
strcasecmp(table->db, db_name) == 0 &&
596
strcasecmp(table->table_name, table_name) == 0)
1319
if ((table->table == 0 || table->table->s->tmp_table == NO_TMP_TABLE) &&
1320
strcmp(table->db, db_name) == 0 &&
1321
strcmp(table->table_name, table_name) == 0)
689
void Session::doGetTableNames(const SchemaIdentifier &schema_identifier,
690
std::set<std::string>& set_of_names)
692
for (Table *table= temporary_tables ; table ; table= table->getNext())
694
if (schema_identifier.compare(table->getShare()->getSchemaName()))
696
set_of_names.insert(table->getShare()->getTableName());
701
void Session::doGetTableNames(CachedDirectory &,
702
const SchemaIdentifier &schema_identifier,
703
std::set<std::string> &set_of_names)
705
doGetTableNames(schema_identifier, set_of_names);
708
void Session::doGetTableIdentifiers(const SchemaIdentifier &schema_identifier,
709
TableIdentifiers &set_of_identifiers)
711
for (Table *table= temporary_tables ; table ; table= table->getNext())
713
if (schema_identifier.compare(table->getShare()->getSchemaName()))
715
set_of_identifiers.push_back(TableIdentifier(table->getShare()->getSchemaName(),
716
table->getShare()->getTableName(),
717
table->getShare()->getPath()));
722
void Session::doGetTableIdentifiers(CachedDirectory &,
723
const SchemaIdentifier &schema_identifier,
724
TableIdentifiers &set_of_identifiers)
726
doGetTableIdentifiers(schema_identifier, set_of_identifiers);
729
bool Session::doDoesTableExist(const TableIdentifier &identifier)
731
for (Table *table= temporary_tables ; table ; table= table->getNext())
733
if (table->getShare()->getType() == message::Table::TEMPORARY)
735
if (identifier.getKey() == table->getShare()->getCacheKey())
745
int Session::doGetTableDefinition(const TableIdentifier &identifier,
746
message::Table &table_proto)
748
for (Table *table= temporary_tables ; table ; table= table->getNext())
750
if (table->getShare()->getType() == message::Table::TEMPORARY)
752
if (identifier.getKey() == table->getShare()->getCacheKey())
754
table_proto.CopyFrom(*(table->getShare()->getTableProto()));
764
Table *Session::find_temporary_table(const char *new_db, const char *table_name)
1418
Issue correct error message in case we found 2 duplicate tables which
1419
prevent some update operation
1422
update_non_unique_table_error()
1423
update table which we try to update
1424
operation name of update operation
1425
duplicate duplicate table which we found
1428
here we hide view underlying tables if we have them
1431
void update_non_unique_table_error(TableList *update,
1432
const char *operation __attribute__((unused)),
1433
TableList *duplicate __attribute__((unused)))
1435
my_error(ER_UPDATE_TABLE_USED, MYF(0), update->alias);
1439
Table *find_temporary_table(THD *thd, const char *db, const char *table_name)
1441
TableList table_list;
1443
table_list.db= (char*) db;
1444
table_list.table_name= (char*) table_name;
1445
return find_temporary_table(thd, &table_list);
1449
Table *find_temporary_table(THD *thd, TableList *table_list)
766
1451
char key[MAX_DBKEY_LENGTH];
767
1452
uint key_length;
769
key_length= TableIdentifier::createKey(key, new_db, table_name);
771
for (Table *table= temporary_tables ; table ; table= table->getNext())
773
const TableIdentifier::Key &share_key(table->getShare()->getCacheKey());
774
if (share_key.size() == key_length &&
775
not memcmp(&share_key[0], key, key_length))
780
return NULL; // Not a temporary table
783
Table *Session::find_temporary_table(TableList *table_list)
785
return find_temporary_table(table_list->db, table_list->table_name);
788
Table *Session::find_temporary_table(TableIdentifier &identifier)
790
for (Table *table= temporary_tables ; table ; table= table->getNext())
792
if (identifier.getKey() == table->getShare()->getCacheKey())
796
return NULL; // Not a temporary table
1455
key_length= create_table_def_key(thd, key, table_list, 1);
1456
for (table=thd->temporary_tables ; table ; table= table->next)
1458
if (table->s->table_cache_key.length == key_length &&
1459
!memcmp(table->s->table_cache_key.str, key, key_length))
1462
return(0); // Not a temporary table
801
1467
Drop a temporary table.
803
Try to locate the table in the list of session->temporary_tables.
1469
Try to locate the table in the list of thd->temporary_tables.
804
1470
If the table is found:
805
- if the table is being used by some outer statement, fail.
806
- if the table is in session->locked_tables, unlock it and
807
remove it from the list of locked tables. Currently only transactional
808
temporary tables are present in the locked_tables list.
809
- Close the temporary table, remove its .FRM
810
- remove the table from the list of temporary tables
1471
- if the table is being used by some outer statement, fail.
1472
- if the table is in thd->locked_tables, unlock it and
1473
remove it from the list of locked tables. Currently only transactional
1474
temporary tables are present in the locked_tables list.
1475
- Close the temporary table, remove its .FRM
1476
- remove the table from the list of temporary tables
812
1478
This function is used to drop user temporary tables, as well as
813
1479
internal tables created in CREATE TEMPORARY TABLE ... SELECT
814
1480
or ALTER Table. Even though part of the work done by this function
815
1481
is redundant when the table is internal, as long as we
816
1482
link both internal and user temporary tables into the same
817
session->temporary_tables list, it's impossible to tell here whether
1483
thd->temporary_tables list, it's impossible to tell here whether
818
1484
we're dealing with an internal or a user temporary table.
820
1486
@retval 0 the table was found and dropped successfully.
821
1487
@retval 1 the table was not found in the list of temporary tables
823
1489
@retval -1 the table is in use by a outer query
826
int Session::drop_temporary_table(TableList *table_list)
1492
int drop_temporary_table(THD *thd, TableList *table_list)
830
if (not (table= find_temporary_table(table_list)))
1496
if (!(table= find_temporary_table(thd, table_list)))
833
1499
/* Table might be in use by some outer statement. */
834
if (table->query_id && table->query_id != query_id)
836
my_error(ER_CANT_REOPEN_TABLE, MYF(0), table->getAlias());
840
close_temporary_table(table);
1500
if (table->query_id && table->query_id != thd->query_id)
1502
my_error(ER_CANT_REOPEN_TABLE, MYF(0), table->alias);
1507
If LOCK TABLES list is not empty and contains this table,
1508
unlock the table and remove the table from this list.
1510
mysql_lock_remove(thd, thd->locked_tables, table, false);
1511
close_temporary_table(thd, table, 1, 1);
1516
unlink from thd->temporary tables and close temporary table
1519
void close_temporary_table(THD *thd, Table *table,
1520
bool free_share, bool delete_table)
1524
table->prev->next= table->next;
1525
if (table->prev->next)
1526
table->next->prev= table->prev;
1530
/* removing the item from the list */
1531
assert(table == thd->temporary_tables);
1533
slave must reset its temporary list pointer to zero to exclude
1534
passing non-zero value to end_slave via rli->save_temporary_tables
1535
when no temp tables opened, see an invariant below.
1537
thd->temporary_tables= table->next;
1538
if (thd->temporary_tables)
1539
table->next->prev= 0;
1541
if (thd->slave_thread)
1543
/* natural invariant of temporary_tables */
1544
assert(slave_open_temp_tables || !thd->temporary_tables);
1545
slave_open_temp_tables--;
1547
close_temporary(table, free_share, delete_table);
1553
Close and delete a temporary table
1556
This dosn't unlink table from thd->temporary
1557
If this is needed, use close_temporary_table()
1560
void close_temporary(Table *table, bool free_share, bool delete_table)
1562
handlerton *table_type= table->s->db_type();
1564
free_io_cache(table);
1567
Check that temporary table has not been created with
1568
frm_only because it has then not been created in any storage engine
1571
rm_temporary_table(table_type, table->s->path.str,
1572
table->s->tmp_table == TMP_TABLE_FRM_FILE_ONLY);
1575
free_table_share(table->s);
1576
free((char*) table);
1583
Used by ALTER Table when the table is a temporary one. It changes something
1584
only if the ALTER contained a RENAME clause (otherwise, table_name is the old
1586
Prepares a table cache key, which is the concatenation of db, table_name and
1587
thd->slave_proxy_id, separated by '\0'.
1590
bool rename_temporary_table(THD* thd, Table *table, const char *db,
1591
const char *table_name)
1594
uint32_t key_length;
1595
TABLE_SHARE *share= table->s;
1596
TableList table_list;
1598
if (!(key=(char*) alloc_root(&share->mem_root, MAX_DBKEY_LENGTH)))
1599
return(1); /* purecov: inspected */
1601
table_list.db= (char*) db;
1602
table_list.table_name= (char*) table_name;
1603
key_length= create_table_def_key(thd, key, &table_list, 1);
1604
share->set_table_cache_key(key, key_length);
1609
/* move table first in unused links */
1611
static void relink_unused(Table *table)
1613
if (table != unused_tables)
1615
table->prev->next=table->next; /* Remove from unused list */
1616
table->next->prev=table->prev;
1617
table->next=unused_tables; /* Link in unused tables */
1618
table->prev=unused_tables->prev;
1619
unused_tables->prev->next=table;
1620
unused_tables->prev=table;
1621
unused_tables=table;
847
Remove all instances of table from thread's open list and
850
@param session Thread context
851
@param find Table to remove
1627
Remove all instances of table from thread's open list and
1630
@param thd Thread context
1631
@param find Table to remove
1632
@param unlock true - free all locks on tables removed that are
1633
done with LOCK TABLES
1636
@note When unlock parameter is false or current thread doesn't have
1637
any tables locked with LOCK TABLES, tables are assumed to be
1638
not locked (for example already unlocked).
854
void Session::unlink_open_table(Table *find)
1641
void unlink_open_table(THD *thd, Table *find, bool unlock)
856
1643
char key[MAX_DBKEY_LENGTH];
857
uint32_t key_length= find->getShare()->getCacheKeySize();
1644
uint32_t key_length= find->s->table_cache_key.length;
858
1645
Table *list, **prev;
859
safe_mutex_assert_owner(LOCK_open.native_handle());
861
memcpy(key, &find->getMutableShare()->getCacheKey()[0], key_length);
1647
safe_mutex_assert_owner(&LOCK_open);
1649
memcpy(key, find->s->table_cache_key.str, key_length);
863
1651
Note that we need to hold LOCK_open while changing the
864
1652
open_tables list. Another thread may work on it.
866
1654
Closing a MERGE child before the parent would be fatal if the
867
1655
other thread tries to abort the MERGE lock in between.
869
for (prev= &open_tables; *prev; )
1657
for (prev= &thd->open_tables; *prev; )
873
if (list->getShare()->getCacheKeySize() == key_length &&
874
not memcmp(&list->getShare()->getCacheKey()[0], key, key_length))
1661
if (list->s->table_cache_key.length == key_length &&
1662
!memcmp(list->s->table_cache_key.str, key, key_length))
1664
if (unlock && thd->locked_tables)
1665
mysql_lock_remove(thd, thd->locked_tables, list, true);
876
1667
/* Remove table from open_tables list. */
877
*prev= list->getNext();
879
1669
/* Close table. */
1670
hash_delete(&open_cache,(unsigned char*) list); // Close table
884
1674
/* Step to next entry in open_tables list. */
885
prev= list->getNextPtr();
889
1679
// Notify any 'refresh' threads
890
1680
broadcast_refresh();
895
Auxiliary routine which closes and drops open table.
897
@param session Thread handle
898
@param table Table object for table to be dropped
899
@param db_name Name of database for this table
900
@param table_name Name of this table
902
@note This routine assumes that table to be closed is open only
903
by calling thread so we needn't wait until other threads
904
will close the table. Also unless called under implicit or
905
explicit LOCK TABLES mode it assumes that table to be
906
dropped is already unlocked. In the former case it will
907
also remove lock on the table. But one should not rely on
908
this behaviour as it may change in future.
909
Currently, however, this function is never called for a
910
table that was locked with LOCK TABLES.
1686
Auxiliary routine which closes and drops open table.
1688
@param thd Thread handle
1689
@param table Table object for table to be dropped
1690
@param db_name Name of database for this table
1691
@param table_name Name of this table
1693
@note This routine assumes that table to be closed is open only
1694
by calling thread so we needn't wait until other threads
1695
will close the table. Also unless called under implicit or
1696
explicit LOCK TABLES mode it assumes that table to be
1697
dropped is already unlocked. In the former case it will
1698
also remove lock on the table. But one should not rely on
1699
this behaviour as it may change in future.
1700
Currently, however, this function is never called for a
1701
table that was locked with LOCK TABLES.
913
void Session::drop_open_table(Table *table, TableIdentifier &identifier)
1704
void drop_open_table(THD *thd, Table *table, const char *db_name,
1705
const char *table_name)
915
if (table->getShare()->getType())
917
close_temporary_table(table);
1707
if (table->s->tmp_table)
1708
close_temporary_table(thd, table, 1, 1);
921
boost::mutex::scoped_lock scoped_lock(LOCK_open); /* Close and drop a table (AUX routine) */
1711
handlerton *table_type= table->s->db_type();
1712
pthread_mutex_lock(&LOCK_open);
923
1714
unlink_open_table() also tells threads waiting for refresh or close
924
1715
that something has happened.
926
unlink_open_table(table);
927
quick_rm_table(*this, identifier);
1717
unlink_open_table(thd, table, false);
1718
quick_rm_table(table_type, db_name, table_name, 0);
1719
pthread_mutex_unlock(&LOCK_open);
933
Wait for condition but allow the user to send a kill to mysqld
1725
Wait for condition but allow the user to send a kill to mysqld
937
session Thread Cursor
938
mutex mutex that is currently hold that is associated with condition
939
Will be unlocked on return
940
cond Condition to wait for
1728
wait_for_condition()
1730
mutex mutex that is currently hold that is associated with condition
1731
Will be unlocked on return
1732
cond Condition to wait for
943
void Session::wait_for_condition(boost::mutex &mutex, boost::condition_variable &cond)
1735
void wait_for_condition(THD *thd, pthread_mutex_t *mutex, pthread_cond_t *cond)
945
1737
/* Wait until the current table is up to date */
946
const char *saved_proc_info;
947
mysys_var->current_mutex= &mutex;
948
mysys_var->current_cond= &cond;
949
saved_proc_info= get_proc_info();
950
set_proc_info("Waiting for table");
952
(void) pthread_cond_wait(cond.native_handle(), mutex.native_handle());
1738
const char *proc_info;
1739
thd->mysys_var->current_mutex= mutex;
1740
thd->mysys_var->current_cond= cond;
1741
proc_info=thd->get_proc_info();
1742
thd->set_proc_info("Waiting for table");
1744
(void) pthread_cond_wait(cond, mutex);
955
1747
We must unlock mutex first to avoid deadlock becasue conditions are
1018
1846
object to its original state.
1020
1848
*table= orig_table;
1024
share= table->getMutableShare();
1026
1854
We want to prevent other connections from opening this table until end
1027
1855
of statement as it is likely that modifications of table's metadata are
1028
not yet finished (for example CREATE TRIGGER have to change .TRG cursor,
1856
not yet finished (for example CREATE TRIGGER have to change .TRG file,
1029
1857
or we might want to drop table if CREATE TABLE ... SELECT fails).
1030
1858
This also allows us to assume that no other connection will sneak in
1031
1859
before we will get table-level lock on this table.
1033
share->resetVersion();
1034
table->in_use = this;
1862
table->in_use = thd;
1038
table->setNext(open_tables);
1866
table->next= thd->open_tables;
1867
thd->open_tables= table;
1044
Table object should be already in Session::open_tables list so we just
1872
Table object should be already in THD::open_tables list so we just
1045
1873
need to set Table::next correctly.
1047
table->setNext(orig_table.getNext());
1875
table->next= orig_table.next;
1050
table->tablenr= current_tablenr++;
1051
table->used_fields= 0;
1052
table->const_table= 0;
1878
table->tablenr=thd->current_tablenr++;
1879
table->used_fields=0;
1880
table->const_table=0;
1053
1881
table->null_row= false;
1054
1882
table->maybe_null= false;
1055
1883
table->force_index= false;
1056
table->status= STATUS_NO_RECORD;
1884
table->status=STATUS_NO_RECORD;
1063
Create and insert into table cache placeholder for table
1064
which will prevent its opening (or creation) (a.k.a lock
1067
@param session Thread context
1068
@param key Table cache key for name to be locked
1069
@param key_length Table cache key length
1071
@return Pointer to Table object used for name locking or 0 in
1890
Create and insert into table cache placeholder for table
1891
which will prevent its opening (or creation) (a.k.a lock
1894
@param thd Thread context
1895
@param key Table cache key for name to be locked
1896
@param key_length Table cache key length
1898
@return Pointer to Table object used for name locking or 0 in
1075
Table *Session::table_cache_insert_placeholder(const char *db_name, const char *table_name)
1902
Table *table_cache_insert_placeholder(THD *thd, const char *key,
1903
uint32_t key_length)
1077
safe_mutex_assert_owner(LOCK_open.native_handle());
1909
safe_mutex_assert_owner(&LOCK_open);
1080
1912
Create a table entry with the right key and with an old refresh version
1913
Note that we must use my_multi_malloc() here as this is freed by the
1082
TableIdentifier identifier(db_name, table_name, message::Table::INTERNAL);
1083
TablePlaceholder *table= new TablePlaceholder(this, identifier);
1085
if (not add_table(table))
1916
if (!my_multi_malloc(MYF(MY_WME | MY_ZEROFILL),
1917
&table, sizeof(*table),
1918
&share, sizeof(*share),
1919
&key_buff, key_length,
1924
share->set_table_cache_key(key_buff, key, key_length);
1925
share->tmp_table= INTERNAL_TMP_TABLE; // for intern_close_table
1927
table->locked_by_name=1;
1929
if (my_hash_insert(&open_cache, (unsigned char*)table))
1931
free((unsigned char*) table);
1097
Obtain an exclusive name lock on the table if it is not cached
1100
@param session Thread context
1101
@param db Name of database
1102
@param table_name Name of table
1103
@param[out] table Out parameter which is either:
1104
- set to NULL if table cache contains record for
1106
- set to point to the Table instance used for
1109
@note This function takes into account all records for table in table
1110
cache, even placeholders used for name-locking. This means that
1111
'table' parameter can be set to NULL for some situations when
1112
table does not really exist.
1114
@retval true Error occured (OOM)
1115
@retval false Success. 'table' parameter set according to above rules.
1940
Obtain an exclusive name lock on the table if it is not cached
1943
@param thd Thread context
1944
@param db Name of database
1945
@param table_name Name of table
1946
@param[out] table Out parameter which is either:
1947
- set to NULL if table cache contains record for
1949
- set to point to the Table instance used for
1952
@note This function takes into account all records for table in table
1953
cache, even placeholders used for name-locking. This means that
1954
'table' parameter can be set to NULL for some situations when
1955
table does not really exist.
1957
@retval true Error occured (OOM)
1958
@retval false Success. 'table' parameter set according to above rules.
1117
bool Session::lock_table_name_if_not_cached(TableIdentifier &identifier, Table **table)
1961
bool lock_table_name_if_not_cached(THD *thd, const char *db,
1962
const char *table_name, Table **table)
1119
const TableIdentifier::Key &key(identifier.getKey());
1121
boost::mutex::scoped_lock scope_lock(LOCK_open); /* Obtain a name lock even though table is not in cache (like for create table) */
1123
TableOpenCache::iterator iter;
1125
iter= get_open_cache().find(key);
1127
if (iter != get_open_cache().end())
1964
char key[MAX_DBKEY_LENGTH];
1965
uint32_t key_length;
1967
key_length= (uint)(my_stpcpy(my_stpcpy(key, db) + 1, table_name) - key) + 1;
1968
pthread_mutex_lock(&LOCK_open);
1970
if (hash_search(&open_cache, (unsigned char *)key, key_length))
1972
pthread_mutex_unlock(&LOCK_open);
1133
if (not (*table= table_cache_insert_placeholder(identifier.getSchemaName().c_str(), identifier.getTableName().c_str())))
1137
(*table)->open_placeholder= true;
1138
(*table)->setNext(open_tables);
1139
open_tables= *table;
1976
if (!(*table= table_cache_insert_placeholder(thd, key, key_length)))
1978
pthread_mutex_unlock(&LOCK_open);
1981
(*table)->open_placeholder= 1;
1982
(*table)->next= thd->open_tables;
1983
thd->open_tables= *table;
1984
pthread_mutex_unlock(&LOCK_open);
1990
Check that table exists in table definition cache, on disk
1991
or in some storage engine.
1993
@param thd Thread context
1994
@param table Table list element
1995
@param[out] exists Out parameter which is set to true if table
1996
exists and to false otherwise.
1998
@note This function assumes that caller owns LOCK_open mutex.
1999
It also assumes that the fact that there are no name-locks
2000
on the table was checked beforehand.
2002
@note If there is no .FRM file for the table but it exists in one
2003
of engines (e.g. it was created on another node of NDB cluster)
2004
this function will fetch and create proper .FRM file for it.
2006
@retval true Some error occured
2007
@retval false No error. 'exists' out parameter set accordingly.
2010
bool check_if_table_exists(THD *thd, TableList *table, bool *exists)
2012
char path[FN_REFLEN];
2015
safe_mutex_assert_owner(&LOCK_open);
2019
if (get_cached_table_share(table->db, table->table_name))
2022
build_table_filename(path, sizeof(path) - 1, table->db, table->table_name,
2025
if (!access(path, F_OK))
2028
/* .FRM file doesn't exist. Check if some engine can provide it. */
2030
rc= ha_create_table_from_engine(thd, table->db, table->table_name);
2034
/* Table does not exists in engines as well. */
2040
/* Table exists in some engine and .FRM for it was created. */
2045
my_printf_error(ER_UNKNOWN_ERROR, "Failed to open '%-.64s', error while "
2046
"unpacking from engine", MYF(0), table->table_name);
1149
session Thread context.
1150
table_list Open first table in list.
1151
refresh INOUT Pointer to memory that will be set to 1 if
1152
we need to close all tables and reopen them.
1153
If this is a NULL pointer, then the table is not
1154
put in the thread-open-list.
1155
flags Bitmap of flags to modify how open works:
1156
DRIZZLE_LOCK_IGNORE_FLUSH - Open table even if
1157
someone has done a flush or namelock on it.
1158
No version number checking is done.
1159
DRIZZLE_OPEN_TEMPORARY_ONLY - Open only temporary
1160
table not the base table or view.
2058
table_list Open first table in list.
2059
refresh INOUT Pointer to memory that will be set to 1 if
2060
we need to close all tables and reopen them.
2061
If this is a NULL pointer, then the table is not
2062
put in the thread-open-list.
2063
flags Bitmap of flags to modify how open works:
2064
DRIZZLE_LOCK_IGNORE_FLUSH - Open table even if
2065
someone has done a flush or namelock on it.
2066
No version number checking is done.
2067
DRIZZLE_OPEN_TEMPORARY_ONLY - Open only temporary
2068
table not the base table or view.
1163
Uses a cache of open tables to find a table not in use.
2071
Uses a cache of open tables to find a table not in use.
1165
If table list element for the table to be opened has "create" flag
1166
set and table does not exist, this function will automatically insert
1167
a placeholder for exclusive name lock into the open tables cache and
1168
will return the Table instance that corresponds to this placeholder.
2073
If table list element for the table to be opened has "create" flag
2074
set and table does not exist, this function will automatically insert
2075
a placeholder for exclusive name lock into the open tables cache and
2076
will return the Table instance that corresponds to this placeholder.
1171
NULL Open failed. If refresh is set then one should close
1172
all other tables and retry the open.
1173
# Success. Pointer to Table object for open table.
2079
NULL Open failed. If refresh is set then one should close
2080
all other tables and retry the open.
2081
# Success. Pointer to Table object for open table.
1177
Table *Session::openTable(TableList *table_list, bool *refresh, uint32_t flags)
2085
Table *open_table(THD *thd, TableList *table_list, bool *refresh, uint32_t flags)
1180
const char *alias= table_list->alias;
2087
register Table *table;
2088
char key[MAX_DBKEY_LENGTH];
2089
unsigned int key_length;
2090
char *alias= table_list->alias;
2091
HASH_SEARCH_STATE state;
1182
/* Parsing of partitioning information from .frm needs session->lex set up. */
1183
assert(lex->is_lex_started);
2093
/* Parsing of partitioning information from .frm needs thd->lex set up. */
2094
assert(thd->lex->is_lex_started);
1185
2096
/* find a unused table in the open table cache */
1189
2100
/* an open table operation needs a lot of the stack space */
1190
if (check_stack_overrun(this, STACK_MIN_SIZE_FOR_OPEN, (unsigned char *)&alias))
1196
TableIdentifier identifier(table_list->db, table_list->table_name);
1197
const TableIdentifier::Key &key(identifier.getKey());
1198
TableOpenCacheRange ppp;
2101
if (check_stack_overrun(thd, STACK_MIN_SIZE_FOR_OPEN, (unsigned char *)&alias))
2107
key_length= (create_table_def_key(thd, key, table_list, 1) -
2108
TMP_TABLE_KEY_EXTRA);
1201
2111
Unless requested otherwise, try to resolve this table in the list
1202
2112
of temporary tables of this thread. In MySQL temporary tables
1203
2113
are always thread-local and "shadow" possible base tables with the
1204
2114
same name. This block implements the behaviour.
1205
TODO -> move this block into a separate function.
2115
TODO: move this block into a separate function.
1207
for (table= temporary_tables; table ; table=table->getNext())
1209
if (table->getShare()->getCacheKey() == key)
2118
for (table= thd->temporary_tables; table ; table=table->next)
1212
We're trying to use the same temporary table twice in a query.
1213
Right now we don't support this because a temporary table
1214
is always represented by only one Table object in Session, and
1215
it can not be cloned. Emit an error for an unsupported behaviour.
1217
if (table->query_id)
2120
if (table->s->table_cache_key.length == key_length +
2121
TMP_TABLE_KEY_EXTRA &&
2122
!memcmp(table->s->table_cache_key.str, key,
2123
key_length + TMP_TABLE_KEY_EXTRA))
1219
my_error(ER_CANT_REOPEN_TABLE, MYF(0), table->getAlias());
2126
We're trying to use the same temporary table twice in a query.
2127
Right now we don't support this because a temporary table
2128
is always represented by only one Table object in THD, and
2129
it can not be cloned. Emit an error for an unsupported behaviour.
2131
if (table->query_id)
2133
my_error(ER_CANT_REOPEN_TABLE, MYF(0), table->alias);
2136
table->query_id= thd->query_id;
2137
thd->thread_specific_used= true;
1222
table->query_id= getQueryId();
1227
2143
if (flags & DRIZZLE_OPEN_TEMPORARY_ONLY)
1229
2145
my_error(ER_NO_SUCH_TABLE, MYF(0), table_list->db, table_list->table_name);
1234
If it's the first table from a list of tables used in a query,
1235
remember refresh_version (the version of open_cache state).
1236
If the version changes while we're opening the remaining tables,
1237
we will have to back off, close all the tables opened-so-far,
1238
and try to reopen them.
1240
Note-> refresh_version is currently changed only during FLUSH TABLES.
1244
version= refresh_version;
1246
else if ((version != refresh_version) &&
1247
! (flags & DRIZZLE_LOCK_IGNORE_FLUSH))
1249
/* Someone did a refresh while thread was opening tables */
1257
Before we test the global cache, we test our local session cache.
1261
assert(false); /* Not implemented yet */
2150
The table is not temporary - if we're in pre-locked or LOCK TABLES
2151
mode, let's try to find the requested table in the list of pre-opened
2152
and locked tables. If the table is not there, return an error - we can't
2153
open not pre-opened tables in pre-locked/LOCK TABLES mode.
2154
TODO: move this block into a separate function.
2156
if (thd->locked_tables)
2157
{ // Using table locks
2158
Table *best_table= 0;
2159
int best_distance= INT_MIN;
2160
bool check_if_used= false;
2161
for (table=thd->open_tables; table ; table=table->next)
2163
if (table->s->table_cache_key.length == key_length &&
2164
!memcmp(table->s->table_cache_key.str, key, key_length))
2166
if (check_if_used && table->query_id &&
2167
table->query_id != thd->query_id)
2170
If we are in stored function or trigger we should ensure that
2171
we won't change table that is already used by calling statement.
2172
So if we are opening table for writing, we should check that it
2173
is not already open by some calling stamement.
2175
my_error(ER_CANT_UPDATE_USED_TABLE_IN_SF_OR_TRG, MYF(0),
2176
table->s->table_name.str);
2180
When looking for a usable Table, ignore MERGE children, as they
2181
belong to their parent and cannot be used explicitly.
2183
if (!my_strcasecmp(system_charset_info, table->alias, alias) &&
2184
table->query_id != thd->query_id) /* skip tables already used */
2186
int distance= ((int) table->reginfo.lock_type -
2187
(int) table_list->lock_type);
2189
Find a table that either has the exact lock type requested,
2190
or has the best suitable lock. In case there is no locked
2191
table that has an equal or higher lock than requested,
2192
we us the closest matching lock to be able to produce an error
2193
message about wrong lock mode on the table. The best_table
2194
is changed if bd < 0 <= d or bd < d < 0 or 0 <= d < bd.
2196
distance < 0 - No suitable lock found
2197
distance > 0 - we have lock mode higher then we require
2198
distance == 0 - we have lock mode exactly which we need
2200
if ((best_distance < 0 && distance > best_distance) || (distance >= 0 && distance < best_distance))
2202
best_distance= distance;
2204
if (best_distance == 0 && !check_if_used)
2207
If we have found perfect match and we don't need to check that
2208
table is not used by one of calling statements (assuming that
2209
we are inside of function or trigger) we can finish iterating
2210
through open tables list.
2221
table->query_id= thd->query_id;
2225
No table in the locked tables list. In case of explicit LOCK TABLES
2226
this can happen if a user did not include the able into the list.
2227
In case of pre-locked mode locked tables list is generated automatically,
2228
so we may only end up here if the table did not exist when
2229
locked tables list was created.
2231
my_error(ER_TABLE_NOT_LOCKED, MYF(0), alias);
1288
2290
an implicit "pending locks queue" - see
1289
2291
wait_for_locked_table_names for details.
1291
ppp= get_open_cache().equal_range(key);
1294
for (TableOpenCache::const_iterator iter= ppp.first;
1295
iter != ppp.second; ++iter, table= NULL)
2293
for (table= (Table*) hash_first(&open_cache, (unsigned char*) key, key_length,
2295
table && table->in_use ;
2296
table= (Table*) hash_next(&open_cache, (unsigned char*) key, key_length,
1297
table= (*iter).second;
1299
if (not table->in_use)
1302
2300
Here we flush tables marked for flush.
1303
Normally, table->getShare()->version contains the value of
2301
Normally, table->s->version contains the value of
1304
2302
refresh_version from the moment when this table was
1305
2303
(re-)opened and added to the cache.
1306
2304
If since then we did (or just started) FLUSH TABLES
1307
2305
statement, refresh_version has been increased.
1308
For "name-locked" Table instances, table->getShare()->version is set
2306
For "name-locked" Table instances, table->s->version is set
1309
2307
to 0 (see lock_table_name for details).
1310
2308
In case there is a pending FLUSH TABLES or a name lock, we
1311
2309
need to back off and re-start opening tables.
1312
2310
If we do not back off now, we may dead lock in case of lock
1313
2311
order mismatch with some other thread:
1314
c1-> name lock t1; -- sort of exclusive lock
1315
c2-> open t2; -- sort of shared lock
1316
c1-> name lock t2; -- blocks
1317
c2-> open t1; -- blocks
2312
c1: name lock t1; -- sort of exclusive lock
2313
c2: open t2; -- sort of shared lock
2314
c1: name lock t2; -- blocks
2315
c2: open t1; -- blocks
1319
2317
if (table->needs_reopen_or_name_lock())
1321
2319
if (flags & DRIZZLE_LOCK_IGNORE_FLUSH)
1323
2321
/* Force close at once after usage */
1324
version= table->getShare()->getVersion();
2322
thd->version= table->s->version;
1328
2326
/* Avoid self-deadlocks by detecting self-dependencies. */
1329
if (table->open_placeholder && table->in_use == this)
2327
if (table->open_placeholder && table->in_use == thd)
1332
my_error(ER_UPDATE_TABLE_USED, MYF(0), table->getMutableShare()->getTableName());
2329
pthread_mutex_unlock(&LOCK_open);
2330
my_error(ER_UPDATE_TABLE_USED, MYF(0), table->s->table_name.str);
1337
2335
Back off, part 1: mark the table as "unused" for the
1338
2336
purpose of name-locking by setting table->db_stat to 0. Do
1339
2337
that only for the tables in this thread that have an old
1340
table->getShare()->version (this is an optimization (?)).
2338
table->s->version (this is an optimization (?)).
1341
2339
table->db_stat == 0 signals wait_for_locked_table_names
1342
2340
that the tables in question are not used any more. See
1343
2341
table_is_used call for details.
2343
Notice that HANDLER tables were already taken care of by
2344
the earlier call to mysql_ha_flush() in this same critical
1345
close_old_data_files(false, false);
2347
close_old_data_files(thd,thd->open_tables,0,0);
1348
2349
Back-off part 2: try to avoid "busy waiting" on the table:
1349
2350
if the table is in use by some other thread, we suspend
1350
2351
and wait till the operation is complete: when any
1351
operation that juggles with table->getShare()->version completes,
2352
operation that juggles with table->s->version completes,
1352
2353
it broadcasts COND_refresh condition variable.
1353
2354
If 'old' table we met is in use by current thread we return
1354
2355
without waiting since in this situation it's this thread
1355
2356
which is responsible for broadcasting on COND_refresh
1356
(and this was done already in Session::close_old_data_files()).
2357
(and this was done already in close_old_data_files()).
1357
2358
Good example of such situation is when we have statement
1358
2359
that needs two instances of table and FLUSH TABLES comes
1359
2360
after we open first instance but before we open second
1362
if (table->in_use != this)
2363
if (table->in_use != thd)
1364
2365
/* wait_for_conditionwill unlock LOCK_open for us */
1365
wait_for_condition(LOCK_open, COND_refresh);
2366
wait_for_condition(thd, &LOCK_open, &COND_refresh);
2370
pthread_mutex_unlock(&LOCK_open);
1372
2373
There is a refresh in progress for this table.
1373
2374
Signal the caller that it has to try again.
1382
unused_tables.unlink(table);
1383
table->in_use= this;
2383
/* Unlink the table from "unused_tables" list. */
2384
if (table == unused_tables)
2386
unused_tables=unused_tables->next; // Remove from link
2387
if (table == unused_tables)
2390
table->prev->next=table->next; /* Remove from unused list */
2391
table->next->prev=table->prev;
1387
2396
/* Insert a new Table instance into the open cache */
1389
2398
/* Free cache if too big */
1390
unused_tables.cull();
2399
while (open_cache.records > table_cache_size && unused_tables)
2400
hash_delete(&open_cache,(unsigned char*) unused_tables); /* purecov: tested */
1392
if (table_list->isCreate())
2402
if (table_list->create)
1394
TableIdentifier lock_table_identifier(table_list->db, table_list->table_name, message::Table::STANDARD);
1396
if (not plugin::StorageEngine::doesTableExist(*this, lock_table_identifier))
2406
if (check_if_table_exists(thd, table_list, &exists))
2408
pthread_mutex_unlock(&LOCK_open);
1399
2415
Table to be created, so we need to create placeholder in table-cache.
1401
if (!(table= table_cache_insert_placeholder(table_list->db, table_list->table_name)))
2417
if (!(table= table_cache_insert_placeholder(thd, key, key_length)))
2419
pthread_mutex_unlock(&LOCK_open);
1407
2423
Link placeholder to the open tables list so it will be automatically
1408
2424
removed once tables are closed. Also mark it so it won't be ignored
1409
2425
by other trying to take name-lock.
1411
table->open_placeholder= true;
1412
table->setNext(open_tables);
2427
table->open_placeholder= 1;
2428
table->next= thd->open_tables;
2429
thd->open_tables= table;
2430
pthread_mutex_unlock(&LOCK_open);
1418
2433
/* Table exists. Let us try to open it. */
1421
2436
/* make a new table */
2437
if (!(table=(Table*) my_malloc(sizeof(*table),MYF(MY_WME))))
2439
pthread_mutex_unlock(&LOCK_open);
1429
error= open_unireg_entry(this, table, alias, identifier);
1436
(void)add_table(table);
2443
error= open_unireg_entry(thd, table, table_list, alias, key, key_length);
2444
/* Combine the follow two */
2447
free((unsigned char*)table);
2448
pthread_mutex_unlock(&LOCK_open);
2453
free((unsigned char*)table);
2454
pthread_mutex_unlock(&LOCK_open);
2457
my_hash_insert(&open_cache,(unsigned char*) table);
2460
pthread_mutex_unlock(&LOCK_open);
1442
table->setNext(open_tables); /* Link into simple list */
2463
table->next=thd->open_tables; /* Link into simple list */
2464
thd->open_tables=table;
1445
table->reginfo.lock_type= TL_READ; /* Assume read */
1448
assert(table->getShare()->getTableCount() > 0 || table->getShare()->getType() != message::Table::STANDARD);
1450
if (lex->need_correct_ident())
2466
table->reginfo.lock_type=TL_READ; /* Assume read */
2469
assert(table->s->ref_count > 0 || table->s->tmp_table != NO_TMP_TABLE);
2471
if (thd->lex->need_correct_ident())
1451
2472
table->alias_name_used= my_strcasecmp(table_alias_charset,
1452
table->getMutableShare()->getTableName(), alias);
2473
table->s->table_name.str, alias);
1453
2474
/* Fix alias if table name changes */
1454
if (strcmp(table->getAlias(), alias))
2475
if (strcmp(table->alias, alias))
1456
uint32_t length=(uint32_t) strlen(alias)+1;
1457
table->alias= (char*) realloc((char*) table->alias, length);
2477
uint32_t length=(uint) strlen(alias)+1;
2478
table->alias= (char*) my_realloc((char*) table->alias, length,
1458
2480
memcpy((void*) table->alias, alias, length);
1461
2482
/* These variables are also set in reopen_table() */
1462
table->tablenr= current_tablenr++;
1463
table->used_fields= 0;
1464
table->const_table= 0;
2483
table->tablenr=thd->current_tablenr++;
2484
table->used_fields=0;
2485
table->const_table=0;
1465
2486
table->null_row= false;
1466
2487
table->maybe_null= false;
1467
2488
table->force_index= false;
1468
2489
table->status=STATUS_NO_RECORD;
1469
table->insert_values.clear();
2490
table->insert_values= 0;
1470
2491
/* Catch wrong handling of the auto_increment_field_not_null. */
1471
2492
assert(!table->auto_increment_field_not_null);
1472
2493
table->auto_increment_field_not_null= false;
1473
2494
if (table->timestamp_field)
1475
2495
table->timestamp_field_type= table->timestamp_field->get_auto_set_type();
1477
2496
table->pos_in_table_list= table_list;
1478
2497
table->clear_column_bitmaps();
1479
2498
assert(table->key_read == 0);
2503
Table *find_locked_table(THD *thd, const char *db,const char *table_name)
2505
char key[MAX_DBKEY_LENGTH];
2506
uint32_t key_length=(uint) (my_stpcpy(my_stpcpy(key,db)+1,table_name)-key)+1;
2508
for (Table *table=thd->open_tables; table ; table=table->next)
2510
if (table->s->table_cache_key.length == key_length &&
2511
!memcmp(table->s->table_cache_key.str, key, key_length))
1487
2519
Reopen an table because the definition has changed.
1494
The data cursor for the table is already closed and the share is released
1495
The table has a 'dummy' share that mainly contains database and table name.
2526
The data file for the table is already closed and the share is released
2527
The table has a 'dummy' share that mainly contains database and table name.
1499
1 error. The old table object is not changed.
2531
1 error. The old table object is not changed.
1502
2534
bool reopen_table(Table *table)
1954
3016
other threads trying to get the lock.
1957
void abort_locked_tables(Session *session, const drizzled::TableIdentifier &identifier)
3019
void abort_locked_tables(THD *thd,const char *db, const char *table_name)
1960
for (table= session->open_tables; table ; table= table->getNext())
3022
for (table= thd->open_tables; table ; table= table->next)
1962
if (table->getShare()->getCacheKey() == identifier.getKey())
3024
if (!strcmp(table->s->table_name.str, table_name) &&
3025
!strcmp(table->s->db.str, db))
1964
3027
/* If MERGE child, forward lock handling to parent. */
1965
mysql_lock_abort(session, table);
3028
mysql_lock_abort(thd, table, true);
1972
Load a table definition from cursor and open unireg table
3036
Function to assign a new table map id to a table share.
3040
share - Pointer to table share structure
3044
We are intentionally not checking that share->mutex is locked
3045
since this function should only be called when opening a table
3046
share and before it is entered into the table_def_cache (meaning
3047
that it cannot be fetched by another thread, even accidentally).
3052
The LOCK_open mutex is locked
3056
share->table_map_id is given a value that with a high certainty is
3057
not used by any other table (the only case where a table id can be
3058
reused is on wrap-around, which means more than 4 billion table
3059
share opens have been executed while one table was open all the
3062
share->table_map_id is not UINT32_MAX.
3064
void assign_new_table_id(TABLE_SHARE *share)
3066
static uint32_t last_table_id= UINT32_MAX;
3069
assert(share != NULL);
3070
safe_mutex_assert_owner(&LOCK_open);
3072
ulong tid= ++last_table_id; /* get next id */
3074
There is one reserved number that cannot be used. Remember to
3075
change this when 6-byte global table id's are introduced.
3077
if (unlikely(tid == UINT32_MAX))
3078
tid= ++last_table_id;
3079
share->table_map_id= tid;
3081
/* Post conditions */
3082
assert(share->table_map_id != UINT32_MAX);
3088
Load a table definition from file and open unireg table
1976
session Thread handle
1977
entry Store open table definition here
1978
table_list TableList with db, table_name
1980
cache_key Key for share_cache
1981
cache_key_length length of cache_key
3093
entry Store open table definition here
3094
table_list TableList with db, table_name
3096
cache_key Key for share_cache
3097
cache_key_length length of cache_key
1984
Extra argument for open is taken from session->open_options
1985
One must have a lock on LOCK_open when calling this function
3100
Extra argument for open is taken from thd->open_options
3101
One must have a lock on LOCK_open when calling this function
1992
static int open_unireg_entry(Session *session,
3108
static int open_unireg_entry(THD *thd, Table *entry, TableList *table_list,
1994
3109
const char *alias,
1995
TableIdentifier &identifier)
3110
char *cache_key, uint32_t cache_key_length)
1999
3114
uint32_t discover_retry_count= 0;
2001
safe_mutex_assert_owner(LOCK_open.native_handle());
3116
safe_mutex_assert_owner(&LOCK_open);
2003
if (not (share= TableShare::getShareCreate(session,
3118
if (!(share= get_table_share_with_create(thd, table_list, cache_key,
3120
table_list->i_s_requested_object,
2008
while ((error= share->open_table_from_share(session,
2011
(uint32_t) (HA_OPEN_KEYFILE |
2015
session->open_options, *entry)))
3124
while ((error= open_table_from_share(thd, share, alias,
3125
(uint) (HA_OPEN_KEYFILE |
3130
thd->open_options, entry, OTM_OPEN)))
2017
3132
if (error == 7) // Table def changed
2019
share->resetVersion(); // Mark share as old
3134
share->version= 0; // Mark share as old
2020
3135
if (discover_retry_count++) // Retry once
2025
3140
Here we should wait until all threads has released the table.
2026
3141
For now we do one retry. This may cause a deadlock if there
2027
3142
is other threads waiting for other tables used by this thread.
2029
3144
Proper fix would be to if the second retry failed:
2030
3145
- Mark that table def changed
2031
3146
- Return from open table
2239
3525
table_list->lock_type= lock_type;
2240
3526
table_list->table= table;
2242
assert(lock == 0); // You must lock everything at once
2243
if ((table->reginfo.lock_type= lock_type) != TL_UNLOCK)
2244
if (! (lock= mysql_lock_tables(this, &table_list->table, 1, 0, &refresh)))
3527
if (thd->locked_tables)
3529
if (check_lock_and_start_stmt(thd, table, lock_type))
3534
assert(thd->lock == 0); // You must lock everything at once
3535
if ((table->reginfo.lock_type= lock_type) != TL_UNLOCK)
3536
if (! (thd->lock= mysql_lock_tables(thd, &table_list->table, 1,
3537
lock_flags, &refresh)))
3542
thd->set_proc_info(0);
3548
Open all tables in list, locks them and optionally process derived tables.
3551
open_and_lock_tables_derived()
3552
thd - thread handler
3553
tables - list of tables for open&locking
3554
derived - if to handle derived tables
3561
The lock will automaticaly be freed by close_thread_tables()
3564
There are two convenience functions:
3565
- simple_open_n_lock_tables(thd, tables) without derived handling
3566
- open_and_lock_tables(thd, tables) with derived handling
3567
Both inline functions call open_and_lock_tables_derived() with
3568
the third argument set appropriately.
3571
int open_and_lock_tables_derived(THD *thd, TableList *tables, bool derived)
3578
if (open_tables(thd, &tables, &counter, 0))
3581
if (!lock_tables(thd, tables, counter, &need_reopen))
3585
close_tables_for_reopen(thd, &tables);
3588
(mysql_handle_derived(thd->lex, &mysql_derived_prepare) ||
3589
(thd->fill_derived_tables() &&
3590
mysql_handle_derived(thd->lex, &mysql_derived_filling))))
3591
return(true); /* purecov: inspected */
3597
Open all tables in list and process derived tables
3600
open_normal_and_derived_tables
3601
thd - thread handler
3602
tables - list of tables for open
3603
flags - bitmap of flags to modify how the tables will be open:
3604
DRIZZLE_LOCK_IGNORE_FLUSH - open table even if someone has
3605
done a flush or namelock on it.
3612
This is to be used on prepare stage when you don't read any
3613
data from the tables.
3616
bool open_normal_and_derived_tables(THD *thd, TableList *tables, uint32_t flags)
3619
assert(!thd->fill_derived_tables());
3620
if (open_tables(thd, &tables, &counter, flags) ||
3621
mysql_handle_derived(thd->lex, &mysql_derived_prepare))
3622
return(true); /* purecov: inspected */
3628
Decide on logging format to use for the statement.
3630
Compute the capabilities vector for the involved storage engines
3631
and mask out the flags for the binary log. Right now, the binlog
3632
flags only include the capabilities of the storage engines, so this
3635
We now have three alternatives that prevent the statement from
3638
1. If there are no capabilities left (all flags are clear) it is
3639
not possible to log the statement at all, so we roll back the
3640
statement and report an error.
3642
2. Statement mode is set, but the capabilities indicate that
3643
statement format is not possible.
3645
3. Row mode is set, but the capabilities indicate that row
3646
format is not possible.
3648
4. Statement is unsafe, but the capabilities indicate that row
3649
format is not possible.
3651
If we are in MIXED mode, we then decide what logging format to use:
3653
1. If the statement is unsafe, row-based logging is used.
3655
2. If statement-based logging is not possible, row-based logging is
3658
3. Otherwise, statement-based logging is used.
3660
@param thd Client thread
3661
@param tables Tables involved in the query
3664
int decide_logging_format(THD *thd, TableList *tables)
3666
if (mysql_bin_log.is_open() && (thd->options & OPTION_BIN_LOG))
3668
handler::Table_flags flags_some_set= handler::Table_flags();
3669
handler::Table_flags flags_all_set= ~handler::Table_flags();
3670
bool multi_engine= false;
3671
void* prev_ht= NULL;
3672
for (TableList *table= tables; table; table= table->next_global)
3674
if (!table->placeholder() && table->lock_type >= TL_WRITE_ALLOW_WRITE)
3676
uint64_t const flags= table->table->file->ha_table_flags();
3677
if (prev_ht && prev_ht != table->table->file->ht)
3679
prev_ht= table->table->file->ht;
3680
flags_all_set &= flags;
3681
flags_some_set |= flags;
3686
if (flags_all_set == 0)
3688
my_error((error= ER_BINLOG_LOGGING_IMPOSSIBLE), MYF(0),
3689
"Statement cannot be logged to the binary log in"
3690
" row-based nor statement-based format");
3692
else if (thd->variables.binlog_format == BINLOG_FORMAT_STMT &&
3693
(flags_all_set & HA_BINLOG_STMT_CAPABLE) == 0)
3695
my_error((error= ER_BINLOG_LOGGING_IMPOSSIBLE), MYF(0),
3696
"Statement-based format required for this statement,"
3697
" but not allowed by this combination of engines");
3699
else if ((thd->variables.binlog_format == BINLOG_FORMAT_ROW ||
3700
thd->lex->is_stmt_unsafe()) &&
3701
(flags_all_set & HA_BINLOG_ROW_CAPABLE) == 0)
3703
my_error((error= ER_BINLOG_LOGGING_IMPOSSIBLE), MYF(0),
3704
"Row-based format required for this statement,"
3705
" but not allowed by this combination of engines");
3712
We switch to row-based format if we are in mixed mode and one of
3713
the following are true:
3715
1. If the statement is unsafe
3716
2. If statement format cannot be used
3718
Observe that point to cannot be decided before the tables
3719
involved in a statement has been checked, i.e., we cannot put
3720
this code in reset_current_stmt_binlog_row_based(), it has to be
3723
if (thd->lex->is_stmt_unsafe() ||
3724
(flags_all_set & HA_BINLOG_STMT_CAPABLE) == 0)
3726
thd->set_current_stmt_binlog_row_based_if_mixed();
2254
3734
Lock all tables in list
2258
session Thread Cursor
2259
tables Tables to lock
2260
count Number of opened tables
2261
need_reopen Out parameter which if true indicates that some
2262
tables were dropped or altered during this call
2263
and therefore invoker should reopen tables and
2264
try to lock them once again (in this case
2265
lock_tables() will also return error).
3739
tables Tables to lock
3740
count Number of opened tables
3741
need_reopen Out parameter which if true indicates that some
3742
tables were dropped or altered during this call
3743
and therefore invoker should reopen tables and
3744
try to lock them once again (in this case
3745
lock_tables() will also return error).
2268
You can't call lock_tables twice, as this would break the dead-lock-free
2269
handling thr_lock gives us. You most always get all needed locks at
3748
You can't call lock_tables twice, as this would break the dead-lock-free
3749
handling thr_lock gives us. You most always get all needed locks at
2272
If query for which we are calling this function marked as requring
2273
prelocking, this function will do implicit LOCK TABLES and change
2274
session::prelocked_mode accordingly.
3752
If query for which we are calling this function marked as requring
3753
prelocking, this function will do implicit LOCK TABLES and change
3754
thd::prelocked_mode accordingly.
2281
int Session::lock_tables(TableList *tables, uint32_t count, bool *need_reopen)
3761
int lock_tables(THD *thd, TableList *tables, uint32_t count, bool *need_reopen)
2283
3763
TableList *table;
2284
Session *session= this;
2287
3766
We can't meet statement requiring prelocking if we already
2318
3848
Open a single table without table caching and don't set it in open_list
2321
open_temporary_table()
2322
session Thread object
2323
path Path (without .frm)
2325
table_name Table name
2326
link_in_list 1 if table should be linked into session->temporary_tables
2329
Used by alter_table to open a temporary table and when creating
2330
a temporary table with CREATE TEMPORARY ...
3851
open_temporary_table()
3853
path Path (without .frm)
3855
table_name Table name
3856
link_in_list 1 if table should be linked into thd->temporary_tables
3859
Used by alter_table to open a temporary table and when creating
3860
a temporary table with CREATE TEMPORARY ...
2337
Table *Session::open_temporary_table(TableIdentifier &identifier,
3867
Table *open_temporary_table(THD *thd, const char *path, const char *db,
3868
const char *table_name, bool link_in_list,
3869
open_table_mode open_mode)
2342
assert(identifier.isTmp());
2343
share= new TableShare(identifier.getType(),
2345
const_cast<char *>(identifier.getPath().c_str()), static_cast<uint32_t>(identifier.getPath().length()));
2348
Table *new_tmp_table= new Table;
2349
if (not new_tmp_table)
2353
First open the share, and then open the table from the share we just opened.
2355
if (share->open_table_def(*this, identifier) ||
2356
share->open_table_from_share(this, identifier, identifier.getTableName().c_str(),
2357
(uint32_t) (HA_OPEN_KEYFILE | HA_OPEN_RNDFILE |
3873
char cache_key[MAX_DBKEY_LENGTH], *saved_cache_key, *tmp_path;
3874
uint32_t key_length;
3875
TableList table_list;
3877
table_list.db= (char*) db;
3878
table_list.table_name= (char*) table_name;
3879
/* Create the cache_key for temporary tables */
3880
key_length= create_table_def_key(thd, cache_key, &table_list, 1);
3882
if (!(tmp_table= (Table*) my_malloc(sizeof(*tmp_table) + sizeof(*share) +
3883
strlen(path)+1 + key_length,
3885
return(0); /* purecov: inspected */
3887
share= (TABLE_SHARE*) (tmp_table+1);
3888
tmp_path= (char*) (share+1);
3889
saved_cache_key= my_stpcpy(tmp_path, path)+1;
3890
memcpy(saved_cache_key, cache_key, key_length);
3892
init_tmp_table_share(thd, share, saved_cache_key, key_length,
3893
strchr(saved_cache_key, '\0')+1, tmp_path);
3895
if (open_table_def(thd, share, 0) ||
3896
open_table_from_share(thd, share, table_name,
3897
(open_mode == OTM_ALTER) ? 0 :
3898
(uint) (HA_OPEN_KEYFILE | HA_OPEN_RNDFILE |
3900
(open_mode == OTM_ALTER) ?
3901
(EXTRA_RECORD | OPEN_FRM_FILE_ONLY)
2359
3903
ha_open_options,
3904
tmp_table, open_mode))
2362
3906
/* No need to lock share->mutex as this is not needed for tmp tables */
2364
delete new_tmp_table;
2369
new_tmp_table->reginfo.lock_type= TL_WRITE; // Simulate locked
3907
free_table_share(share);
3908
free((char*) tmp_table);
3912
tmp_table->reginfo.lock_type= TL_WRITE; // Simulate locked
3913
if (open_mode == OTM_ALTER)
3916
Temporary table has been created with frm_only
3917
and has not been created in any storage engine
3919
share->tmp_table= TMP_TABLE_FRM_FILE_ONLY;
3922
share->tmp_table= (tmp_table->file->has_transactions() ?
3923
TRANSACTIONAL_TMP_TABLE : NON_TRANSACTIONAL_TMP_TABLE);
2371
3925
if (link_in_list)
2373
3927
/* growing temp list at the head */
2374
new_tmp_table->setNext(this->temporary_tables);
2375
if (new_tmp_table->getNext())
2377
new_tmp_table->getNext()->setPrev(new_tmp_table);
2379
this->temporary_tables= new_tmp_table;
2380
this->temporary_tables->setPrev(0);
2382
new_tmp_table->pos_in_table_list= 0;
2384
return new_tmp_table;
3928
tmp_table->next= thd->temporary_tables;
3929
if (tmp_table->next)
3930
tmp_table->next->prev= tmp_table;
3931
thd->temporary_tables= tmp_table;
3932
thd->temporary_tables->prev= 0;
3933
if (thd->slave_thread)
3934
slave_open_temp_tables++;
3936
tmp_table->pos_in_table_list= 0;
3941
bool rm_temporary_table(handlerton *base, char *path, bool frm_only)
3947
my_stpcpy(ext= strchr(path, '\0'), reg_ext);
3948
if (my_delete(path,MYF(0)))
3949
error=1; /* purecov: inspected */
3950
*ext= 0; // remove extension
3951
file= get_new_handler((TABLE_SHARE*) 0, current_thd->mem_root, base);
3952
if (!frm_only && file && file->ha_delete_table(path))
3955
sql_print_warning(_("Could not remove temporary table: '%s', error: %d"),
2388
3963
/*****************************************************************************
2389
* The following find_field_in_XXX procedures implement the core of the
2390
* name resolution functionality. The entry point to resolve a column name in a
2391
* list of tables is 'find_field_in_tables'. It calls 'find_field_in_table_ref'
2392
* for each table reference. In turn, depending on the type of table reference,
2393
* 'find_field_in_table_ref' calls one of the 'find_field_in_XXX' procedures
2394
* below specific for the type of table reference.
2395
******************************************************************************/
3964
* The following find_field_in_XXX procedures implement the core of the
3965
* name resolution functionality. The entry point to resolve a column name in a
3966
* list of tables is 'find_field_in_tables'. It calls 'find_field_in_table_ref'
3967
* for each table reference. In turn, depending on the type of table reference,
3968
* 'find_field_in_table_ref' calls one of the 'find_field_in_XXX' procedures
3969
* below specific for the type of table reference.
3970
******************************************************************************/
2397
3972
/* Special Field pointers as return values of find_field_in_XXX functions. */
2398
3973
Field *not_found_field= (Field*) 0x1;
2399
Field *view_ref_found= (Field*) 0x2;
2401
static void update_field_dependencies(Session *session, Field *field, Table *table)
3974
Field *view_ref_found= (Field*) 0x2;
3976
#define WRONG_GRANT (Field*) -1
3978
static void update_field_dependencies(THD *thd, Field *field, Table *table)
2403
if (session->mark_used_columns != MARK_COLUMNS_NONE)
3980
if (thd->mark_used_columns != MARK_COLUMNS_NONE)
2405
MyBitmap *current_bitmap, *other_bitmap;
3982
MY_BITMAP *current_bitmap, *other_bitmap;
2408
3985
We always want to register the used keys, as the column bitmap may have
2409
3986
been set for all fields (for example for view).
2412
table->covering_keys&= field->part_of_key;
2413
table->merge_keys|= field->part_of_key;
2415
if (session->mark_used_columns == MARK_COLUMNS_READ)
3989
table->covering_keys.intersect(field->part_of_key);
3990
table->merge_keys.merge(field->part_of_key);
3992
if (thd->mark_used_columns == MARK_COLUMNS_READ)
2417
3994
current_bitmap= table->read_set;
2418
3995
other_bitmap= table->write_set;
2702
4291
natural join, thus if the field is not qualified, we will search
2703
4292
directly the top-most NATURAL/USING join.
2705
fld= find_field_in_natural_join(session, table_list, name, length, ref,
4294
fld= find_field_in_natural_join(thd, table_list, name, length, ref,
2706
4295
register_tree_change, actual_table);
2711
if (session->mark_used_columns != MARK_COLUMNS_NONE)
2714
Get rw_set correct for this field so that the Cursor
2715
knows that this field is involved in the query and gets
2718
Field *field_to_set= NULL;
2719
if (fld == view_ref_found)
2721
Item *it= (*ref)->real_item();
2722
if (it->type() == Item::FIELD_ITEM)
2723
field_to_set= ((Item_field*)it)->field;
2726
if (session->mark_used_columns == MARK_COLUMNS_READ)
2727
it->walk(&Item::register_field_in_read_map, 1, (unsigned char *) 0);
2734
Table *table= field_to_set->getTable();
2735
if (session->mark_used_columns == MARK_COLUMNS_READ)
2736
table->setReadSet(field_to_set->field_index);
2738
table->setWriteSet(field_to_set->field_index);
4300
if (thd->mark_used_columns != MARK_COLUMNS_NONE)
4303
Get rw_set correct for this field so that the handler
4304
knows that this field is involved in the query and gets
4307
Field *field_to_set= NULL;
4308
if (fld == view_ref_found)
4310
Item *it= (*ref)->real_item();
4311
if (it->type() == Item::FIELD_ITEM)
4312
field_to_set= ((Item_field*)it)->field;
4315
if (thd->mark_used_columns == MARK_COLUMNS_READ)
4316
it->walk(&Item::register_field_in_read_map, 1, (unsigned char *) 0);
4323
Table *table= field_to_set->table;
4324
if (thd->mark_used_columns == MARK_COLUMNS_READ)
4325
bitmap_set_bit(table->read_set, field_to_set->field_index);
4327
bitmap_set_bit(table->write_set, field_to_set->field_index);
4336
Find field in table, no side effects, only purpose is to check for field
4337
in table object and get reference to the field if found.
4340
find_field_in_table_sef()
4342
table table where to find
4343
name Name of field searched for
4346
0 field is not found
4350
Field *find_field_in_table_sef(Table *table, const char *name)
4353
if (table->s->name_hash.records)
4355
field_ptr= (Field**)hash_search(&table->s->name_hash,(unsigned char*) name,
4360
field_ptr points to field in TABLE_SHARE. Convert it to the matching
4363
field_ptr= (table->field + (field_ptr - table->s->field));
4368
if (!(field_ptr= table->field))
4370
for (; *field_ptr; ++field_ptr)
4371
if (!my_strcasecmp(system_charset_info, (*field_ptr)->field_name, name))
2747
4382
Find field in table list.
2750
find_field_in_tables()
2751
session pointer to current thread structure
2752
item field item that should be found
2753
first_table list of tables to be searched for item
2754
last_table end of the list of tables to search for item. If NULL
2755
then search to the end of the list 'first_table'.
2756
ref if 'item' is resolved to a view field, ref is set to
2757
point to the found view field
2758
report_error Degree of error reporting:
2759
- IGNORE_ERRORS then do not report any error
2760
- IGNORE_EXCEPT_NON_UNIQUE report only non-unique
2761
fields, suppress all other errors
2762
- REPORT_EXCEPT_NON_UNIQUE report all other errors
2763
except when non-unique fields were found
2765
register_tree_change true if ref is not a stack variable and we
2766
to need register changes in item tree
4385
find_field_in_tables()
4386
thd pointer to current thread structure
4387
item field item that should be found
4388
first_table list of tables to be searched for item
4389
last_table end of the list of tables to search for item. If NULL
4390
then search to the end of the list 'first_table'.
4391
ref if 'item' is resolved to a view field, ref is set to
4392
point to the found view field
4393
report_error Degree of error reporting:
4394
- IGNORE_ERRORS then do not report any error
4395
- IGNORE_EXCEPT_NON_UNIQUE report only non-unique
4396
fields, suppress all other errors
4397
- REPORT_EXCEPT_NON_UNIQUE report all other errors
4398
except when non-unique fields were found
4400
check_privileges need to check privileges
4401
register_tree_change true if ref is not a stack variable and we
4402
to need register changes in item tree
2769
0 If error: the found field is not unique, or there are
2770
no sufficient access priviliges for the found field,
2771
or the field is qualified with non-existing table.
2772
not_found_field The function was called with report_error ==
2773
(IGNORE_ERRORS || IGNORE_EXCEPT_NON_UNIQUE) and a
2774
field was not found.
2775
view_ref_found View field is found, item passed through ref parameter
2776
found field If a item was resolved to some field
4405
0 If error: the found field is not unique, or there are
4406
no sufficient access priviliges for the found field,
4407
or the field is qualified with non-existing table.
4408
not_found_field The function was called with report_error ==
4409
(IGNORE_ERRORS || IGNORE_EXCEPT_NON_UNIQUE) and a
4410
field was not found.
4411
view_ref_found View field is found, item passed through ref parameter
4412
found field If a item was resolved to some field
2780
find_field_in_tables(Session *session, Item_ident *item,
4416
find_field_in_tables(THD *thd, Item_ident *item,
2781
4417
TableList *first_table, TableList *last_table,
2782
Item **ref, find_item_error_report_type report_error,
2783
bool register_tree_change)
4418
Item **ref, find_item_error_report_type report_error,
4419
bool check_privileges, bool register_tree_change)
2785
4421
Field *found=0;
2786
4422
const char *db= item->db_name;
2787
4423
const char *table_name= item->table_name;
2788
4424
const char *name= item->field_name;
2789
uint32_t length=(uint32_t) strlen(name);
4425
uint32_t length=(uint) strlen(name);
2790
4426
char name_buff[NAME_LEN+1];
2791
4427
TableList *cur_table= first_table;
2792
4428
TableList *actual_table;
4419
6162
On INSERT or UPDATE fields are checked to be from the same table,
4420
6163
thus we safely can take table from the first field.
4422
table= (*ptr)->getTable();
6165
table= (*ptr)->table;
4423
6166
table->auto_increment_field_not_null= false;
4425
while ((field = *ptr++) && ! session->is_error())
6168
while ((field = *ptr++) && ! thd->is_error())
4428
table= field->getTable();
6171
table= field->table;
4429
6172
if (field == table->next_number_field)
4430
6173
table->auto_increment_field_not_null= true;
4431
6174
if (value->save_in_field(field, 0) < 0)
4435
return(session->is_error());
6177
return(thd->is_error());
4439
6181
table->auto_increment_field_not_null= false;
4445
bool drizzle_rm_tmp_tables()
6186
bool mysql_rm_tmp_tables(void)
4449
assert(drizzle_tmpdir.size());
4451
if (!(session= new Session(plugin::Listen::getNullClient())))
4453
session->thread_stack= (char*) &session;
4454
session->storeGlobals();
4456
plugin::StorageEngine::removeLostTemporaryTables(*session, drizzle_tmpdir.c_str());
4458
session->lockForDelete();
6189
char filePath[FN_REFLEN], *tmpdir, filePathCopy[FN_REFLEN];
6195
if (!(thd= new THD))
6197
thd->thread_stack= (char*) &thd;
6198
thd->store_globals();
6200
for (i=0; i<=mysql_tmpdir_list.max; i++)
6202
tmpdir=mysql_tmpdir_list.list[i];
6203
/* See if the directory exists */
6204
if (!(dirp = my_dir(tmpdir,MYF(MY_WME | MY_DONT_SORT))))
6207
/* Remove all SQLxxx tables from directory */
6209
for (idx=0 ; idx < (uint) dirp->number_off_files ; idx++)
6211
file=dirp->dir_entry+idx;
6213
/* skiping . and .. */
6214
if (file->name[0] == '.' && (!file->name[1] ||
6215
(file->name[1] == '.' && !file->name[2])))
6218
if (!memcmp(file->name, tmp_file_prefix, tmp_file_prefix_length))
6220
char *ext= fn_ext(file->name);
6221
uint32_t ext_len= strlen(ext);
6222
uint32_t filePath_len= snprintf(filePath, sizeof(filePath),
6223
"%s%c%s", tmpdir, FN_LIBCHAR,
6225
if (!memcmp(reg_ext, ext, ext_len))
6227
handler *handler_file= 0;
6228
/* We should cut file extention before deleting of table */
6229
memcpy(filePathCopy, filePath, filePath_len - ext_len);
6230
filePathCopy[filePath_len - ext_len]= 0;
6231
init_tmp_table_share(thd, &share, "", 0, "", filePathCopy);
6232
if (!open_table_def(thd, &share, 0) &&
6233
((handler_file= get_new_handler(&share, thd->mem_root,
6236
handler_file->ha_delete_table(filePathCopy);
6237
delete handler_file;
6239
free_table_share(&share);
6242
File can be already deleted by tmp_table.file->delete_table().
6243
So we hide error messages which happnes during deleting of these
6246
my_delete(filePath, MYF(0));
6252
my_pthread_setspecific_ptr(THR_THD, 0);
4466
6258
/*****************************************************************************
4467
unireg support functions
4468
*****************************************************************************/
6259
unireg support functions
6260
*****************************************************************************/
4471
6263
Invalidate any cache entries that are for some DB
4474
remove_db_from_cache()
4475
db Database name. This will be in lower case if
4476
lower_case_table_name is set
6266
remove_db_from_cache()
6267
db Database name. This will be in lower case if
6268
lower_case_table_name is set
4479
We can't use hash_delete when looping hash_elements. We mark them first
4480
and afterwards delete those marked unused.
6271
We can't use hash_delete when looping hash_elements. We mark them first
6272
and afterwards delete those marked unused.
4483
void remove_db_from_cache(const SchemaIdentifier &schema_identifier)
6275
void remove_db_from_cache(const char *db)
4485
safe_mutex_assert_owner(LOCK_open.native_handle());
4487
for (TableOpenCache::const_iterator iter= get_open_cache().begin();
4488
iter != get_open_cache().end();
6277
for (uint32_t idx=0 ; idx < open_cache.records ; idx++)
4491
Table *table= (*iter).second;
4493
if (not schema_identifier.getPath().compare(table->getMutableShare()->getSchemaName()))
6279
Table *table=(Table*) hash_element(&open_cache,idx);
6280
if (!strcmp(table->s->db.str, db))
4495
table->getMutableShare()->resetVersion(); /* Free when thread is ready */
4496
if (not table->in_use)
4497
unused_tables.relink(table);
6282
table->s->version= 0L; /* Free when thread is ready */
6284
relink_unused(table);
4501
unused_tables.cullByVersion();
6287
while (unused_tables && !unused_tables->s->version)
6288
hash_delete(&open_cache,(unsigned char*) unused_tables);
6293
free all unused tables
6296
This is called by 'handle_manager' when one wants to periodicly flush
6297
all not used tables.
6302
(void) pthread_mutex_lock(&LOCK_open);
6303
while (unused_tables)
6304
hash_delete(&open_cache,(unsigned char*) unused_tables);
6305
(void) pthread_mutex_unlock(&LOCK_open);