-
Notifications
You must be signed in to change notification settings - Fork 4k
/
Copy pathsql_table.cc
20248 lines (17652 loc) · 770 KB
/
sql_table.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, 2025, Oracle and/or its affiliates.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License, version 2.0,
as published by the Free Software Foundation.
This program is designed to work with certain software (including
but not limited to OpenSSL) that is licensed under separate terms,
as designated in a particular file or component or in included license
documentation. The authors of MySQL hereby grant you an additional
permission to link the program and your derivative works with the
separately licensed software that they have either included with
the program or referenced in the documentation.
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, version 2.0, 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 St, Fifth Floor, Boston, MA 02110-1301 USA
*/
/* drop and alter of tables */
#include "sql/sql_table.h"
#include <assert.h>
#include <errno.h>
#include <fcntl.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include <sstream>
#include <algorithm>
#include <atomic>
#include <chrono>
#include <functional>
#include <memory>
#include <optional>
#include <ranges>
#include <string>
#include <string_view>
#include <type_traits>
/* HAVE_PSI_*_INTERFACE */
#include "my_psi_config.h" // IWYU pragma: keep
/* drop_table_share with WITH_LOCK_ORDER */
#include "mysql/psi/psi_table.h" // IWYU pragma: keep
/* PSI_TABLE_CALL() with WITH_LOCK_ORDER */
#include "dd/object_id.h"
#include "decimal.h"
#include "field_types.h" // enum_field_types
#include "lex_string.h"
#include "m_string.h" // my_stpncpy
#include "map_helpers.h"
#include "mem_root_deque.h"
#include "my_alloc.h"
#include "my_base.h"
#include "my_bitmap.h"
#include "my_check_opt.h" // T_EXTEND
#include "my_checksum.h"
#include "my_compiler.h"
#include "my_dbug.h"
#include "my_io.h"
#include "my_md5.h"
#include "my_md5_size.h"
#include "my_psi_config.h"
#include "my_sqlcommand.h"
#include "my_sys.h"
#include "my_systime.h"
#include "my_thread_local.h"
#include "my_time.h"
#include "mysql/binlog/event/binlog_event.h"
#include "mysql/components/services/bits/psi_bits.h"
#include "mysql/components/services/bits/psi_stage_bits.h"
#include "mysql/components/services/log_builtins.h"
#include "mysql/components/services/log_shared.h"
#include "mysql/my_loglevel.h"
#include "mysql/plugin.h"
#include "mysql/psi/mysql_mutex.h"
#include "mysql/psi/mysql_stage.h"
#include "mysql/psi/mysql_table.h" // IWYU pragma: keep
#include "mysql/strings/dtoa.h"
#include "mysql/strings/int2str.h"
#include "mysql/strings/m_ctype.h"
#include "mysql_com.h"
#include "mysql_time.h"
#include "mysqld_error.h" // ER_*
#include "nulls.h"
#include "pfs_table_provider.h"
#include "prealloced_array.h"
#include "scope_guard.h"
#include "sql-common/my_decimal.h"
#include "sql/auth/auth_acls.h"
#include "sql/auth/auth_common.h" // check_fk_parent_table_access
#include "sql/binlog.h" // mysql_bin_log
#include "sql/create_field.h"
#include "sql/current_thd.h"
#include "sql/dd/cache/dictionary_client.h" // dd::cache::Dictionary_client
#include "sql/dd/collection.h"
#include "sql/dd/dd.h" // dd::get_dictionary
#include "sql/dd/dd_schema.h" // dd::schema_exists
#include "sql/dd/dd_table.h" // dd::drop_table, dd::update_keys...
#include "sql/dd/dictionary.h" // dd::Dictionary
#include "sql/dd/properties.h" // dd::Properties
#include "sql/dd/sdi_api.h" // dd::sdi::drop_sdis
#include "sql/dd/string_type.h"
#include "sql/dd/types/abstract_table.h"
#include "sql/dd/types/check_constraint.h" // dd::Check_constraint
#include "sql/dd/types/column.h"
#include "sql/dd/types/foreign_key.h" // dd::Foreign_key
#include "sql/dd/types/foreign_key_element.h" // dd::Foreign_key_element
#include "sql/dd/types/index.h" // dd::Index
#include "sql/dd/types/index_element.h" // dd::Index_element
#include "sql/dd/types/partition.h" // dd::Partition
#include "sql/dd/types/schema.h"
#include "sql/dd/types/table.h" // dd::Table
#include "sql/dd/types/trigger.h"
#include "sql/dd_sql_view.h" // update_referencing_views_metadata
#include "sql/dd_table_share.h" // open_table_def
#include "sql/debug_sync.h" // DEBUG_SYNC
#include "sql/derror.h" // ER_THD
#include "sql/enum_query_type.h"
#include "sql/error_handler.h" // Drop_table_error_handler
#include "sql/field.h"
#include "sql/field_common_properties.h"
#include "sql/filesort.h" // Filesort
#include "sql/gis/srid.h"
#include "sql/handler.h"
#include "sql/histograms/histogram.h"
#include "sql/item.h"
#include "sql/item_timefunc.h" // Item_func_now_local
#include "sql/iterators/row_iterator.h"
#include "sql/join_optimizer/access_path.h"
#include "sql/join_optimizer/bit_utils.h"
#include "sql/key.h" // KEY
#include "sql/key_spec.h" // Key_part_spec
#include "sql/lock.h" // mysql_lock_remove, lock_tablespace_names
#include "sql/locked_tables_list.h"
#include "sql/log.h"
#include "sql/log_event.h" // Query_log_event
#include "sql/mdl.h"
#include "sql/mem_root_array.h"
#include "sql/mysqld.h" // lower_case_table_names
#include "sql/partition_element.h"
#include "sql/partition_info.h" // partition_info
#include "sql/partitioning/partition_handler.h" // Partition_handler
#include "sql/protocol.h"
#include "sql/psi_memory_key.h"
#include "sql/query_options.h"
#include "sql/rpl_gtid.h"
#include "sql/rpl_rli.h" // rli_slave etc
#include "sql/session_tracker.h"
#include "sql/sql_alter.h"
#include "sql/sql_backup_lock.h" // acquire_shared_backup_lock
#include "sql/sql_base.h" // lock_table_names
#include "sql/sql_bitmap.h"
#include "sql/sql_check_constraint.h" // Sql_check_constraint_spec*
#include "sql/sql_class.h" // THD
#include "sql/sql_const.h"
#include "sql/sql_constraint.h" // Constraint_type_resolver
#include "sql/sql_db.h" // get_default_db_collation
#include "sql/sql_error.h"
#include "sql/sql_executor.h" // unique_ptr_destroy_only<RowIterator>
#include "sql/sql_gipk.h"
#include "sql/sql_handler.h"
#include "sql/sql_lex.h"
#include "sql/sql_list.h"
#include "sql/sql_parse.h" // test_if_data_home_dir
#include "sql/sql_partition.h"
#include "sql/sql_plist.h"
#include "sql/sql_plugin.h"
#include "sql/sql_plugin_ref.h"
#include "sql/sql_resolver.h" // setup_order
#include "sql/sql_show.h"
#include "sql/sql_tablespace.h" // validate_tablespace_name
#include "sql/sql_time.h" // make_truncated_value_warning
#include "sql/sql_trigger.h" // change_trigger_table_name
#include "sql/srs_fetcher.h"
#include "sql/stateless_allocator.h"
#include "sql/strfunc.h" // find_type2
#include "sql/system_variables.h"
#include "sql/table.h"
#include "sql/thd_raii.h"
#include "sql/thr_malloc.h"
#include "sql/transaction.h" // trans_commit_stmt
#include "sql/transaction_info.h"
#include "sql/trigger.h"
#include "sql/xa.h"
#include "sql_string.h"
#include "string_with_len.h"
#include "strmake.h"
#include "strxmov.h"
#include "strxnmov.h"
#include "template_utils.h"
#include "thr_lock.h"
#include "typelib.h"
namespace dd {
class View;
} // namespace dd
using mysql::binlog::event::checksum_crc32;
using std::max;
using std::min;
using std::string;
using std::to_string;
/** Count number of times foreign key is created on non standard index keys. */
std::atomic_ulong deprecated_use_fk_on_non_standard_key_count = 0;
/** Last time fk is created on non standard index key, as usec since epoch. */
std::atomic_ullong deprecated_use_fk_on_non_standard_key_last_timestamp = 0;
/** Don't pack string keys shorter than this (if PACK_KEYS=1 isn't used). */
static constexpr const int KEY_DEFAULT_PACK_LENGTH{8};
/* Max number of enumeration values */
static constexpr const int MAX_ENUM_VALUES{65535};
#define ER_THD_OR_DEFAULT(thd, X) \
((thd) ? ER_THD_NONCONST(thd, X) : ER_DEFAULT_NONCONST(X))
const char *primary_key_name = "PRIMARY";
namespace {
bool is_temp_table(const HA_CREATE_INFO &ci) {
return (ci.options & HA_LEX_CREATE_TMP_TABLE);
}
bool is_engine_specified(const HA_CREATE_INFO &ci) {
assert((ci.used_fields & HA_CREATE_USED_ENGINE) == 0 ||
ci.db_type != nullptr);
return (ci.used_fields & HA_CREATE_USED_ENGINE);
}
handlerton *default_handlerton(THD *thd, const HA_CREATE_INFO &ci) {
return is_temp_table(ci) ? ha_default_temp_handlerton(thd)
: ha_default_handlerton(thd);
}
handlerton *requested_handlerton(THD *thd, const HA_CREATE_INFO &ci) {
return is_engine_specified(ci) ? ci.db_type : default_handlerton(thd, ci);
}
struct Handlerton_pair {
handlerton *requested;
handlerton *alternate;
};
using Viability_error_emitter = std::function<void(const char *engine_name)>;
using Viability_substitution_warning_emitter = std::function<void(
THD *, const char *requested_engine_name,
const char *substituted_engine_name, const char *table_name)>;
struct Viability {
bool value{true};
Viability_error_emitter emit_error;
Viability_substitution_warning_emitter emit_substitution_warning;
Viability() = default;
Viability(Viability_error_emitter &&error_emitter,
Viability_substitution_warning_emitter &&warning_emitter)
: value{false},
emit_error{std::move(error_emitter)},
emit_substitution_warning{std::move(warning_emitter)} {
assert(emit_error);
assert(emit_substitution_warning);
}
};
Viability get_viability(const handlerton &hton, const HA_CREATE_INFO &ci) {
DBUG_TRACE;
if (ha_is_externally_disabled(hton)) {
return {[](const char *en) {
my_error(ER_DISABLED_STORAGE_ENGINE, MYF(0), en);
},
[](THD *t, const char *ren, const char *sen, const char *tn) {
push_warning_printf(t, Sql_condition::SL_WARNING,
ER_DISABLED_STORAGE_ENGINE,
ER_THD(t, ER_DISABLED_STORAGE_ENGINE), ren);
push_warning_printf(
t, Sql_condition::SL_WARNING, ER_WARN_USING_OTHER_HANDLER,
ER_THD(t, ER_WARN_USING_OTHER_HANDLER), sen, tn);
}};
}
if (is_temp_table(ci) &&
ha_check_storage_engine_flag(&hton, HTON_TEMPORARY_NOT_SUPPORTED)) {
return {
[](const char *en) {
my_error(ER_ILLEGAL_HA_CREATE_OPTION, MYF(0), en, "TEMPORARY");
},
[](THD *, const char *, const char *,
const char *) { /* Nothing, no warning emitted in this case */ }};
}
return {};
}
handlerton *get_viable_handlerton_for_create_impl(THD *thd,
const char *table_name,
const HA_CREATE_INFO &ci,
Handlerton_pair hp) {
DBUG_TRACE;
assert(hp.requested != nullptr);
auto viability = get_viability(*hp.requested, ci);
if (viability.value) {
return hp.requested;
}
assert(viability.emit_error);
const char *en = ha_resolve_storage_engine_name(hp.requested);
if (hp.alternate == nullptr) {
viability.emit_error(en);
return nullptr;
}
auto alt_viability = get_viability(*hp.alternate, ci);
const char *an = ha_resolve_storage_engine_name(hp.alternate);
if (!alt_viability.value) {
viability.emit_error(en);
return nullptr;
}
viability.emit_substitution_warning(thd, en, an, table_name);
return hp.alternate;
}
/**
Check if source is enabled AND NOT explicitly disabled (listed in the
disabled_storages_engines system variable.
If not; falls back to the default (tmp) storage engine if substitution
is allowed, unless this is also disabled.
Otherwise, if substitution does take place, ER_DISABLED_STORAGE_ENGINE and
ER_USING_OTHER_HANDLER are emitted as warnings.
For temporary tables the above also applies, and in addition the source
handlerton is checked to see if it supports temporary tables.
Note that this substitution is allowed even when no_substitution is ON, but
will fail if the default handlerton for temporary tables is disabled or does
not support temporary tables (unlikely).
@param thd Thread handler.
@param table_name Table name.
@param ci create info struct from parser.
@param source Handlerton requested by query.
@retval source if this is viable.
@retval The default hton if viable and engine substitution is allowed.
@retval The default temp hton if viable and a temporary table and source
does not support temporary tables.
@retval nullptr if error (source not viable and substitution
not possible).
*/
handlerton *get_viable_handlerton_for_create_like(THD *thd,
const char *table_name,
const HA_CREATE_INFO &ci,
handlerton *source) {
return get_viable_handlerton_for_create_impl(
thd, table_name, ci,
{source, is_engine_substitution_allowed(thd) || is_temp_table(ci)
? default_handlerton(thd, ci)
: nullptr});
}
/**
Does nothing (returns existing) unless ALTER changes the ENGINE. The
handlerton for the specified ENGINE is considered viable if it is enabled AND
NOT explicitly disabled (listed in the disabled_storages_engines system
variable).
If the specified handleton is not viable it falls back to existing if
substitution is allowed. existing is used without further checking,
and ER_UNKNOWN_STORAGE_ENGINE is emitted as warning.
@param thd Thread handler.
@param ci create info struct from parser.
@param existing Handlerton requested by query.
@retval existing if ENGINE is not specified or is the same as existing, or if
ENGINE is not viable and substitution is permitted.
@retval Handlerton of specified engine if this is viable.
@retval nullptr if error (specified engine not viable and substitution
not permitted).
*/
handlerton *get_viable_handlerton_for_alter(THD *thd, const HA_CREATE_INFO &ci,
handlerton *existing) {
DBUG_TRACE;
if (!is_engine_specified(ci) || ci.db_type == existing) return existing;
const Handlerton_pair hp = {
ci.db_type, is_engine_substitution_allowed(thd) ? existing : nullptr};
assert(hp.requested != nullptr);
auto viability = get_viability(*hp.requested, ci);
if (viability.value) {
return hp.requested;
}
const char *en = ha_resolve_storage_engine_name(hp.requested);
if (hp.alternate == nullptr) {
viability.emit_error(en);
return nullptr;
}
push_warning_printf(thd, Sql_condition::SL_WARNING, ER_UNKNOWN_STORAGE_ENGINE,
ER_THD(thd, ER_UNKNOWN_STORAGE_ENGINE), en);
return hp.alternate;
}
} // namespace
/**
Checks if the handlerton for the specified ENGINE is enabled AND NOT
explicitly disabled (listed in the disabled_storages_engines system
variable). In the case of temporary tables the handlerton must also support
those to be viable.
When returning a handlerton different from the one specified
ER_DISABLED_STORAGE_ENGINE and ER_USING_OTHER_HANDLER are emitted as
warnings.
@param thd Thread handler.
@param table_name Table name.
@param ci create_info struct from parser.
@retval Handlerton for specified ENGINE if this is viable.
@retval The default (tmp) handlerton if viable and engine substitution is
allowed.
@retval nullptr if error (specified ENGINE not viable and substitution
not permitted).
*/
handlerton *get_viable_handlerton_for_create(THD *thd, const char *table_name,
const HA_CREATE_INFO &ci) {
return get_viable_handlerton_for_create_impl(
thd, table_name, ci,
{requested_handlerton(thd, ci),
(is_engine_specified(ci) && is_engine_substitution_allowed(thd))
? default_handlerton(thd, ci)
: nullptr});
}
static bool check_if_keyname_exists(const char *name, KEY *start, KEY *end);
static const char *make_unique_key_name(const char *field_name, KEY *start,
KEY *end);
static const dd::Index *find_fk_supporting_key(handlerton *hton,
const dd::Table *table_def,
const dd::Foreign_key *fk);
namespace {
const dd::Index *find_fk_parent_key(THD *thd, handlerton *hton,
const dd::Index *supporting_key,
const dd::Table *parent_table_def,
const dd::Foreign_key *fk);
} // namespace
static int copy_data_between_tables(
THD *thd, PSI_stage_progress *psi, TABLE *from, TABLE *to,
List<Create_field> &create, ha_rows *copied, ha_rows *deleted,
Alter_info::enum_enable_or_disable keys_onoff, Alter_table_ctx *alter_ctx);
static bool prepare_blob_field(THD *thd, Create_field *sql_field,
bool convert_character_set);
static bool check_engine(const char *db_name, const char *table_name,
HA_CREATE_INFO *create_info);
static bool prepare_set_field(THD *thd, Create_field *sql_field);
static bool prepare_enum_field(THD *thd, Create_field *sql_field);
static uint blob_length_by_type(enum_field_types type);
static const Create_field *get_field_by_index(Alter_info *alter_info, uint idx);
static bool generate_check_constraint_name(THD *thd, const char *table_name,
uint ordinal_number,
LEX_STRING &name,
bool skip_validation);
static bool push_check_constraint_mdl_request_to_list(
THD *thd, const char *db, const char *cc_name,
MDL_request_list &cc_mdl_request_list);
static bool prepare_check_constraints_for_create_like_table(
THD *thd, Table_ref *src_table, Table_ref *table, Alter_info *alter_info);
static bool prepare_check_constraints_for_alter(THD *thd, const TABLE *table,
Alter_info *alter_info,
Alter_table_ctx *alter_tbl_ctx);
static void set_check_constraints_alter_mode(dd::Table *table,
Alter_info *alter_info);
static void reset_check_constraints_alter_mode(dd::Table *table);
static bool adjust_check_constraint_names_for_old_table_version(
THD *thd, const char *old_table_db, dd::Table *old_table);
static bool is_any_check_constraints_evaluation_required(
const Alter_info *alter_info);
static bool check_if_field_used_by_generated_column_or_default(
TABLE *table, const Field *field, const Alter_info *alter_info);
/**
RAII class to control the atomic DDL commit on slave.
A slave context flag responsible to mark the DDL as committed is
raised and kept for the entirety of DDL commit block.
While DDL commits the slave info table won't take part
in its transaction.
*/
class Disable_slave_info_update_guard {
Relay_log_info *m_rli;
bool m_flag;
public:
Disable_slave_info_update_guard(THD *thd)
: m_rli(thd->rli_slave), m_flag(false) {
if (!thd->slave_thread) {
assert(!m_rli);
return;
}
assert(m_rli->current_event);
m_flag = static_cast<Query_log_event *>(thd->rli_slave->current_event)
->has_ddl_committed;
static_cast<Query_log_event *>(m_rli->current_event)->has_ddl_committed =
true;
}
~Disable_slave_info_update_guard() {
if (m_rli) {
static_cast<Query_log_event *>(m_rli->current_event)->has_ddl_committed =
m_flag;
}
}
};
static bool trans_intermediate_ddl_commit(THD *thd, bool error) {
// Must be used for intermediate (but not final) DDL commits.
const Implicit_substatement_state_guard substatement_guard(thd);
if (error) {
trans_rollback_stmt(thd);
// Full rollback in case we have THD::transaction_rollback_request.
trans_rollback(thd);
return true;
}
return trans_commit_stmt(thd) || trans_commit(thd);
}
/**
@brief Helper function for explain_filename
@param thd Thread handle
@param to_p Explained name in system_charset_info
@param end_p End of the to_p buffer
@param name Name to be converted
@param name_len Length of the name, in bytes
*/
static char *add_identifier(THD *thd, char *to_p, const char *end_p,
const char *name, size_t name_len) {
size_t res;
uint errors;
const char *conv_name;
char tmp_name[FN_REFLEN];
char conv_string[FN_REFLEN];
int quote;
DBUG_TRACE;
if (!name[name_len])
conv_name = name;
else {
my_stpnmov(tmp_name, name, name_len);
tmp_name[name_len] = 0;
conv_name = tmp_name;
}
res = strconvert(&my_charset_filename, conv_name, system_charset_info,
conv_string, FN_REFLEN, &errors);
if (!res || errors) {
DBUG_PRINT("error", ("strconvert of '%s' failed with %u (errors: %u)",
conv_name, static_cast<uint>(res), errors));
conv_name = name;
} else {
DBUG_PRINT("info", ("conv '%s' -> '%s'", conv_name, conv_string));
conv_name = conv_string;
}
quote = thd ? get_quote_char_for_identifier(thd, conv_name, res - 1) : '`';
if (quote != EOF && (end_p - to_p > 2)) {
*(to_p++) = (char)quote;
while (*conv_name && (end_p - to_p - 1) > 0) {
uint length = my_mbcharlen(system_charset_info, *conv_name);
if (!length) length = 1;
if (length == 1 && *conv_name == (char)quote) {
if ((end_p - to_p) < 3) break;
*(to_p++) = (char)quote;
*(to_p++) = *(conv_name++);
} else if (((long)length) < (end_p - to_p)) {
to_p = my_stpnmov(to_p, conv_name, length);
conv_name += length;
} else
break; /* string already filled */
}
if (end_p > to_p) {
*(to_p++) = (char)quote;
if (end_p > to_p)
*to_p = 0; /* terminate by NUL, but do not include it in the count */
}
} else
to_p = my_stpnmov(to_p, conv_name, end_p - to_p);
return to_p;
}
/**
@brief Explain a path name by split it to database, table etc.
@details Break down the path name to its logic parts
(database, table, partition, subpartition).
filename_to_tablename cannot be used on partitions, due to the @#P@# part.
There can be up to 6 '#', @#P@# for partition, @#SP@# for subpartition
and @#TMP@# or @#REN@# for temporary or renamed partitions.
This should be used when something should be presented to a user in a
diagnostic, error etc. when it would be useful to know what a particular
file [and directory] means. Such as SHOW ENGINE STATUS, error messages etc.
@param thd Thread handle
@param from Path name in my_charset_filename
Null terminated in my_charset_filename, normalized
to use '/' as directory separation character.
@param to Explained name in system_charset_info
@param to_length Size of to buffer
@param explain_mode Requested output format.
EXPLAIN_ALL_VERBOSE ->
[Database `db`, ]Table `tbl`[,[ Temporary| Renamed]
Partition `p` [, Subpartition `sp`]]
EXPLAIN_PARTITIONS_VERBOSE -> `db`.`tbl`
[[ Temporary| Renamed] Partition `p`
[, Subpartition `sp`]]
EXPLAIN_PARTITIONS_AS_COMMENT -> `db`.`tbl` |*
[,[ Temporary| Renamed] Partition `p`
[, Subpartition `sp`]] *|
(| is really a /, and it is all in one line)
@retval Length of returned string
*/
size_t explain_filename(THD *thd, const char *from, char *to, size_t to_length,
enum_explain_filename_mode explain_mode) {
char *to_p = to;
char *end_p = to_p + to_length;
const char *db_name = nullptr;
size_t db_name_len = 0;
const char *table_name;
size_t table_name_len = 0;
const char *part_name = nullptr;
size_t part_name_len = 0;
const char *subpart_name = nullptr;
size_t subpart_name_len = 0;
enum enum_part_name_type { NORMAL, TEMP, RENAMED } part_type = NORMAL;
const char *tmp_p;
DBUG_TRACE;
DBUG_PRINT("enter", ("from '%s'", from));
tmp_p = from;
table_name = from;
/*
If '/' then take last directory part as database.
'/' is the directory separator, not FN_LIB_CHAR
*/
while ((tmp_p = strchr(tmp_p, '/'))) {
db_name = table_name;
/* calculate the length */
db_name_len = tmp_p - db_name;
tmp_p++;
table_name = tmp_p;
}
tmp_p = table_name;
/* Look if there are partition tokens in the table name. */
while ((tmp_p = strchr(tmp_p, '#'))) {
tmp_p++;
switch (tmp_p[0]) {
case 'P':
case 'p':
if (tmp_p[1] == '#') {
part_name = tmp_p + 2;
tmp_p += 2;
}
break;
case 'S':
case 's':
if ((tmp_p[1] == 'P' || tmp_p[1] == 'p') && tmp_p[2] == '#') {
part_name_len = tmp_p - part_name - 1;
subpart_name = tmp_p + 3;
tmp_p += 3;
}
break;
case 'T':
case 't':
if ((tmp_p[1] == 'M' || tmp_p[1] == 'm') &&
(tmp_p[2] == 'P' || tmp_p[2] == 'p') && tmp_p[3] == '#' &&
!tmp_p[4]) {
part_type = TEMP;
tmp_p += 4;
}
break;
case 'R':
case 'r':
if ((tmp_p[1] == 'E' || tmp_p[1] == 'e') &&
(tmp_p[2] == 'N' || tmp_p[2] == 'n') && tmp_p[3] == '#' &&
!tmp_p[4]) {
part_type = RENAMED;
tmp_p += 4;
}
break;
default:
/* Not partition name part. */
;
}
}
if (part_name) {
table_name_len = part_name - table_name - 3;
if (subpart_name)
subpart_name_len = strlen(subpart_name);
else
part_name_len = strlen(part_name);
if (part_type != NORMAL) {
if (subpart_name)
subpart_name_len -= 5;
else
part_name_len -= 5;
}
} else
table_name_len = strlen(table_name);
if (db_name) {
if (explain_mode == EXPLAIN_ALL_VERBOSE) {
to_p = my_stpncpy(to_p, ER_THD_OR_DEFAULT(thd, ER_DATABASE_NAME),
end_p - to_p);
*(to_p++) = ' ';
to_p = add_identifier(thd, to_p, end_p, db_name, db_name_len);
to_p = my_stpncpy(to_p, ", ", end_p - to_p);
} else {
to_p = add_identifier(thd, to_p, end_p, db_name, db_name_len);
to_p = my_stpncpy(to_p, ".", end_p - to_p);
}
}
if (explain_mode == EXPLAIN_ALL_VERBOSE) {
to_p =
my_stpncpy(to_p, ER_THD_OR_DEFAULT(thd, ER_TABLE_NAME), end_p - to_p);
*(to_p++) = ' ';
to_p = add_identifier(thd, to_p, end_p, table_name, table_name_len);
} else
to_p = add_identifier(thd, to_p, end_p, table_name, table_name_len);
if (part_name) {
if (explain_mode == EXPLAIN_PARTITIONS_AS_COMMENT)
to_p = my_stpncpy(to_p, " /* ", end_p - to_p);
else if (explain_mode == EXPLAIN_PARTITIONS_VERBOSE)
to_p = my_stpncpy(to_p, " ", end_p - to_p);
else
to_p = my_stpncpy(to_p, ", ", end_p - to_p);
if (part_type != NORMAL) {
if (part_type == TEMP)
to_p = my_stpncpy(to_p, ER_THD_OR_DEFAULT(thd, ER_TEMPORARY_NAME),
end_p - to_p);
else
to_p = my_stpncpy(to_p, ER_THD_OR_DEFAULT(thd, ER_RENAMED_NAME),
end_p - to_p);
to_p = my_stpncpy(to_p, " ", end_p - to_p);
}
to_p = my_stpncpy(to_p, ER_THD_OR_DEFAULT(thd, ER_PARTITION_NAME),
end_p - to_p);
*(to_p++) = ' ';
to_p = add_identifier(thd, to_p, end_p, part_name, part_name_len);
if (subpart_name) {
to_p = my_stpncpy(to_p, ", ", end_p - to_p);
to_p = my_stpncpy(to_p, ER_THD_OR_DEFAULT(thd, ER_SUBPARTITION_NAME),
end_p - to_p);
*(to_p++) = ' ';
to_p = add_identifier(thd, to_p, end_p, subpart_name, subpart_name_len);
}
if (explain_mode == EXPLAIN_PARTITIONS_AS_COMMENT)
to_p = my_stpncpy(to_p, " */", end_p - to_p);
}
DBUG_PRINT("exit", ("to '%s'", to));
return static_cast<size_t>(to_p - to);
}
/*
Translate a file name to a table name (WL #1324).
SYNOPSIS
filename_to_tablename()
from The file name in my_charset_filename.
to OUT The table name in system_charset_info.
to_length The size of the table name buffer.
stay_quiet Silence the errors.
has_errors OUT True, if there are errors.
RETURN
Table name length.
*/
size_t filename_to_tablename(const char *from, char *to, size_t to_length,
bool stay_quiet, bool *has_errors) {
uint errors;
size_t res;
DBUG_TRACE;
DBUG_PRINT("enter", ("from '%s'", from));
if (has_errors != nullptr) *has_errors = false;
if (strlen(from) >= tmp_file_prefix_length &&
!memcmp(from, tmp_file_prefix, tmp_file_prefix_length)) {
/* Temporary table name. */
res = (my_stpnmov(to, from, to_length) - to);
} else {
res = strconvert(&my_charset_filename, from, system_charset_info, to,
to_length, &errors);
if (errors) // Old 5.0 name
{
if (has_errors != nullptr) *has_errors = true;
if (!stay_quiet) {
LogErr(ERROR_LEVEL, ER_INVALID_OR_OLD_TABLE_OR_DB_NAME, from);
}
/*
TODO: add a stored procedure for fix table and database names,
and mention its name in error log.
*/
}
}
DBUG_PRINT("exit", ("to '%s'", to));
return res;
}
/*
Translate a table name to a file name (WL #1324).
SYNOPSIS
tablename_to_filename()
from The table name in system_charset_info.
to OUT The file name in my_charset_filename.
to_length The size of the file name buffer.
RETURN
File name length.
*/
size_t tablename_to_filename(const char *from, char *to, size_t to_length) {
uint errors;
size_t length;
DBUG_TRACE;
DBUG_PRINT("enter", ("from '%s'", from));
length = strconvert(system_charset_info, from, &my_charset_filename, to,
to_length, &errors);
if (check_if_legal_tablename(to) && length + 4 < to_length) {
memcpy(to + length, "@@@", 4);
length += 3;
}
DBUG_PRINT("exit", ("to '%s'", to));
return length;
}
/*
@brief Creates path to a file: mysql_data_dir/db/table.ext
@param buff Where to write result in my_charset_filename.
This may be the same as table_name.
@param bufflen buff size
@param db Database name in system_charset_info.
@param table_name Table name in system_charset_info.
@param ext File extension.
@param flags FN_FROM_IS_TMP or FN_TO_IS_TMP or FN_IS_TMP
table_name is temporary, do not change.
@param was_truncated points to location that will be
set to true if path was truncated,
to false otherwise.
@note
Uses database and table name, and extension to create
a file name in mysql_data_dir. Database and table
names are converted from system_charset_info into "fscs".
Unless flags indicate a temporary table name.
'db' is always converted.
'ext' is not converted.
The conversion suppression is required for ALTER TABLE. This
statement creates intermediate tables. These are regular
(non-temporary) tables with a temporary name. Their path names must
be derivable from the table name. So we cannot use
build_tmptable_filename() for them.
@return
path length
*/
size_t build_table_filename(char *buff, size_t bufflen, const char *db,
const char *table_name, const char *ext, uint flags,
bool *was_truncated) {
char tbbuff[FN_REFLEN], dbbuff[FN_REFLEN];
size_t tab_len, db_len;
DBUG_TRACE;
DBUG_PRINT("enter", ("db: '%s' table_name: '%s' ext: '%s' flags: %x", db,
table_name, ext, flags));
if (flags & FN_IS_TMP) // FN_FROM_IS_TMP | FN_TO_IS_TMP
tab_len = my_stpnmov(tbbuff, table_name, sizeof(tbbuff)) - tbbuff;
else
tab_len = tablename_to_filename(table_name, tbbuff, sizeof(tbbuff));
db_len = tablename_to_filename(db, dbbuff, sizeof(dbbuff));
char *end = buff + bufflen;
/* Don't add FN_ROOTDIR if mysql_data_home already includes it */
char *pos = my_stpnmov(buff, mysql_data_home, bufflen);
size_t rootdir_len = strlen(FN_ROOTDIR);
if (pos - rootdir_len >= buff &&
memcmp(pos - rootdir_len, FN_ROOTDIR, rootdir_len) != 0)
pos = my_stpnmov(pos, FN_ROOTDIR, end - pos);
else
rootdir_len = 0;
pos = strxnmov(pos, end - pos, dbbuff, FN_ROOTDIR, NullS);
pos = strxnmov(pos, end - pos, tbbuff, ext, NullS);
/**
Mark OUT param if path gets truncated.
Most of functions which invoke this function are sure that the
path will not be truncated. In case some functions are not sure,
we can use 'was_truncated' OUTPARAM
*/
*was_truncated = false;
if (pos == end && (bufflen < mysql_data_home_len + rootdir_len + db_len +
strlen(FN_ROOTDIR) + tab_len + strlen(ext)))
*was_truncated = true;
DBUG_PRINT("exit", ("buff: '%s'", buff));
return pos - buff;
}
/**
Create path to a temporary table, like mysql_tmpdir/@#sql1234_12_1
(i.e. to its .FRM file but without an extension).
@param thd The thread handle.
@param buff Where to write result in my_charset_filename.
@param bufflen buff size
@note
Uses current_pid, thread_id, and tmp_table counter to create
a file name in mysql_tmpdir.
@return Path length.
*/
size_t build_tmptable_filename(THD *thd, char *buff, size_t bufflen) {
DBUG_TRACE;
char *p = my_stpnmov(buff, mysql_tmpdir, bufflen);
assert(sizeof(my_thread_id) == 4);
snprintf(p, bufflen - (p - buff), "/%s%lx_%x_%x", tmp_file_prefix,
current_pid, thd->thread_id(), thd->tmp_table++);
if (lower_case_table_names) {
/* Convert all except tmpdir to lower case */
my_casedn_str(files_charset_info, p);
}
const size_t length = unpack_filename(buff, buff);
DBUG_PRINT("exit", ("buff: '%s'", buff));
return length;
}
/**
Create a dd::Table-object specifying the temporary table
definition, but do not put it into the Data Dictionary. The created
dd::Table-instance is returned via tmp_table_def out-parameter.
The temporary table is also created in the storage engine, depending
on the 'no_ha_table' argument.
@param thd Thread handler
@param path Name of file (including database)
@param sch_obj Schema.
@param db Schema name.
Cannot use dd::Schema::name() directly due to LCTN.
@param table_name Table name
@param create_info create info parameters
@param create_fields Fields to create
@param keys number of keys to create
@param key_info Keys to create
@param keys_onoff Enable or disable keys.
@param check_cons_spec List of check constraint specification.
@param file Handler to use
@param no_ha_table Indicates that only definitions needs to be created
and not a table in the storage engine.
@param[out] binlog_to_trx_cache
Which binlog cache should be used?
If true => trx cache
If false => stmt cache
@param[out] tmp_table_def Data-dictionary object for temporary table
which was created. Is not set if no_ha_table
was false.
@retval false ok
@retval true error
*/
static bool rea_create_tmp_table(
THD *thd, const char *path, const dd::Schema &sch_obj, const char *db,