/
sql_base.cc
8676 lines (7557 loc) · 285 KB
/
sql_base.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* Copyright (c) 2000, 2016, Oracle and/or its affiliates.
Copyright (c) 2010, 2016, MariaDB
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; version 2 of the License.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA */
/* Basic functions needed by many modules */
#include <my_global.h>
#include "sql_base.h" // setup_table_map
#include "sql_priv.h"
#include "unireg.h"
#include "debug_sync.h"
#include "lock.h" // mysql_lock_remove,
// mysql_unlock_tables,
// mysql_lock_have_duplicate
#include "sql_show.h" // append_identifier
#include "strfunc.h" // find_type
#include "sql_view.h" // mysql_make_view, VIEW_ANY_ACL
#include "sql_parse.h" // check_table_access
#include "sql_insert.h" // kill_delayed_threads
#include "sql_acl.h" // *_ACL, check_grant_all_columns,
// check_column_grant_in_table_ref,
// get_column_grant
#include "sql_partition.h" // ALTER_PARTITION_PARAM_TYPE
#include "sql_derived.h" // mysql_derived_prepare,
// mysql_handle_derived,
// mysql_derived_filling
#include "sql_handler.h" // mysql_ha_flush
#include "sql_test.h"
#include "sql_partition.h" // ALTER_PARTITION_PARAM_TYPE
#include "log_event.h" // Query_log_event
#include "sql_select.h"
#include "sp_head.h"
#include "sp.h"
#include "sp_cache.h"
#include "sql_trigger.h"
#include "transaction.h"
#include "sql_prepare.h"
#include "sql_statistics.h"
#include "sql_cte.h"
#include <m_ctype.h>
#include <my_dir.h>
#include <hash.h>
#include "rpl_filter.h"
#include "sql_table.h" // build_table_filename
#include "datadict.h" // dd_frm_is_view()
#include "sql_hset.h" // Hash_set
#include "rpl_rli.h" // rpl_group_info
#ifdef __WIN__
#include <io.h>
#endif
#include "wsrep_mysqld.h"
#include "wsrep_thd.h"
bool
No_such_table_error_handler::handle_condition(THD *,
uint sql_errno,
const char*,
Sql_condition::enum_warning_level *level,
const char*,
Sql_condition ** cond_hdl)
{
*cond_hdl= NULL;
if (sql_errno == ER_NO_SUCH_TABLE || sql_errno == ER_NO_SUCH_TABLE_IN_ENGINE)
{
m_handled_errors++;
return TRUE;
}
if (*level == Sql_condition::WARN_LEVEL_ERROR)
m_unhandled_errors++;
return FALSE;
}
bool No_such_table_error_handler::safely_trapped_errors()
{
/*
If m_unhandled_errors != 0, something else, unanticipated, happened,
so the error is not trapped but returned to the caller.
Multiple ER_NO_SUCH_TABLE can be raised in case of views.
*/
return ((m_handled_errors > 0) && (m_unhandled_errors == 0));
}
/**
This internal handler is used to trap ER_NO_SUCH_TABLE and
ER_WRONG_MRG_TABLE errors during CHECK/REPAIR TABLE for MERGE
tables.
*/
class Repair_mrg_table_error_handler : public Internal_error_handler
{
public:
Repair_mrg_table_error_handler()
: m_handled_errors(false), m_unhandled_errors(false)
{}
bool handle_condition(THD *thd,
uint sql_errno,
const char* sqlstate,
Sql_condition::enum_warning_level *level,
const char* msg,
Sql_condition ** cond_hdl);
/**
Returns TRUE if there were ER_NO_SUCH_/WRONG_MRG_TABLE and there
were no unhandled errors. FALSE otherwise.
*/
bool safely_trapped_errors()
{
/*
Check for m_handled_errors is here for extra safety.
It can be useful in situation when call to open_table()
fails because some error which was suppressed by another
error handler (e.g. in case of MDL deadlock which we
decided to solve by back-off and retry).
*/
return (m_handled_errors && (! m_unhandled_errors));
}
private:
bool m_handled_errors;
bool m_unhandled_errors;
};
bool
Repair_mrg_table_error_handler::handle_condition(THD *,
uint sql_errno,
const char*,
Sql_condition::enum_warning_level *level,
const char*,
Sql_condition ** cond_hdl)
{
*cond_hdl= NULL;
if (sql_errno == ER_NO_SUCH_TABLE ||
sql_errno == ER_NO_SUCH_TABLE_IN_ENGINE ||
sql_errno == ER_WRONG_MRG_TABLE)
{
m_handled_errors= true;
return TRUE;
}
m_unhandled_errors= true;
return FALSE;
}
/**
@defgroup Data_Dictionary Data Dictionary
@{
*/
static bool check_and_update_table_version(THD *thd, TABLE_LIST *tables,
TABLE_SHARE *table_share);
static bool open_table_entry_fini(THD *thd, TABLE_SHARE *share, TABLE *entry);
static bool auto_repair_table(THD *thd, TABLE_LIST *table_list);
/**
Get table cache key for a table list element.
@param table_list[in] Table list element.
@param key[out] On return points to table cache key for the table.
@note Unlike create_table_def_key() call this function doesn't construct
key in a buffer provided by caller. Instead it relies on the fact
that table list element for which key is requested has properly
initialized MDL_request object and the fact that table definition
cache key is suffix of key used in MDL subsystem. So to get table
definition key it simply needs to return pointer to appropriate
part of MDL_key object nested in this table list element.
Indeed, this means that lifetime of key produced by this call is
limited by the lifetime of table list element which it got as
parameter.
@return Length of key.
*/
uint get_table_def_key(const TABLE_LIST *table_list, const char **key)
{
/*
This call relies on the fact that TABLE_LIST::mdl_request::key object
is properly initialized, so table definition cache can be produced
from key used by MDL subsystem.
*/
DBUG_ASSERT(!strcmp(table_list->get_db_name(),
table_list->mdl_request.key.db_name()) &&
!strcmp(table_list->get_table_name(),
table_list->mdl_request.key.name()));
*key= (const char*)table_list->mdl_request.key.ptr() + 1;
return table_list->mdl_request.key.length() - 1;
}
/*****************************************************************************
Functions to handle table definition cache (TABLE_SHARE)
*****************************************************************************/
/*
Create a list for all open tables matching SQL expression
SYNOPSIS
list_open_tables()
thd Thread THD
wild SQL like expression
NOTES
One gets only a list of tables for which one has any kind of privilege.
db and table names are allocated in result struct, so one doesn't need
a lock when traversing the return list.
RETURN VALUES
NULL Error (Probably OOM)
# Pointer to list of names of open tables.
*/
struct list_open_tables_arg
{
THD *thd;
const char *db;
const char *wild;
TABLE_LIST table_list;
OPEN_TABLE_LIST **start_list, *open_list;
};
static my_bool list_open_tables_callback(TDC_element *element,
list_open_tables_arg *arg)
{
char *db= (char*) element->m_key;
char *table_name= (char*) element->m_key + strlen((char*) element->m_key) + 1;
if (arg->db && my_strcasecmp(system_charset_info, arg->db, db))
return FALSE;
if (arg->wild && wild_compare(table_name, arg->wild, 0))
return FALSE;
/* Check if user has SELECT privilege for any column in the table */
arg->table_list.db= db;
arg->table_list.table_name= table_name;
arg->table_list.grant.privilege= 0;
if (check_table_access(arg->thd, SELECT_ACL, &arg->table_list, TRUE, 1, TRUE))
return FALSE;
if (!(*arg->start_list= (OPEN_TABLE_LIST *) arg->thd->alloc(
sizeof(**arg->start_list) + element->m_key_length)))
return TRUE;
strmov((*arg->start_list)->table=
strmov(((*arg->start_list)->db= (char*) ((*arg->start_list) + 1)),
db) + 1, table_name);
(*arg->start_list)->in_use= 0;
mysql_mutex_lock(&element->LOCK_table_share);
All_share_tables_list::Iterator it(element->all_tables);
TABLE *table;
while ((table= it++))
if (table->in_use)
++(*arg->start_list)->in_use;
mysql_mutex_unlock(&element->LOCK_table_share);
(*arg->start_list)->locked= 0; /* Obsolete. */
arg->start_list= &(*arg->start_list)->next;
*arg->start_list= 0;
return FALSE;
}
OPEN_TABLE_LIST *list_open_tables(THD *thd, const char *db, const char *wild)
{
list_open_tables_arg argument;
DBUG_ENTER("list_open_tables");
argument.thd= thd;
argument.db= db;
argument.wild= wild;
bzero((char*) &argument.table_list, sizeof(argument.table_list));
argument.start_list= &argument.open_list;
argument.open_list= 0;
if (tdc_iterate(thd, (my_hash_walk_action) list_open_tables_callback,
&argument, true))
DBUG_RETURN(0);
DBUG_RETURN(argument.open_list);
}
/*
Close all tables which aren't in use by any thread
@param thd Thread context
@param tables List of tables to remove from the cache
@param wait_for_refresh Wait for a impending flush
@param timeout Timeout for waiting for flush to be completed.
@note THD can be NULL, but then wait_for_refresh must be FALSE
and tables must be NULL.
@note When called as part of FLUSH TABLES WITH READ LOCK this function
ignores metadata locks held by other threads. In order to avoid
situation when FLUSH TABLES WITH READ LOCK sneaks in at the moment
when some write-locked table is being reopened (by FLUSH TABLES or
ALTER TABLE) we have to rely on additional global shared metadata
lock taken by thread trying to obtain global read lock.
*/
struct close_cached_tables_arg
{
ulong refresh_version;
TDC_element *element;
};
static my_bool close_cached_tables_callback(TDC_element *element,
close_cached_tables_arg *arg)
{
mysql_mutex_lock(&element->LOCK_table_share);
if (element->share && element->flushed &&
element->version < arg->refresh_version)
{
/* wait_for_old_version() will unlock mutex and free share */
arg->element= element;
return TRUE;
}
mysql_mutex_unlock(&element->LOCK_table_share);
return FALSE;
}
bool close_cached_tables(THD *thd, TABLE_LIST *tables,
bool wait_for_refresh, ulong timeout)
{
bool result= FALSE;
struct timespec abstime;
ulong refresh_version;
DBUG_ENTER("close_cached_tables");
DBUG_ASSERT(thd || (!wait_for_refresh && !tables));
refresh_version= tdc_increment_refresh_version();
if (!tables)
{
/*
Force close of all open tables.
Note that code in TABLE_SHARE::wait_for_old_version() assumes that
incrementing of refresh_version is followed by purge of unused table
shares.
*/
kill_delayed_threads();
/*
Get rid of all unused TABLE and TABLE_SHARE instances. By doing
this we automatically close all tables which were marked as "old".
*/
tc_purge(true);
/* Free table shares which were not freed implicitly by loop above. */
tdc_purge(true);
}
else
{
bool found=0;
for (TABLE_LIST *table= tables; table; table= table->next_local)
{
/* tdc_remove_table() also sets TABLE_SHARE::version to 0. */
found|= tdc_remove_table(thd, TDC_RT_REMOVE_UNUSED, table->db,
table->table_name, TRUE);
}
if (!found)
wait_for_refresh=0; // Nothing to wait for
}
DBUG_PRINT("info", ("open table definitions: %d",
(int) tdc_records()));
if (!wait_for_refresh)
DBUG_RETURN(result);
if (thd->locked_tables_mode)
{
/*
If we are under LOCK TABLES, we need to reopen the tables without
opening a door for any concurrent threads to sneak in and get
lock on our tables. To achieve this we use exclusive metadata
locks.
*/
TABLE_LIST *tables_to_reopen= (tables ? tables :
thd->locked_tables_list.locked_tables());
/* Close open HANDLER instances to avoid self-deadlock. */
mysql_ha_flush_tables(thd, tables_to_reopen);
for (TABLE_LIST *table_list= tables_to_reopen; table_list;
table_list= table_list->next_global)
{
/* A check that the table was locked for write is done by the caller. */
TABLE *table= find_table_for_mdl_upgrade(thd, table_list->db,
table_list->table_name, TRUE);
/* May return NULL if this table has already been closed via an alias. */
if (! table)
continue;
if (wait_while_table_is_used(thd, table,
HA_EXTRA_PREPARE_FOR_FORCED_CLOSE))
{
result= TRUE;
goto err_with_reopen;
}
close_all_tables_for_name(thd, table->s, HA_EXTRA_NOT_USED, NULL);
}
}
/* Wait until all threads have closed all the tables we are flushing. */
DBUG_PRINT("info", ("Waiting for other threads to close their open tables"));
/*
To a self-deadlock or deadlocks with other FLUSH threads
waiting on our open HANDLERs, we have to flush them.
*/
mysql_ha_flush(thd);
DEBUG_SYNC(thd, "after_flush_unlock");
if (!tables)
{
int r= 0;
close_cached_tables_arg argument;
argument.refresh_version= refresh_version;
set_timespec(abstime, timeout);
while (!thd->killed &&
(r= tdc_iterate(thd,
(my_hash_walk_action) close_cached_tables_callback,
&argument)) == 1 &&
!argument.element->share->wait_for_old_version(thd, &abstime,
MDL_wait_for_subgraph::DEADLOCK_WEIGHT_DDL))
/* no-op */;
if (r)
result= TRUE;
}
else
{
for (TABLE_LIST *table= tables; table; table= table->next_local)
{
if (thd->killed)
break;
if (tdc_wait_for_old_version(thd, table->db, table->table_name, timeout,
MDL_wait_for_subgraph::DEADLOCK_WEIGHT_DDL,
refresh_version))
{
result= TRUE;
break;
}
}
}
err_with_reopen:
if (thd->locked_tables_mode)
{
/*
No other thread has the locked tables open; reopen them and get the
old locks. This should always succeed (unless some external process
has removed the tables)
*/
thd->locked_tables_list.reopen_tables(thd);
/*
Since downgrade_lock() won't do anything with shared
metadata lock it is much simpler to go through all open tables rather
than picking only those tables that were flushed.
*/
for (TABLE *tab= thd->open_tables; tab; tab= tab->next)
tab->mdl_ticket->downgrade_lock(MDL_SHARED_NO_READ_WRITE);
}
DBUG_RETURN(result);
}
/**
Close all tables which match specified connection string or
if specified string is NULL, then any table with a connection string.
*/
struct close_cached_connection_tables_arg
{
THD *thd;
LEX_STRING *connection;
TABLE_LIST *tables;
};
static my_bool close_cached_connection_tables_callback(
TDC_element *element, close_cached_connection_tables_arg *arg)
{
TABLE_LIST *tmp;
mysql_mutex_lock(&element->LOCK_table_share);
/* Ignore if table is not open or does not have a connect_string */
if (!element->share || !element->share->connect_string.length ||
!element->ref_count)
goto end;
/* Compare the connection string */
if (arg->connection &&
(arg->connection->length > element->share->connect_string.length ||
(arg->connection->length < element->share->connect_string.length &&
(element->share->connect_string.str[arg->connection->length] != '/' &&
element->share->connect_string.str[arg->connection->length] != '\\')) ||
strncasecmp(arg->connection->str, element->share->connect_string.str,
arg->connection->length)))
goto end;
/* close_cached_tables() only uses these elements */
if (!(tmp= (TABLE_LIST*) alloc_root(arg->thd->mem_root, sizeof(TABLE_LIST))) ||
!(tmp->db= strdup_root(arg->thd->mem_root, element->share->db.str)) ||
!(tmp->table_name= strdup_root(arg->thd->mem_root,
element->share->table_name.str)))
{
mysql_mutex_unlock(&element->LOCK_table_share);
return TRUE;
}
tmp->next_local= arg->tables;
arg->tables= tmp;
end:
mysql_mutex_unlock(&element->LOCK_table_share);
return FALSE;
}
bool close_cached_connection_tables(THD *thd, LEX_STRING *connection)
{
close_cached_connection_tables_arg argument;
DBUG_ENTER("close_cached_connections");
DBUG_ASSERT(thd);
argument.thd= thd;
argument.connection= connection;
argument.tables= NULL;
if (tdc_iterate(thd,
(my_hash_walk_action) close_cached_connection_tables_callback,
&argument))
DBUG_RETURN(true);
DBUG_RETURN(argument.tables ?
close_cached_tables(thd, argument.tables, FALSE, LONG_TIMEOUT) :
false);
}
/*
Mark all tables in the list which were used by current substatement
as free for reuse.
SYNOPSIS
mark_used_tables_as_free_for_reuse()
thd - thread context
table - head of the list of tables
DESCRIPTION
Marks all tables in the list which were used by current substatement
(they are marked by its query_id) as free for reuse.
NOTE
The reason we reset query_id is that it's not enough to just test
if table->query_id != thd->query_id to know if a table is in use.
For example
SELECT f1_that_uses_t1() FROM t1;
In f1_that_uses_t1() we will see one instance of t1 where query_id is
set to query_id of original query.
*/
static void mark_used_tables_as_free_for_reuse(THD *thd, TABLE *table)
{
for (; table ; table= table->next)
{
DBUG_ASSERT(table->pos_in_locked_tables == NULL ||
table->pos_in_locked_tables->table == table);
if (table->query_id == thd->query_id)
{
table->query_id= 0;
table->file->ha_reset();
}
}
}
/**
Close all open instances of the table but keep the MDL lock.
Works both under LOCK TABLES and in the normal mode.
Removes all closed instances of the table from the table cache.
@param thd thread handle
@param[in] share table share, but is just a handy way to
access the table cache key
@param[in] extra
HA_EXTRA_PREPARE_FOR_DROP
- The table is dropped
HA_EXTRA_PREPARE_FOR_RENAME
- The table is renamed
HA_EXTRA_NOT_USED
- The table is marked as closed in the
locked_table_list but kept there so one can call
locked_table_list->reopen_tables() to put it back.
In case of drop/rename the documented behavior is to
implicitly remove the table from LOCK TABLES
list.
@pre Must be called with an X MDL lock on the table.
*/
void
close_all_tables_for_name(THD *thd, TABLE_SHARE *share,
ha_extra_function extra,
TABLE *skip_table)
{
DBUG_ASSERT(!share->tmp_table);
char key[MAX_DBKEY_LENGTH];
uint key_length= share->table_cache_key.length;
const char *db= key;
const char *table_name= db + share->db.length + 1;
memcpy(key, share->table_cache_key.str, key_length);
for (TABLE **prev= &thd->open_tables; *prev; )
{
TABLE *table= *prev;
if (table->s->table_cache_key.length == key_length &&
!memcmp(table->s->table_cache_key.str, key, key_length) &&
table != skip_table)
{
thd->locked_tables_list.unlink_from_list(thd,
table->pos_in_locked_tables,
extra != HA_EXTRA_NOT_USED);
/* Inform handler that there is a drop table or a rename going on */
if (extra != HA_EXTRA_NOT_USED && table->db_stat)
{
table->file->extra(extra);
extra= HA_EXTRA_NOT_USED; // Call extra once!
}
/*
Does nothing if the table is not locked.
This allows one to use this function after a table
has been unlocked, e.g. in partition management.
*/
mysql_lock_remove(thd, thd->lock, table);
close_thread_table(thd, prev);
}
else
{
/* Step to next entry in open_tables list. */
prev= &table->next;
}
}
if (skip_table == NULL)
{
/* Remove the table share from the cache. */
tdc_remove_table(thd, TDC_RT_REMOVE_ALL, db, table_name,
FALSE);
}
}
/*
Close all tables used by the current substatement, or all tables
used by this thread if we are on the upper level.
SYNOPSIS
close_thread_tables()
thd Thread handler
IMPLEMENTATION
Unlocks tables and frees derived tables.
Put all normal tables used by thread in free list.
It will only close/mark as free for reuse tables opened by this
substatement, it will also check if we are closing tables after
execution of complete query (i.e. we are on upper level) and will
leave prelocked mode if needed.
*/
void close_thread_tables(THD *thd)
{
TABLE *table;
DBUG_ENTER("close_thread_tables");
THD_STAGE_INFO(thd, stage_closing_tables);
#ifdef EXTRA_DEBUG
DBUG_PRINT("tcache", ("open tables:"));
for (table= thd->open_tables; table; table= table->next)
DBUG_PRINT("tcache", ("table: '%s'.'%s' 0x%lx", table->s->db.str,
table->s->table_name.str, (long) table));
#endif
#if defined(ENABLED_DEBUG_SYNC)
/* debug_sync may not be initialized for some slave threads */
if (thd->debug_sync_control)
DEBUG_SYNC(thd, "before_close_thread_tables");
#endif
DBUG_ASSERT(thd->transaction.stmt.is_empty() || thd->in_sub_stmt ||
(thd->state_flags & Open_tables_state::BACKUPS_AVAIL));
/* Detach MERGE children after every statement. Even under LOCK TABLES. */
for (table= thd->open_tables; table; table= table->next)
{
/* Table might be in use by some outer statement. */
DBUG_PRINT("tcache", ("table: '%s' query_id: %lu",
table->s->table_name.str, (ulong) table->query_id));
if (thd->locked_tables_mode <= LTM_LOCK_TABLES ||
table->query_id == thd->query_id)
{
DBUG_ASSERT(table->file);
table->file->extra(HA_EXTRA_DETACH_CHILDREN);
}
}
/*
We are assuming here that thd->derived_tables contains ONLY derived
tables for this substatement. i.e. instead of approach which uses
query_id matching for determining which of the derived tables belong
to this substatement we rely on the ability of substatements to
save/restore thd->derived_tables during their execution.
TODO: Probably even better approach is to simply associate list of
derived tables with (sub-)statement instead of thread and destroy
them at the end of its execution.
*/
if (thd->derived_tables)
{
TABLE *next;
/*
Close all derived tables generated in queries like
SELECT * FROM (SELECT * FROM t1)
*/
for (table= thd->derived_tables ; table ; table= next)
{
next= table->next;
free_tmp_table(thd, table);
}
thd->derived_tables= 0;
}
if (thd->rec_tables)
{
TABLE *next;
/*
Close all temporary tables created for recursive table references.
This action was postponed because the table could be used in the
statements like ANALYZE WITH r AS (...) SELECT * from r
where r is defined through recursion.
*/
for (table= thd->rec_tables ; table ; table= next)
{
next= table->next;
free_tmp_table(thd, table);
}
thd->rec_tables= 0;
}
/*
Mark all temporary tables used by this statement as free for reuse.
*/
thd->mark_tmp_tables_as_free_for_reuse();
if (thd->locked_tables_mode)
{
/* Ensure we are calling ha_reset() for all used tables */
mark_used_tables_as_free_for_reuse(thd, thd->open_tables);
/*
We are under simple LOCK TABLES or we're inside a sub-statement
of a prelocked statement, so should not do anything else.
Note that even if we are in LTM_LOCK_TABLES mode and statement
requires prelocking (e.g. when we are closing tables after
failing ot "open" all tables required for statement execution)
we will exit this function a few lines below.
*/
if (! thd->lex->requires_prelocking())
DBUG_VOID_RETURN;
/*
We are in the top-level statement of a prelocked statement,
so we have to leave the prelocked mode now with doing implicit
UNLOCK TABLES if needed.
*/
if (thd->locked_tables_mode == LTM_PRELOCKED_UNDER_LOCK_TABLES)
thd->locked_tables_mode= LTM_LOCK_TABLES;
if (thd->locked_tables_mode == LTM_LOCK_TABLES)
DBUG_VOID_RETURN;
thd->leave_locked_tables_mode();
/* Fallthrough */
}
if (thd->lock)
{
/*
For RBR we flush the pending event just before we unlock all the
tables. This means that we are at the end of a topmost
statement, so we ensure that the STMT_END_F flag is set on the
pending event. For statements that are *inside* stored
functions, the pending event will not be flushed: that will be
handled either before writing a query log event (inside
binlog_query()) or when preparing a pending event.
*/
(void)thd->binlog_flush_pending_rows_event(TRUE);
mysql_unlock_tables(thd, thd->lock);
thd->lock=0;
}
/*
Closing a MERGE child before the parent would be fatal if the
other thread tries to abort the MERGE lock in between.
*/
while (thd->open_tables)
(void) close_thread_table(thd, &thd->open_tables);
DBUG_VOID_RETURN;
}
/* move one table to free list */
void close_thread_table(THD *thd, TABLE **table_ptr)
{
TABLE *table= *table_ptr;
DBUG_ENTER("close_thread_table");
DBUG_PRINT("tcache", ("table: '%s'.'%s' 0x%lx", table->s->db.str,
table->s->table_name.str, (long) table));
DBUG_ASSERT(!table->file->keyread_enabled());
DBUG_ASSERT(!table->file || table->file->inited == handler::NONE);
/*
The metadata lock must be released after giving back
the table to the table cache.
*/
DBUG_ASSERT(thd->mdl_context.is_lock_owner(MDL_key::TABLE,
table->s->db.str,
table->s->table_name.str,
MDL_SHARED));
table->mdl_ticket= NULL;
if (table->file)
{
table->file->update_global_table_stats();
table->file->update_global_index_stats();
}
mysql_mutex_lock(&thd->LOCK_thd_data);
*table_ptr=table->next;
mysql_mutex_unlock(&thd->LOCK_thd_data);
if (! table->needs_reopen())
{
/* Avoid having MERGE tables with attached children in table cache. */
table->file->extra(HA_EXTRA_DETACH_CHILDREN);
/* Free memory and reset for next loop. */
free_field_buffers_larger_than(table, MAX_TDC_BLOB_SIZE);
table->file->ha_reset();
}
/*
Do this *before* entering the TABLE_SHARE::tdc.LOCK_table_share
critical section.
*/
MYSQL_UNBIND_TABLE(table->file);
tc_release_table(table);
DBUG_VOID_RETURN;
}
/*
Find table in list.
SYNOPSIS
find_table_in_list()
table Pointer to table list
offset Offset to which list in table structure to use
db_name Data base name
table_name Table name
NOTES:
This is called by find_table_in_local_list() and
find_table_in_global_list().
RETURN VALUES
NULL Table not found
# Pointer to found table.
*/
TABLE_LIST *find_table_in_list(TABLE_LIST *table,
TABLE_LIST *TABLE_LIST::*link,
const char *db_name,
const char *table_name)
{
for (; table; table= table->*link )
{
if (strcmp(table->db, db_name) == 0 &&
strcmp(table->table_name, table_name) == 0)
break;
}
return table;
}
/**
Test that table is unique (It's only exists once in the table list)
@param thd thread handle
@param table table which should be checked
@param table_list list of tables
@param check_alias whether to check tables' aliases
NOTE: to exclude derived tables from check we use following mechanism:
a) during derived table processing set THD::derived_tables_processing
b) JOIN::prepare set SELECT::exclude_from_table_unique_test if
THD::derived_tables_processing set. (we can't use JOIN::execute
because for PS we perform only JOIN::prepare, but we can't set this
flag in JOIN::prepare if we are not sure that we are in derived table
processing loop, because multi-update call fix_fields() for some its
items (which mean JOIN::prepare for subqueries) before unique_table
call to detect which tables should be locked for write).
c) find_dup_table skip all tables which belong to SELECT with
SELECT::exclude_from_table_unique_test set.
Also SELECT::exclude_from_table_unique_test used to exclude from check
tables of main SELECT of multi-delete and multi-update
We also skip tables with TABLE_LIST::prelocking_placeholder set,
because we want to allow SELECTs from them, and their modification
will rise the error anyway.
TODO: when we will have table/view change detection we can do this check
only once for PS/SP
@retval !=0 found duplicate
@retval 0 if table is unique
*/
static
TABLE_LIST* find_dup_table(THD *thd, TABLE_LIST *table, TABLE_LIST *table_list,
bool check_alias)
{
TABLE_LIST *res;
const char *d_name, *t_name, *t_alias;
DBUG_ENTER("find_dup_table");
DBUG_PRINT("enter", ("table alias: %s", table->alias));
/*
If this function called for query which update table (INSERT/UPDATE/...)
then we have in table->table pointer to TABLE object which we are
updating even if it is VIEW so we need TABLE_LIST of this TABLE object
to get right names (even if lower_case_table_names used).
If this function called for CREATE command that we have not opened table
(table->table equal to 0) and right names is in current TABLE_LIST
object.
*/
if (table->table)
{
/* All MyISAMMRG children are plain MyISAM tables. */
DBUG_ASSERT(table->table->file->ht->db_type != DB_TYPE_MRG_MYISAM);
table= table->find_underlying_table(table->table);
/*
as far as we have table->table we have to find real TABLE_LIST of
it in underlying tables
*/