Debian Codegraph @

storage/innobase/handler/ha_innodb.cc

raw
1 /*****************************************************************************
2
3 Copyright (c) 2000, 2026, Oracle and/or its affiliates.
4 Copyright (c) 2008, 2009 Google Inc.
5 Copyright (c) 2009, Percona Inc.
6 Copyright (c) 2012, Facebook Inc.
7
8 Portions of this file contain modifications contributed and copyrighted by
9 Google, Inc. Those modifications are gratefully acknowledged and are described
10 briefly in the InnoDB documentation. The contributions by Google are
11 incorporated with their permission, and subject to the conditions contained in
12 the file COPYING.Google.
13
14 Portions of this file contain modifications contributed and copyrighted
15 by Percona Inc.. Those modifications are
16 gratefully acknowledged and are described briefly in the InnoDB
17 documentation. The contributions by Percona Inc. are incorporated with
18 their permission, and subject to the conditions contained in the file
19 COPYING.Percona.
20
21 This program is free software; you can redistribute it and/or modify it under
22 the terms of the GNU General Public License, version 2.0, as published by the
23 Free Software Foundation.
24
25 This program is designed to work with certain software (including
26 but not limited to OpenSSL) that is licensed under separate terms,
27 as designated in a particular file or component or in included license
28 documentation. The authors of MySQL hereby grant you an additional
29 permission to link the program and your derivative works with the
30 separately licensed software that they have either included with
31 the program or referenced in the documentation.
32
33 This program is distributed in the hope that it will be useful, but WITHOUT
34 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
35 FOR A PARTICULAR PURPOSE. See the GNU General Public License, version 2.0,
36 for more details.
37
38 You should have received a copy of the GNU General Public License along with
39 this program; if not, write to the Free Software Foundation, Inc.,
40 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
41
42 *****************************************************************************/
43
44 /** @file ha_innodb.cc */
45
46 #ifndef UNIV_HOTBACKUP
47 #include "my_config.h"
48 #endif /* !UNIV_HOTBACKUP */
49
50 #include <auto_thd.h>
51 #include <errno.h>
52 #include <fcntl.h>
53 #include <gstream.h>
54 #include <limits.h>
55 #include <log.h>
56 #include <math.h>
57 #include <my_compare.h>
58 #include <mysqld.h>
59 #include <stdlib.h>
60 #include <strfunc.h>
61 #include <time.h>
62
63 #include <algorithm>
64 #include <cstdint>
65 #include <memory>
66
67 #include <sql_table.h>
68 #include "mysql/components/services/system_variable_source.h"
69
70 #ifndef UNIV_HOTBACKUP
71 #include <current_thd.h>
72 #include <debug_sync.h>
73 #include <derror.h>
74 #include <my_bitmap.h>
75 #include <my_check_opt.h>
76 #include <mysql/service_thd_alloc.h>
77 #include <mysql/service_thd_wait.h>
78 #include <mysql_com.h>
79 #include <sql_acl.h>
80 #include <sql_class.h>
81 #include <sql_show.h>
82 #include <sql_tablespace.h>
83 #include <sql_thd_internal_api.h>
84 #include "api0api.h"
85 #include "api0misc.h"
86 #include "arch0arch.h"
87 #include "arch0page.h"
88 #include "auth_acls.h"
89 #include "btr0btr.h"
90 #include "btr0cur.h"
91 #include "btr0sea.h"
92 #include "buf0dblwr.h"
93 #include "buf0dump.h"
94 #include "buf0flu.h"
95 #include "buf0lru.h"
96 #include "buf0stats.h"
97 #include "clone0api.h"
98 #include "clone0clone.h"
99 #include "dd/dd.h"
100 #include "dd/dictionary.h"
101 #include "dd/impl/bootstrap/bootstrap_ctx.h"
102 #include "dd/properties.h"
103 #include "dd/types/index.h"
104 #include "dd/types/object_table.h"
105 #include "dd/types/object_table_definition.h"
106 #include "dd/types/partition.h"
107 #include "dd/types/table.h"
108 #include "dd/types/tablespace.h"
109 #include "ddl0ddl.h"
110 #include "dict0boot.h"
111 #include "dict0crea.h"
112 #include "dict0dd.h"
113 #include "dict0dict.h"
114 #include "dict0load.h"
115 #include "dict0stats.h"
116 #include "dict0stats_bg.h"
117 #include "fil0fil.h"
118 #include "fsp0fsp.h"
119 #include "fsp0space.h"
120 #include "fsp0sysspace.h"
121 #include "fts0fts.h"
122 #include "fts0plugin.h"
123 #include "fts0priv.h"
124 #include "fts0types.h"
125 #include "ha_innodb.h"
126 #include "ha_innopart.h"
127 #include "ha_prototypes.h"
128 #include "handler0alter.h" //alter_stats_rebuild()
129 #include "i_s.h"
130 #include "ibuf0ibuf.h"
131 #include "lex_string.h"
132 #include "lob0lob.h"
133 #include "lock0lock.h"
134 #include "log0buf.h"
135 #include "log0chkp.h"
136 #include "log0encryption.h"
137 #include "log0meb.h"
138 #include "log0pfs.h"
139 #include "log0pre_8_0_30.h"
140 #include "log0sys.h"
141 #include "log0write.h"
142 #include "mem0mem.h"
143 #include "mtr0mtr.h"
144 #include "my_compare.h"
145 #include "my_compiler.h"
146 #include "my_dbug.h"
147 #include "my_double2ulonglong.h"
148 #include "my_io.h"
149 #include "my_macros.h"
150 #include "my_psi_config.h"
151 #include "mysql/components/services/log_builtins.h"
152 #include "mysql/plugin.h"
153 #include "mysql/psi/mysql_data_lock.h"
154 #include "mysys_err.h"
155 #include "os0thread-create.h"
156 #include "os0thread.h"
157 #include "p_s.h"
158 #include "page0zip.h"
159 #include "pars0pars.h"
160 #include "rem0types.h"
161 #include "row0ext.h"
162 #include "row0import.h"
163 #include "row0ins.h"
164 #include "row0mysql.h"
165 #include "row0quiesce.h"
166 #include "row0sel.h"
167 #include "row0upd.h"
168 #include "sql/plugin_table.h"
169 #include "srv0mon.h"
170 #include "srv0srv.h"
171 #include "srv0start.h"
172 #include "sync0sync.h"
173 #ifdef UNIV_DEBUG
174 #include "trx0purge.h"
175 #endif /* UNIV_DEBUG */
176 #include "dict0priv.h"
177 #include "dict0sdi.h"
178 #include "dict0upgrade.h"
179 #include "os0thread-create.h"
180 #include "os0thread.h"
181 #include "sql/item.h"
182 #include "sql_base.h"
183 #include "srv0tmp.h"
184 #include "trx0rec.h"
185 #include "trx0roll.h"
186 #include "trx0rseg.h"
187 #include "trx0sys.h"
188 #include "trx0trx.h"
189 #include "trx0xa.h"
190 #include "ut0mem.h"
191 #include "ut0test.h"
192 #else
193 #include <typelib.h>
194 #include "buf0types.h"
195 #include "univ.i"
196 #endif /* !UNIV_HOTBACKUP */
197
198 #include "log0files_io.h"
199
200 #include "sql-common/json_binary.h"
201 #include "sql-common/json_dom.h"
202
203 #include "os0enc.h"
204 #include "os0file.h"
205
206 #include <scope_guard.h>
207 #include <mutex>
208 #include <sstream>
209 #include <string>
210 #include <vector>
211
212 #ifdef HAVE_UNISTD_H
213 #include <unistd.h>
214 #endif /* HAVE_UNISTD_H */
215
216 #ifndef UNIV_HOTBACKUP
217
218 namespace innobase {
219 namespace component_services {
220 SERVICE_TYPE(registry) *reg_srv = nullptr;
221
222 /** Initialize component service handles */
223 static bool intitialize_service_handles() {
224 DBUG_TRACE;
225
226 auto cleanup = [&]() {
227 /* Add module specific deinitialization here */
228 innobase::encryption::deinit_keyring_services(reg_srv);
229 mysql_plugin_registry_release(reg_srv);
230 };
231
232 reg_srv = mysql_plugin_registry_acquire();
233 if (reg_srv == nullptr) {
234 return false;
235 }
236
237 /* Add module specific initialization here */
238 if (innobase::encryption::init_keyring_services(reg_srv) == false) {
239 cleanup();
240 return false;
241 }
242
243 /* During initialize, PFS is not ready. */
244 if (!opt_initialize &&
245 !log_pfs_acquire_services(innobase::component_services::reg_srv)) {
246 ib::warn(ER_IB_MSG_LOG_PFS_ACQUIRE_SERVICES_FAILED);
247 }
248
249 return true;
250 }
251
252 /** Deinitialize component service handles */
253 static void deinitialize_service_handles() {
254 DBUG_TRACE;
255 if (!opt_initialize) {
256 log_pfs_release_services(reg_srv);
257 }
258 innobase::encryption::deinit_keyring_services(reg_srv);
259 if (reg_srv != nullptr) {
260 mysql_plugin_registry_release(reg_srv);
261 }
262 }
263
264 } // namespace component_services
265 } // namespace innobase
266
267 /** Stop printing warnings, if the count exceeds this threshold. */
268 static const size_t MOVED_FILES_PRINT_THRESHOLD = 32;
269
270 SERVICE_TYPE(registry) * reg_svc;
271 SERVICE_TYPE(system_variable_source) * sysvar_source_svc;
272 SERVICE_TYPE(clone_protocol) * clone_protocol_svc;
273
274 static const uint64_t KB = 1024;
275 static const uint64_t MB = KB * 1024;
276 static const uint64_t GB = MB * 1024;
277
278 /** fil_space_t::flags for hard-coded tablespaces */
279 uint32_t predefined_flags;
280
281 /** to protect innobase_open_files */
282 static mysql_mutex_t innobase_share_mutex;
283
284 /* mutex protecting the master_key_id change. */
285 ib_mutex_t master_key_id_mutex;
286
287 /** to force correct commit order in binlog */
288 static ulong commit_threads = 0;
289 static mysql_cond_t commit_cond;
290 static mysql_mutex_t commit_cond_m;
291 mysql_cond_t resume_encryption_cond;
292 mysql_mutex_t resume_encryption_cond_m;
293 os_event_t recovery_lock_taken;
294 static bool innodb_inited = false;
295
296 [[maybe_unused]] static inline bool EQ_CURRENT_THD(THD *thd) {
297 return thd == current_thd;
298 }
299
300 static struct handlerton *innodb_hton_ptr;
301
302 static const long AUTOINC_OLD_STYLE_LOCKING = 0;
303 static const long AUTOINC_NEW_STYLE_LOCKING = 1;
304 static const long AUTOINC_NO_LOCKING = 2;
305
306 static long innobase_open_files;
307 static long innobase_autoinc_lock_mode;
308 static ulong innobase_commit_concurrency = 0;
309
310 /* Boolean @@innodb_buffer_pool_in_core_file. */
311 bool srv_buffer_pool_in_core_file = true;
312
313 /** Percentage of the buffer pool to reserve for 'old' blocks.
314 Connected to buf_LRU_old_ratio. */
315 static uint innobase_old_blocks_pct;
316
317 /* The default values for the following char* start-up parameters
318 are determined in innodb_init_params(). */
319
320 static char *innobase_data_home_dir = nullptr;
321 static char *innobase_data_file_path = nullptr;
322 static char *innobase_temp_data_file_path = nullptr;
323 static char *innobase_enable_monitor_counter = nullptr;
324 static char *innobase_disable_monitor_counter = nullptr;
325 static char *innobase_reset_monitor_counter = nullptr;
326 static char *innobase_reset_all_monitor_counter = nullptr;
327 static char *innobase_doublewrite_dir = nullptr;
328
329 static ulong innodb_flush_method;
330
331 /* This variable can be set in the server configure file, specifying
332 stopword table to be used */
333 static char *innobase_server_stopword_table = nullptr;
334
335 /* Below we have boolean-valued start-up parameters, and their default
336 values */
337
338 static bool innobase_rollback_on_timeout = false;
339 static bool innobase_create_status_file = false;
340 bool innobase_stats_on_metadata = true;
341 static bool innodb_optimize_fulltext_only = false;
342
343 static char *innodb_version_str = (char *)INNODB_VERSION_STR;
344
345 static Innodb_data_lock_inspector innodb_data_lock_inspector;
346
347 /** Note we cannot use rec_format_enum because we do not allow
348 COMPRESSED row format for innodb_default_row_format option. */
349 enum default_row_format_enum {
350 DEFAULT_ROW_FORMAT_REDUNDANT = 0,
351 DEFAULT_ROW_FORMAT_COMPACT = 1,
352 DEFAULT_ROW_FORMAT_DYNAMIC = 2,
353 };
354
355 #if defined(_WIN32) || defined(_WIN64)
356 #include <Windows.h>
357 static double get_mem_GlobalMemoryStatus() {
358 MEMORYSTATUSEX ms;
359 ms.dwLength = sizeof(ms);
360 GlobalMemoryStatusEx(&ms);
361 return (((double)ms.ullTotalPhys) / GB);
362 }
363 #undef get_sys_mem
364 #define get_sys_mem get_mem_GlobalMemoryStatus
365 #else
366 static double get_mem_sysconf() {
367 return (((double)sysconf(_SC_PHYS_PAGES)) *
368 ((double)sysconf(_SC_PAGESIZE) / GB));
369 }
370 #undef get_sys_mem
371 #define get_sys_mem get_mem_sysconf
372 #endif /* defined(_WIN32) || defined(_WIN64) */
373
374 /** Release all acquired services from mysql server. */
375 static void release_plugin_services() {
376 if (reg_svc == nullptr) {
377 return;
378 }
379
380 if (sysvar_source_svc != nullptr) {
381 using sysvar_source_svc_t = SERVICE_TYPE_NO_CONST(system_variable_source);
382 reg_svc->release(reinterpret_cast<my_h_service>(
383 const_cast<sysvar_source_svc_t *>(sysvar_source_svc)));
384 sysvar_source_svc = nullptr;
385 }
386
387 if (clone_protocol_svc != nullptr) {
388 using clone_protocol_t = SERVICE_TYPE_NO_CONST(clone_protocol);
389 reg_svc->release(reinterpret_cast<my_h_service>(
390 const_cast<clone_protocol_t *>(clone_protocol_svc)));
391 clone_protocol_svc = nullptr;
392 }
393
394 /* Release registry service */
395 mysql_plugin_registry_release(reg_svc);
396 reg_svc = nullptr;
397 }
398
399 /** Acquire required services from mysql server. */
400 static void acquire_plugin_services() {
401 /* Acquire mysql_server's registry service */
402 reg_svc = mysql_plugin_registry_acquire();
403
404 if (reg_svc == nullptr) {
405 ib::warn(ER_IB_WRN_FAILED_TO_ACQUIRE_SERVICE, "plugin registry");
406 return;
407 }
408
409 my_h_service service;
410
411 /* Acquire system_variable_source service */
412 if (reg_svc->acquire("system_variable_source", &service)) {
413 ib::warn(ER_IB_WRN_FAILED_TO_ACQUIRE_SERVICE, "system_variable_source");
414
415 } else {
416 sysvar_source_svc =
417 reinterpret_cast<SERVICE_TYPE(system_variable_source) *>(service);
418 }
419
420 /* Acquire clone protocol service handle. */
421 if (reg_svc->acquire("clone_protocol", &service)) {
422 ib::warn(ER_IB_WRN_FAILED_TO_ACQUIRE_SERVICE, "clone_protocol");
423
424 } else {
425 clone_protocol_svc =
426 reinterpret_cast<SERVICE_TYPE(clone_protocol) *>(service);
427 }
428 }
429
430 /** Return the InnoDB ROW_FORMAT enum value
431 @param[in] row_format row_format from "innodb_default_row_format"
432 @return InnoDB ROW_FORMAT value from rec_format_t enum. */
433 static rec_format_t get_row_format(ulong row_format) {
434 switch (row_format) {
435 case DEFAULT_ROW_FORMAT_REDUNDANT:
436 return (REC_FORMAT_REDUNDANT);
437 case DEFAULT_ROW_FORMAT_COMPACT:
438 return (REC_FORMAT_COMPACT);
439 case DEFAULT_ROW_FORMAT_DYNAMIC:
440 return (REC_FORMAT_DYNAMIC);
441 default:
442 ut_d(ut_error);
443 ut_o(return (REC_FORMAT_DYNAMIC));
444 }
445 }
446
447 /** Note that a transaction has been deregistered.
448 @param[in] trx transaction */
449 static void trx_deregister_from_2pc(trx_t *trx);
450 static ulong innodb_default_row_format = DEFAULT_ROW_FORMAT_DYNAMIC;
451
452 #ifdef UNIV_DEBUG
453 /** Values for --innodb-debug-compress names. */
454 static const char *innodb_debug_compress_names[] = {"none", "zlib", "lz4",
455 "lz4hc", NullS};
456
457 /** Enumeration of --innodb-debug-compress */
458 static TYPELIB innodb_debug_compress_typelib = {
459 array_elements(innodb_debug_compress_names) - 1,
460 "innodb_debug_compress_typelib", innodb_debug_compress_names, nullptr};
461 #endif /* UNIV_DEBUG */
462
463 /** Possible values for system variable "innodb_stats_method". The values
464 are defined the same as its corresponding MyISAM system variable
465 "myisam_stats_method"(see "myisam_stats_method_names"), for better usability */
466 static const char *innodb_stats_method_names[] = {
467 "nulls_equal", "nulls_unequal", "nulls_ignored", NullS};
468
469 /** Used to define an enumerate type of the system variable innodb_stats_method.
470 This is the same as "myisam_stats_method_typelib" */
471 static TYPELIB innodb_stats_method_typelib = {
472 array_elements(innodb_stats_method_names) - 1,
473 "innodb_stats_method_typelib", innodb_stats_method_names, nullptr};
474
475 #endif /* UNIV_HOTBACKUP */
476
477 /** Possible values of the parameter innodb_checksum_algorithm */
478 static const char *innodb_checksum_algorithm_names[] = {
479 "crc32", "strict_crc32", "innodb", "strict_innodb",
480 "none", "strict_none", NullS};
481
482 /** Used to define an enumerate type of the system variable
483 innodb_checksum_algorithm. */
484 static TYPELIB innodb_checksum_algorithm_typelib = {
485 array_elements(innodb_checksum_algorithm_names) - 1,
486 "innodb_checksum_algorithm_typelib", innodb_checksum_algorithm_names,
487 nullptr};
488
489 #ifndef UNIV_HOTBACKUP
490 /** Names of allowed values of innodb_flush_method */
491 static const char *innodb_flush_method_names[] = {
492 #ifndef _WIN32 /* See srv_unix_flush_t */
493 "fsync", "O_DSYNC", "littlesync", "nosync", "O_DIRECT", "O_DIRECT_NO_FSYNC",
494 #else /* _WIN32; see srv_win_flush_t */
495 "unbuffered", "normal",
496 #endif
497 NullS};
498
499 /** Enumeration of innodb_flush_method */
500 static TYPELIB innodb_flush_method_typelib = {
501 array_elements(innodb_flush_method_names) - 1,
502 "innodb_flush_method_typelib", innodb_flush_method_names, nullptr};
503
504 /** Possible values for system variable "innodb_default_row_format". */
505 static const char *innodb_default_row_format_names[] = {"redundant", "compact",
506 "dynamic", NullS};
507
508 /** Used to define an enumerate type of the system variable
509 innodb_default_row_format. */
510 static TYPELIB innodb_default_row_format_typelib = {
511 array_elements(innodb_default_row_format_names) - 1,
512 "innodb_default_row_format_typelib", innodb_default_row_format_names,
513 nullptr};
514
515 /** Possible values for system variable "innodb_doublewrite".
516 @note: If you change order or add new values, please update dblwr::mode_t. */
517 static const char *innodb_doublewrite_names[] = {
518 "OFF", "ON", "DETECT_ONLY", "DETECT_AND_RECOVER", "FALSE", "TRUE", NullS};
519
520 /** Used to define an enumerate type of the system variable
521 innodb_default_row_format. */
522 static TYPELIB innodb_doublewrite_typelib = {
523 array_elements(innodb_doublewrite_names) - 1, "innodb_doublewrite_typelib",
524 innodb_doublewrite_names, nullptr};
525
526 #else /* !UNIV_HOTBACKUP */
527
528 /** Returns the name of the checksum algorithm corresponding to the
529 algorithm id given by "algo_enum" parameter.
530 @param[in] algo_enum algorithm enumerator
531 @return C-string algorithm name */
532 const char *meb_get_checksum_algorithm_name(
533 srv_checksum_algorithm_t algo_enum) {
534 return (get_type(&innodb_checksum_algorithm_typelib, algo_enum));
535 }
536
537 /** Retrieves the enum corresponding to the checksum algorithm
538 name specified by algo_name. If the call succeeds, returns
539 true and checksum algorithm enum is returned in algo_enum.
540 @param[in] algo_name algorithm name
541 @param[out] algo_enum algorithm enumerator
542 @retval true if successful
543 @retval false if algorithn name not found */
544 bool meb_get_checksum_algorithm_enum(const char *algo_name,
545 srv_checksum_algorithm_t &algo_enum) {
546 int type =
547 find_type(algo_name, &innodb_checksum_algorithm_typelib, FIND_TYPE_BASIC);
548 if (type <= 0) {
549 /** Invalid algorithm name */
550 return false;
551 } else {
552 algo_enum = srv_checksum_algorithm_t(type - 1);
553 }
554
555 return true;
556 }
557 #endif /* !UNIV_HOTBACKUP */
558
559 #ifndef UNIV_HOTBACKUP
560 /* The following counter is used to convey information to InnoDB
561 about server activity: in case of normal DML ops it is not
562 sensible to call srv_active_wake_master_thread after each
563 operation, we only do it every INNOBASE_WAKE_INTERVAL'th step. */
564
565 constexpr uint32_t INNOBASE_WAKE_INTERVAL = 32;
566 static ulong innobase_active_counter = 0;
567
568 static hash_table_t *innobase_open_tables;
569
570 /** Array of data files of the system tablespace */
571 static std::vector<Plugin_tablespace::Plugin_tablespace_file *,
572 ut::allocator<Plugin_tablespace::Plugin_tablespace_file *>>
573 innobase_sys_files;
574
575 /** Allowed values of innodb_change_buffering */
576 static const char *innodb_change_buffering_names[] = {
577 "none", /* IBUF_USE_NONE */
578 "inserts", /* IBUF_USE_INSERT */
579 "deletes", /* IBUF_USE_DELETE_MARK */
580 "changes", /* IBUF_USE_INSERT_DELETE_MARK */
581 "purges", /* IBUF_USE_DELETE */
582 "all", /* IBUF_USE_ALL */
583 NullS};
584
585 /** Enumeration of innodb_change_buffering */
586 static TYPELIB innodb_change_buffering_typelib = {
587 array_elements(innodb_change_buffering_names) - 1,
588 "innodb_change_buffering_typelib", innodb_change_buffering_names, nullptr};
589
590 /** Retrieve the FTS Relevance Ranking result for doc with doc_id
591 of m_prebuilt->fts_doc_id
592 @param[in,out] fts_hdl FTS handler
593 @return the relevance ranking value */
594 static float innobase_fts_retrieve_ranking(FT_INFO *fts_hdl);
595 /** Free the memory for the FTS handler
596 @param[in,out] fts_hdl FTS handler */
597 static void innobase_fts_close_ranking(FT_INFO *fts_hdl);
598
599 /** Find and Retrieve the FTS Relevance Ranking result for doc with doc_id
600 of m_prebuilt->fts_doc_id
601 @param[in,out] fts_hdl FTS handler
602 @return the relevance ranking value */
603 static float innobase_fts_find_ranking(FT_INFO *fts_hdl, uchar *, uint);
604
605 /* Call back function array defined by MySQL and used to
606 retrieve FTS results. */
607 const struct _ft_vft ft_vft_result = {nullptr, innobase_fts_find_ranking,
608 innobase_fts_close_ranking,
609 innobase_fts_retrieve_ranking, nullptr};
610
611 /** @return version of the extended FTS API */
612 static uint innobase_fts_get_version() {
613 /* Currently this doesn't make much sense as returning
614 HA_CAN_FULLTEXT_EXT automatically mean this version is supported.
615 This supposed to ease future extensions. */
616 return (2);
617 }
618
619 /** @return Which part of the extended FTS API is supported */
620 static ulonglong innobase_fts_flags() {
621 return (FTS_ORDERED_RESULT | FTS_DOCID_IN_RESULT);
622 }
623
624 /** Find and Retrieve the FTS doc_id for the current result row
625 @param[in,out] fts_hdl FTS handler
626 @return the document ID */
627 static ulonglong innobase_fts_retrieve_docid(FT_INFO_EXT *fts_hdl);
628
629 /** Find and retrieve the size of the current result
630 @param[in,out] fts_hdl FTS handler
631 @return number of matching rows */
632 static ulonglong innobase_fts_count_matches(
633 FT_INFO_EXT *fts_hdl) /*!< in: FTS handler */
634 {
635 NEW_FT_INFO *handle = reinterpret_cast<NEW_FT_INFO *>(fts_hdl);
636
637 if (handle->ft_result->rankings_by_id != nullptr) {
638 return (rbt_size(handle->ft_result->rankings_by_id));
639 } else {
640 return (0);
641 }
642 }
643
644 const struct _ft_vft_ext ft_vft_ext_result = {
645 innobase_fts_get_version, innobase_fts_flags, innobase_fts_retrieve_docid,
646 innobase_fts_count_matches};
647
648 #ifdef HAVE_PSI_INTERFACE
649 #define PSI_KEY(n, flag, volatility, doc) \
650 { &(n##_key.m_value), #n, flag, volatility, doc }
651 #define PSI_MEMORY_KEY(n, flag, volatility, doc) \
652 { &(n##_key), #n, flag, volatility, doc }
653 #define PSI_MUTEX_KEY(n, flag, volatility, doc) \
654 { &(n##_key.m_value), #n, flag, volatility, doc }
655 /* All RWLOCK used in Innodb are SX-locks */
656 #define PSI_RWLOCK_KEY(n, volatility, doc) \
657 { &n##_key.m_value, #n, PSI_FLAG_RWLOCK_SX, volatility, doc }
658 #define PSI_THREAD_KEY(n, osn, flag, volatility, doc) \
659 { &(n##_key.m_value), #n, osn, flag, volatility, doc }
660
661 /* Keys to register pthread mutexes/cond in the current file with
662 performance schema */
663 static mysql_pfs_key_t innobase_share_mutex_key;
664 static mysql_pfs_key_t commit_cond_mutex_key;
665 static mysql_pfs_key_t commit_cond_key;
666 mysql_pfs_key_t resume_encryption_cond_mutex_key;
667 mysql_pfs_key_t resume_encryption_cond_key;
668
669 static PSI_mutex_info all_pthread_mutexes[] = {
670 PSI_MUTEX_KEY(commit_cond_mutex, 0, 0, PSI_DOCUMENT_ME),
671 PSI_MUTEX_KEY(innobase_share_mutex, 0, 0, PSI_DOCUMENT_ME),
672 PSI_MUTEX_KEY(resume_encryption_cond_mutex, 0, 0, PSI_DOCUMENT_ME)};
673
674 static PSI_cond_info all_innodb_conds[] = {
675 PSI_KEY(commit_cond, 0, 0, PSI_DOCUMENT_ME),
676 PSI_KEY(resume_encryption_cond, 0, 0, PSI_DOCUMENT_ME)};
677
678 #ifdef UNIV_PFS_MEMORY
679 /* pfs keys related to memory that is performance schema instrumented
680 when "UNIV_PFS_MEMORY" is defined */
681 static PSI_memory_info pfs_instrumented_innodb_memory[] = {
682 PSI_MEMORY_KEY(log_buffer_memory, 0, 0, "Redo log buffer")};
683 #endif /* UNIV_PFS_MEMORY */
684
685 #ifdef UNIV_PFS_MUTEX
686 /* all_innodb_mutexes array contains mutexes that are
687 performance schema instrumented if "UNIV_PFS_MUTEX"
688 is defined */
689 static PSI_mutex_info all_innodb_mutexes[] = {
690 PSI_MUTEX_KEY(alter_stage_mutex, 0, 0, PSI_DOCUMENT_ME),
691 PSI_MUTEX_KEY(autoinc_mutex, 0, 0, PSI_DOCUMENT_ME),
692 PSI_MUTEX_KEY(autoinc_persisted_mutex, 0, 0, PSI_DOCUMENT_ME),
693 #ifndef PFS_SKIP_BUFFER_MUTEX_RWLOCK
694 PSI_MUTEX_KEY(buffer_block_mutex, 0, 0, PSI_DOCUMENT_ME),
695 #endif /* !PFS_SKIP_BUFFER_MUTEX_RWLOCK */
696 PSI_MUTEX_KEY(buf_pool_chunks_mutex, 0, 0, PSI_DOCUMENT_ME),
697 PSI_MUTEX_KEY(buf_pool_flush_state_mutex, 0, 0, PSI_DOCUMENT_ME),
698 PSI_MUTEX_KEY(buf_pool_LRU_list_mutex, 0, 0, PSI_DOCUMENT_ME),
699 PSI_MUTEX_KEY(buf_pool_free_list_mutex, 0, 0, PSI_DOCUMENT_ME),
700 PSI_MUTEX_KEY(buf_pool_zip_free_mutex, 0, 0, PSI_DOCUMENT_ME),
701 PSI_MUTEX_KEY(buf_pool_zip_hash_mutex, 0, 0, PSI_DOCUMENT_ME),
702 PSI_MUTEX_KEY(buf_pool_zip_mutex, 0, 0, PSI_DOCUMENT_ME),
703 PSI_MUTEX_KEY(clone_snapshot_mutex, 0, 0, PSI_DOCUMENT_ME),
704 PSI_MUTEX_KEY(clone_sys_mutex, 0, 0, PSI_DOCUMENT_ME),
705 PSI_MUTEX_KEY(clone_task_mutex, 0, 0, PSI_DOCUMENT_ME),
706 PSI_MUTEX_KEY(ddl_autoinc_mutex, 0, 0, PSI_DOCUMENT_ME),
707 PSI_MUTEX_KEY(dict_foreign_err_mutex, 0, 0, PSI_DOCUMENT_ME),
708 PSI_MUTEX_KEY(dict_persist_dirty_tables_mutex, 0, 0, PSI_DOCUMENT_ME),
709 PSI_MUTEX_KEY(dict_sys_mutex, 0, 0, PSI_DOCUMENT_ME),
710 PSI_MUTEX_KEY(dict_table_mutex, 0, 0, PSI_DOCUMENT_ME),
711 PSI_MUTEX_KEY(parser_mutex, 0, 0, PSI_DOCUMENT_ME),
712 PSI_MUTEX_KEY(recalc_pool_mutex, 0, 0, PSI_DOCUMENT_ME),
713 PSI_MUTEX_KEY(fil_system_mutex, 0, 0, PSI_DOCUMENT_ME),
714 PSI_MUTEX_KEY(file_open_mutex, 0, 0, PSI_DOCUMENT_ME),
715 PSI_MUTEX_KEY(flush_list_mutex, 0, 0, PSI_DOCUMENT_ME),
716 PSI_MUTEX_KEY(fts_bg_threads_mutex, 0, 0, PSI_DOCUMENT_ME),
717 PSI_MUTEX_KEY(fts_delete_mutex, 0, 0, PSI_DOCUMENT_ME),
718 PSI_MUTEX_KEY(fts_optimize_mutex, 0, 0, PSI_DOCUMENT_ME),
719 PSI_MUTEX_KEY(fts_doc_id_mutex, 0, 0, PSI_DOCUMENT_ME),
720 PSI_MUTEX_KEY(fts_pll_tokenize_mutex, 0, 0, PSI_DOCUMENT_ME),
721 PSI_MUTEX_KEY(hash_table_mutex, 0, 0, PSI_DOCUMENT_ME),
722 PSI_MUTEX_KEY(ibuf_bitmap_mutex, 0, 0, PSI_DOCUMENT_ME),
723 PSI_MUTEX_KEY(ibuf_mutex, 0, 0, PSI_DOCUMENT_ME),
724 PSI_MUTEX_KEY(ibuf_pessimistic_insert_mutex, 0, 0, PSI_DOCUMENT_ME),
725 PSI_MUTEX_KEY(lock_free_hash_mutex, 0, 0, PSI_DOCUMENT_ME),
726 PSI_MUTEX_KEY(log_limits_mutex, 0, 0, PSI_DOCUMENT_ME),
727 PSI_MUTEX_KEY(log_files_mutex, 0, 0, PSI_DOCUMENT_ME),
728 PSI_MUTEX_KEY(log_checkpointer_mutex, 0, 0, PSI_DOCUMENT_ME),
729 PSI_MUTEX_KEY(log_closer_mutex, 0, 0, PSI_DOCUMENT_ME),
730 PSI_MUTEX_KEY(log_writer_mutex, 0, 0, PSI_DOCUMENT_ME),
731 PSI_MUTEX_KEY(log_flusher_mutex, 0, 0, PSI_DOCUMENT_ME),
732 PSI_MUTEX_KEY(log_write_notifier_mutex, 0, 0, PSI_DOCUMENT_ME),
733 PSI_MUTEX_KEY(log_flush_notifier_mutex, 0, 0, PSI_DOCUMENT_ME),
734 PSI_MUTEX_KEY(log_sys_arch_mutex, 0, 0, PSI_DOCUMENT_ME),
735 PSI_MUTEX_KEY(log_cmdq_mutex, 0, 0, PSI_DOCUMENT_ME),
736 PSI_MUTEX_KEY(log_sn_mutex, 0, 0, PSI_DOCUMENT_ME),
737 PSI_MUTEX_KEY(mutex_list_mutex, 0, 0, PSI_DOCUMENT_ME),
738 PSI_MUTEX_KEY(page_sys_arch_mutex, 0, 0, PSI_DOCUMENT_ME),
739 PSI_MUTEX_KEY(page_sys_arch_oper_mutex, 0, 0, PSI_DOCUMENT_ME),
740 PSI_MUTEX_KEY(page_sys_arch_client_mutex, 0, 0, PSI_DOCUMENT_ME),
741 PSI_MUTEX_KEY(page_zip_stat_per_index_mutex, 0, 0, PSI_DOCUMENT_ME),
742 PSI_MUTEX_KEY(page_cleaner_mutex, 0, 0, PSI_DOCUMENT_ME),
743 PSI_MUTEX_KEY(parallel_read_mutex, 0, 0, PSI_DOCUMENT_ME),
744 PSI_MUTEX_KEY(dblwr_mutex, 0, 0, PSI_DOCUMENT_ME),
745 PSI_MUTEX_KEY(purge_sys_pq_mutex, 0, 0, PSI_DOCUMENT_ME),
746 PSI_MUTEX_KEY(recv_sys_mutex, 0, 0, PSI_DOCUMENT_ME),
747 PSI_MUTEX_KEY(recv_writer_mutex, 0, 0, PSI_DOCUMENT_ME),
748 PSI_MUTEX_KEY(temp_space_rseg_mutex, 0, 0, PSI_DOCUMENT_ME),
749 PSI_MUTEX_KEY(undo_space_rseg_mutex, 0, 0, PSI_DOCUMENT_ME),
750 PSI_MUTEX_KEY(trx_sys_rseg_mutex, 0, 0, PSI_DOCUMENT_ME),
751 #ifdef UNIV_DEBUG
752 PSI_MUTEX_KEY(rw_lock_debug_mutex, 0, 0, PSI_DOCUMENT_ME),
753 #endif /* UNIV_DEBUG */
754 PSI_MUTEX_KEY(rw_lock_list_mutex, 0, 0, PSI_DOCUMENT_ME),
755 PSI_MUTEX_KEY(rw_lock_mutex, 0, 0, PSI_DOCUMENT_ME),
756 PSI_MUTEX_KEY(srv_innodb_monitor_mutex, 0, 0, PSI_DOCUMENT_ME),
757 PSI_MUTEX_KEY(srv_misc_tmpfile_mutex, 0, 0, PSI_DOCUMENT_ME),
758 PSI_MUTEX_KEY(srv_monitor_file_mutex, 0, 0, PSI_DOCUMENT_ME),
759 #ifdef UNIV_DEBUG
760 PSI_MUTEX_KEY(sync_thread_mutex, 0, 0, PSI_DOCUMENT_ME),
761 #endif /* UNIV_DEBUG */
762 PSI_MUTEX_KEY(trx_undo_mutex, 0, 0, PSI_DOCUMENT_ME),
763 PSI_MUTEX_KEY(trx_pool_mutex, 0, 0, PSI_DOCUMENT_ME),
764 PSI_MUTEX_KEY(trx_pool_manager_mutex, 0, 0, PSI_DOCUMENT_ME),
765 PSI_MUTEX_KEY(temp_pool_manager_mutex, 0, 0, PSI_DOCUMENT_ME),
766 PSI_MUTEX_KEY(srv_sys_mutex, 0, 0, PSI_DOCUMENT_ME),
767 PSI_MUTEX_KEY(lock_sys_page_mutex, 0, 0, PSI_DOCUMENT_ME),
768 PSI_MUTEX_KEY(lock_sys_table_mutex, 0, 0, PSI_DOCUMENT_ME),
769 PSI_MUTEX_KEY(lock_wait_mutex, 0, 0, PSI_DOCUMENT_ME),
770 PSI_MUTEX_KEY(trx_mutex, 0, 0, PSI_DOCUMENT_ME),
771 PSI_MUTEX_KEY(srv_threads_mutex, 0, 0, PSI_DOCUMENT_ME),
772 #ifndef PFS_SKIP_EVENT_MUTEX
773 PSI_MUTEX_KEY(event_mutex, 0, 0, PSI_DOCUMENT_ME),
774 PSI_MUTEX_KEY(event_manager_mutex, 0, 0, PSI_DOCUMENT_ME),
775 #endif /* PFS_SKIP_EVENT_MUTEX */
776 PSI_MUTEX_KEY(rtr_active_mutex, 0, 0, PSI_DOCUMENT_ME),
777 PSI_MUTEX_KEY(rtr_match_mutex, 0, 0, PSI_DOCUMENT_ME),
778 PSI_MUTEX_KEY(rtr_path_mutex, 0, 0, PSI_DOCUMENT_ME),
779 PSI_MUTEX_KEY(rtr_ssn_mutex, 0, 0, PSI_DOCUMENT_ME),
780 PSI_MUTEX_KEY(trx_sys_mutex, 0, 0, PSI_DOCUMENT_ME),
781 PSI_MUTEX_KEY(trx_sys_shard_mutex, 0, 0, PSI_DOCUMENT_ME),
782 PSI_MUTEX_KEY(trx_sys_serialisation_mutex, 0, 0, PSI_DOCUMENT_ME),
783 PSI_MUTEX_KEY(zip_pad_mutex, 0, 0, PSI_DOCUMENT_ME),
784 PSI_MUTEX_KEY(master_key_id_mutex, 0, 0, PSI_DOCUMENT_ME),
785 PSI_MUTEX_KEY(sync_array_mutex, 0, 0, PSI_DOCUMENT_ME),
786 PSI_MUTEX_KEY(row_drop_list_mutex, 0, 0, PSI_DOCUMENT_ME),
787 PSI_MUTEX_KEY(ahi_enabled_mutex, 0, 0,
788 "Mutex used for AHI disabling and enabling.")};
789 #endif /* UNIV_PFS_MUTEX */
790
791 #ifdef UNIV_PFS_RWLOCK
792 /* all_innodb_rwlocks array contains rwlocks that are
793 performance schema instrumented if "UNIV_PFS_RWLOCK"
794 is defined */
795 static PSI_rwlock_info all_innodb_rwlocks[] = {
796 PSI_RWLOCK_KEY(btr_search_latch, 0, PSI_DOCUMENT_ME),
797 #ifndef PFS_SKIP_BUFFER_MUTEX_RWLOCK
798 PSI_RWLOCK_KEY(buf_block_lock, 0, PSI_DOCUMENT_ME),
799 #endif /* !PFS_SKIP_BUFFER_MUTEX_RWLOCK */
800 #ifdef UNIV_DEBUG
801 PSI_RWLOCK_KEY(buf_block_debug_latch, 0, PSI_DOCUMENT_ME),
802 #endif /* UNIV_DEBUG */
803 PSI_RWLOCK_KEY(dict_operation_lock, 0, PSI_DOCUMENT_ME),
804 PSI_RWLOCK_KEY(fil_space_latch, 0, PSI_DOCUMENT_ME),
805 PSI_RWLOCK_KEY(log_sn_lock, 0, PSI_DOCUMENT_ME),
806 PSI_RWLOCK_KEY(undo_spaces_lock, 0, PSI_DOCUMENT_ME),
807 PSI_RWLOCK_KEY(rsegs_lock, 0, PSI_DOCUMENT_ME),
808 PSI_RWLOCK_KEY(lock_sys_global_rw_lock, 0, PSI_DOCUMENT_ME),
809 PSI_RWLOCK_KEY(fts_cache_rw_lock, 0, PSI_DOCUMENT_ME),
810 PSI_RWLOCK_KEY(fts_cache_init_rw_lock, 0, PSI_DOCUMENT_ME),
811 PSI_RWLOCK_KEY(trx_i_s_cache_lock, 0, PSI_DOCUMENT_ME),
812 PSI_RWLOCK_KEY(trx_purge_latch, 0, PSI_DOCUMENT_ME),
813 PSI_RWLOCK_KEY(index_tree_rw_lock, 0, PSI_DOCUMENT_ME),
814 PSI_RWLOCK_KEY(index_online_log, 0, PSI_DOCUMENT_ME),
815 PSI_RWLOCK_KEY(dict_table_stats, 0, PSI_DOCUMENT_ME),
816 PSI_RWLOCK_KEY(hash_table_locks, 0, PSI_DOCUMENT_ME),
817 };
818 #endif /* UNIV_PFS_RWLOCK */
819
820 #ifdef UNIV_PFS_THREAD
821 /* all_innodb_threads array contains threads that are
822 performance schema instrumented if "UNIV_PFS_THREAD"
823 is defined */
824 static PSI_thread_info all_innodb_threads[] = {
825 PSI_THREAD_KEY(log_archiver_thread, "ib_log_arch", PSI_FLAG_SINGLETON, 0,
826 PSI_DOCUMENT_ME),
827 PSI_THREAD_KEY(page_archiver_thread, "ib_page_arch", PSI_FLAG_SINGLETON, 0,
828 PSI_DOCUMENT_ME),
829 PSI_THREAD_KEY(buf_pool_create_thread, "ib_buf_create", PSI_FLAG_SINGLETON,
830 0, PSI_DOCUMENT_ME),
831 PSI_THREAD_KEY(buf_dump_thread, "ib_buf_dump", PSI_FLAG_SINGLETON, 0,
832 PSI_DOCUMENT_ME),
833 PSI_THREAD_KEY(clone_ddl_thread, "ib_clone_ddl", PSI_FLAG_SINGLETON, 0,
834 PSI_DOCUMENT_ME),
835 PSI_THREAD_KEY(clone_gtid_thread, "ib_clone_gtid", PSI_FLAG_SINGLETON, 0,
836 PSI_DOCUMENT_ME),
837 PSI_THREAD_KEY(ddl_thread, "ib_ddl", 0, 0, PSI_DOCUMENT_ME),
838 PSI_THREAD_KEY(dict_stats_thread, "ib_dict_stats", PSI_FLAG_SINGLETON, 0,
839 PSI_DOCUMENT_ME),
840 PSI_THREAD_KEY(io_ibuf_thread, "ib_io_ibuf", PSI_FLAG_SINGLETON, 0,
841 PSI_DOCUMENT_ME),
842 PSI_THREAD_KEY(io_read_thread, "ib_io_rd", 0, 0, PSI_DOCUMENT_ME),
843 PSI_THREAD_KEY(io_write_thread, "ib_io_wr", 0, 0, PSI_DOCUMENT_ME),
844 PSI_THREAD_KEY(buf_resize_thread, "ib_buf_resize", PSI_FLAG_SINGLETON, 0,
845 PSI_DOCUMENT_ME),
846 PSI_THREAD_KEY(log_files_governor_thread, "ib_log_files_g",
847 PSI_FLAG_SINGLETON, 0, PSI_DOCUMENT_ME),
848 PSI_THREAD_KEY(log_writer_thread, "ib_log_writer", PSI_FLAG_SINGLETON, 0,
849 PSI_DOCUMENT_ME),
850 PSI_THREAD_KEY(log_checkpointer_thread, "ib_log_checkpt",
851 PSI_FLAG_SINGLETON, 0, PSI_DOCUMENT_ME),
852 PSI_THREAD_KEY(log_flusher_thread, "ib_log_flush", PSI_FLAG_SINGLETON, 0,
853 PSI_DOCUMENT_ME),
854 PSI_THREAD_KEY(log_write_notifier_thread, "ib_log_wr_notif",
855 PSI_FLAG_SINGLETON, 0, PSI_DOCUMENT_ME),
856 PSI_THREAD_KEY(log_flush_notifier_thread, "ib_log_fl_notif",
857 PSI_FLAG_SINGLETON, 0, PSI_DOCUMENT_ME),
858 PSI_THREAD_KEY(recv_writer_thread, "ib_recv_write", PSI_FLAG_SINGLETON, 0,
859 PSI_DOCUMENT_ME),
860 PSI_THREAD_KEY(srv_error_monitor_thread, "ib_srv_err_mon",
861 PSI_FLAG_SINGLETON, 0, PSI_DOCUMENT_ME),
862 PSI_THREAD_KEY(srv_lock_timeout_thread, "ib_srv_lock_to",
863 PSI_FLAG_SINGLETON, 0, PSI_DOCUMENT_ME),
864 PSI_THREAD_KEY(srv_master_thread, "ib_src_main", PSI_FLAG_SINGLETON, 0,
865 PSI_DOCUMENT_ME),
866 PSI_THREAD_KEY(srv_monitor_thread, "ib_srv_mon", PSI_FLAG_SINGLETON, 0,
867 PSI_DOCUMENT_ME),
868 PSI_THREAD_KEY(srv_purge_thread, "ib_srv_purge", PSI_FLAG_SINGLETON, 0,
869 PSI_DOCUMENT_ME),
870 PSI_THREAD_KEY(srv_worker_thread, "ib_srv_wkr", 0, 0, PSI_DOCUMENT_ME),
871 PSI_THREAD_KEY(trx_recovery_rollback_thread, "ib_tx_recov", 0, 0,
872 PSI_DOCUMENT_ME),
873 PSI_THREAD_KEY(page_flush_thread, "ib_pg_flush", 0, 0, PSI_DOCUMENT_ME),
874 PSI_THREAD_KEY(page_flush_coordinator_thread, "ib_pg_flush_co",
875 PSI_FLAG_SINGLETON, 0, PSI_DOCUMENT_ME),
876 PSI_THREAD_KEY(fts_optimize_thread, "ib_fts_opt", PSI_FLAG_SINGLETON, 0,
877 PSI_DOCUMENT_ME),
878 PSI_THREAD_KEY(fts_parallel_merge_thread, "ib_fts_merge", 0, 0,
879 PSI_DOCUMENT_ME),
880 PSI_THREAD_KEY(fts_parallel_tokenization_thread, "ib_fts_token", 0, 0,
881 PSI_DOCUMENT_ME),
882 PSI_THREAD_KEY(srv_ts_alter_encrypt_thread, "ib_ts_encrypt",
883 PSI_FLAG_SINGLETON, 0, PSI_DOCUMENT_ME),
884 PSI_THREAD_KEY(parallel_read_thread, "ib_par_rd", 0, 0, PSI_DOCUMENT_ME),
885 PSI_THREAD_KEY(parallel_rseg_init_thread, "ib_par_rseg", 0, 0,
886 PSI_DOCUMENT_ME),
887 PSI_THREAD_KEY(meb::redo_log_archive_consumer_thread, "ib_meb_rl",
888 PSI_FLAG_SINGLETON, 0, PSI_DOCUMENT_ME)};
889 #endif /* UNIV_PFS_THREAD */
890
891 #ifdef UNIV_PFS_IO
892 /* all_innodb_files array contains the type of files that are
893 performance schema instrumented if "UNIV_PFS_IO" is defined */
894 static PSI_file_info all_innodb_files[] = {
895 PSI_KEY(innodb_dblwr_file, 0, 0, PSI_DOCUMENT_ME),
896 PSI_KEY(innodb_tablespace_open_file, 0, 0, PSI_DOCUMENT_ME),
897 PSI_KEY(innodb_data_file, 0, 0, PSI_DOCUMENT_ME),
898 PSI_KEY(innodb_log_file, 0, 0, PSI_DOCUMENT_ME),
899 PSI_KEY(innodb_temp_file, 0, 0, PSI_DOCUMENT_ME),
900 PSI_KEY(innodb_arch_file, 0, 0, PSI_DOCUMENT_ME),
901 PSI_KEY(innodb_clone_file, 0, 0, PSI_DOCUMENT_ME),
902 PSI_KEY(meb::redo_log_archive_file, 0, 0, PSI_DOCUMENT_ME)};
903 #endif /* UNIV_PFS_IO */
904 #endif /* HAVE_PSI_INTERFACE */
905
906 /** Plugin update function to handle validation and then switch the
907 innodb_doublewrite mode
908 @param[in] thd thread handle
909 @param[in] var pointer to system variable
910 @param[in] var_ptr where the formal string goes
911 @param[in] save immediate result from check function */
912 static void doublewrite_update(THD *thd [[maybe_unused]],
913 SYS_VAR *var [[maybe_unused]], void *var_ptr,
914 const void *save) {
915 ulong new_value = *static_cast<const ulong *>(save);
916
917 if (dblwr::Mode::is_enabled_to_disabled(new_value)) {
918 char msg[FN_REFLEN];
919 snprintf(msg, sizeof(msg),
920 "InnoDB: cannot change doublewrite mode to %s if"
921 " doublewrite is enabled. Please shutdown and"
922 " change value to %s",
923 dblwr::Mode::to_string(new_value),
924 dblwr::Mode::to_string(new_value));
925 my_error(ER_WRONG_ARGUMENTS, MYF(0), msg);
926 return;
927 }
928
929 if (dblwr::Mode::is_disabled_to_enabled(new_value)) {
930 char msg[FN_REFLEN];
931 snprintf(msg, sizeof(msg),
932 "InnoDB: cannot change doublewrite mode to %s if"
933 " doublewrite is disabled. Please shutdown and"
934 " change value to %s",
935 dblwr::Mode::to_string(new_value),
936 dblwr::Mode::to_string(new_value));
937
938 my_error(ER_WRONG_ARGUMENTS, MYF(0), msg);
939
940 return;
941 }
942
943 if (dblwr::Mode::is_same(new_value)) {
944 return;
945 }
946
947 /* Handle DETECT_AND_RECOVER to DETECT_ONLY
948 1. Check if DETECT_ONLY setup is already initialized. If not, initialize
949 DETECT_ONLY files and structures.
950 2. Flush the partially filled dblwr buffers. */
951 if (dblwr::Mode::is_reduced_low(new_value)) {
952 dberr_t err = dblwr::enable_reduced();
953 if (err != DB_SUCCESS) {
954 char msg[FN_REFLEN];
955 snprintf(msg, sizeof(msg),
956 "InnoDB: cannot change doublewrite mode to %s."
957 " Please check if doublewrite directory is writable"
958 " Error code: %d",
959 dblwr::Mode::to_string(new_value), err);
960 my_error(ER_WRONG_ARGUMENTS, MYF(0), msg);
961 return;
962 }
963 }
964
965 /* Handle DETECT_ONLY to DETECT_AND_RECOVER.
966 1. Flush partially filled reduced dblwr buffers */
967 dblwr::force_flush_all();
968
969 *static_cast<ulong *>(var_ptr) = *static_cast<const ulong *>(save);
970 }
971
972 /** Set up InnoDB API callback function array */
973 /*
974 Generates array elements which look like:
975 (ib_cb_t)ib_cursor_open_table,
976 for each api function.
977 */
978 #define INNODB_API_CB_ARRAY_ELEMENT_TRANSFORM(stem) (ib_cb_t) ib_##stem,
979
980 static ib_cb_t innodb_api_cb[] = {
981 FOR_EACH_API_METHOD_NAME_STEM(INNODB_API_CB_ARRAY_ELEMENT_TRANSFORM)};
982
983 static int innodb_check_session_admin(THD *thd, SYS_VAR *self, void *save,
984 struct st_mysql_value *value);
985
986 /**Check whether valid argument given to innobase_*_stopword_table.
987 This function is registered as a callback with MySQL.
988 @param[in] thd thread handle
989 @param[in] var pointer to system variable
990 @param[out] save immediate result for update function
991 @param[in] value incoming string
992 @return 0 for valid stopword table */
993 static int innodb_stopword_table_validate(THD *thd, SYS_VAR *var, void *save,
994 struct st_mysql_value *value);
995
996 /** Validate passed-in "value" is a valid directory name.
997 This function is registered as a callback with MySQL.
998 @param[in,out] thd thread handle
999 @param[out] save immediate result for update
1000 @param[in] value incoming string
1001 @return 0 for valid name */
1002 static int innodb_tmpdir_validate(THD *thd, SYS_VAR *, void *save,
1003 struct st_mysql_value *value) {
1004 char *alter_tmp_dir;
1005 char *innodb_tmp_dir;
1006 char buff[OS_FILE_MAX_PATH];
1007 int len = sizeof(buff);
1008 char tmp_abs_path[FN_REFLEN + 2];
1009
1010 ut_ad(save != nullptr);
1011 ut_ad(value != nullptr);
1012
1013 if (check_global_access(thd, FILE_ACL)) {
1014 push_warning_printf(thd, Sql_condition::SL_WARNING, ER_WRONG_ARGUMENTS,
1015 "InnoDB: FILE Permissions required");
1016 *static_cast<const char **>(save) = nullptr;
1017 return (1);
1018 }
1019
1020 alter_tmp_dir = (char *)value->val_str(value, buff, &len);
1021
1022 if (!alter_tmp_dir) {
1023 *static_cast<const char **>(save) = alter_tmp_dir;
1024 return (0);
1025 }
1026
1027 if (strlen(alter_tmp_dir) > FN_REFLEN) {
1028 push_warning_printf(thd, Sql_condition::SL_WARNING, ER_WRONG_ARGUMENTS,
1029 "Path length should not exceed %d bytes", FN_REFLEN);
1030 *static_cast<const char **>(save) = nullptr;
1031 return (1);
1032 }
1033
1034 Fil_path::normalize(alter_tmp_dir);
1035 my_realpath(tmp_abs_path, alter_tmp_dir, 0);
1036 size_t tmp_abs_len = strlen(tmp_abs_path);
1037
1038 if (my_access(tmp_abs_path, F_OK)) {
1039 push_warning_printf(thd, Sql_condition::SL_WARNING, ER_WRONG_ARGUMENTS,
1040 "InnoDB: Path doesn't exist.");
1041 *static_cast<const char **>(save) = nullptr;
1042 return (1);
1043 } else if (my_access(tmp_abs_path, R_OK | W_OK)) {
1044 push_warning_printf(thd, Sql_condition::SL_WARNING, ER_WRONG_ARGUMENTS,
1045 "InnoDB: Server doesn't have permission in "
1046 "the given location.");
1047 *static_cast<const char **>(save) = nullptr;
1048 return (1);
1049 }
1050
1051 MY_STAT stat_info_dir;
1052
1053 if (my_stat(tmp_abs_path, &stat_info_dir, MYF(0))) {
1054 if ((stat_info_dir.st_mode & S_IFDIR) != S_IFDIR) {
1055 push_warning_printf(thd, Sql_condition::SL_WARNING, ER_WRONG_ARGUMENTS,
1056 "Given path is not a directory. ");
1057 *static_cast<const char **>(save) = nullptr;
1058 return (1);
1059 }
1060 }
1061
1062 if (!is_mysql_datadir_path(tmp_abs_path)) {
1063 push_warning_printf(thd, Sql_condition::SL_WARNING, ER_WRONG_ARGUMENTS,
1064 "InnoDB: Path location should not be same as "
1065 "mysql data directory location.");
1066 *static_cast<const char **>(save) = nullptr;
1067 return (1);
1068 }
1069
1070 innodb_tmp_dir =
1071 static_cast<char *>(thd_memdup(thd, tmp_abs_path, tmp_abs_len + 1));
1072 *static_cast<const char **>(save) = innodb_tmp_dir;
1073 return (0);
1074 }
1075
1076 /** Gets field offset for a field in a table.
1077 @param[in] table MySQL table object
1078 @param[in] field MySQL field object
1079 @return offset */
1080 static inline uint get_field_offset(const TABLE *table, const Field *field);
1081
1082 static MYSQL_THDVAR_BOOL(table_locks, PLUGIN_VAR_OPCMDARG,
1083 "Enable InnoDB locking in LOCK TABLES",
1084 /* check_func */ nullptr, /* update_func */ nullptr,
1085 /* default */ true);
1086
1087 static MYSQL_THDVAR_BOOL(strict_mode, PLUGIN_VAR_OPCMDARG,
1088 "Use strict mode when evaluating create options.",
1089 innodb_check_session_admin, nullptr, true);
1090
1091 static MYSQL_THDVAR_BOOL(ft_enable_stopword, PLUGIN_VAR_OPCMDARG,
1092 "Create FTS index with stopword.", nullptr, nullptr,
1093 /* default */ true);
1094
1095 static MYSQL_THDVAR_ULONG(lock_wait_timeout, PLUGIN_VAR_RQCMDARG,
1096 "Timeout in seconds an InnoDB transaction may wait "
1097 "for a lock before being rolled back. Values above "
1098 "100000000 disable the timeout.",
1099 nullptr, nullptr, 50, 1, 1024 * 1024 * 1024, 0);
1100
1101 static MYSQL_THDVAR_STR(
1102 ft_user_stopword_table, PLUGIN_VAR_OPCMDARG | PLUGIN_VAR_MEMALLOC,
1103 "User supplied stopword table name, effective in the session level.",
1104 innodb_stopword_table_validate, nullptr, nullptr);
1105
1106 static MYSQL_THDVAR_STR(tmpdir, PLUGIN_VAR_OPCMDARG | PLUGIN_VAR_MEMALLOC,
1107 "Directory for temporary non-tablespace files.",
1108 innodb_tmpdir_validate, nullptr, nullptr);
1109
1110 static MYSQL_THDVAR_ULONG(parallel_read_threads, PLUGIN_VAR_RQCMDARG,
1111 "Number of threads to do parallel read.", nullptr,
1112 nullptr, 4, /* Default. */
1113 1, /* Minimum. */
1114 Parallel_reader::MAX_THREADS, /* Maximum. */
1115 0);
1116
1117 static MYSQL_THDVAR_ULONG(ddl_buffer_size, PLUGIN_VAR_RQCMDARG,
1118 "Maximum size of memory to use (in bytes) for DDL.",
1119 nullptr, nullptr, 1048576, /* Default. */
1120 65536, /* Minimum. */
1121 4294967295, 0); /* Maximum. */
1122
1123 static MYSQL_THDVAR_ULONG(ddl_threads, PLUGIN_VAR_RQCMDARG,
1124 "Maximum number of threads to use for DDL.", nullptr,
1125 nullptr, 4, /* Default. */
1126 1, /* Minimum. */
1127 64, 0); /* Maximum. */
1128
1129 static SHOW_VAR innodb_status_variables[] = {
1130 {"buffer_pool_dump_status",
1131 (char *)&export_vars.innodb_buffer_pool_dump_status, SHOW_CHAR,
1132 SHOW_SCOPE_GLOBAL},
1133 {"buffer_pool_load_status",
1134 (char *)&export_vars.innodb_buffer_pool_load_status, SHOW_CHAR,
1135 SHOW_SCOPE_GLOBAL},
1136 {"buffer_pool_resize_status",
1137 (char *)&export_vars.innodb_buffer_pool_resize_status, SHOW_CHAR,
1138 SHOW_SCOPE_GLOBAL},
1139 {"buffer_pool_resize_status_code",
1140 (char *)&export_vars.innodb_buffer_pool_resize_status_code, SHOW_INT,
1141 SHOW_SCOPE_GLOBAL},
1142 {"buffer_pool_resize_status_progress",
1143 (char *)&export_vars.innodb_buffer_pool_resize_status_progress, SHOW_INT,
1144 SHOW_SCOPE_GLOBAL},
1145 {"buffer_pool_pages_data",
1146 (char *)&export_vars.innodb_buffer_pool_pages_data, SHOW_LONG,
1147 SHOW_SCOPE_GLOBAL},
1148 {"buffer_pool_bytes_data",
1149 (char *)&export_vars.innodb_buffer_pool_bytes_data, SHOW_LONG,
1150 SHOW_SCOPE_GLOBAL},
1151 {"buffer_pool_pages_dirty",
1152 (char *)&export_vars.innodb_buffer_pool_pages_dirty, SHOW_LONG,
1153 SHOW_SCOPE_GLOBAL},
1154 {"buffer_pool_bytes_dirty",
1155 (char *)&export_vars.innodb_buffer_pool_bytes_dirty, SHOW_LONG,
1156 SHOW_SCOPE_GLOBAL},
1157 {"buffer_pool_pages_flushed",
1158 (char *)&export_vars.innodb_buffer_pool_pages_flushed, SHOW_LONG,
1159 SHOW_SCOPE_GLOBAL},
1160 {"buffer_pool_pages_free",
1161 (char *)&export_vars.innodb_buffer_pool_pages_free, SHOW_LONG,
1162 SHOW_SCOPE_GLOBAL},
1163 #ifdef UNIV_DEBUG
1164 {"buffer_pool_pages_latched",
1165 (char *)&export_vars.innodb_buffer_pool_pages_latched, SHOW_LONG,
1166 SHOW_SCOPE_GLOBAL},
1167 #endif /* UNIV_DEBUG */
1168 {"buffer_pool_pages_misc",
1169 (char *)&export_vars.innodb_buffer_pool_pages_misc, SHOW_LONG,
1170 SHOW_SCOPE_GLOBAL},
1171 {"buffer_pool_pages_total",
1172 (char *)&export_vars.innodb_buffer_pool_pages_total, SHOW_LONG,
1173 SHOW_SCOPE_GLOBAL},
1174 {"buffer_pool_read_ahead_rnd",
1175 (char *)&export_vars.innodb_buffer_pool_read_ahead_rnd, SHOW_LONG,
1176 SHOW_SCOPE_GLOBAL},
1177 {"buffer_pool_read_ahead",
1178 (char *)&export_vars.innodb_buffer_pool_read_ahead, SHOW_LONG,
1179 SHOW_SCOPE_GLOBAL},
1180 {"buffer_pool_read_ahead_evicted",
1181 (char *)&export_vars.innodb_buffer_pool_read_ahead_evicted, SHOW_LONG,
1182 SHOW_SCOPE_GLOBAL},
1183 {"buffer_pool_read_requests",
1184 (char *)&export_vars.innodb_buffer_pool_read_requests, SHOW_LONG,
1185 SHOW_SCOPE_GLOBAL},
1186 {"buffer_pool_reads", (char *)&export_vars.innodb_buffer_pool_reads,
1187 SHOW_LONG, SHOW_SCOPE_GLOBAL},
1188 {"buffer_pool_wait_free", (char *)&export_vars.innodb_buffer_pool_wait_free,
1189 SHOW_LONG, SHOW_SCOPE_GLOBAL},
1190 {"buffer_pool_write_requests",
1191 (char *)&export_vars.innodb_buffer_pool_write_requests, SHOW_LONG,
1192 SHOW_SCOPE_GLOBAL},
1193 {"data_fsyncs", (char *)&export_vars.innodb_data_fsyncs, SHOW_LONG,
1194 SHOW_SCOPE_GLOBAL},
1195 {"data_pending_fsyncs", (char *)&export_vars.innodb_data_pending_fsyncs,
1196 SHOW_LONG, SHOW_SCOPE_GLOBAL},
1197 {"data_pending_reads", (char *)&export_vars.innodb_data_pending_reads,
1198 SHOW_LONG, SHOW_SCOPE_GLOBAL},
1199 {"data_pending_writes", (char *)&export_vars.innodb_data_pending_writes,
1200 SHOW_LONG, SHOW_SCOPE_GLOBAL},
1201 {"data_read", (char *)&export_vars.innodb_data_read, SHOW_LONG,
1202 SHOW_SCOPE_GLOBAL},
1203 {"data_reads", (char *)&export_vars.innodb_data_reads, SHOW_LONG,
1204 SHOW_SCOPE_GLOBAL},
1205 {"data_writes", (char *)&export_vars.innodb_data_writes, SHOW_LONG,
1206 SHOW_SCOPE_GLOBAL},
1207 {"data_written", (char *)&export_vars.innodb_data_written, SHOW_LONG,
1208 SHOW_SCOPE_GLOBAL},
1209 {"dblwr_pages_written", (char *)&export_vars.innodb_dblwr_pages_written,
1210 SHOW_LONG, SHOW_SCOPE_GLOBAL},
1211 {"dblwr_writes", (char *)&export_vars.innodb_dblwr_writes, SHOW_LONG,
1212 SHOW_SCOPE_GLOBAL},
1213 {"redo_log_read_only", (char *)&export_vars.innodb_redo_log_read_only,
1214 SHOW_BOOL, SHOW_SCOPE_GLOBAL},
1215 {"redo_log_uuid", (char *)&export_vars.innodb_redo_log_uuid, SHOW_LONGLONG,
1216 SHOW_SCOPE_GLOBAL},
1217 {"redo_log_checkpoint_lsn",
1218 (char *)&export_vars.innodb_redo_log_checkpoint_lsn, SHOW_LONGLONG,
1219 SHOW_SCOPE_GLOBAL},
1220 {"redo_log_current_lsn", (char *)&export_vars.innodb_redo_log_current_lsn,
1221 SHOW_LONGLONG, SHOW_SCOPE_GLOBAL},
1222 {"redo_log_flushed_to_disk_lsn",
1223 (char *)&export_vars.innodb_redo_log_flushed_to_disk_lsn, SHOW_LONGLONG,
1224 SHOW_SCOPE_GLOBAL},
1225 {"redo_log_logical_size", (char *)&export_vars.innodb_redo_log_logical_size,
1226 SHOW_LONGLONG, SHOW_SCOPE_GLOBAL},
1227 {"redo_log_physical_size",
1228 (char *)&export_vars.innodb_redo_log_physical_size, SHOW_LONGLONG,
1229 SHOW_SCOPE_GLOBAL},
1230 {"redo_log_capacity_resized",
1231 (char *)&export_vars.innodb_redo_log_capacity_resized, SHOW_LONGLONG,
1232 SHOW_SCOPE_GLOBAL},
1233 {"redo_log_resize_status",
1234 (char *)&export_vars.innodb_redo_log_resize_status, SHOW_CHAR,
1235 SHOW_SCOPE_GLOBAL},
1236 {"log_waits", (char *)&export_vars.innodb_log_waits, SHOW_LONG,
1237 SHOW_SCOPE_GLOBAL},
1238 {"log_write_requests", (char *)&export_vars.innodb_log_write_requests,
1239 SHOW_LONG, SHOW_SCOPE_GLOBAL},
1240 {"log_writes", (char *)&export_vars.innodb_log_writes, SHOW_LONG,
1241 SHOW_SCOPE_GLOBAL},
1242 {"os_log_fsyncs", (char *)&export_vars.innodb_os_log_fsyncs, SHOW_LONG,
1243 SHOW_SCOPE_GLOBAL},
1244 {"os_log_pending_fsyncs", (char *)&export_vars.innodb_os_log_pending_fsyncs,
1245 SHOW_LONG, SHOW_SCOPE_GLOBAL},
1246 {"os_log_pending_writes", (char *)&export_vars.innodb_os_log_pending_writes,
1247 SHOW_LONG, SHOW_SCOPE_GLOBAL},
1248 {"os_log_written", (char *)&export_vars.innodb_os_log_written,
1249 SHOW_LONGLONG, SHOW_SCOPE_GLOBAL},
1250 {"page_size", (char *)&export_vars.innodb_page_size, SHOW_LONG,
1251 SHOW_SCOPE_GLOBAL},
1252 {"pages_created", (char *)&export_vars.innodb_pages_created, SHOW_LONG,
1253 SHOW_SCOPE_GLOBAL},
1254 {"pages_read", (char *)&export_vars.innodb_pages_read, SHOW_LONG,
1255 SHOW_SCOPE_GLOBAL},
1256 {"pages_written", (char *)&export_vars.innodb_pages_written, SHOW_LONG,
1257 SHOW_SCOPE_GLOBAL},
1258 {"redo_log_enabled", (char *)&export_vars.innodb_redo_log_enabled,
1259 SHOW_BOOL, SHOW_SCOPE_GLOBAL},
1260 {"row_lock_current_waits",
1261 (char *)&export_vars.innodb_row_lock_current_waits, SHOW_LONG,
1262 SHOW_SCOPE_GLOBAL},
1263 {"row_lock_time", (char *)&export_vars.innodb_row_lock_time, SHOW_LONGLONG,
1264 SHOW_SCOPE_GLOBAL},
1265 {"row_lock_time_avg", (char *)&export_vars.innodb_row_lock_time_avg,
1266 SHOW_LONG, SHOW_SCOPE_GLOBAL},
1267 {"row_lock_time_max", (char *)&export_vars.innodb_row_lock_time_max,
1268 SHOW_LONG, SHOW_SCOPE_GLOBAL},
1269 {"row_lock_waits", (char *)&export_vars.innodb_row_lock_waits, SHOW_LONG,
1270 SHOW_SCOPE_GLOBAL},
1271 {"rows_deleted", (char *)&export_vars.innodb_rows_deleted, SHOW_LONG,
1272 SHOW_SCOPE_GLOBAL},
1273 {"rows_inserted", (char *)&export_vars.innodb_rows_inserted, SHOW_LONG,
1274 SHOW_SCOPE_GLOBAL},
1275 {"rows_read", (char *)&export_vars.innodb_rows_read, SHOW_LONG,
1276 SHOW_SCOPE_GLOBAL},
1277 {"rows_updated", (char *)&export_vars.innodb_rows_updated, SHOW_LONG,
1278 SHOW_SCOPE_GLOBAL},
1279 {"system_rows_deleted", (char *)&export_vars.innodb_system_rows_deleted,
1280 SHOW_LONG, SHOW_SCOPE_GLOBAL},
1281 {"system_rows_inserted", (char *)&export_vars.innodb_system_rows_inserted,
1282 SHOW_LONG, SHOW_SCOPE_GLOBAL},
1283 {"system_rows_read", (char *)&export_vars.innodb_system_rows_read,
1284 SHOW_LONG, SHOW_SCOPE_GLOBAL},
1285 {"system_rows_updated", (char *)&export_vars.innodb_system_rows_updated,
1286 SHOW_LONG, SHOW_SCOPE_GLOBAL},
1287 {"sampled_pages_read", (char *)&export_vars.innodb_sampled_pages_read,
1288 SHOW_LONG, SHOW_SCOPE_GLOBAL},
1289 {"sampled_pages_skipped", (char *)&export_vars.innodb_sampled_pages_skipped,
1290 SHOW_LONG, SHOW_SCOPE_GLOBAL},
1291 {"num_open_files", (char *)&export_vars.innodb_num_open_files, SHOW_LONG,
1292 SHOW_SCOPE_GLOBAL},
1293 {"truncated_status_writes",
1294 (char *)&export_vars.innodb_truncated_status_writes, SHOW_LONG,
1295 SHOW_SCOPE_GLOBAL},
1296 {"undo_tablespaces_total",
1297 (char *)&export_vars.innodb_undo_tablespaces_total, SHOW_LONG,
1298 SHOW_SCOPE_GLOBAL},
1299 {"undo_tablespaces_implicit",
1300 (char *)&export_vars.innodb_undo_tablespaces_implicit, SHOW_LONG,
1301 SHOW_SCOPE_GLOBAL},
1302 {"undo_tablespaces_explicit",
1303 (char *)&export_vars.innodb_undo_tablespaces_explicit, SHOW_LONG,
1304 SHOW_SCOPE_GLOBAL},
1305 {"undo_tablespaces_active",
1306 (char *)&export_vars.innodb_undo_tablespaces_active, SHOW_LONG,
1307 SHOW_SCOPE_GLOBAL},
1308 #ifdef UNIV_DEBUG
1309 {"purge_trx_id_age", (char *)&export_vars.innodb_purge_trx_id_age,
1310 SHOW_LONG, SHOW_SCOPE_GLOBAL},
1311 {"purge_view_trx_id_age", (char *)&export_vars.innodb_purge_view_trx_id_age,
1312 SHOW_LONG, SHOW_SCOPE_GLOBAL},
1313 {"ahi_drop_lookups", (char *)&export_vars.innodb_ahi_drop_lookups,
1314 SHOW_LONG, SHOW_SCOPE_GLOBAL},
1315 #endif /* UNIV_DEBUG */
1316 {NullS, NullS, SHOW_LONG, SHOW_SCOPE_GLOBAL}};
1317
1318 /** Handling the shared INNOBASE_SHARE structure that is needed to provide table
1319 locking. Register the table name if it doesn't exist in the hash table. */
1320 static INNOBASE_SHARE *get_share(
1321 const char *table_name); /*!< in: table to lookup */
1322
1323 /** Free the shared object that was registered with get_share(). */
1324 static void free_share(INNOBASE_SHARE *share); /*!< in/own: share to free */
1325
1326 /** Frees a possible InnoDB trx object associated with the current THD.
1327 @return 0 or error number */
1328 static int innobase_close_connection(
1329 handlerton *hton, /*!< in/out: InnoDB handlerton */
1330 THD *thd); /*!< in: MySQL thread handle for
1331 which to close the connection */
1332
1333 /** Cancel any pending lock request associated with the current THD. */
1334 static void innobase_kill_connection(
1335 handlerton *hton, /*!< in/out: InnoDB handlerton */
1336 THD *thd); /*!< in: MySQL thread handle for
1337 which to close the connection */
1338
1339 /** Commits a transaction in an InnoDB database or marks an SQL statement
1340 ended.
1341 @return 0 */
1342 static int innobase_commit(handlerton *hton, /*!< in/out: InnoDB handlerton */
1343 THD *thd, /*!< in: MySQL thread handle of the
1344 user for whom the transaction should
1345 be committed */
1346 bool commit_trx); /*!< in: true - commit transaction
1347 false - the current SQL statement
1348 ended */
1349
1350 /** Rolls back a transaction to a savepoint.
1351 @return 0 if success, HA_ERR_NO_SAVEPOINT if no savepoint with the
1352 given name */
1353 static int innobase_rollback(handlerton *hton, /*!< in/out: InnoDB handlerton */
1354 THD *thd, /*!< in: handle to the MySQL thread
1355 of the user whose transaction should
1356 be rolled back */
1357 bool rollback_trx); /*!< in: true - rollback entire
1358 transaction false - rollback
1359 the current statement only */
1360
1361 /** Rolls back a transaction to a savepoint.
1362 @return 0 if success, HA_ERR_NO_SAVEPOINT if no savepoint with the
1363 given name */
1364 static int innobase_rollback_to_savepoint(
1365 handlerton *hton, /*!< in/out: InnoDB handlerton */
1366 THD *thd, /*!< in: handle to the MySQL thread of
1367 the user whose XA transaction should
1368 be rolled back to savepoint */
1369 void *savepoint); /*!< in: savepoint data */
1370
1371 /** Check whether innodb state allows to safely release MDL locks after
1372 rollback to savepoint.
1373 @return true if it is safe, false if its not safe. */
1374 static bool innobase_rollback_to_savepoint_can_release_mdl(
1375 handlerton *hton, /*!< in/out: InnoDB handlerton */
1376 THD *thd); /*!< in: handle to the MySQL thread of
1377 the user whose XA transaction should
1378 be rolled back to savepoint */
1379
1380 /** Sets a transaction savepoint.
1381 @return always 0, that is, always succeeds */
1382 static int innobase_savepoint(
1383 handlerton *hton, /*!< in/out: InnoDB handlerton */
1384 THD *thd, /*!< in: handle to the MySQL thread of
1385 the user's XA transaction for which
1386 we need to take a savepoint */
1387 void *savepoint); /*!< in: savepoint data */
1388
1389 /** Release transaction savepoint name.
1390 @return 0 if success, HA_ERR_NO_SAVEPOINT if no savepoint with the
1391 given name */
1392 static int innobase_release_savepoint(
1393 handlerton *hton, /*!< in/out: handlerton for InnoDB */
1394 THD *thd, /*!< in: handle to the MySQL thread
1395 of the user whose transaction's
1396 savepoint should be released */
1397 void *savepoint); /*!< in: savepoint data */
1398
1399 /** Function for constructing an InnoDB table handler instance.
1400 @param[in,out] hton handlerton for InnoDB
1401 @param[in] table MySQL table
1402 @param[in] partitioned Indicates whether table is partitioned
1403 @param[in] mem_root memory context */
1404 static handler *innobase_create_handler(handlerton *hton, TABLE_SHARE *table,
1405 bool partitioned, MEM_ROOT *mem_root);
1406
1407 /** Retrieve table satistics.
1408 @param[in] db_name database name
1409 @param[in] table_name table name
1410 @param[in] se_private_id The internal id of the table
1411 @param[in] ts_se_private_data Tablespace SE Private data
1412 @param[in] tbl_se_private_data Table SE private data
1413 @param[in] stat_flags flags used to retrieve specific stats
1414 @param[in,out] stats structure to save the
1415 retrieved statistics
1416 @return false on success, true on failure */
1417 static bool innobase_get_table_statistics(
1418 const char *db_name, const char *table_name, dd::Object_id se_private_id,
1419 const dd::Properties &ts_se_private_data,
1420 const dd::Properties &tbl_se_private_data, uint stat_flags,
1421 ha_statistics *stats);
1422
1423 /** Retrieve index column cardinality.
1424 @param[in] db_name name of schema
1425 @param[in] table_name name of table
1426 @param[in] index_name name of index
1427 @param[in] index_ordinal_position position of index
1428 @param[in] column_ordinal_position position of column in index
1429 @param[in] se_private_id the internal id of the table
1430 @param[in,out] cardinality cardinality of index column
1431 @retval false success
1432 @retval true failure */
1433 static bool innobase_get_index_column_cardinality(
1434 const char *db_name, const char *table_name, const char *index_name,
1435 uint index_ordinal_position, uint column_ordinal_position,
1436 dd::Object_id se_private_id, ulonglong *cardinality);
1437
1438 /** Retrieve ha_tablespace_statistics for the tablespace.
1439
1440 @param tablespace_name Tablespace_name
1441 @param file_name Data file name.
1442 @param ts_se_private_data Tablespace SE private data.
1443 @param[out] stats Contains tablespace
1444 statistics read from SE.
1445 @return false on success, true on failure */
1446 static bool innobase_get_tablespace_statistics(
1447 const char *tablespace_name, const char *file_name,
1448 const dd::Properties &ts_se_private_data, ha_tablespace_statistics *stats);
1449
1450 /** Retrieve the tablespace type.
1451
1452 @param space Tablespace object.
1453 @param[out] space_type Tablespace category.
1454 @return false on success, true on failure */
1455 static bool innobase_get_tablespace_type(const dd::Tablespace &space,
1456 Tablespace_type *space_type);
1457
1458 /** Get the tablespace type given the name.
1459
1460 @param[in] tablespace_name tablespace name
1461 @param[out] space_type type of space
1462
1463 @return Operation status.
1464 @retval false on success and true for failure.
1465 */
1466 static bool innobase_get_tablespace_type_by_name(const char *tablespace_name,
1467 Tablespace_type *space_type);
1468
1469 /** Perform post-commit/rollback cleanup after DDL statement.
1470 @param[in,out] thd connection thread */
1471 static void innobase_post_ddl(THD *thd);
1472
1473 /** Check if types of child and parent columns in foreign key are compatible.
1474 @param[in] child_column_type Child column type description.
1475 @param[in] parent_column_type Parent column type description.
1476 @param[in] check_charsets Indicates whether we need to check
1477 that charsets of string columns
1478 match. Which is true in most cases.
1479 @return True if types are compatible, False if not. */
1480 static bool innodb_check_fk_column_compat(
1481 const Ha_fk_column_type *child_column_type,
1482 const Ha_fk_column_type *parent_column_type, bool check_charsets);
1483
1484 /** @brief Initialize the default value of innodb_commit_concurrency.
1485
1486 Once InnoDB is running, the innodb_commit_concurrency must not change
1487 from zero to nonzero. (Bug #42101)
1488
1489 The initial default value is 0, and without this extra initialization,
1490 SET GLOBAL innodb_commit_concurrency=DEFAULT would set the parameter
1491 to 0, even if it was initially set to nonzero at the command line
1492 or configuration file. */
1493 static void innobase_commit_concurrency_init_default();
1494
1495 /** This function is used to prepare an X/Open XA distributed transaction.
1496 @return 0 or error number */
1497 static int innobase_xa_prepare(handlerton *hton, /*!< in: InnoDB handlerton */
1498 THD *thd, /*!< in: handle to the MySQL thread of
1499 the user whose XA transaction should
1500 be prepared */
1501 bool all); /*!< in: true - prepare transaction
1502 false - the current SQL statement
1503 ended */
1504 /** This function is used to recover X/Open XA distributed transactions.
1505 @return number of prepared transactions stored in xid_list */
1506 static int innobase_xa_recover(
1507 handlerton *hton, /*!< in: InnoDB handlerton */
1508 XA_recover_txn *txn_list, /*!< in/out: prepared transactions */
1509 uint len, /*!< in: number of slots in xid_list */
1510 MEM_ROOT *mem_root); /*!< in: memory for table names */
1511 /** Find prepared transactions that are marked as prepared in TC, for recovery
1512 purposes.
1513 @param[in] hton InnoDB handlerton
1514 @param[in,out] xa_list prepared transactions state
1515 @return 0 if successful or error number */
1516 static int innobase_xa_recover_prepared_in_tc(handlerton *hton,
1517 Xa_state_list &xa_list);
1518 /** This function is used to commit one X/Open XA distributed transaction
1519 which is in the prepared state
1520 @return 0 or error number */
1521 static xa_status_code innobase_commit_by_xid(
1522 handlerton *hton, /*!< in: InnoDB handlerton */
1523 XID *xid); /*!< in: X/Open XA transaction
1524 identification */
1525 /** This function is used to rollback one X/Open XA distributed transaction
1526 which is in the prepared state
1527 @return 0 or error number */
1528 static xa_status_code innobase_rollback_by_xid(
1529 handlerton *hton, /*!< in: InnoDB handlerton */
1530 XID *xid); /*!< in: X/Open XA transaction
1531 identification */
1532 /** This function is used to write mark an X/Open XA distributed transaction
1533 as been prepared in the server transaction coordinator
1534 @param[in] hton InnoDB handlerton
1535 @param[in] thd handle to the MySQL thread of the user whose XA transaction
1536 should be prepared
1537 @return 0 or error number */
1538 static int innobase_set_prepared_in_tc(handlerton *hton, THD *thd);
1539 /** Mark an X/Open XA distributed transaction
1540 as been prepared in the server transaction coordinator
1541 @param[in] hton InnoDB handlerton
1542 @param[in] xid X/Open XA transaction identification the MySQL thread of the
1543 user whosefo the XA transaction that should be prepared
1544 @return XA_OK or error number */
1545 static xa_status_code innobase_set_prepared_in_tc_by_xid(handlerton *hton,
1546 XID *xid);
1547 /** Checks if the file name is reserved in InnoDB. Currently
1548 redo log file names from the old redo format (ib_logfile*)
1549 are reserved. There is no need to reserve file names from the
1550 newer redo formats, because they start with '#'.
1551 @return true if the name is reserved
1552 @param[in] hton handlerton of InnoDB
1553 @param[in] name Name of the database */
1554 static bool innobase_check_reserved_file_name(handlerton *hton,
1555 const char *name);
1556 /** Check tablespace name validity.
1557 @param[in] ts_cmd whether this is tablespace DDL or not
1558 @param[in] name name to check
1559 @retval false invalid name
1560 @retval true valid name */
1561 static bool innobase_is_valid_tablespace_name(ts_command_type ts_cmd,
1562 const char *name);
1563
1564 /** This API handles CREATE, ALTER & DROP commands for InnoDB tablespaces.
1565 @param[in] hton Handlerton of InnoDB
1566 @param[in] thd Connection
1567 @param[in] alter_info Describes the command and how to do it.
1568 @param[in] old_ts_def Old version of dd::Tablespace object for the
1569 tablespace.
1570 @param[in,out] new_ts_def New version of dd::Tablespace object for the
1571 tablespace. Can be adjusted by SE. Changes will be persisted in the
1572 data-dictionary at statement commit.
1573 @return MySQL error code*/
1574 static int innobase_alter_tablespace(handlerton *hton, THD *thd,
1575 st_alter_tablespace *alter_info,
1576 const dd::Tablespace *old_ts_def,
1577 dd::Tablespace *new_ts_def);
1578
1579 /**
1580 Get tablespace datafile name extension.
1581 */
1582 static const char *innobase_get_tablespace_filename_ext();
1583
1584 /** Free tablespace resources. */
1585 static void innodb_space_shutdown() {
1586 DBUG_TRACE;
1587
1588 srv_sys_space.shutdown();
1589 if (srv_tmp_space.get_sanity_check_status()) {
1590 fil_space_close(srv_tmp_space.space_id());
1591 srv_tmp_space.delete_files();
1592 }
1593 srv_tmp_space.shutdown();
1594 }
1595
1596 /** Shut down InnoDB after the Global Data Dictionary has been shut down.
1597 @see innodb_pre_dd_shutdown()
1598 @retval 0 always */
1599 static int innodb_shutdown(handlerton *, ha_panic_function) {
1600 DBUG_TRACE;
1601
1602 if (innodb_inited) {
1603 log_pfs_delete_tables();
1604
1605 innodb_inited = false;
1606 ut::delete_(innobase_open_tables);
1607 innobase_open_tables = nullptr;
1608
1609 for (auto file : innobase_sys_files) {
1610 ut::delete_(file);
1611 }
1612 innobase_sys_files.clear();
1613 innobase_sys_files.shrink_to_fit();
1614
1615 mutex_free(&master_key_id_mutex);
1616 srv_shutdown();
1617 innodb_space_shutdown();
1618
1619 mysql_mutex_destroy(&innobase_share_mutex);
1620 mysql_mutex_destroy(&commit_cond_m);
1621 mysql_cond_destroy(&commit_cond);
1622 mysql_mutex_destroy(&resume_encryption_cond_m);
1623 mysql_cond_destroy(&resume_encryption_cond);
1624 os_event_destroy(recovery_lock_taken);
1625
1626 os_event_global_destroy();
1627 }
1628
1629 innobase::component_services::deinitialize_service_handles();
1630
1631 return 0;
1632 }
1633
1634 /** Shut down all InnoDB background tasks that may access
1635 the Global Data Dictionary, before the Global Data Dictionary
1636 and the rest of InnoDB have been shut down.
1637 @see dd::shutdown()
1638 @see innodb_shutdown() */
1639 static void innodb_pre_dd_shutdown(handlerton *) {
1640 if (innodb_inited) {
1641 srv_pre_dd_shutdown();
1642 }
1643 }
1644
1645 /** Creates an InnoDB transaction struct for the thd if it does not yet have
1646 one. Starts a new InnoDB transaction if a transaction is not yet started. And
1647 assigns a new snapshot for a consistent read if the transaction does not yet
1648 have one.
1649 @return 0 */
1650 static int innobase_start_trx_and_assign_read_view(
1651 handlerton *hton, /* in: InnoDB handlerton */
1652 THD *thd); /* in: MySQL thread handle of the
1653 user for whom the transaction should
1654 be committed */
1655 /** Flush InnoDB redo logs to the file system.
1656 @param[in] hton InnoDB handlerton
1657 @param[in] binlog_group_flush true if we got invoked by binlog
1658 group commit during flush stage, false in other cases.
1659 @return false */
1660 static bool innobase_flush_logs(handlerton *hton, bool binlog_group_flush);
1661
1662 /** Implements the SHOW ENGINE INNODB STATUS command. Sends the output of the
1663 InnoDB Monitor to the client.
1664 @param[in] hton the innodb handlerton
1665 @param[in] thd the MySQL query thread of the caller
1666 @param[in] stat_print print function
1667 @return 0 on success */
1668 static int innodb_show_status(handlerton *hton, THD *thd,
1669 stat_print_fn *stat_print);
1670
1671 /** Implements Log_resource lock.
1672 @param[in] hton the innodb handlerton
1673 @return false on success */
1674 static bool innobase_lock_hton_log(handlerton *hton);
1675
1676 /** Implements Log_resource unlock.
1677 @param[in] hton the innodb handlerton
1678 @return false on success */
1679 static bool innobase_unlock_hton_log(handlerton *hton);
1680
1681 /** Implements Log_resource collect_info.
1682 @param[in] hton the innodb handlerton
1683 @param[in] json the JSON dom to receive the log info
1684 @return false on success */
1685 static bool innobase_collect_hton_log_info(handlerton *hton, Json_dom *json);
1686
1687 /** Return 0 on success and non-zero on failure. Note: the bool return type
1688 seems to be abused here, should be an int.
1689 @param[in] hton the innodb handlerton
1690 @param[in] thd the MySQL query thread of the caller
1691 @param[in] stat_print print function
1692 @param[in] stat_type status to show */
1693 static bool innobase_show_status(handlerton *hton, THD *thd,
1694 stat_print_fn *stat_print,
1695 enum ha_stat_type stat_type);
1696
1697 /** Parse and enable InnoDB monitor counters during server startup.
1698 User can enable monitor counters/groups by specifying
1699 "loose-innodb_monitor_enable = monitor_name1;monitor_name2..."
1700 in server configuration file or at the command line. */
1701 static void innodb_enable_monitor_at_startup(
1702 char *str); /*!< in: monitor counter enable list */
1703
1704 /** Fill handlerton based INFORMATION_SCHEMA tables.
1705 @param[in] hton (unused) Handle to the handlerton structure
1706 @param[in] thd Thread/connection descriptor
1707 @param[in,out] tables Information Schema tables to fill
1708 @param[in] idx_cond (unused) Intended for conditional pushdown
1709 @param[in] idx Table id that indicates which I_S table to fill
1710 @return Operation status */
1711 static int innobase_fill_i_s_table(handlerton *hton [[maybe_unused]],
1712 THD *thd [[maybe_unused]],
1713 Table_ref *tables [[maybe_unused]],
1714 Item *idx_cond [[maybe_unused]],
1715 enum_schema_tables idx) {
1716 assert(idx == SCH_TABLESPACES);
1717
1718 /** InnoDB does not implement I_S.TABLESPACES */
1719
1720 return (0);
1721 }
1722
1723 /** Store doc_id value into FTS_DOC_ID field
1724 @param[in,out] tbl table containing FULLTEXT index
1725 @param[in] doc_id FTS_DOC_ID value */
1726 static void innobase_fts_store_docid(TABLE *tbl, ulonglong doc_id) {
1727 my_bitmap_map *old_map = dbug_tmp_use_all_columns(tbl, tbl->write_set);
1728
1729 tbl->fts_doc_id_field->store(static_cast<longlong>(doc_id), true);
1730
1731 dbug_tmp_restore_column_map(tbl->write_set, old_map);
1732 }
1733
1734 /** Check for a valid value of innobase_commit_concurrency.
1735 @return 0 for valid innodb_commit_concurrency */
1736 static int innobase_commit_concurrency_validate(
1737 THD *, /*!< in: thread handle */
1738 SYS_VAR *, /*!< in: pointer to system
1739 variable */
1740 void *save, /*!< out: immediate result
1741 for update function */
1742 struct st_mysql_value *value) /*!< in: incoming string */
1743 {
1744 long long intbuf;
1745 ulong commit_concurrency;
1746
1747 DBUG_TRACE;
1748
1749 if (value->val_int(value, &intbuf)) {
1750 /* The value is NULL. That is invalid. */
1751 return 1;
1752 }
1753
1754 *reinterpret_cast<ulong *>(save) = commit_concurrency =
1755 static_cast<ulong>(intbuf);
1756
1757 /* Allow the value to be updated, as long as it remains zero
1758 or nonzero. */
1759 return !(!commit_concurrency == !innobase_commit_concurrency);
1760 }
1761
1762 /** Function for constructing an InnoDB table handler instance.
1763 @param[in,out] hton handlerton for InnoDB
1764 @param[in] table MySQL table
1765 @param[in] partitioned Indicates whether table is partitioned
1766 @param[in] mem_root memory context */
1767 static handler *innobase_create_handler(handlerton *hton, TABLE_SHARE *table,
1768 bool partitioned, MEM_ROOT *mem_root) {
1769 if (partitioned) {
1770 ha_innopart *file = new (mem_root) ha_innopart(hton, table);
1771 if (file && file->init_partitioning(mem_root)) {
1772 destroy(file);
1773 return (nullptr);
1774 }
1775 return (file);
1776 }
1777
1778 return (new (mem_root) ha_innobase(hton, table));
1779 }
1780
1781 /* General functions */
1782
1783 /** Returns true if the thread is the replication thread on the slave
1784 server. Used in srv_conc_enter_innodb() to determine if the thread
1785 should be allowed to enter InnoDB - the replication thread is treated
1786 differently than other threads. Also used in
1787 srv_conc_force_exit_innodb().
1788 @return true if thd is the replication thread */
1789 bool thd_is_replication_slave_thread(THD *thd) /*!< in: thread handle */
1790 {
1791 return thd != nullptr && thd_slave_thread(thd);
1792 }
1793
1794 /** Gets information on the durability property requested by thread.
1795 Used when writing either a prepare or commit record to the log
1796 buffer. @return the durability property. */
1797 enum durability_properties thd_requested_durability(
1798 const THD *thd) /*!< in: thread handle */
1799 {
1800 return (thd_get_durability_property(thd));
1801 }
1802
1803 /** Returns true if transaction should be flagged as read-only.
1804 @return true if the thd is marked as read-only */
1805 bool thd_trx_is_read_only(THD *thd) /*!< in: thread handle */
1806 {
1807 return (thd != nullptr && thd_tx_is_read_only(thd));
1808 }
1809
1810 /**
1811 Check if the transaction can be rolled back
1812 @param[in] requestor Session requesting the lock
1813 @param[in] holder Session that holds the lock
1814 @return the session that will be rolled back, null don't care */
1815
1816 THD *thd_trx_arbitrate(THD *requestor, THD *holder) {
1817 /* Non-user (thd==0) transactions by default can't rollback, in
1818 practice DDL transactions should never rollback and that's because
1819 they should never wait on table/record locks either */
1820
1821 ut_a(holder != nullptr);
1822 ut_a(holder != requestor);
1823
1824 THD *victim = thd_tx_arbitrate(requestor, holder);
1825
1826 ut_a(victim == nullptr || victim == requestor || victim == holder);
1827
1828 return (victim);
1829 }
1830
1831 /**
1832 @param[in] thd Session to check
1833 @return the priority */
1834
1835 int thd_trx_priority(THD *thd) {
1836 return (thd == nullptr ? 0 : thd_tx_priority(thd));
1837 }
1838
1839 /** Check if the transaction is an auto-commit transaction. true also
1840 implies that it is a SELECT (read-only) transaction.
1841 @return true if the transaction is an auto commit read-only transaction. */
1842 bool thd_trx_is_auto_commit(THD *thd) /*!< in: thread handle, can be NULL */
1843 {
1844 return thd != nullptr &&
1845 !thd_test_options(thd, OPTION_NOT_AUTOCOMMIT | OPTION_BEGIN) &&
1846 thd_is_query_block(thd);
1847 }
1848
1849 extern "C" time_t thd_start_time(const THD *thd);
1850
1851 std::chrono::system_clock::time_point thd_start_time(THD *) {
1852 // FIXME: This function should be added to the server code.
1853 // return(thd_start_time(thd));
1854 return std::chrono::system_clock::from_time_t(time(nullptr));
1855 }
1856
1857 /** Enter InnoDB engine after checking the max number of user threads
1858 allowed, else the thread is put into sleep.
1859 @param[in,out] prebuilt row prebuilt handler
1860 @return InnoDB error code. */
1861 static inline dberr_t innobase_srv_conc_enter_innodb(row_prebuilt_t *prebuilt) {
1862 /* We rely on server to do external_lock(F_UNLCK) to reset the
1863 srv_conc.n_active counter. */
1864 if (prebuilt->skip_concurrency_ticket()) {
1865 return DB_SUCCESS;
1866 }
1867
1868 dberr_t err = DB_SUCCESS;
1869 trx_t *trx = prebuilt->trx;
1870
1871 if (srv_thread_concurrency) {
1872 if (trx->n_tickets_to_enter_innodb > 0) {
1873 /* If trx has 'free tickets' to enter the engine left,
1874 then use one such ticket */
1875
1876 --trx->n_tickets_to_enter_innodb;
1877
1878 } else if (trx->mysql_thd != nullptr &&
1879 thd_is_replication_slave_thread(trx->mysql_thd)) {
1880 ut::wait_for(
1881 [&]() {
1882 return srv_conc_get_active_threads() <
1883 (int32_t)srv_thread_concurrency;
1884 },
1885 get_srv_replication_delay());
1886
1887 } else {
1888 err = srv_conc_enter_innodb(prebuilt);
1889 }
1890 }
1891
1892 return err;
1893 }
1894
1895 /** Note that the thread wants to leave InnoDB only if it doesn't have
1896 any spare tickets.
1897 @param[in,out] prebuilt row prebuilt handler */
1898 static inline void innobase_srv_conc_exit_innodb(row_prebuilt_t *prebuilt) {
1899 /* We rely on server to do external_lock(F_UNLCK) to reset the
1900 srv_conc.n_active counter. */
1901 if (prebuilt->skip_concurrency_ticket()) {
1902 return;
1903 }
1904
1905 trx_t *trx = prebuilt->trx;
1906 #ifdef UNIV_DEBUG
1907 btrsea_sync_check check(trx->has_search_latch);
1908
1909 ut_ad(!sync_check_iterate(check));
1910 #endif /* UNIV_DEBUG */
1911
1912 /* This is to avoid making an unnecessary function call. */
1913 if (trx->declared_to_be_inside_innodb &&
1914 trx->n_tickets_to_enter_innodb == 0) {
1915 srv_conc_force_exit_innodb(trx);
1916 }
1917 }
1918
1919 /** Force a thread to leave InnoDB even if it has spare tickets. */
1920 static inline void innobase_srv_conc_force_exit_innodb(
1921 trx_t *trx) /*!< in: transaction handle */
1922 {
1923 #ifdef UNIV_DEBUG
1924 btrsea_sync_check check(trx->has_search_latch);
1925
1926 ut_ad(!sync_check_iterate(check));
1927 #endif /* UNIV_DEBUG */
1928
1929 /* This is to avoid making an unnecessary function call. */
1930 if (trx->declared_to_be_inside_innodb) {
1931 srv_conc_force_exit_innodb(trx);
1932 }
1933 }
1934
1935 /** Returns the NUL terminated value of glob_hostname.
1936 @return pointer to glob_hostname. */
1937 const char *server_get_hostname() { return (glob_hostname); }
1938
1939 /** Returns true if the transaction this thread is processing has edited
1940 non-transactional tables. Used by the deadlock detector when deciding
1941 which transaction to rollback in case of a deadlock - we try to avoid
1942 rolling back transactions that have edited non-transactional tables.
1943 @return true if non-transactional tables have been edited */
1944 bool thd_has_edited_nontrans_tables(THD *thd) /*!< in: thread handle */
1945 {
1946 return thd_non_transactional_update(thd);
1947 }
1948
1949 /** Returns true if the thread is executing a SELECT statement.
1950 @return true if thd is executing SELECT */
1951 bool thd_is_query_block(const THD *thd) /*!< in: thread handle */
1952 {
1953 return thd_sql_command(thd) == SQLCOM_SELECT;
1954 }
1955
1956 /** Checks sys_vars and determines if allocator should mark
1957 large memory segments with MADV_DONTDUMP
1958 @return true iff @@global.core_file AND
1959 NOT @@global.innodb_buffer_pool_in_core_file */
1960 bool innobase_should_madvise_buf_pool() {
1961 return (test_flags & TEST_CORE_ON_SIGNAL) && !srv_buffer_pool_in_core_file;
1962 }
1963
1964 /** Make sure that core file will not be generated, as generating a core file
1965 might violate our promise to not dump buffer pool data, and/or might dump not
1966 the expected memory pages due to failure in using madvise */
1967 void innobase_disable_core_dump() {
1968 /* TODO: There is a race condition here, as test_flags is not an atomic<>
1969 and there might be multiple threads calling this function
1970 in parallel (once for each buffer pool thread).
1971 One approach would be to use a loop with os_compare_and_swap_ulint
1972 unfortunately test_flags is defined as uint, not ulint, and we don't
1973 have nice portable function for dealing with uint in InnoDB.
1974 Moreover that would only prevent problems with mangled bits, but not
1975 help at all with that some other thread might be reading test_flags
1976 and making decisions based on observed value while we are changing it.
1977 The good news is that all these threads try to do the same thing: clear the
1978 same bit. So this happens to work.
1979 */
1980
1981 test_flags &= ~TEST_CORE_ON_SIGNAL;
1982 }
1983
1984 std::chrono::seconds thd_lock_wait_timeout(THD *thd) {
1985 /* According to <mysql/plugin.h>, passing thd == NULL
1986 returns the global value of the session variable. */
1987 return std::chrono::seconds{THDVAR(thd, lock_wait_timeout)};
1988 }
1989
1990 void thd_set_lock_wait_time(THD *thd,
1991 std::chrono::steady_clock::duration value) {
1992 if (thd) {
1993 thd_storage_lock_wait(
1994 thd,
1995 std::chrono::duration_cast<std::chrono::microseconds>(value).count());
1996 }
1997 }
1998
1999 const char *thd_innodb_tmpdir(THD *thd) {
2000 #ifdef UNIV_DEBUG
2001 if (thd != nullptr) {
2002 auto trx = thd_to_trx(thd);
2003
2004 btrsea_sync_check check(trx->has_search_latch);
2005
2006 ut_ad(!sync_check_iterate(check));
2007 }
2008 #endif /* UNIV_DEBUG */
2009
2010 const char *tmp_dir = THDVAR(thd, tmpdir);
2011
2012 if (tmp_dir != nullptr && *tmp_dir == '\0') {
2013 tmp_dir = nullptr;
2014 }
2015
2016 return tmp_dir;
2017 }
2018
2019 /** Obtain the private handler of InnoDB session specific data.
2020 @param[in,out] thd MySQL thread handler.
2021 @return reference to private handler */
2022
2023 [[nodiscard]] innodb_session_t *&thd_to_innodb_session(THD *thd) {
2024 innodb_session_t *&innodb_session =
2025 *(innodb_session_t **)thd_ha_data(thd, innodb_hton_ptr);
2026
2027 if (innodb_session != nullptr) {
2028 return (innodb_session);
2029 }
2030
2031 innodb_session = ut::new_withkey<innodb_session_t>(UT_NEW_THIS_FILE_PSI_KEY);
2032 return (innodb_session);
2033 }
2034
2035 /** Obtain the InnoDB transaction of a MySQL thread.
2036 @param[in,out] thd MySQL thread handler.
2037 @return reference to transaction pointer */
2038
2039 [[nodiscard]] trx_t *&thd_to_trx(THD *thd) {
2040 innodb_session_t *&innodb_session = thd_to_innodb_session(thd);
2041 ut_ad(innodb_session != nullptr);
2042
2043 return (innodb_session->m_trx);
2044 }
2045
2046 ulong thd_parallel_read_threads(THD *thd) {
2047 return THDVAR(thd, parallel_read_threads);
2048 }
2049
2050 ulong thd_ddl_buffer_size(THD *thd) { return THDVAR(thd, ddl_buffer_size); }
2051
2052 size_t thd_ddl_threads(THD *thd) noexcept { return THDVAR(thd, ddl_threads); }
2053
2054 /** Check if statement is of type INSERT .... SELECT that involves
2055 use of intrinsic tables.
2056 @param[in] user_thd thread handler
2057 @return true if INSERT .... SELECT statement. */
2058 static inline bool thd_is_ins_sel_stmt(THD *user_thd) {
2059 /* If the session involves use of intrinsic table
2060 and it is trying to fetch the result from non-temporary tables
2061 it indicates "insert .... select" statement. For non-temporary
2062 table this is verifed using the locked tables count but for
2063 intrinsic table as external_lock is not invoked this count is
2064 not updated.
2065
2066 Why is this needed ?
2067 Use of AHI is blocked if statement is insert .... select statement. */
2068 innodb_session_t *innodb_priv = thd_to_innodb_session(user_thd);
2069 return (innodb_priv->count_register_table_handler() > 0 ? true : false);
2070 }
2071
2072 /** Add the table handler to thread cache.
2073 Obtain the InnoDB transaction of a MySQL thread.
2074 @param[in,out] table table handler
2075 @param[in,out] heap heap for allocating system columns.
2076 @param[in,out] thd MySQL thread handler */
2077 static inline void add_table_to_thread_cache(dict_table_t *table,
2078 mem_heap_t *heap, THD *thd) {
2079 dict_table_add_system_columns(table, heap);
2080
2081 dict_table_set_big_rows(table);
2082
2083 innodb_session_t *&priv = thd_to_innodb_session(thd);
2084 priv->register_table_handler(table->name.m_name, table);
2085 }
2086
2087 /** Increments innobase_active_counter and every INNOBASE_WAKE_INTERVALth
2088 time calls srv_active_wake_master_thread. This function should be used
2089 when a single database operation may introduce a small need for
2090 server utility activity, like checkpointing. */
2091 inline void innobase_active_small(void) {
2092 innobase_active_counter++;
2093
2094 if ((innobase_active_counter % INNOBASE_WAKE_INTERVAL) == 0) {
2095 srv_active_wake_master_thread();
2096 }
2097 }
2098
2099 /** Converts an InnoDB error code to a MySQL error code.
2100 Also tells to MySQL about a possible transaction rollback inside InnoDB caused
2101 by a lock wait timeout or a deadlock.
2102 @param[in] error InnoDB error code.
2103 @param[in] flags InnoDB table flags or 0.
2104 @param[in] thd MySQL thread or NULL.
2105 @return MySQL error code */
2106 int convert_error_code_to_mysql(dberr_t error, uint32_t flags, THD *thd) {
2107 switch (error) {
2108 case DB_SUCCESS:
2109 return (0);
2110
2111 case DB_INTERRUPTED:
2112 thd_set_kill_status(thd != nullptr ? thd : current_thd);
2113 return (HA_ERR_GENERIC);
2114
2115 case DB_FOREIGN_EXCEED_MAX_CASCADE:
2116 ut_ad(thd);
2117 my_error(ER_FK_DEPTH_EXCEEDED, MYF(0), FK_MAX_CASCADE_DEL);
2118 return (HA_ERR_FK_DEPTH_EXCEEDED);
2119
2120 case DB_CANT_CREATE_GEOMETRY_OBJECT:
2121 my_error(ER_CANT_CREATE_GEOMETRY_OBJECT, MYF(0));
2122 return (HA_ERR_NULL_IN_SPATIAL);
2123
2124 case DB_ERROR:
2125 default:
2126 return (HA_ERR_GENERIC); /* unspecified error */
2127
2128 case DB_DUPLICATE_KEY:
2129 /* Be cautious with returning this error, since
2130 mysql could re-enter the storage layer to get
2131 duplicated key info, the operation requires a
2132 valid table handle and/or transaction information,
2133 which might not always be available in the error
2134 handling stage. */
2135 return (HA_ERR_FOUND_DUPP_KEY);
2136
2137 case DB_READ_ONLY:
2138 if (srv_force_recovery) {
2139 return (HA_ERR_INNODB_FORCED_RECOVERY);
2140 }
2141 return (HA_ERR_TABLE_READONLY);
2142
2143 case DB_FOREIGN_DUPLICATE_KEY:
2144 return (HA_ERR_FOREIGN_DUPLICATE_KEY);
2145
2146 case DB_MISSING_HISTORY:
2147 return (HA_ERR_TABLE_DEF_CHANGED);
2148
2149 case DB_RECORD_NOT_FOUND:
2150 return (HA_ERR_NO_ACTIVE_RECORD);
2151
2152 case DB_FORCED_ABORT:
2153 case DB_DEADLOCK:
2154 /* Since we rolled back the whole transaction, we must
2155 tell it also to MySQL so that MySQL knows to empty the
2156 cached binlog for this transaction */
2157
2158 if (thd != nullptr) {
2159 thd_mark_transaction_to_rollback(thd, 1);
2160 }
2161
2162 return (HA_ERR_LOCK_DEADLOCK);
2163
2164 case DB_LOCK_WAIT_TIMEOUT:
2165 /* Starting from 5.0.13, we let MySQL just roll back the
2166 latest SQL statement in a lock wait timeout. Previously, we
2167 rolled back the whole transaction. */
2168
2169 if (thd) {
2170 thd_mark_transaction_to_rollback(thd, (int)row_rollback_on_timeout);
2171 }
2172
2173 return (HA_ERR_LOCK_WAIT_TIMEOUT);
2174
2175 case DB_NO_REFERENCED_ROW:
2176 return (HA_ERR_NO_REFERENCED_ROW);
2177
2178 case DB_ROW_IS_REFERENCED:
2179 return (HA_ERR_ROW_IS_REFERENCED);
2180
2181 case DB_NO_FK_ON_S_BASE_COL:
2182 case DB_CANNOT_ADD_CONSTRAINT:
2183 case DB_CHILD_NO_INDEX:
2184 case DB_PARENT_NO_INDEX:
2185 return (HA_ERR_CANNOT_ADD_FOREIGN);
2186
2187 case DB_CANNOT_DROP_CONSTRAINT:
2188
2189 return (HA_ERR_ROW_IS_REFERENCED); /* TODO: This is a bit
2190 misleading, a new MySQL error
2191 code should be introduced */
2192
2193 case DB_CORRUPTION:
2194 return (HA_ERR_CRASHED);
2195
2196 case DB_OUT_OF_FILE_SPACE:
2197 return (HA_ERR_RECORD_FILE_FULL);
2198
2199 case DB_OUT_OF_DISK_SPACE:
2200 return (HA_ERR_DISK_FULL_NOWAIT);
2201
2202 case DB_TEMP_FILE_WRITE_FAIL:
2203 return (HA_ERR_TEMP_FILE_WRITE_FAILURE);
2204
2205 case DB_TABLE_IN_FK_CHECK:
2206 return (HA_ERR_TABLE_IN_FK_CHECK);
2207
2208 case DB_TABLE_IS_BEING_USED:
2209 return (HA_ERR_WRONG_COMMAND);
2210
2211 case DB_TABLE_NOT_FOUND:
2212 return (HA_ERR_NO_SUCH_TABLE);
2213
2214 case DB_TABLESPACE_NOT_FOUND:
2215 return (HA_ERR_TABLESPACE_MISSING);
2216
2217 case DB_TOO_BIG_RECORD: {
2218 /* If prefix is true then a 768-byte prefix is stored
2219 locally for BLOB fields. Refer to dict_table_get_format().
2220 We limit max record size to 16k for 64k page size. */
2221 bool prefix = !DICT_TF_HAS_ATOMIC_BLOBS(flags);
2222 my_printf_error(
2223 ER_TOO_BIG_ROWSIZE,
2224 "Row size too large (> " ULINTPF
2225 "). Changing some columns"
2226 " to TEXT or BLOB %smay help. In current row"
2227 " format, BLOB prefix of %d bytes is stored inline.",
2228 MYF(0),
2229 srv_page_size == UNIV_PAGE_SIZE_MAX
2230 ? REC_MAX_DATA_SIZE - 1
2231 : page_get_free_space_of_empty(flags & DICT_TF_COMPACT) / 2,
2232 prefix ? "or using ROW_FORMAT=DYNAMIC or"
2233 " ROW_FORMAT=COMPRESSED "
2234 : "",
2235 prefix ? DICT_MAX_FIXED_COL_LEN : 0);
2236 return (HA_ERR_TOO_BIG_ROW);
2237 }
2238
2239 case DB_TOO_BIG_INDEX_COL:
2240 my_error(ER_INDEX_COLUMN_TOO_LONG, MYF(0),
2241 DICT_MAX_FIELD_LEN_BY_FORMAT_FLAG(flags));
2242 return (HA_ERR_INDEX_COL_TOO_LONG);
2243
2244 case DB_NO_SAVEPOINT:
2245 return (HA_ERR_NO_SAVEPOINT);
2246
2247 case DB_LOCK_TABLE_FULL:
2248 /* Since we rolled back the whole transaction, we must
2249 tell it also to MySQL so that MySQL knows to empty the
2250 cached binlog for this transaction */
2251
2252 if (thd) {
2253 thd_mark_transaction_to_rollback(thd, 1);
2254 }
2255
2256 return (HA_ERR_LOCK_TABLE_FULL);
2257
2258 case DB_FTS_INVALID_DOCID:
2259 return (HA_FTS_INVALID_DOCID);
2260 case DB_FTS_EXCEED_RESULT_CACHE_LIMIT:
2261 return (HA_ERR_FTS_EXCEED_RESULT_CACHE_LIMIT);
2262 case DB_TOO_MANY_CONCURRENT_TRXS:
2263 return (HA_ERR_TOO_MANY_CONCURRENT_TRXS);
2264 case DB_UNSUPPORTED:
2265 return (HA_ERR_UNSUPPORTED);
2266 case DB_INDEX_CORRUPT:
2267 return (HA_ERR_INDEX_CORRUPT);
2268 case DB_UNDO_RECORD_TOO_BIG:
2269 return (HA_ERR_UNDO_REC_TOO_BIG);
2270 case DB_OUT_OF_MEMORY:
2271 return (HA_ERR_OUT_OF_MEM);
2272 case DB_TABLESPACE_EXISTS:
2273 return (HA_ERR_TABLESPACE_EXISTS);
2274 case DB_TABLESPACE_DELETED:
2275 return (HA_ERR_TABLESPACE_MISSING);
2276 case DB_IDENTIFIER_TOO_LONG:
2277 return (HA_ERR_INTERNAL_ERROR);
2278 case DB_TOO_LONG_PATH:
2279 return (HA_ERR_TOO_LONG_PATH);
2280 case DB_TABLE_CORRUPT:
2281 return (HA_ERR_TABLE_CORRUPT);
2282 case DB_FTS_TOO_MANY_WORDS_IN_PHRASE:
2283 return (HA_ERR_FTS_TOO_MANY_WORDS_IN_PHRASE);
2284 case DB_WRONG_FILE_NAME:
2285 return (HA_ERR_WRONG_FILE_NAME);
2286 case DB_COMPUTE_VALUE_FAILED:
2287 return (HA_ERR_COMPUTE_FAILED);
2288 case DB_LOCK_NOWAIT:
2289 my_error(ER_LOCK_NOWAIT, MYF(0));
2290 return (HA_ERR_NO_WAIT_LOCK);
2291 case DB_NO_SESSION_TEMP:
2292 return (HA_ERR_NO_SESSION_TEMP);
2293 case DB_BTREE_LEVEL_LIMIT_EXCEEDED:
2294 return (HA_ERR_INTERNAL_ERROR);
2295 case DB_FTS_TOO_MANY_NESTED_EXP:
2296 return (HA_ERR_FTS_TOO_MANY_NESTED_EXP);
2297 case DB_IO_NO_PUNCH_HOLE:
2298 case DB_IO_NO_PUNCH_HOLE_FS:
2299 case DB_IO_NO_PUNCH_HOLE_TABLESPACE:
2300 return HA_ERR_UNSUPPORTED;
2301 }
2302 }
2303
2304 /** Prints info of a THD object (== user session thread) to the given file. */
2305 void innobase_mysql_print_thd(FILE *f, /*!< in: output stream */
2306 THD *thd, /*!< in: MySQL THD object */
2307 uint max_query_len) /*!< in: max query length to
2308 print, must be positive */
2309 {
2310 // This is meant to be an upper bound for non-SQL part of the context,
2311 // such as trx's id, state and stats.
2312 ut_a(0 < max_query_len);
2313 constexpr size_t ADDITIONAL_CTX_LEN = 1024;
2314 ut::vector<char> buffer(ADDITIONAL_CTX_LEN + max_query_len);
2315
2316 fputs(thd_security_context(thd, buffer.data(), buffer.size(), max_query_len),
2317 f);
2318 putc('\n', f);
2319 }
2320
2321 /** Get the error message format string.
2322 @return the format string or 0 if not found. */
2323 const char *innobase_get_err_msg(int error_code) /*!< in: MySQL error code */
2324 {
2325 return (my_get_err_msg(error_code));
2326 }
2327
2328 /** Get the variable length bounds of the given character set.
2329 @param[in] cset Mysql charset-collation code
2330 @param[out] mbminlen Minimum length of a char (in bytes)
2331 @param[out] mbmaxlen Maximum length of a char (in bytes) */
2332 void innobase_get_cset_width(ulint cset, ulint *mbminlen, ulint *mbmaxlen) {
2333 CHARSET_INFO *cs;
2334 ut_ad(cset <= MAX_CHAR_COLL_NUM);
2335 ut_ad(mbminlen);
2336 ut_ad(mbmaxlen);
2337
2338 cs = all_charsets[cset];
2339 if (cs) {
2340 *mbminlen = cs->mbminlen;
2341 *mbmaxlen = cs->mbmaxlen;
2342 ut_ad(*mbminlen < DATA_MBMAX);
2343 ut_ad(*mbmaxlen < DATA_MBMAX);
2344 } else {
2345 THD *thd = current_thd;
2346
2347 if (thd && thd_sql_command(thd) == SQLCOM_DROP_TABLE) {
2348 /* Fix bug#46256: allow tables to be dropped if the
2349 collation is not found, but issue a warning. */
2350 if (cset != 0) {
2351 log_errlog(ERROR_LEVEL, ER_INNODB_UNKNOWN_COLLATION);
2352 }
2353 } else {
2354 ut_a(cset == 0);
2355 }
2356
2357 *mbminlen = *mbmaxlen = 0;
2358 }
2359 }
2360
2361 /**********************************************************************
2362 Check if the length of the identifier exceeds the maximum allowed.
2363 return true when length of identifier is too long. */
2364 bool innobase_check_identifier_length(
2365 const char *id) /* in: FK identifier to check excluding the
2366 database portion. */
2367 {
2368 int well_formed_error = 0;
2369 CHARSET_INFO *cs = system_charset_info;
2370 DBUG_TRACE;
2371
2372 size_t len = cs->cset->well_formed_len(cs, id, id + strlen(id), NAME_CHAR_LEN,
2373 &well_formed_error);
2374
2375 if (well_formed_error || len != strlen(id)) {
2376 my_error(ER_TOO_LONG_IDENT, MYF(0), id);
2377 return true;
2378 }
2379 return false;
2380 }
2381 #endif /* !UNIV_HOTBACKUP */
2382
2383 /** Compares NUL-terminated UTF-8 strings case insensitively.
2384 @return 0 if a=b, <0 if a\<b, >1 if a>b */
2385 int innobase_strcasecmp(const char *a, /*!< in: first string to compare */
2386 const char *b) /*!< in: second string to compare */
2387 {
2388 if (!a) {
2389 if (!b) {
2390 return (0);
2391 } else {
2392 return (-1);
2393 }
2394 } else if (!b) {
2395 return (1);
2396 }
2397
2398 return (my_strcasecmp(system_charset_info, a, b));
2399 }
2400
2401 #ifndef UNIV_HOTBACKUP
2402 /** Compares NUL-terminated UTF-8 strings case insensitively. The
2403 second string contains wildcards.
2404 @return 0 if a match is found, 1 if not */
2405 static int innobase_wildcasecmp(
2406 const char *a, /*!< in: string to compare */
2407 const char *b) /*!< in: wildcard string to compare */
2408 {
2409 return (wild_case_compare(system_charset_info, a, b));
2410 }
2411 #endif /* !UNIV_HOTBACKUP */
2412
2413 /** Strip dir name from a full path name and return only the file name
2414 @param[in] path_name full path name
2415 @return file name or "null" if no file name */
2416 const char *innobase_basename(const char *path_name) {
2417 const char *name = base_name(path_name);
2418
2419 return ((name) ? name : "null");
2420 }
2421
2422 #ifndef UNIV_HOTBACKUP
2423
2424 /** Makes all characters in a NUL-terminated UTF-8 string lower case. */
2425 void innobase_casedn_str(char *a) /*!< in/out: string to put in lower case */
2426 {
2427 my_casedn_str(system_charset_info, a);
2428 }
2429
2430 /** Makes all characters in a NUL-terminated UTF-8 path string lower case. */
2431 void innobase_casedn_path(char *a) /*!< in/out: string to put in lower case */
2432 {
2433 my_casedn_str(&my_charset_filename, a);
2434 }
2435
2436 /** Determines the connection character set.
2437 @return connection character set */
2438 const CHARSET_INFO *innobase_get_charset(
2439 THD *mysql_thd) /*!< in: MySQL thread handle */
2440 {
2441 return (thd_charset(mysql_thd));
2442 }
2443
2444 /** Determines the current SQL statement.
2445 Thread unsafe, can only be called from the thread owning the THD.
2446 @param[in] thd MySQL thread handle
2447 @param[out] length Length of the SQL statement
2448 @return SQL statement string */
2449 const char *innobase_get_stmt_unsafe(THD *thd, size_t *length) {
2450 LEX_CSTRING stmt;
2451
2452 stmt = thd_query_unsafe(thd);
2453 *length = stmt.length;
2454 return (stmt.str);
2455 }
2456
2457 /** Determines the current SQL statement.
2458 Thread safe, can be called from any thread as the string is copied
2459 into the provided buffer.
2460 @param[in] thd MySQL thread handle
2461 @param[out] buf Buffer containing SQL statement
2462 @param[in] buflen Length of provided buffer
2463 @return Length of the SQL statement */
2464 size_t innobase_get_stmt_safe(THD *thd, char *buf, size_t buflen) {
2465 return (thd_query_safe(thd, buf, buflen));
2466 }
2467
2468 /** Get the current setting of the table_def_size global parameter. We do
2469 a dirty read because for one there is no synchronization object and
2470 secondly there is little harm in doing so even if we get a torn read.
2471 @return value of table_def_size */
2472 ulint innobase_get_table_cache_size(void) { return (table_def_size); }
2473
2474 /** Get the current setting of the lower_case_table_names global parameter from
2475 mysqld.cc. We do a dirty read because for one there is no synchronization
2476 object and secondly there is little harm in doing so even if we get a torn
2477 read.
2478 @return value of lower_case_table_names */
2479 ulint innobase_get_lower_case_table_names(void) {
2480 return (lower_case_table_names);
2481 }
2482
2483 char *innobase_mysql_tmpdir() { return (mysql_tmpdir); }
2484
2485 os_fd_t innobase_mysql_tmpfile(const char *path) {
2486 DBUG_EXECUTE_IF("innobase_tmpfile_creation_failure", return (-1););
2487
2488 auto fd =
2489 (path == nullptr) ? mysql_tmpfile("ib") : mysql_tmpfile_path(path, "ib");
2490
2491 os_fd_t fd2{OS_FD_CLOSED};
2492
2493 if (fd >= 0) {
2494 /* Copy the file descriptor, so that the additional resources
2495 allocated by create_temp_file() can be freed by invoking
2496 my_close().
2497
2498 Because the file descriptor returned by this function
2499 will be passed to fdopen(), it will be closed by invoking
2500 fclose(), which in turn will invoke close() instead of
2501 my_close(). */
2502
2503 #ifdef _WIN32
2504 /* Note that on Windows, the integer returned by mysql_tmpfile
2505 has no relation to C runtime file descriptor. Here, we need
2506 to call my_get_osfhandle to get the HANDLE and then convert it
2507 to C runtime filedescriptor. */
2508 {
2509 HANDLE hDup;
2510
2511 auto hFile = my_get_osfhandle(fd);
2512
2513 auto bOK =
2514 DuplicateHandle(GetCurrentProcess(), hFile, GetCurrentProcess(),
2515 &hDup, 0, false, DUPLICATE_SAME_ACCESS);
2516 if (bOK) {
2517 fd2 = _open_osfhandle((intptr_t)hDup, 0);
2518 } else {
2519 my_osmaperr(GetLastError());
2520 fd2 = OS_FD_CLOSED;
2521 }
2522 }
2523 #else
2524 fd2 = dup(fd);
2525 #endif
2526
2527 if (fd2 < 0) {
2528 char errbuf[MYSYS_STRERROR_SIZE];
2529
2530 DBUG_PRINT("error", ("Got error %d on dup", fd2));
2531
2532 set_my_errno(errno);
2533
2534 my_error(EE_OUT_OF_FILERESOURCES, MYF(0), "ib*", my_errno(),
2535 my_strerror(errbuf, sizeof(errbuf), my_errno()));
2536 }
2537
2538 my_close(fd, MYF(MY_WME));
2539 }
2540
2541 return fd2;
2542 }
2543
2544 /** Wrapper around MySQL's copy_and_convert function.
2545 @return number of bytes copied to 'to' */
2546 static ulint innobase_convert_string(
2547 void *to, /*!< out: converted string */
2548 ulint to_length, /*!< in: number of bytes reserved
2549 for the converted string */
2550 CHARSET_INFO *to_cs, /*!< in: character set to convert to */
2551 const void *from, /*!< in: string to convert */
2552 ulint from_length, /*!< in: number of bytes to convert */
2553 CHARSET_INFO *from_cs, /*!< in: character set to convert
2554 from */
2555 uint *errors) /*!< out: number of errors encountered
2556 during the conversion */
2557 {
2558 return (copy_and_convert((char *)to, (uint32)to_length, to_cs,
2559 (const char *)from, (uint32)from_length, from_cs,
2560 errors));
2561 }
2562
2563 /** Formats the raw data in "data" (in InnoDB on-disk format) that is of
2564 type DATA_(CHAR|VARCHAR|MYSQL|VARMYSQL) using "charset_coll" and writes
2565 the result to "buf". The result is converted to "system_charset_info".
2566 Not more than "buf_size" bytes are written to "buf".
2567 The result is always NUL-terminated (provided buf_size > 0) and the
2568 number of bytes that were written to "buf" is returned (including the
2569 terminating NUL).
2570 @return number of bytes that were written */
2571 ulint innobase_raw_format(const char *data, /*!< in: raw data */
2572 ulint data_len, /*!< in: raw data length
2573 in bytes */
2574 ulint charset_coll, /*!< in: charset collation */
2575 char *buf, /*!< out: output buffer */
2576 ulint buf_size) /*!< in: output buffer size
2577 in bytes */
2578 {
2579 /* XXX we use a hard limit instead of allocating
2580 but_size bytes from the heap */
2581 CHARSET_INFO *data_cs;
2582 char buf_tmp[8192];
2583 ulint buf_tmp_used;
2584 uint num_errors;
2585
2586 data_cs = all_charsets[charset_coll];
2587
2588 buf_tmp_used =
2589 innobase_convert_string(buf_tmp, sizeof(buf_tmp), system_charset_info,
2590 data, data_len, data_cs, &num_errors);
2591
2592 return (ut_str_sql_format(buf_tmp, buf_tmp_used, buf, buf_size));
2593 }
2594
2595 #endif /* !UNIV_HOTBACKUP */
2596
2597 /** Check if the string is "empty" or "none".
2598 @param[in] algorithm Compression algorithm to check
2599 @return true if no algorithm requested */
2600 bool Compression::is_none(const char *algorithm) {
2601 /* NULL is the same as NONE */
2602 if (algorithm == nullptr || *algorithm == 0 ||
2603 innobase_strcasecmp(algorithm, "none") == 0) {
2604 return (true);
2605 }
2606
2607 return (false);
2608 }
2609
2610 /** Check whether the compression algorithm is supported.
2611 @param[in] algorithm Compression algorithm to check
2612 @param[out] compression The type that algorithm maps to
2613 @return DB_SUCCESS or error code */
2614 dberr_t Compression::check(const char *algorithm, Compression *compression) {
2615 if (is_none(algorithm)) {
2616 compression->m_type = NONE;
2617
2618 } else if (innobase_strcasecmp(algorithm, "zlib") == 0) {
2619 compression->m_type = ZLIB;
2620
2621 } else if (innobase_strcasecmp(algorithm, "lz4") == 0) {
2622 compression->m_type = LZ4;
2623
2624 } else {
2625 return (DB_UNSUPPORTED);
2626 }
2627
2628 return (DB_SUCCESS);
2629 }
2630
2631 /** Validate the algorithm string.
2632 @param[in] algorithm Compression algorithm to check
2633 @return DB_SUCCESS or error code */
2634 dberr_t Compression::validate(const char *algorithm) {
2635 Compression compression;
2636
2637 return (check(algorithm, &compression));
2638 }
2639
2640 bool Compression::validate(const Compression::Type type) {
2641 bool ret = true;
2642
2643 switch (type) {
2644 case NONE:
2645 case ZLIB:
2646 case LZ4:
2647 break;
2648 default:
2649 ret = false;
2650 break;
2651 }
2652
2653 return ret;
2654 }
2655
2656 #ifndef UNIV_HOTBACKUP
2657 bool Encryption::is_none(const char *algorithm) noexcept {
2658 /* NULL is the same as NONE */
2659 if (algorithm == nullptr || innobase_strcasecmp(algorithm, "n") == 0) {
2660 return (true);
2661 }
2662
2663 return (false);
2664 }
2665
2666 dberr_t Encryption::validate(const char *option) noexcept {
2667 return (is_none(option) || (innobase_strcasecmp(option, "y") == 0))
2668 ? DB_SUCCESS
2669 : DB_UNSUPPORTED;
2670 }
2671
2672 /** Compute the next autoinc value.
2673
2674 For MySQL replication the autoincrement values can be partitioned among
2675 the nodes. The offset is the start or origin of the autoincrement value
2676 for a particular node. For n nodes the increment will be n and the offset
2677 will be in the interval [1, n]. The formula tries to allocate the next
2678 value for a particular node.
2679
2680 Note: This function is also called with increment set to the number of
2681 values we want to reserve for multi-value inserts e.g.,
2682
2683 INSERT INTO T VALUES(), (), ();
2684
2685 innobase_next_autoinc() will be called with increment set to 3 where
2686 autoinc_lock_mode != TRADITIONAL because we want to reserve 3 values for
2687 the multi-value INSERT above.
2688 @return the next value */
2689 ulonglong innobase_next_autoinc(
2690 ulonglong current, /*!< in: Current value */
2691 ulonglong need, /*!< in: count of values needed */
2692 ulonglong step, /*!< in: AUTOINC increment step */
2693 ulonglong offset, /*!< in: AUTOINC offset */
2694 ulonglong max_value) /*!< in: max value for type */
2695 {
2696 ulonglong next_value;
2697 ulonglong block = need * step;
2698
2699 /* Should never be 0. */
2700 ut_a(need > 0);
2701 ut_a(block > 0);
2702 ut_a(max_value > 0);
2703
2704 /* According to MySQL documentation, if the offset is greater than
2705 the step then the offset is ignored. */
2706 if (offset > block) {
2707 offset = 0;
2708 }
2709
2710 /* Check for overflow. Current can be > max_value if the value is
2711 in reality a negative value.The visual studio compilers converts
2712 large double values automatically into unsigned long long datatype
2713 maximum value */
2714
2715 if (block >= max_value || offset > max_value || current >= max_value ||
2716 max_value - offset <= offset) {
2717 next_value = max_value;
2718 } else {
2719 ut_a(max_value > current);
2720
2721 ulonglong free = max_value - current;
2722
2723 if (free < offset || free - offset <= block) {
2724 next_value = max_value;
2725 } else {
2726 next_value = 0;
2727 }
2728 }
2729
2730 if (next_value == 0) {
2731 ulonglong next;
2732
2733 if (current > offset) {
2734 next = (current - offset) / step;
2735 } else {
2736 next = (offset - current) / step;
2737 }
2738
2739 ut_a(max_value > next);
2740 next_value = next * step;
2741 /* Check for multiplication overflow. */
2742 ut_a(next_value >= next);
2743 ut_a(max_value > next_value);
2744
2745 /* Check for overflow */
2746 if (max_value - next_value >= block) {
2747 next_value += block;
2748
2749 if (max_value - next_value >= offset) {
2750 next_value += offset;
2751 } else {
2752 next_value = max_value;
2753 }
2754 } else {
2755 next_value = max_value;
2756 }
2757 }
2758
2759 ut_a(next_value != 0);
2760 ut_a(next_value <= max_value);
2761
2762 return (next_value);
2763 }
2764
2765 /** Initializes some fields in an InnoDB transaction object. */
2766 static void innobase_trx_init(
2767 THD *thd, /*!< in: user thread handle */
2768 trx_t *trx) /*!< in/out: InnoDB transaction handle */
2769 {
2770 DBUG_TRACE;
2771 assert(EQ_CURRENT_THD(thd));
2772 assert(thd == trx->mysql_thd);
2773
2774 trx->check_foreigns = !thd_test_options(thd, OPTION_NO_FOREIGN_KEY_CHECKS);
2775
2776 trx->check_unique_secondary =
2777 !thd_test_options(thd, OPTION_RELAXED_UNIQUE_CHECKS);
2778 }
2779
2780 /** Allocates an InnoDB transaction for a MySQL handler object for DML.
2781 @return InnoDB transaction handle */
2782 trx_t *innobase_trx_allocate(THD *thd) /*!< in: user thread handle */
2783 {
2784 trx_t *trx;
2785
2786 DBUG_TRACE;
2787 assert(thd != nullptr);
2788 assert(EQ_CURRENT_THD(thd));
2789
2790 MONITOR_ATOMIC_INC(MONITOR_TRX_ALLOCATIONS);
2791 trx = trx_allocate_for_mysql();
2792
2793 trx->purge_sys_trx = purge_sys->is_this_a_purge_thread;
2794
2795 trx->mysql_thd = thd;
2796
2797 innobase_trx_init(thd, trx);
2798
2799 return trx;
2800 }
2801
2802 /** Gets the InnoDB transaction handle for a MySQL handler object, creates
2803 an InnoDB transaction struct if the corresponding MySQL thread struct still
2804 lacks one.
2805 @return InnoDB transaction handle */
2806 trx_t *check_trx_exists(THD *thd) /*!< in: user thread handle */
2807 {
2808 /* We request to stop master thread in srv_shutdown, which is invoked
2809 after DD has been shut down. Since that point of time, we must not need
2810 transaction objects for any reasons. */
2811 ut_ad(srv_shutdown_state_matches([](auto state) {
2812 return state < SRV_SHUTDOWN_MASTER_STOP ||
2813 state == SRV_SHUTDOWN_EXIT_THREADS;
2814 }));
2815
2816 trx_t *&trx = thd_to_trx(thd);
2817
2818 ut_ad(EQ_CURRENT_THD(thd));
2819
2820 if (trx == nullptr) {
2821 trx = innobase_trx_allocate(thd);
2822
2823 /* User trx can be forced to rollback,
2824 so we unset the disable flag. */
2825 ut_ad(trx->in_innodb & TRX_FORCE_ROLLBACK_DISABLE);
2826 trx->in_innodb &= TRX_FORCE_ROLLBACK_MASK;
2827 } else {
2828 ut_a(trx->magic_n == TRX_MAGIC_N);
2829
2830 innobase_trx_init(thd, trx);
2831 }
2832
2833 return (trx);
2834 }
2835
2836 /** InnoDB transaction object that is currently associated with THD is
2837 replaced with that of the 2nd argument. The previous value is
2838 returned through the 3rd argument's buffer, unless it's NULL. When
2839 the buffer is not provided (value NULL) that should mean the caller
2840 restores previously saved association so the current trx has to be
2841 additionally freed from all association with MYSQL.
2842
2843 @param[in,out] thd MySQL thread handle
2844 @param[in] new_trx_arg replacement trx_t
2845 @param[in,out] ptr_trx_arg pointer to a buffer to store old trx_t */
2846 static void innodb_replace_trx_in_thd(THD *thd, void *new_trx_arg,
2847 void **ptr_trx_arg) {
2848 DBUG_TRACE;
2849 trx_t *&trx = thd_to_trx(thd);
2850
2851 ut_ad(new_trx_arg == nullptr || (((trx_t *)new_trx_arg)->mysql_thd == thd &&
2852 !((trx_t *)new_trx_arg)->is_recovered));
2853
2854 if (ptr_trx_arg) {
2855 *ptr_trx_arg = trx;
2856
2857 ut_ad(trx == nullptr || (trx->mysql_thd == thd && !trx->is_recovered));
2858
2859 } else if (trx != nullptr) {
2860 ut_ad(trx_can_be_handled_by_current_thread_or_is_hp_victim(trx));
2861 if (trx->state.load(std::memory_order_relaxed) == TRX_STATE_NOT_STARTED) {
2862 ut_ad(thd == trx->mysql_thd);
2863 ut_ad(!trx_is_registered_for_2pc(trx));
2864 trx_free_for_mysql(trx);
2865 } else {
2866 ut_ad(thd == trx->mysql_thd);
2867 ut_ad(trx_state_eq(trx, TRX_STATE_PREPARED));
2868 /* The choice not to disconnect transaction when
2869 trx_is_redo_rseg_updated(trx) is false is copied from
2870 the existing detach logic for prepared XA
2871 transactions in innobase_close_connection().
2872 If transaction did not modify anything, rolling it back doesn't modify
2873 the db, but lets us deregister and free the trx object to conserve
2874 resources, while still allowing XA COMMIT it in the future, as it
2875 succeeds on missing xids. */
2876 if (trx_is_redo_rseg_updated(trx)) {
2877 trx_disconnect_prepared(trx);
2878 } else {
2879 trx_rollback_for_mysql(trx);
2880 trx_deregister_from_2pc(trx);
2881 trx_free_for_mysql(trx);
2882 }
2883 }
2884 }
2885 trx = static_cast<trx_t *>(new_trx_arg);
2886 }
2887
2888 /** Note that a transaction has been registered with MySQL 2PC coordinator. */
2889 static inline void trx_register_for_2pc(trx_t *trx) /* in: transaction */
2890 {
2891 trx->is_registered = true;
2892 }
2893
2894 static inline void trx_deregister_from_2pc(trx_t *trx) {
2895 trx->is_registered = false;
2896 }
2897
2898 /** Copy table flags from MySQL's HA_CREATE_INFO into an InnoDB table object.
2899 Those flags are stored in .frm file and end up in the MySQL table object,
2900 but are frequently used inside InnoDB so we keep their copies into the
2901 InnoDB table object. */
2902 static void innobase_copy_frm_flags_from_create_info(
2903 dict_table_t *innodb_table, /*!< in/out: InnoDB table */
2904 const HA_CREATE_INFO *create_info) /*!< in: create info */
2905 {
2906 bool ps_on;
2907 bool ps_off;
2908
2909 if (innodb_table->is_temporary()) {
2910 /* Temp tables do not use persistent stats. */
2911 ps_on = false;
2912 ps_off = true;
2913 } else {
2914 ps_on = create_info->table_options & HA_OPTION_STATS_PERSISTENT;
2915 ps_off = create_info->table_options & HA_OPTION_NO_STATS_PERSISTENT;
2916 }
2917
2918 dict_stats_set_persistent(innodb_table, ps_on, ps_off);
2919
2920 dict_stats_auto_recalc_set(
2921 innodb_table, create_info->stats_auto_recalc == HA_STATS_AUTO_RECALC_ON,
2922 create_info->stats_auto_recalc == HA_STATS_AUTO_RECALC_OFF);
2923
2924 innodb_table->stats_sample_pages = create_info->stats_sample_pages;
2925 }
2926
2927 /** Copy table flags from MySQL's TABLE_SHARE into an InnoDB table object.
2928 Those flags are stored in .frm file and end up in the MySQL table object,
2929 but are frequently used inside InnoDB so we keep their copies into the
2930 InnoDB table object. */
2931 void innobase_copy_frm_flags_from_table_share(
2932 dict_table_t *innodb_table, /*!< in/out: InnoDB table */
2933 const TABLE_SHARE *table_share) /*!< in: table share */
2934 {
2935 bool ps_on;
2936 bool ps_off;
2937
2938 if (innodb_table->is_temporary()) {
2939 /* Temp tables do not use persistent stats */
2940 ps_on = false;
2941 ps_off = true;
2942 } else {
2943 ps_on = table_share->db_create_options & HA_OPTION_STATS_PERSISTENT;
2944 ps_off = table_share->db_create_options & HA_OPTION_NO_STATS_PERSISTENT;
2945 }
2946
2947 dict_stats_set_persistent(innodb_table, ps_on, ps_off);
2948
2949 dict_stats_auto_recalc_set(
2950 innodb_table, table_share->stats_auto_recalc == HA_STATS_AUTO_RECALC_ON,
2951 table_share->stats_auto_recalc == HA_STATS_AUTO_RECALC_OFF);
2952
2953 innodb_table->stats_sample_pages = table_share->stats_sample_pages;
2954 }
2955
2956 int ha_innobase::srv_concurrency_enter() {
2957 auto err = innobase_srv_conc_enter_innodb(m_prebuilt);
2958
2959 trx_t *trx = m_prebuilt->trx;
2960 return convert_error_code_to_mysql(err, 0, trx->mysql_thd);
2961 }
2962
2963 void ha_innobase::srv_concurrency_exit() {
2964 innobase_srv_conc_exit_innodb(m_prebuilt);
2965 }
2966
2967 /** Construct ha_innobase handler. */
2968
2969 ha_innobase::ha_innobase(handlerton *hton, TABLE_SHARE *table_arg)
2970 : handler(hton, table_arg),
2971 m_ds_mrr(this),
2972 m_prebuilt(),
2973 m_user_thd(),
2974 m_int_table_flags(
2975 HA_NULL_IN_KEY | HA_CAN_INDEX_BLOBS | HA_CAN_SQL_HANDLER |
2976 HA_PRIMARY_KEY_REQUIRED_FOR_POSITION | HA_PRIMARY_KEY_IN_READ_INDEX |
2977 HA_BINLOG_ROW_CAPABLE | HA_CAN_GEOMETRY | HA_PARTIAL_COLUMN_READ |
2978 HA_TABLE_SCAN_ON_INDEX | HA_CAN_FULLTEXT | HA_CAN_FULLTEXT_EXT |
2979 HA_CAN_FULLTEXT_HINTS | HA_CAN_EXPORT | HA_CAN_RTREEKEYS |
2980 HA_NO_READ_LOCAL_LOCK | HA_GENERATED_COLUMNS |
2981 HA_ATTACHABLE_TRX_COMPATIBLE | HA_CAN_INDEX_VIRTUAL_GENERATED_COLUMN |
2982 HA_DESCENDING_INDEX | HA_MULTI_VALUED_KEY_SUPPORT |
2983 HA_BLOB_PARTIAL_UPDATE | HA_SUPPORTS_GEOGRAPHIC_GEOMETRY_COLUMN |
2984 HA_SUPPORTS_DEFAULT_EXPRESSION),
2985 m_start_of_scan(),
2986 m_stored_select_lock_type(LOCK_NONE_UNSET),
2987 m_mysql_has_locked() {}
2988
2989 /** Updates the user_thd field in a handle and also allocates a new InnoDB
2990 transaction handle if needed, and updates the transaction fields in the
2991 m_prebuilt struct. */
2992 void ha_innobase::update_thd(THD *thd) /*!< in: thd to use the handle */
2993 {
2994 DBUG_TRACE;
2995 DBUG_PRINT("ha_innobase::update_thd",
2996 ("user_thd: %p -> %p", m_user_thd, thd));
2997
2998 /* The table should have been opened in ha_innobase::open(). */
2999 assert(m_prebuilt->table->n_ref_count > 0);
3000
3001 trx_t *trx = check_trx_exists(thd);
3002
3003 TrxInInnoDB trx_in_innodb(trx);
3004
3005 if (m_prebuilt->trx != trx) {
3006 row_update_prebuilt_trx(m_prebuilt, trx);
3007 }
3008
3009 m_user_thd = thd;
3010
3011 assert(m_prebuilt->trx->magic_n == TRX_MAGIC_N);
3012 assert(m_prebuilt->trx == thd_to_trx(m_user_thd));
3013 }
3014
3015 /** Updates the user_thd field in a handle and also allocates a new InnoDB
3016 transaction handle if needed, and updates the transaction fields in the
3017 m_prebuilt struct. */
3018
3019 void ha_innobase::update_thd() {
3020 THD *thd = ha_thd();
3021
3022 ut_ad(EQ_CURRENT_THD(thd));
3023 update_thd(thd);
3024 }
3025
3026 /** Registers an InnoDB transaction with the MySQL 2PC coordinator, so that
3027 the MySQL XA code knows to call the InnoDB prepare and commit, or rollback
3028 for the transaction. This MUST be called for every transaction for which
3029 the user may call commit or rollback. Calling this several times to register
3030 the same transaction is allowed, too. This function also registers the
3031 current SQL statement. */
3032 void innobase_register_trx(handlerton *hton, /* in: Innobase handlerton */
3033 THD *thd, /* in: MySQL thd (connection) object */
3034 trx_t *trx) /* in: transaction to register */
3035 {
3036 const ulonglong trx_id = static_cast<ulonglong>(trx_get_id_for_print(trx));
3037
3038 trans_register_ha(thd, false, hton, &trx_id);
3039
3040 if (!trx_is_registered_for_2pc(trx) &&
3041 thd_test_options(thd, OPTION_NOT_AUTOCOMMIT | OPTION_BEGIN)) {
3042 trans_register_ha(thd, true, hton, &trx_id);
3043 }
3044
3045 trx_register_for_2pc(trx);
3046 }
3047
3048 /** Quote a standard SQL identifier like tablespace, index or column name.
3049 @param[in] file output stream
3050 @param[in] trx InnoDB transaction, or NULL
3051 @param[in] id identifier to quote */
3052 void innobase_quote_identifier(FILE *file, trx_t *trx, const char *id) {
3053 const int q =
3054 trx != nullptr && trx->mysql_thd != nullptr
3055 ? get_quote_char_for_identifier(trx->mysql_thd, id, strlen(id))
3056 : '`';
3057
3058 if (q == EOF) {
3059 fputs(id, file);
3060 } else {
3061 putc(q, file);
3062
3063 while (int c = *id++) {
3064 if (c == q) {
3065 putc(c, file);
3066 }
3067 putc(c, file);
3068 }
3069
3070 putc(q, file);
3071 }
3072 }
3073
3074 /** Convert a table name to the MySQL system_charset_info (UTF-8)
3075 and quote it.
3076 @param[out] buf buffer for converted identifier
3077 @param[in] buflen length of buf, in bytes
3078 @param[in] id identifier to convert
3079 @param[in] idlen length of id, in bytes
3080 @param[in] thd MySQL connection thread, or NULL
3081 @return pointer to the end of buf */
3082 static char *innobase_convert_identifier(char *buf, ulint buflen,
3083 const char *id, ulint idlen,
3084 THD *thd) {
3085 const char *s = id;
3086
3087 char nz[MAX_TABLE_NAME_LEN + 1];
3088 char nz2[MAX_TABLE_NAME_LEN + 1];
3089
3090 /* Decode the table name. The MySQL function expects
3091 a NUL-terminated string. The input and output strings
3092 buffers must not be shared. */
3093 ut_a(idlen <= MAX_TABLE_NAME_LEN);
3094 memcpy(nz, id, idlen);
3095 nz[idlen] = 0;
3096
3097 s = nz2;
3098 idlen =
3099 explain_filename(thd, nz, nz2, sizeof nz2, EXPLAIN_PARTITIONS_AS_COMMENT);
3100 if (idlen > buflen) {
3101 idlen = buflen;
3102 }
3103 memcpy(buf, s, idlen);
3104 return (buf + idlen);
3105 }
3106
3107 /** Convert a table name to the MySQL system_charset_info (UTF-8).
3108 @return pointer to the end of buf */
3109 char *innobase_convert_name(
3110 char *buf, /*!< out: buffer for converted identifier */
3111 ulint buflen, /*!< in: length of buf, in bytes */
3112 const char *id, /*!< in: table name to convert */
3113 ulint idlen, /*!< in: length of id, in bytes */
3114 THD *thd) /*!< in: MySQL connection thread, or NULL */
3115 {
3116 char *s = buf;
3117 const char *bufend = buf + buflen;
3118
3119 const char *slash = (const char *)memchr(id, '/', idlen);
3120
3121 if (slash == nullptr) {
3122 return (innobase_convert_identifier(buf, buflen, id, idlen, thd));
3123 }
3124
3125 /* Print the database name and table name separately. */
3126 s = innobase_convert_identifier(s, bufend - s, id, slash - id, thd);
3127 if (s < bufend) {
3128 *s++ = '.';
3129 s = innobase_convert_identifier(s, bufend - s, slash + 1,
3130 idlen - (slash - id) - 1, thd);
3131 }
3132
3133 return (s);
3134 }
3135
3136 /** A wrapper function of innobase_convert_name(), convert a table name
3137 to the MySQL system_charset_info (UTF-8) and quote it if needed.
3138 @param[out] buf Buffer for converted identifier
3139 @param[in] buflen Length of buf, in bytes
3140 @param[in] name Table name to format */
3141 void innobase_format_name(char *buf, ulint buflen, const char *name) {
3142 const char *bufend;
3143
3144 bufend = innobase_convert_name(buf, buflen, name, strlen(name), nullptr);
3145
3146 ut_ad((ulint)(bufend - buf) < buflen);
3147
3148 buf[bufend - buf] = '\0';
3149 }
3150
3151 /** Determines if the currently running transaction has been interrupted.
3152 @return true if interrupted */
3153 bool trx_is_interrupted(const trx_t *trx) /*!< in: transaction */
3154 {
3155 return (trx && trx->mysql_thd && thd_killed(trx->mysql_thd));
3156 }
3157
3158 /** Determines if the currently running transaction is in strict mode.
3159 @return true if strict */
3160 bool trx_is_strict(trx_t *trx) /*!< in: transaction */
3161 {
3162 /* Relax strict check if table is in truncate create table */
3163 return (trx && trx->mysql_thd && THDVAR(trx->mysql_thd, strict_mode) &&
3164 (!trx->in_truncate));
3165 }
3166
3167 /** Resets some fields of a m_prebuilt struct. The template is used in fast
3168 retrieval of just those column values MySQL needs in its processing. */
3169 void ha_innobase::reset_template(void) {
3170 ut_ad(m_prebuilt->magic_n == ROW_PREBUILT_ALLOCATED);
3171 ut_ad(m_prebuilt->magic_n2 == m_prebuilt->magic_n);
3172
3173 /* Force table to be freed in close_thread_table(). */
3174 DBUG_EXECUTE_IF(
3175 "free_table_in_fts_query",
3176 if (m_prebuilt->in_fts_query) { table->invalidate_dict(); });
3177
3178 m_prebuilt->keep_other_fields_on_keyread = 0;
3179 m_prebuilt->read_just_key = 0;
3180 m_prebuilt->in_fts_query = false;
3181 m_prebuilt->m_end_range = false;
3182
3183 /* Reset index condition pushdown state. */
3184 if (m_prebuilt->idx_cond) {
3185 m_prebuilt->idx_cond = false;
3186 m_prebuilt->idx_cond_n_cols = 0;
3187 /* Invalidate m_prebuilt->mysql_template
3188 in ha_innobase::write_row(). */
3189 m_prebuilt->template_type = ROW_MYSQL_NO_TEMPLATE;
3190 }
3191 }
3192
3193 /** Call this when you have opened a new table handle in HANDLER, before you
3194 call index_read_map() etc. Actually, we can let the cursor stay open even
3195 over a transaction commit! Then you should call this before every operation,
3196 fetch next etc. This function inits the necessary things even after a
3197 transaction commit. */
3198
3199 void ha_innobase::init_table_handle_for_HANDLER(void) {
3200 /* If current thd does not yet have a trx struct, create one.
3201 If the current handle does not yet have a m_prebuilt struct, create
3202 one. Update the trx pointers in the m_prebuilt struct. Normally
3203 this operation is done in external_lock. */
3204
3205 update_thd(ha_thd());
3206
3207 /* Initialize the m_prebuilt struct much like it would be inited in
3208 external_lock */
3209
3210 innobase_srv_conc_force_exit_innodb(m_prebuilt->trx);
3211
3212 /* If the transaction is not started yet, start it */
3213
3214 trx_start_if_not_started_xa(m_prebuilt->trx, false, UT_LOCATION_HERE);
3215
3216 TrxInInnoDB trx_in_innodb(m_prebuilt->trx);
3217
3218 /* Assign a read view if the transaction does not have it yet */
3219
3220 trx_assign_read_view(m_prebuilt->trx);
3221
3222 innobase_register_trx(ht, m_user_thd, m_prebuilt->trx);
3223
3224 /* We did the necessary inits in this function, no need to repeat them
3225 in row_search_for_mysql */
3226
3227 m_prebuilt->sql_stat_start = false;
3228
3229 /* We let HANDLER always to do the reads as consistent reads, even
3230 if the trx isolation level would have been specified as SERIALIZABLE */
3231
3232 m_prebuilt->select_lock_type = LOCK_NONE;
3233 m_prebuilt->select_mode = SELECT_ORDINARY;
3234 m_stored_select_lock_type = LOCK_NONE;
3235
3236 /* Always fetch all columns in the index record */
3237
3238 m_prebuilt->hint_need_to_fetch_extra_cols = ROW_RETRIEVE_ALL_COLS;
3239
3240 /* We want always to fetch all columns in the whole row? Or do
3241 we???? */
3242
3243 m_prebuilt->used_in_HANDLER = true;
3244
3245 reset_template();
3246 }
3247
3248 /** Free any resources that were allocated and return failure.
3249 @return always return 1 */
3250 static int innodb_init_abort() {
3251 DBUG_TRACE;
3252 srv_shutdown_exit_threads();
3253 innodb_space_shutdown();
3254 innobase::component_services::deinitialize_service_handles();
3255 release_plugin_services();
3256 return 1;
3257 }
3258
3259 /** Open or create InnoDB data files.
3260 @param[in] dict_init_mode whether to create or open the files
3261 @param[in,out] tablespaces predefined tablespaces created by the DDSE
3262 @return 0 on success, 1 on failure */
3263 [[nodiscard]] static int innobase_init_files(
3264 dict_init_mode_t dict_init_mode,
3265 List<const Plugin_tablespace> *tablespaces);
3266
3267 /** Initialize InnoDB for being used to store the DD tables.
3268 Create the required files according to the dict_init_mode.
3269 Create strings representing the required DDSE tables, i.e.,
3270 tables that InnoDB expects to exist in the DD,
3271 and add them to the appropriate out parameter.
3272
3273 @param[in] dict_init_mode How to initialize files
3274
3275 @param[in] version Target DD version if a new server
3276 is being installed.
3277 0 if restarting an existing server.
3278
3279 @param[out] tables List of SQL DDL statements
3280 for creating DD tables that
3281 are needed by the DDSE.
3282
3283 @param[out] tablespaces List of meta data for predefined
3284 tablespaces created by the DDSE.
3285
3286 @retval true An error occurred.
3287 @retval false Success - no errors. */
3288 static bool innobase_ddse_dict_init(dict_init_mode_t dict_init_mode,
3289 uint version,
3290 List<const dd::Object_table> *tables,
3291 List<const Plugin_tablespace> *tablespaces);
3292
3293 /** Save the state of undo tablespaces from the dd to the undo::Tablespace
3294 @param[in] space_id tablespace ID
3295 @param[in] dd_space dd::Tablespace object
3296 @return true if success and false if the undo tablespace state is not saved. */
3297 bool apply_dd_undo_state(space_id_t space_id, const dd::Tablespace *dd_space) {
3298 bool success = true;
3299 if (!fsp_is_undo_tablespace(space_id)) {
3300 return (success);
3301 }
3302
3303 /* Get the state of undo tablespaces from the DD. */
3304 dd_space_states state = dd_tablespace_get_state_enum(dd_space, space_id);
3305
3306 undo::spaces->s_lock();
3307
3308 space_id_t space_num = undo::id2num(space_id);
3309 undo::Tablespace *undo_space = undo::spaces->find(space_num);
3310
3311 switch (state) {
3312 case DD_SPACE_STATE__LAST:
3313 /* If the "state" key is missing the DD might have been built with
3314 an older version. */
3315 case DD_SPACE_STATE_ACTIVE:
3316 /* Explicit undo spaces with no undo logs are set empty during
3317 startup to avoid getting undo. */
3318 if (undo_space->is_empty()) {
3319 undo_space->set_active();
3320 }
3321 ut_ad(undo_space->is_active());
3322 break;
3323 case DD_SPACE_STATE_INACTIVE:
3324 undo_space->set_inactive_explicit();
3325 srv_wake_purge_thread_if_not_active();
3326
3327 break;
3328 case DD_SPACE_STATE_EMPTY:
3329 undo_space->set_empty();
3330 break;
3331 case DD_SPACE_STATE_NORMAL:
3332 case DD_SPACE_STATE_DISCARDED:
3333 case DD_SPACE_STATE_CORRUPTED:
3334 success = false;
3335 break;
3336 }
3337
3338 undo::spaces->s_unlock();
3339
3340 return (success);
3341 }
3342
3343 /** Initialize the set of hard coded DD table ids.
3344 @param[in] dd_table_id Table id of DD table. */
3345 static void innobase_dict_register_dd_table_id(dd::Object_id dd_table_id);
3346
3347 /** Validate the DD tablespace data against what's read during the
3348 directory scan on startup. */
3349 class Validate_files {
3350 using DD_tablespaces = std::vector<const dd::Tablespace *>;
3351 using Const_iter = DD_tablespaces::const_iterator;
3352
3353 public:
3354 /** Constructor */
3355 Validate_files()
3356 : m_space_max_id(),
3357 m_n_to_check(),
3358 m_n_threads(),
3359 m_start_time(std::chrono::steady_clock::time_point{}),
3360 m_n_validated(),
3361 m_n_skipped(),
3362 m_n_moved(),
3363 m_n_missing(),
3364 m_n_deleted(),
3365 m_n_errors() {}
3366
3367 /** Validate the discovered tablespaces against the DD and attempt to open
3368 any DD tablespace not already open using a Parallel For Loop (par_for).
3369 @param[in] tablespaces Tablespace files read from the DD
3370 @return DB_SUCCESS if all OK */
3371 [[nodiscard]] dberr_t validate(const DD_tablespaces &tablespaces);
3372
3373 private:
3374 /** Validate a range of tablespaces from the DD.
3375 1. Compare the discovered files against those known to the dictionary.
3376 2. Open any tablespace known to the DD but not discovered and opened
3377 from the known directories.
3378 3. Update the DD if a tablespace has moved.
3379 4. Update the DD if an undo tablespace was truncated and replaced.
3380 5. If innodb_validate_tablespace_paths is set and this is not called
3381 while in recovery, only validate undo tablespaces.
3382 6. Track the number of skipped, moved, missing and deleted tablespaces.
3383 7. Return failure for any unexpected error.
3384 @param[in] begin Start of the slice
3385 @param[in] end End of the slice
3386 @param[in] thread_id Thread ID */
3387 void check(const Const_iter &begin, const Const_iter &end, size_t thread_id);
3388
3389 /** @return true if there were failures. */
3390 bool failed() const { return (m_n_errors.load() != 0); }
3391
3392 /** @return the maximum tablespace ID found. */
3393 space_id_t get_space_max_id() const { return (m_space_max_id); }
3394
3395 private:
3396 /** Maximum tablespace ID found. */
3397 std::atomic<space_id_t> m_space_max_id;
3398
3399 /** Number of tablespaces to check. */
3400 size_t m_n_to_check;
3401
3402 /** Number of threads used in the parallel for. */
3403 size_t m_n_threads;
3404
3405 /** The time when Validate_files::validate() starts or the last time
3406 one of the threads reported progress. */
3407 std::atomic<std::chrono::steady_clock::time_point> m_start_time;
3408 static_assert(decltype(m_start_time)::is_always_lock_free);
3409
3410 /** Number of tablespaces validated. */
3411 std::atomic_size_t m_n_validated;
3412
3413 /** Number of tablespaces skipped. */
3414 std::atomic_size_t m_n_skipped;
3415
3416 /** Number of tablespaces moved. */
3417 std::atomic_size_t m_n_moved;
3418
3419 /** Number of tablespaces missing. */
3420 std::atomic_size_t m_n_missing;
3421
3422 /** Number of tablespaces deleted. */
3423 std::atomic_size_t m_n_deleted;
3424
3425 /** Number of threads that failed. */
3426 std::atomic_size_t m_n_errors;
3427 };
3428
3429 void Validate_files::check(const Const_iter &begin, const Const_iter &end,
3430 size_t thread_id) {
3431 const auto sys_space_name = dict_sys_t::s_sys_space_name;
3432 THD *internal_thd = nullptr;
3433 if (current_thd == nullptr) {
3434 internal_thd = create_internal_thd();
3435 ut_a(internal_thd);
3436 ut_ad(internal_thd == current_thd);
3437 }
3438
3439 const auto thd_guard = create_scope_guard([internal_thd]() {
3440 if (internal_thd != nullptr) {
3441 destroy_internal_thd(internal_thd);
3442 }
3443 });
3444
3445 /* Validate all tablespaces if innodb_validate_tablespace_paths=ON OR
3446 server is in recovery OR Change buffer is not empty. Change buffer
3447 applier background thread will skip the change buffer entries of the
3448 tablespaces which are not loaded which will cause corruption of
3449 secondary indexes, so it is important to load the tablespaces for which
3450 entry is present in the change buffer. Presently we are loading all the
3451 tablespaces. If all the conditions mentioned above are false then
3452 validate only undo tablespaces */
3453
3454 const bool ibd_validate =
3455 srv_validate_tablespace_paths || recv_needed_recovery || !ibuf_is_empty();
3456
3457 std::string prefix;
3458 if (m_n_threads > 0) {
3459 std::ostringstream msg;
3460 msg << "Thread# " << thread_id << " - ";
3461 prefix = msg.str();
3462 }
3463
3464 for (auto it = begin; it != end; ++it) {
3465 const auto &dd_tablespace = *it;
3466
3467 if (std::chrono::steady_clock::now() - m_start_time.load() >=
3468 PRINT_INTERVAL) {
3469 m_start_time = std::chrono::steady_clock::now();
3470
3471 std::ostringstream msg;
3472
3473 if (m_n_threads) {
3474 msg << m_n_threads << "threads have validated ";
3475 } else {
3476 msg << "Validated ";
3477 }
3478
3479 msg << m_n_validated << " out of " << m_n_to_check
3480 << " tablespaces so far.";
3481
3482 if (m_n_skipped > 0) {
3483 msg << " Skipped=" << m_n_skipped << ".";
3484 }
3485 if (m_n_moved > 0) {
3486 msg << " Moved=" << m_n_moved << ".";
3487 }
3488 if (m_n_missing > 0) {
3489 msg << " Missing=" << m_n_missing << ".";
3490 }
3491 if (m_n_deleted > 0) {
3492 msg << " Deleted=" << m_n_deleted << ".";
3493 }
3494
3495 ib::info(ER_IB_MSG_525) << msg.str();
3496 }
3497
3498 if (dd_tablespace->engine() != innobase_hton_name) {
3499 ++m_n_skipped;
3500 continue;
3501 }
3502
3503 const auto &p = dd_tablespace->se_private_data();
3504 const auto &o = dd_tablespace->options();
3505 const char *space_name = dd_tablespace->name().c_str();
3506 const auto se_key_value = dd_space_key_strings;
3507
3508 /* There should be exactly one file name associated
3509 with each InnoDB tablespace, except innodb_system */
3510
3511 space_id_t space_id;
3512 if (p.get(se_key_value[DD_SPACE_ID], &space_id)) {
3513 /* Failed to fetch the tablespace ID */
3514 ++m_n_errors;
3515 break;
3516 }
3517
3518 /* If --innodb_validate_tablespace_paths=OFF and
3519 startup is not in recovery and change buffer is empty,
3520 then skip all IBD files. */
3521 if (!ibd_validate && !fsp_is_undo_tablespace(space_id)) {
3522 ++m_n_skipped;
3523 continue;
3524 }
3525
3526 /* Do not open a discovered tablespace that is currently discarded.
3527 It will be opened properly when it is imported. */
3528 dd_space_states dd_state = dd_tablespace_get_state_enum(&p, space_id);
3529 if (dd_state == DD_SPACE_STATE_DISCARDED) {
3530 ++m_n_skipped;
3531 continue;
3532 }
3533
3534 /* Get the spacename for this tablespace from the DD. */
3535 if (dd_tablespace->files().size() != 1 &&
3536 strcmp(space_name, sys_space_name) != 0) {
3537 /* Only the InnoDB system tablespace has support for
3538 multiple files per tablespace. For historial reasons. */
3539 ++m_n_errors;
3540 break;
3541 }
3542
3543 if (!dict_sys_t::is_reserved(space_id)) {
3544 /* Currently try to find the max space_id only.
3545 It should be able to reuse the deleted smaller ones later */
3546 auto current_max = m_space_max_id.load();
3547 while (current_max < space_id &&
3548 !m_space_max_id.compare_exchange_weak(current_max, space_id))
3549 ;
3550 }
3551
3552 /* System and temp files are tracked and opened separately.
3553 Consider them validated. */
3554 if (fsp_is_system_or_temp_tablespace(space_id)) {
3555 ++m_n_validated;
3556 continue;
3557 }
3558
3559 /* Get the filename for this tablespace from the DD. */
3560 const auto file = *dd_tablespace->files().begin();
3561 std::string dd_path{file->filename().c_str()};
3562 const char *filename = dd_path.c_str();
3563
3564 uint32_t fsp_flags = 0;
3565 if (p.get(se_key_value[DD_SPACE_FLAGS], &fsp_flags)) {
3566 /* Failed to fetch the tablespace flags. */
3567 ++m_n_errors;
3568 break;
3569 }
3570
3571 /* If the trunc log file is still around, this undo tablespace needs to be
3572 rebuilt now. */
3573 if (fsp_is_undo_tablespace(space_id)) {
3574 mutex_enter(&undo::ddl_mutex);
3575 dberr_t err = srv_undo_tablespace_fixup(space_name, filename, space_id);
3576 mutex_exit(&undo::ddl_mutex);
3577 if (err != DB_SUCCESS) {
3578 ib::error(ER_IB_MSG_FAILED_TO_FINISH_TRUNCATE, prefix.c_str(),
3579 space_name);
3580 continue;
3581 }
3582 }
3583
3584 /* Check if IBD tablespaces exist in mem correctly. This call also adjusts
3585 the tablespace name for undo and general tablespace. We still need to check
3586 if the data files are moved. */
3587 if (fil_space_exists_in_mem(space_id, space_name, false, true)) {
3588 if (fsp_is_undo_tablespace(space_id) &&
3589 !apply_dd_undo_state(space_id, dd_tablespace)) {
3590 /* Undo tablespaces are always opened first. But in case they have
3591 been moved and the DD needs to be updated, we fall thru to the location
3592 check below. First though, update the DD tablespace state. */
3593 ib::warn(ER_IB_MSG_FAIL_TO_SAVE_SPACE_STATE, prefix.c_str(),
3594 space_name);
3595 }
3596 }
3597
3598 /* Check the file paths of IBD and Undo datafiles below. */
3599 if (!fsp_is_ibd_tablespace(space_id) && !fsp_is_undo_tablespace(space_id)) {
3600 continue;
3601 }
3602
3603 /* Check if any IBD or Undo files are moved, deleted or missing. */
3604 std::string new_path;
3605
3606 /* Just in case this dictionary was ported between
3607 Windows and POSIX. */
3608 Fil_path::normalize(dd_path);
3609 Fil_state state = Fil_state::MATCHES;
3610 state = fil_tablespace_path_equals(space_id, space_name, fsp_flags, dd_path,
3611 &new_path);
3612
3613 if (state == Fil_state::COMPARE_ERROR) {
3614 ++m_n_errors;
3615 break;
3616 }
3617
3618 if (state == Fil_state::MATCHES) {
3619 new_path.assign(dd_path);
3620 }
3621
3622 std::string space_str(space_name);
3623
3624 std::string old_space;
3625 bool file_name_changed = false;
3626 bool file_path_changed = (state == Fil_state::MOVED);
3627
3628 if (state == Fil_state::MATCHES || state == Fil_state::MOVED ||
3629 state == Fil_state::MOVED_PREV) {
3630 /* We need to update space name and table name for partitioned tables
3631 if letter case is different. */
3632 if (fil_update_partition_name(space_id, fsp_flags, true, space_str,
3633 new_path)) {
3634 file_name_changed = true;
3635 if (state != Fil_state::MOVED_PREV) {
3636 state = Fil_state::MOVED;
3637 }
3638 }
3639
3640 /* Update DD if tablespace name is corrected. */
3641 if (space_str.compare(space_name) != 0) {
3642 old_space.assign(space_name);
3643 space_name = space_str.c_str();
3644 if (state != Fil_state::MOVED_PREV) {
3645 state = Fil_state::MOVED;
3646 }
3647 }
3648 }
3649
3650 switch (state) {
3651 case Fil_state::COMPARE_ERROR:
3652 ut_error;
3653 case Fil_state::MATCHES:
3654 break;
3655
3656 case Fil_state::MISSING:
3657
3658 ib::warn(ER_IB_MSG_526) << prefix << "Tablespace " << space_id << ","
3659 << " name '" << space_name << "',"
3660 << " file '" << dd_path << "'"
3661 << " is missing!";
3662
3663 if (fsp_is_undo_tablespace(space_id)) {
3664 /* This deserves a special error message. */
3665 ib::error(ER_IB_MSG_CANNOT_FIND_DD_UNDO_SPACE, space_name, filename);
3666 }
3667 ++m_n_missing;
3668 continue;
3669
3670 case Fil_state::DELETED:
3671
3672 ib::warn(ER_IB_MSG_527) << prefix << "Tablespace " << space_id << ","
3673 << " name '" << space_name << "',"
3674 << " file '" << dd_path << "'"
3675 << " was deleted!";
3676 ++m_n_deleted;
3677 continue;
3678
3679 case Fil_state::MOVED:
3680 fil_add_moved_space(dd_tablespace->id(), space_id, space_name, dd_path,
3681 new_path, false);
3682 ++m_n_moved;
3683
3684 if (m_n_moved > MOVED_FILES_PRINT_THRESHOLD) {
3685 filename = new_path.c_str();
3686
3687 break;
3688 }
3689
3690 if (!old_space.empty()) {
3691 ib::info(ER_IB_MSG_FIL_STATE_MOVED_CORRECTED, prefix.c_str(),
3692 static_cast<unsigned long long>(dd_tablespace->id()),
3693 static_cast<unsigned int>(space_id), old_space.c_str(),
3694 space_name);
3695 }
3696
3697 if (file_path_changed) {
3698 ib::info(ER_IB_MSG_FIL_STATE_MOVED_CHANGED_PATH, prefix.c_str(),
3699 static_cast<unsigned long long>(dd_tablespace->id()),
3700 static_cast<unsigned int>(space_id), space_name,
3701 dd_path.c_str(), new_path.c_str());
3702
3703 } else if (file_name_changed) {
3704 ib::info(ER_IB_MSG_FIL_STATE_MOVED_CHANGED_NAME, prefix.c_str(),
3705 static_cast<unsigned long long>(dd_tablespace->id()),
3706 static_cast<unsigned int>(space_id), space_name,
3707 dd_path.c_str(), new_path.c_str());
3708 }
3709
3710 filename = new_path.c_str();
3711
3712 if (m_n_moved == MOVED_FILES_PRINT_THRESHOLD) {
3713 ib::info(ER_IB_MSG_FIL_STATE_MOVED_TOO_MANY, prefix.c_str());
3714 }
3715 break;
3716
3717 case Fil_state::MOVED_PREV:
3718 fil_add_moved_space(dd_tablespace->id(), space_id, space_name, dd_path,
3719 new_path, true);
3720 ++m_n_moved;
3721
3722 if (m_n_moved == MOVED_FILES_PRINT_THRESHOLD) {
3723 ib::info(ER_IB_MSG_FIL_STATE_MOVED_TOO_MANY, prefix.c_str());
3724 }
3725
3726 if (m_n_moved < MOVED_FILES_PRINT_THRESHOLD) {
3727 ib::info(ER_IB_MSG_FIL_STATE_MOVED_PREV, prefix.c_str(),
3728 static_cast<unsigned long long>(dd_tablespace->id()),
3729 static_cast<unsigned int>(space_id), space_name,
3730 new_path.c_str());
3731 }
3732 break;
3733
3734 case Fil_state::RENAMED:
3735 break;
3736 }
3737
3738 /* If this space is already open, we can move on to the next. */
3739 if (nullptr != fil_space_get(space_id)) {
3740 /* Set the autoextend_size attribute for the newly opened space. */
3741 uint64_t autoextend_size{};
3742
3743 if (o.exists(autoextend_size_str) &&
3744 !o.get(autoextend_size_str, &autoextend_size)) {
3745 ut_d(dberr_t ret =) fil_set_autoextend_size(space_id, autoextend_size);
3746 ut_ad(ret == DB_SUCCESS);
3747 }
3748 ++m_n_validated;
3749 continue;
3750 }
3751
3752 if (fsp_is_undo_tablespace(space_id)) {
3753 /* The undo space may be open with a alternate space_id */
3754 space_id_t space_num = undo::id2num(space_id);
3755 if (nullptr != undo::spaces->find(space_num)) {
3756 ++m_n_validated;
3757 continue;
3758 }
3759
3760 /* If an undo tablespace from the DD is in an unknown location,
3761 it will not yet be open. */
3762 undo::Tablespace undo_space(space_id);
3763 undo_space.set_space_name(space_name);
3764 undo_space.set_file_name(filename);
3765
3766 mutex_enter(&undo::ddl_mutex);
3767 undo::spaces->x_lock();
3768 undo::use_space_id(space_id);
3769 dberr_t err = srv_undo_tablespace_open(undo_space);
3770 undo::spaces->x_unlock();
3771 mutex_exit(&undo::ddl_mutex);
3772 if (err != DB_SUCCESS) {
3773 ib::error(ER_IB_MSG_CANNOT_FIND_DD_UNDO_SPACE, space_name, filename);
3774 }
3775 ++m_n_validated;
3776 continue;
3777 }
3778
3779 /* The IBD filename from the DD has not yet been opened. Try to open it.
3780 It's safe to pass space_name in tablename charset because filename is
3781 already in filename charset. */
3782 bool validate = recv_needed_recovery && srv_force_recovery == 0;
3783 dberr_t err = fil_ibd_open(validate, FIL_TYPE_TABLESPACE, space_id,
3784 fsp_flags, space_name, filename, false, false);
3785
3786 switch (err) {
3787 case DB_SUCCESS: {
3788 /* Set the autoextend_size attribute for the newly opened space. */
3789 uint64_t autoextend_size{};
3790
3791 if (o.exists(autoextend_size_str) &&
3792 !o.get(autoextend_size_str, &autoextend_size)) {
3793 ut_d(dberr_t ret =)
3794 fil_set_autoextend_size(space_id, autoextend_size);
3795 ut_ad(ret == DB_SUCCESS);
3796 }
3797 ++m_n_validated;
3798 break;
3799 }
3800 case DB_CANNOT_OPEN_FILE:
3801 case DB_WRONG_FILE_NAME:
3802 default:
3803 ib::info(ER_IB_MSG_530) << prefix << "Tablespace " << space_id << ","
3804 << " name '" << space_name << "',"
3805 << " unable to open file"
3806 << " '" << filename << "' - " << ut_strerr(err);
3807 ++m_n_missing;
3808 }
3809 }
3810 }
3811
3812 dberr_t Validate_files::validate(const DD_tablespaces &tablespaces) {
3813 m_n_to_check = tablespaces.size();
3814 m_n_threads = fil_get_scan_threads(m_n_to_check);
3815 m_start_time = std::chrono::steady_clock::now();
3816
3817 if (!srv_validate_tablespace_paths && !recv_needed_recovery &&
3818 ibuf_is_empty()) {
3819 ib::info(ER_IB_TABLESPACE_PATH_VALIDATION_SKIPPED);
3820 }
3821
3822 using std::placeholders::_1;
3823 using std::placeholders::_2;
3824 using std::placeholders::_3;
3825
3826 std::function<void(const Validate_files::Const_iter &,
3827 const Validate_files::Const_iter &, size_t)>
3828 check = std::bind(&Validate_files::check, this, _1, _2, _3);
3829
3830 par_for(PFS_NOT_INSTRUMENTED, tablespaces, m_n_threads, check);
3831
3832 std::ostringstream msg;
3833 msg << "Scanned " << m_n_to_check << " tablespaces."
3834 << " Validated " << m_n_validated.load() << ".";
3835
3836 if (m_n_skipped.load() > 0) {
3837 msg << " Skipped " << m_n_skipped.load() << ".";
3838 }
3839 if (m_n_moved.load() > 0) {
3840 msg << " Found " << m_n_moved.load() << " moved.";
3841 }
3842 if (m_n_missing.load() > 0) {
3843 msg << " Found " << m_n_missing.load() << " missing.";
3844 }
3845 if (m_n_deleted.load() > 0) {
3846 msg << " Found " << m_n_deleted.load() << " deleted.";
3847 }
3848 if (m_n_errors.load() > 0) {
3849 msg << " Encountered " << m_n_errors.load() << " errors.";
3850 }
3851 ib::info(ER_IB_MSG_531) << msg.str();
3852
3853 if (failed()) {
3854 return (DB_ERROR);
3855 }
3856
3857 fil_set_max_space_id_if_bigger(get_space_max_id());
3858
3859 if (srv_validate_tablespace_paths) {
3860 clone_sys->set_space_initialized();
3861 }
3862
3863 return (DB_SUCCESS);
3864 }
3865
3866 /** Discover all InnoDB tablespaces.
3867 @param[in,out] thd thread handle
3868 @retval true on error
3869 @retval false on success */
3870 [[nodiscard]] static bool boot_tablespaces(THD *thd) {
3871 auto dc = dd::get_dd_client(thd);
3872
3873 using DD_tablespaces = std::vector<const dd::Tablespace *>;
3874 using Releaser = dd::cache::Dictionary_client::Auto_releaser;
3875
3876 DD_tablespaces tablespaces;
3877 Releaser releaser(dc);
3878
3879 /* Initialize the max space_id from sys header */
3880 dict_sys_mutex_enter();
3881
3882 mtr_t mtr;
3883
3884 mtr_start(&mtr);
3885
3886 space_id_t space_max_id = mtr_read_ulint(
3887 dict_hdr_get(&mtr) + DICT_HDR_MAX_SPACE_ID, MLOG_4BYTES, &mtr);
3888
3889 mtr_commit(&mtr);
3890
3891 fil_set_max_space_id_if_bigger(space_max_id);
3892
3893 dict_sys_mutex_exit();
3894
3895 ib::info(ER_IB_MSG_532) << "Reading DD tablespace files";
3896
3897 if (dc->fetch_global_components(&tablespaces)) {
3898 /* Failed to fetch the tablespaces from the DD. */
3899
3900 return (DD_FAILURE);
3901 }
3902
3903 Validate_files validator;
3904 dberr_t err = validator.validate(tablespaces);
3905
3906 return (err == DB_SUCCESS ? DD_SUCCESS : DD_FAILURE);
3907 }
3908
3909 /** Create metadata for a predefined tablespace at server initialization.
3910 @param[in,out] dd_client data dictionary client
3911 @param[in] space_id InnoDB tablespace ID
3912 @param[in] flags tablespace flags
3913 @param[in] name tablespace name
3914 @param[in] filename tablespace file name
3915 @retval false on success
3916 @retval true on failure */
3917 static bool predefine_tablespace(dd::cache::Dictionary_client *dd_client,
3918 space_id_t space_id, uint32_t flags,
3919 const char *name, const char *filename) {
3920 dd::Object_id dd_space_id;
3921
3922 return (dd_create_tablespace(dd_client, name, space_id, flags, filename,
3923 false, dd_space_id));
3924 }
3925
3926 /** Check if InnoDB is in a mode where the data dictionary is read-only.
3927 @return true if srv_read_only_mode is true or if srv_force_recovery > 0 */
3928 static bool innobase_is_dict_readonly() {
3929 DBUG_TRACE;
3930 return srv_read_only_mode || srv_force_recovery > 0;
3931 }
3932
3933 #ifndef UNIV_HOTBACKUP
3934 /** Update metadata for innodb_temporary tablespace at server startup.
3935 This information is used by the information_schema.files to show the
3936 filename for the temporary tablespace innodb_temporary.
3937 @param[in,out] thd THD
3938 @retval false on success
3939 @retval true on failure */
3940 static bool update_innodb_temporary_metadata(THD *thd) {
3941 if (innobase_is_dict_readonly()) {
3942 /* Metadata cannot be updated if the server is started in read_only
3943 mode. This means that the values for innodb_temp_data_file_path and
3944 file_name in information_schema.files will not be in same. */
3945 LogErr(WARNING_LEVEL, ER_SKIP_UPDATING_METADATA_IN_SE_RO_MODE,
3946 "information_schema");
3947 return false;
3948 }
3949
3950 /* Get the filename from srv_tmp_space */
3951 auto fpath = srv_tmp_space.first_datafile()->filepath();
3952 auto &dc = *thd->dd_client();
3953 dd::cache::Dictionary_client::Auto_releaser releaser(&dc);
3954 const dd::String_type tbsp_name{dict_sys_t::s_temp_space_name};
3955 dd::Tablespace *tmp_tbsp{nullptr};
3956
3957 if (!dc.acquire_for_modification<dd::Tablespace>(tbsp_name, &tmp_tbsp) &&
3958 tmp_tbsp != nullptr) {
3959 ut_ad(tmp_tbsp->files().size() == 1);
3960
3961 /* Get the tablespace file for innodb_temporary tablespace. */
3962 dd::Tablespace_file *dd_file =
3963 const_cast<dd::Tablespace_file *>(*(tmp_tbsp->files().begin()));
3964
3965 ut_ad(dd_file);
3966
3967 dd_file->set_filename(fpath);
3968
3969 if (dc.update(tmp_tbsp)) {
3970 /* Unable to update the metadata. */
3971 ut_d(ut_error);
3972 ut_o(return true);
3973 }
3974 } else {
3975 /* Unable to acquire innodb_temporary tablespace for modification. */
3976 ut_d(ut_error);
3977 ut_o(return true);
3978 }
3979 return false;
3980 }
3981 #endif /* !UNIV_HOTBACKUP */
3982
3983 /** Predefine the undo tablespace metadata at server initialization.
3984 @param[in,out] dd_client data dictionary client
3985 @retval false on success
3986 @retval true on failure */
3987 static bool predefine_undo_tablespaces(
3988 dd::cache::Dictionary_client *dd_client) {
3989 /** Undo tablespaces use a reserved range of tablespace ID. */
3990 for (auto undo_space : undo::spaces->m_spaces) {
3991 uint32_t flags = fsp_flags_init(univ_page_size, false, false, false, false);
3992
3993 if (predefine_tablespace(dd_client, undo_space->id(), flags,
3994 undo_space->space_name(),
3995 undo_space->file_name())) {
3996 return (true);
3997 }
3998 }
3999
4000 return (false);
4001 }
4002
4003 /** Invalidate an entry or entries for partitioned table from the dict cache.
4004 @param[in] schema_name Schema name
4005 @param[in] table_name Table name */
4006 static void innobase_dict_cache_reset(const char *schema_name,
4007 const char *table_name) {
4008 char name[FN_REFLEN];
4009 snprintf(name, sizeof name, "%s/%s", schema_name, table_name);
4010
4011 dict_sys_mutex_enter();
4012
4013 dict_table_t *table = dict_table_check_if_in_cache_low(name);
4014
4015 if (table != nullptr) {
4016 btr_drop_ahi_for_table(table);
4017 dict_table_remove_from_cache(table);
4018 } else if (strcmp(schema_name, "mysql") != 0) {
4019 dict_partitioned_table_remove_from_cache(name);
4020 }
4021
4022 dict_sys_mutex_exit();
4023 }
4024
4025 /** Invalidate user table dict cache after Replication Plugin recovers. Table
4026 definition could be different with XA commit/rollback of DDL operations */
4027 static void innobase_dict_cache_reset_tables_and_tablespaces() {
4028 dict_sys_mutex_enter();
4029
4030 /* There should be no DDL/DML activity at this stage, so access
4031 the LRU chain without mutex. We only invalidates the table
4032 in LRU list */
4033 for (auto table : dict_sys->table_LRU.removable()) {
4034 /* Make sure table->is_dd_table is set */
4035
4036 std::string db_str;
4037 std::string tbl_str;
4038 dict_name::get_table(table->name.m_name, db_str, tbl_str);
4039
4040 /* TODO: Remove follow if we have better way to identify
4041 DD "system table" */
4042 if (db_str.compare("mysql") == 0 || table->is_dd_table ||
4043 table->is_corrupted() ||
4044 DICT_TF2_FLAG_IS_SET(table, DICT_TF2_RESURRECT_PREPARED)) {
4045 continue;
4046 }
4047
4048 table->acquire();
4049 btr_drop_ahi_for_table(table);
4050 dd_table_close(table, nullptr, nullptr, true);
4051
4052 dict_table_remove_from_cache(table);
4053 }
4054 dict_sys_mutex_exit();
4055 }
4056
4057 /** Perform high-level recovery in InnoDB as part of initializing the
4058 data dictionary.
4059 @param[in] dict_recovery_mode How to do recovery
4060 @param[in] version Target DD version if a new
4061 server is being installed.
4062 Actual DD version if restarting
4063 an existing server.
4064 @retval true An error occurred.
4065 @retval false Success - no errors. */
4066 static bool innobase_dict_recover(dict_recovery_mode_t dict_recovery_mode,
4067 uint version [[maybe_unused]]) {
4068 THD *thd = current_thd;
4069
4070 switch (dict_recovery_mode) {
4071 case DICT_RECOVERY_INITIALIZE_TABLESPACES:
4072 break;
4073 case DICT_RECOVERY_RESTART_SERVER:
4074 [[fallthrough]];
4075 case DICT_RECOVERY_INITIALIZE_SERVER:
4076 if (dict_sys->dynamic_metadata == nullptr) {
4077 dict_sys->dynamic_metadata =
4078 dd_table_open_on_name(thd, nullptr, "mysql/innodb_dynamic_metadata",
4079 false, DICT_ERR_IGNORE_NONE);
4080 dict_persist->table_buffer =
4081 ut::new_withkey<DDTableBuffer>(UT_NEW_THIS_FILE_PSI_KEY);
4082 }
4083
4084 dict_sys->table_stats =
4085 dd_table_open_on_name(thd, nullptr, "mysql/innodb_table_stats", false,
4086 DICT_ERR_IGNORE_NONE);
4087 dict_sys->index_stats =
4088 dd_table_open_on_name(thd, nullptr, "mysql/innodb_index_stats", false,
4089 DICT_ERR_IGNORE_NONE);
4090 dict_sys->ddl_log = dd_table_open_on_name(
4091 thd, nullptr, "mysql/innodb_ddl_log", false, DICT_ERR_IGNORE_NONE);
4092 log_ddl = ut::new_withkey<Log_DDL>(UT_NEW_THIS_FILE_PSI_KEY);
4093 }
4094
4095 switch (dict_recovery_mode) {
4096 case DICT_RECOVERY_INITIALIZE_SERVER:
4097 return (false);
4098 case DICT_RECOVERY_INITIALIZE_TABLESPACES: {
4099 dd::cache::Dictionary_client *client = dd::get_dd_client(thd);
4100 dd::cache::Dictionary_client::Auto_releaser releaser(client);
4101
4102 if (predefine_tablespace(client, dict_sys_t::s_temp_space_id,
4103 srv_tmp_space.flags(),
4104 dict_sys_t::s_temp_space_name,
4105 dict_sys_t::s_temp_space_file_name)) {
4106 return (DD_FAILURE);
4107 }
4108
4109 if (predefine_undo_tablespaces(client)) {
4110 return (DD_FAILURE);
4111 }
4112
4113 break;
4114 }
4115 case DICT_RECOVERY_RESTART_SERVER:
4116 /* Traverse dd::tablespaces and apply/validate this metadata. */
4117 if (boot_tablespaces(thd)) {
4118 return (true);
4119 }
4120
4121 #ifndef UNIV_HOTBACKUP
4122 /* For all tablespaces for which tablespace key is to be reencrypt,
4123 do it now. */
4124 fil_encryption_reencrypt(Encryption::s_tablespaces_to_reencrypt);
4125 #endif /* !UNIV_HOTBACKUP */
4126
4127 /* We might need to fix tables for CSV and MyISAM SE */
4128 if (fix_cloned_tables(thd)) {
4129 return (true);
4130 }
4131
4132 srv_dict_recover_on_restart();
4133 }
4134
4135 srv_start_threads();
4136
4137 #ifndef UNIV_HOTBACKUP
4138 /* Update the metadata for innodb_temporary tablespace to reflect
4139 the correct filename. */
4140 if (update_innodb_temporary_metadata(thd)) {
4141 return true;
4142 }
4143 #endif /* !UNIV_HOTBACKUP */
4144
4145 return (fil_open_for_business(srv_read_only_mode) != DB_SUCCESS);
4146 }
4147
4148 /** DDL crash recovery: process the records recovered from "log_ddl" table */
4149 static void innobase_post_recover() {
4150 if (srv_force_recovery < SRV_FORCE_NO_TRX_UNDO) {
4151 DBUG_EXECUTE_IF("DDL_Log_remove_inject_startup_error_2",
4152 srv_inject_too_many_concurrent_trxs = true;);
4153
4154 dberr_t err = log_ddl->recover();
4155
4156 /* Abort post recovery startup if this is not successful. */
4157 if (err != DB_SUCCESS) {
4158 ib::fatal(UT_LOCATION_HERE, ER_IB_MSG_POST_RECOVER_DDL_LOG_RECOVER);
4159 }
4160 }
4161
4162 fil_free_scanned_files();
4163
4164 /* If undo tablespaces are to be encrypted, encrypt them now */
4165 if (srv_undo_log_encrypt) {
4166 ut_ad(Encryption::check_keyring());
4167
4168 /* There would be at least 2 UNDO tablespaces */
4169 ut_ad(undo::spaces->size() >= FSP_IMPLICIT_UNDO_TABLESPACES);
4170
4171 if (srv_read_only_mode) {
4172 ib::error(ER_IB_MSG_1051);
4173 srv_undo_log_encrypt = false;
4174 } else {
4175 /* Enable encryption for UNDO tablespaces */
4176 mutex_enter(&undo::ddl_mutex);
4177 if (srv_enable_undo_encryption()) {
4178 srv_undo_log_encrypt = false;
4179 ut_d(ut_error);
4180 }
4181 mutex_exit(&undo::ddl_mutex);
4182
4183 /* We have to ensure that the first page of the undo tablespaces gets
4184 flushed to disk. Otherwise during recovery, since we read the first
4185 page without applying the redo logs, it will be determined that
4186 encryption is off. */
4187 buf_flush_sync_all_buf_pools();
4188 }
4189 }
4190
4191 /* If redo log is to be encrypted, encrypt it now */
4192 if (srv_redo_log_encrypt) {
4193 ut_ad(Encryption::check_keyring());
4194
4195 if (srv_read_only_mode) {
4196 ib::error(ER_IB_MSG_LOG_FILES_CANNOT_ENCRYPT_IN_READ_ONLY);
4197 srv_redo_log_encrypt = false;
4198 } else {
4199 /* Enable encryption for REDO log */
4200 if (srv_enable_redo_encryption()) {
4201 srv_redo_log_encrypt = false;
4202 ut_d(ut_error);
4203 }
4204 }
4205 }
4206
4207 if (srv_read_only_mode || srv_force_recovery >= SRV_FORCE_NO_BACKGROUND) {
4208 purge_sys->state = PURGE_STATE_DISABLED;
4209 return;
4210 }
4211
4212 Auto_THD thd;
4213 if (dd_tablespace_update_cache(thd.thd)) {
4214 ut_d(ut_error);
4215 }
4216
4217 srv_start_threads_after_ddl_recovery();
4218
4219 ut_a(innodb_inited);
4220
4221 if (!opt_initialize) {
4222 if (!log_pfs_create_tables()) {
4223 ib::warn(ER_IB_MSG_LOG_PFS_CREATE_TABLES_FAILED);
4224 }
4225 }
4226 }
4227
4228 /**
4229 Get the server version id stored in the header of the
4230 dictionary tablespace.
4231
4232 @param [out] version Version number from the DD
4233 tablespace header.
4234
4235 @retval Operation outcome, false if no error, otherwise true.
4236 */
4237 static bool innobase_dict_get_server_version(uint *version) {
4238 return (fsp_header_dict_get_server_version(version));
4239 }
4240
4241 /**
4242 Store the current server version number into the
4243 header of the dictionary tablespace.
4244
4245 @retval Operation outcome, false if no error, otherwise true.
4246 */
4247 static bool innobase_dict_set_server_version() {
4248 /* Update the server version number, but leave the space version unchanged */
4249 return (upgrade_space_version(dict_sys_t::s_dict_space_id, true));
4250 }
4251
4252 /** Start page tracking.
4253 @param[out] start_id LSN indicating when the tracking was started
4254 @return Operation status.
4255 @retval 0 Success
4256 @retval other ER_* mysql error. Get error details from THD. */
4257 static int innobase_page_track_start(uint64_t *start_id) {
4258 if (srv_read_only_mode) {
4259 my_error(ER_READ_ONLY_MODE, MYF(0));
4260 return ER_READ_ONLY_MODE;
4261 }
4262
4263 Page_Arch_Client_Ctx *ctx = arch_page_sys->get_sys_client();
4264
4265 int err = ctx->start(false, start_id);
4266
4267 return (err);
4268 }
4269
4270 /** Stop page tracking.
4271 @param[out] stop_id Stop LSN indicating when the tracking was stopped
4272 @return Operation status.
4273 @retval 0 Success
4274 @retval other ER_* mysql error. Get error details from THD. */
4275 static int innobase_page_track_stop(uint64_t *stop_id) {
4276 if (srv_read_only_mode) {
4277 my_error(ER_READ_ONLY_MODE, MYF(0));
4278 return ER_READ_ONLY_MODE;
4279 }
4280
4281 Page_Arch_Client_Ctx *ctx = arch_page_sys->get_sys_client();
4282
4283 int err = ctx->stop(stop_id);
4284
4285 return (err);
4286 }
4287
4288 /** Purge page tracking data.
4289 @param[in,out] purge_id Purge LSN initially indicating till where the data
4290 needs to be purged and finally updated to until where it was actually purged
4291 @return Operation status.
4292 @retval 0 Success
4293 @retval other ER_* mysql error. Get error details from THD. */
4294 static int innobase_page_track_purge(uint64_t *purge_id) {
4295 if (srv_read_only_mode) {
4296 my_error(ER_READ_ONLY_MODE, MYF(0));
4297 return ER_READ_ONLY_MODE;
4298 }
4299
4300 auto err = arch_page_sys->purge(purge_id);
4301
4302 return (err);
4303 }
4304
4305 /** Fetch tracked pages.
4306 @param[in] cbk_func callback function return page IDs
4307 @param[in] cbk_ctx caller's context for callback
4308 @param[in,out] start_id SE specific sequence number [LSN for Innodb] from
4309 where the pages tracked would be returned.
4310 @note The range might get expanded and the actual start_id used for the
4311 querying will be updated.
4312 @param[in,out] stop_id SE specific sequence number [LSN for Innodb]
4313 until where the pages tracked would be returned.
4314 @note The range might get expanded and the actual stop_id used for the
4315 querying will be updated.
4316 @param[out] buffer allocated buffer to copy page IDs
4317 @param[in] buffer_len length of buffer in bytes
4318 @return Operation status.
4319 @retval 0 Success
4320 @retval other ER_* mysql error. Get error details from THD. */
4321 static int innobase_page_track_get_page_ids(Page_Track_Callback cbk_func,
4322 void *cbk_ctx, uint64_t *start_id,
4323 uint64_t *stop_id,
4324 unsigned char *buffer,
4325 size_t buffer_len) {
4326 if (srv_read_only_mode) {
4327 my_error(ER_READ_ONLY_MODE, MYF(0));
4328 return ER_READ_ONLY_MODE;
4329 }
4330
4331 auto err =
4332 arch_page_sys->get_pages(nullptr, cbk_func, cbk_ctx, *start_id, *stop_id,
4333 buffer, static_cast<uint>(buffer_len));
4334
4335 if (err != 0) {
4336 DBUG_PRINT("page_archiver", ("Fetch Pages"));
4337 DBUG_PRINT("page_archiver", ("Can't fetch pages"));
4338 }
4339
4340 return (err);
4341 }
4342
4343 /** Fetch approximate number of tracked pages in the given range.
4344 @param[in,out] start_id SE specific sequence number [LSN for Innodb] from
4345 where the pages tracked would be returned.
4346 @note the range might get expanded and the actual start_id used for the
4347 querying will be updated.
4348 @param[in,out] stop_id SE specific sequence number [LSN for Innodb]
4349 until where the pages tracked would be returned.
4350 @note the range might get expanded and the actual stop_id used for the
4351 querying will be updated.
4352 @param[out] num_pages number of pages tracked
4353 @return Operation status.
4354 @retval 0 Success
4355 @retval other ER_* mysql error. Get error details from THD. */
4356 static int innobase_page_track_get_num_page_ids(uint64_t *start_id,
4357 uint64_t *stop_id,
4358 uint64_t *num_pages) {
4359 if (srv_read_only_mode) {
4360 my_error(ER_READ_ONLY_MODE, MYF(0));
4361 return ER_READ_ONLY_MODE;
4362 }
4363
4364 auto err = arch_page_sys->get_num_pages(*start_id, *stop_id, num_pages);
4365
4366 if (err != 0) {
4367 DBUG_PRINT("page_archiver", ("Fetch Pages"));
4368 DBUG_PRINT("page_archiver", ("Can't fetch pages"));
4369 }
4370
4371 return (err);
4372 }
4373
4374 /** Fetch the page tracking status.
4375 @param[out] status vector of a pair of (ID, bool) where ID is the
4376 start/stop point and bool is true if the ID is a start point else false */
4377 static void innobase_page_track_get_status(
4378 std::vector<std::pair<lsn_t, bool>> &status) {
4379 if (srv_read_only_mode) {
4380 my_error(ER_READ_ONLY_MODE, MYF(0));
4381 return;
4382 }
4383
4384 arch_page_sys->get_status(status);
4385 }
4386
4387 /** Gives the file extension of an InnoDB single-table tablespace. */
4388 static const char *ha_innobase_exts[] = {dot_ext[IBD], NullS};
4389
4390 /** This function checks if the given db.tablename is a system table
4391 supported by Innodb and is used as an initializer for the data member
4392 is_supported_system_table of InnoDB storage engine handlerton.
4393 Except general_log and slow_log, currently all system tables are supported
4394 by InnoDB. Please don't add any SE-specific system tables here.
4395
4396 @param is_sql_layer_system_table if the supplied db.table_name is a SQL
4397 layer system table.
4398
4399 @return whether the table name is supported */
4400
4401 static bool innobase_is_supported_system_table(const char *, const char *,
4402 bool is_sql_layer_system_table) {
4403 // Currently InnoDB does not support any other SE specific system tables.
4404 return is_sql_layer_system_table;
4405 }
4406
4407 /** Rotate the encrypted tablespace keys according to master key
4408 rotation.
4409 @return false on success, true on failure */
4410 bool innobase_encryption_key_rotation() {
4411 byte *master_key = nullptr;
4412 bool ret = false;
4413 dberr_t err;
4414
4415 /* Pause here to try other locks while this thread holds the backup locks. */
4416 DEBUG_SYNC_C("ib_pause_encryption_rotate");
4417
4418 if (srv_read_only_mode) {
4419 my_error(ER_INNODB_READ_ONLY, MYF(0));
4420 return (true);
4421 }
4422
4423 /* Take mutex as master_key_id is going to be changed. */
4424 mutex_enter(&master_key_id_mutex);
4425
4426 /* Check if keyring loaded and the currently master key
4427 can be fetched. */
4428 if (Encryption::get_master_key_id() != Encryption::DEFAULT_MASTER_KEY_ID) {
4429 uint32_t master_key_id;
4430
4431 Encryption::get_master_key(&master_key_id, &master_key);
4432
4433 if (master_key == nullptr) {
4434 my_error(ER_CANNOT_FIND_KEY_IN_KEYRING, MYF(0));
4435 ret = true;
4436 goto error_exit;
4437 }
4438 my_free(master_key);
4439 }
4440
4441 master_key = nullptr;
4442
4443 /* Generate the new master key. */
4444 Encryption::create_master_key(&master_key);
4445
4446 if (master_key == nullptr) {
4447 my_error(ER_CANNOT_FIND_KEY_IN_KEYRING, MYF(0));
4448 ret = true;
4449 goto error_exit;
4450 }
4451
4452 /* Rotate all IBD and IBU tablespace that need it. */
4453 if (fil_encryption_rotate() > 0) {
4454 my_free(master_key);
4455 my_error(ER_CANNOT_FIND_KEY_IN_KEYRING, MYF(0));
4456 goto error_exit;
4457 }
4458
4459 err = log_encryption_on_master_key_changed(*log_sys);
4460 ret = (err != DB_SUCCESS);
4461
4462 /* If rotation failure, return error */
4463 if (ret) {
4464 my_free(master_key);
4465 my_error(ER_CANNOT_FIND_KEY_IN_KEYRING, MYF(0));
4466 goto error_exit;
4467 }
4468
4469 my_free(master_key);
4470
4471 error_exit:
4472 /* Release the mutex. */
4473 mutex_exit(&master_key_id_mutex);
4474
4475 return (ret);
4476 }
4477
4478 /** Enable or Disable SE write ahead logging.
4479 @param[in] thd connection THD
4480 @param[in] enable enable/disable redo logging
4481 @return true iff failed. */
4482 static bool innobase_redo_set_state(THD *thd, bool enable) {
4483 if (srv_read_only_mode) {
4484 my_error(ER_INNODB_READ_ONLY, MYF(0));
4485 return (true);
4486 }
4487
4488 int err = 0;
4489
4490 if (enable) {
4491 err = mtr_t::s_logging.enable(thd);
4492 } else {
4493 err = mtr_t::s_logging.disable(thd);
4494 }
4495
4496 if (err != 0) {
4497 return (true);
4498 }
4499
4500 set_srv_redo_log(enable);
4501 return (false);
4502 }
4503
4504 /** Return partitioning flags. */
4505 static uint innobase_partition_flags() {
4506 return (HA_CAN_EXCHANGE_PARTITION | HA_CANNOT_PARTITION_FK |
4507 HA_TRUNCATE_PARTITION_PRECLOSE);
4508 }
4509 #endif /* !UNIV_HOTBACKUP */
4510
4511 /** Update log_checksum_algorithm_ptr with a pointer to the function
4512 corresponding to whether checksums are enabled.
4513 @param[in] check whether redo log block checksums are enabled */
4514 #ifndef UNIV_HOTBACKUP
4515 static
4516 #endif /* !UNIV_HOTBACKUP */
4517 void
4518 innodb_log_checksums_func_update(bool check) {
4519 log_checksum_algorithm_ptr.store(check ? log_block_calc_checksum_crc32
4520 : log_block_calc_checksum_none);
4521 }
4522
4523 #ifndef UNIV_HOTBACKUP
4524
4525 /** Minimum expected tablespace size. (5M) */
4526 static const ulint MIN_EXPECTED_TABLESPACE_SIZE = 5 * 1024 * 1024;
4527
4528 /** Validate innodb_undo_tablespaces. Log a warning if it was set
4529 explicitly. */
4530 static void innodb_undo_tablespaces_deprecate() {
4531 if (sysvar_source_svc == nullptr) {
4532 return;
4533 }
4534
4535 static const char *variable_name = "innodb_undo_tablespaces";
4536 enum enum_variable_source source;
4537
4538 if (sysvar_source_svc->get(variable_name,
4539 static_cast<unsigned int>(strlen(variable_name)),
4540 &source)) {
4541 return;
4542 }
4543
4544 if (source != COMPILED) {
4545 ib::warn(ER_IB_MSG_DEPRECATED_INNODB_UNDO_TABLESPACES);
4546 srv_undo_tablespaces = FSP_IMPLICIT_UNDO_TABLESPACES;
4547 }
4548 }
4549
4550 /** Initialize and normalize innodb_buffer_pool_size. */
4551 static void innodb_buffer_pool_size_init() {
4552 #ifdef UNIV_DEBUG
4553 ulong srv_buf_pool_instances_org = srv_buf_pool_instances;
4554 #endif /* UNIV_DEBUG */
4555
4556 /* If innodb_dedicated_server == ON */
4557 if (srv_dedicated_server && sysvar_source_svc != nullptr) {
4558 static const char *variable_name = "innodb_buffer_pool_size";
4559 enum enum_variable_source source;
4560 if (!sysvar_source_svc->get(
4561 variable_name, static_cast<unsigned int>(strlen(variable_name)),
4562 &source)) {
4563 if (source == COMPILED) {
4564 double server_mem = get_sys_mem();
4565
4566 if (server_mem < 1.0) {
4567 ;
4568 } else if (server_mem <= 4.0) {
4569 srv_buf_pool_size = static_cast<ulint>(server_mem * 0.5 * GB);
4570 } else
4571 srv_buf_pool_size = static_cast<ulint>(server_mem * 0.75 * GB);
4572 } else {
4573 ib::warn(ER_IB_MSG_533)
4574 << "Option innodb_dedicated_server"
4575 " is ignored for"
4576 " innodb_buffer_pool_size because"
4577 " innodb_buffer_pool_size="
4578 << srv_buf_pool_curr_size << " is specified explicitly.";
4579 }
4580 }
4581 }
4582
4583 if (srv_buf_pool_size >= BUF_POOL_SIZE_THRESHOLD) {
4584 if (srv_buf_pool_instances == srv_buf_pool_instances_default) {
4585 #if defined(_WIN32) && !defined(_WIN64)
4586 /* Do not allocate too large of a buffer pool on
4587 Windows 32-bit systems, which can have trouble
4588 allocating larger single contiguous memory blocks. */
4589 srv_buf_pool_instances =
4590 std::min(static_cast<ulong>(MAX_BUFFER_POOLS),
4591 static_cast<ulong>(srv_buf_pool_size / (128 * 1024 * 1024)));
4592 #else /* defined(_WIN32) && !defined(_WIN64) */
4593 /* Default to 8 instances when size > 1GB. */
4594 srv_buf_pool_instances = 8;
4595 #endif /* defined(_WIN32) && !defined(_WIN64) */
4596 }
4597 } else {
4598 /* If buffer pool is less than 1 GiB, assume fewer
4599 threads. Also use only one buffer pool instance. */
4600 if (srv_buf_pool_instances != srv_buf_pool_instances_default &&
4601 srv_buf_pool_instances != 1) {
4602 /* We can't distinguish whether the user has explicitly
4603 started mysqld with --innodb-buffer-pool-instances=0,
4604 (srv_buf_pool_instances_default is 0) or has not
4605 specified that option at all. Thus we have the
4606 limitation that if the user started with =0, we
4607 will not emit a warning here, but we should actually
4608 do so. */
4609 ib::info(ER_IB_MSG_534)
4610 << "Adjusting innodb_buffer_pool_instances"
4611 " from "
4612 << srv_buf_pool_instances
4613 << " to 1"
4614 " since innodb_buffer_pool_size is less than "
4615 << BUF_POOL_SIZE_THRESHOLD / (1024 * 1024) << " MiB";
4616 }
4617
4618 srv_buf_pool_instances = 1;
4619 }
4620
4621 #ifdef UNIV_DEBUG
4622 if (srv_buf_pool_debug &&
4623 srv_buf_pool_instances_org != srv_buf_pool_instances_default) {
4624 srv_buf_pool_instances = srv_buf_pool_instances_org;
4625 };
4626 #endif /* UNIV_DEBUG */
4627
4628 srv_buf_pool_chunk_unit = buf_pool_adjust_chunk_unit(srv_buf_pool_chunk_unit);
4629 srv_buf_pool_size = buf_pool_size_align(srv_buf_pool_size);
4630
4631 ut_ad(srv_buf_pool_chunk_unit >= srv_buf_pool_chunk_unit_min);
4632 ut_ad(srv_buf_pool_chunk_unit <= srv_buf_pool_chunk_unit_max);
4633 ut_ad(srv_buf_pool_chunk_unit % srv_buf_pool_chunk_unit_blk_sz == 0);
4634 ut_ad(srv_buf_pool_chunk_unit % UNIV_PAGE_SIZE == 0);
4635 ut_ad(0 ==
4636 srv_buf_pool_size % (srv_buf_pool_chunk_unit * srv_buf_pool_instances));
4637 ut_ad(srv_buf_pool_chunk_unit * srv_buf_pool_instances <= srv_buf_pool_size);
4638
4639 srv_buf_pool_curr_size = srv_buf_pool_size;
4640 }
4641
4642 template <size_t N>
4643 static bool innodb_variable_is_set(const char (&var_name)[N]) {
4644 enum enum_variable_source source;
4645 ut_a(sysvar_source_svc != nullptr);
4646 const auto svc_result = sysvar_source_svc->get(var_name, N - 1, &source);
4647 ut_a(!svc_result);
4648 return source != COMPILED;
4649 }
4650
4651 static bool innodb_redo_log_capacity_is_set() {
4652 return innodb_variable_is_set("innodb_redo_log_capacity");
4653 }
4654
4655 bool innodb_log_file_size_is_set() {
4656 return innodb_variable_is_set("innodb_log_file_size");
4657 }
4658
4659 bool innodb_log_n_files_is_set() {
4660 return innodb_variable_is_set("innodb_log_files_in_group");
4661 }
4662
4663 /** Initialize srv_redo_log_capacity / srv_redo_log_capacity_used. */
4664 static void innodb_redo_log_capacity_init() {
4665 DBUG_TRACE;
4666
4667 ut_a(MB % UNIV_PAGE_SIZE == 0);
4668 ut_a(srv_redo_log_capacity % MB == 0);
4669 ut_a(srv_redo_log_capacity > 0);
4670
4671 srv_redo_log_capacity_used = srv_redo_log_capacity;
4672
4673 if (sysvar_source_svc == nullptr) {
4674 return;
4675 }
4676
4677 const bool file_size_set = innodb_log_file_size_is_set();
4678
4679 const bool n_files_set = innodb_log_n_files_is_set();
4680
4681 bool capacity_set = innodb_redo_log_capacity_is_set();
4682
4683 if (capacity_set) {
4684 if (file_size_set) {
4685 ib::warn(ER_IB_MSG_LOG_PARAMS_FILE_SIZE_UNUSED);
4686 }
4687 if (n_files_set) {
4688 ib::warn(ER_IB_MSG_LOG_PARAMS_N_FILES_UNUSED);
4689 }
4690 } else {
4691 if (file_size_set || n_files_set) {
4692 srv_redo_log_capacity_used = srv_log_file_size * srv_log_n_files;
4693 capacity_set = true; // do not change it in dedicated_server mode
4694 ib::warn(ER_IB_MSG_LOG_PARAMS_LEGACY_USAGE, srv_redo_log_capacity_used);
4695 }
4696 }
4697
4698 if (srv_dedicated_server) {
4699 double auto_buf_pool_size_in_gb;
4700 static const char *var_name_buf_pool_size = "innodb_buffer_pool_size";
4701 enum enum_variable_source source;
4702
4703 auto_buf_pool_size_in_gb = static_cast<double>(srv_buf_pool_size / GB);
4704
4705 /* If user has set buffer pool size in .cnf, we will not use it as base
4706 line for log_file_size auto tuning, instead, we will get the value of
4707 possible tuned buffer pool size. */
4708 if (!sysvar_source_svc->get(
4709 var_name_buf_pool_size,
4710 static_cast<unsigned int>(strlen(var_name_buf_pool_size)),
4711 &source)) {
4712 if (source != COMPILED) {
4713 double server_mem = get_sys_mem();
4714
4715 #ifdef UNIV_DEBUG_DEDICATED
4716 server_mem = srv_debug_system_mem_size / GB;
4717 #endif /* UNIV_DEBUG_DEDICATED */
4718
4719 if (server_mem < 1.0) {
4720 ;
4721 } else if (server_mem <= 4.0) {
4722 auto_buf_pool_size_in_gb = static_cast<double>(server_mem * 0.5);
4723 } else
4724 auto_buf_pool_size_in_gb = static_cast<double>(server_mem * 0.75);
4725 }
4726 }
4727
4728 if (!capacity_set) {
4729 /* We update srv_redo_log_capacity (underlying sysvar variable),
4730 because that is what innodb_dedicated_server is expected to do. */
4731 if (auto_buf_pool_size_in_gb < 1.0) {
4732 ut_ad(srv_redo_log_capacity == 100 * 1024 * 1024);
4733 } else if (auto_buf_pool_size_in_gb < 8.0) {
4734 srv_redo_log_capacity =
4735 static_cast<ulong>(round(auto_buf_pool_size_in_gb)) * 512ULL * MB;
4736 } else if (auto_buf_pool_size_in_gb <= 128.0) {
4737 srv_redo_log_capacity =
4738 static_cast<ulong>(round(auto_buf_pool_size_in_gb * 0.75)) * GB;
4739 } else {
4740 constexpr os_offset_t LOG_CAPACITY_FOR_BIG_DEDICATED_SERVER = 128 * GB;
4741
4742 static_assert(
4743 LOG_CAPACITY_FOR_BIG_DEDICATED_SERVER <= LOG_CAPACITY_MAX,
4744 "Redo log capacity, for the dedicated server, is too big.");
4745
4746 srv_redo_log_capacity = LOG_CAPACITY_FOR_BIG_DEDICATED_SERVER;
4747 }
4748 srv_redo_log_capacity_used = srv_redo_log_capacity;
4749
4750 } else {
4751 ut_a(srv_redo_log_capacity_used % MB == 0);
4752 ib::warn(ER_IB_MSG_LOG_PARAMS_DEDICATED_SERVER_IGNORED,
4753 ulonglong{srv_redo_log_capacity_used / MB});
4754 }
4755 }
4756
4757 if (capacity_set && srv_read_only_mode) {
4758 ib::warn(ER_IB_WRN_IGNORE_REDO_LOG_CAPACITY);
4759 }
4760
4761 ut_a(LOG_CAPACITY_MIN <= srv_redo_log_capacity_used);
4762 ut_a(srv_redo_log_capacity_used <= LOG_CAPACITY_MAX);
4763 ut_a(srv_redo_log_capacity_used % MB == 0);
4764 }
4765
4766 /** Initialize, validate and normalize the InnoDB startup parameters.
4767 @return failure code
4768 @retval 0 on success
4769 @retval HA_ERR_OUT_OF_MEM when out of memory
4770 @retval HA_ERR_INITIALIZATION when some parameters are out of range */
4771 static int innodb_init_params() {
4772 DBUG_TRACE;
4773
4774 static char current_dir[3];
4775 char *default_path;
4776
4777 /* First calculate the default path for innodb_data_home_dir etc.,
4778 in case the user has not given any value. */
4779
4780 /* It's better to use current lib, to keep paths short */
4781 current_dir[0] = FN_CURLIB;
4782 current_dir[1] = FN_LIBCHAR;
4783 current_dir[2] = 0;
4784 default_path = current_dir;
4785
4786 std::string mysqld_datadir{default_path};
4787
4788 MySQL_datadir_path = Fil_path{mysqld_datadir};
4789
4790 /* Validate, normalize and interpret the InnoDB start-up parameters. */
4791
4792 /* The default dir for data files is the datadir of MySQL */
4793
4794 srv_data_home =
4795 (innobase_data_home_dir == nullptr || *innobase_data_home_dir == '\0')
4796 ? default_path
4797 : innobase_data_home_dir;
4798 Fil_path::normalize(srv_data_home);
4799
4800 /* Validate the undo directory. */
4801 if (srv_undo_dir == nullptr || srv_undo_dir[0] == 0) {
4802 srv_undo_dir = default_path;
4803 } else {
4804 Fil_path::normalize(srv_undo_dir);
4805 }
4806
4807 MySQL_undo_path = Fil_path{srv_undo_dir};
4808
4809 if (MySQL_undo_path.is_ancestor(default_path)) {
4810 log_errlog(ERROR_LEVEL, ER_INNODB_INVALID_INNODB_UNDO_DIRECTORY_LOCATION);
4811 return HA_ERR_INITIALIZATION;
4812 }
4813
4814 /* Validate the temp directory */
4815 if (ibt::srv_temp_dir == nullptr) {
4816 ibt::srv_temp_dir = default_path;
4817 } else {
4818 os_file_type_t type;
4819 bool exists;
4820 os_file_status(ibt::srv_temp_dir, &exists, &type);
4821 if (!exists || type != OS_FILE_TYPE_DIR) {
4822 ib::error(ER_IB_ERR_TEMP_TABLESPACE_DIR_DOESNT_EXIST)
4823 << "Invalid innodb_temp_tablespaces_dir: " << ibt::srv_temp_dir
4824 << ". Directory doesn't exist or not valid";
4825 return HA_ERR_INITIALIZATION;
4826 }
4827
4828 Fil_path temp_dir(ibt::srv_temp_dir);
4829 if (temp_dir.path().empty()) {
4830 ib::error(ER_IB_ERR_TEMP_TABLESPACE_DIR_EMPTY)
4831 << "Invalid innodb_temp_tablespaces dir: " << ibt::srv_temp_dir
4832 << ". Path cannot be empty";
4833 return HA_ERR_INITIALIZATION;
4834 }
4835
4836 if (strchr(ibt::srv_temp_dir, ';')) {
4837 ib::error(ER_IB_ERR_TEMP_TABLESPACE_DIR_CONTAINS_SEMICOLON)
4838 << "Invalid innodb_temp_tablespaces dir: " << ibt::srv_temp_dir
4839 << ". Path cannot contain ;";
4840 return HA_ERR_INITIALIZATION;
4841 }
4842
4843 if (MySQL_datadir_path.is_ancestor(
4844 Fil_path::get_real_path(temp_dir.path()))) {
4845 ib::error(ER_IB_ERR_TEMP_TABLESPACE_DIR_SUBDIR_OF_DATADIR)
4846 << "Invalid innodb_temp_tablespaces_dir=" << ibt::srv_temp_dir
4847 << ". This path should not be a subdirectory of the datadir.";
4848 return HA_ERR_INITIALIZATION;
4849 }
4850 }
4851
4852 Fil_path::normalize(ibt::srv_temp_dir);
4853
4854 /* The default dir for log files is the datadir of MySQL */
4855
4856 if (srv_log_group_home_dir == nullptr) {
4857 srv_log_group_home_dir = default_path;
4858 }
4859 Fil_path::normalize(srv_log_group_home_dir);
4860
4861 if (strchr(srv_log_group_home_dir, ';')) {
4862 log_errlog(ERROR_LEVEL, ER_INNODB_INVALID_LOG_GROUP_HOME_DIR);
4863 return HA_ERR_INITIALIZATION;
4864 }
4865
4866 if (strchr(srv_undo_dir, ';')) {
4867 log_errlog(ERROR_LEVEL, ER_INNODB_INVALID_INNODB_UNDO_DIRECTORY);
4868 return HA_ERR_INITIALIZATION;
4869 }
4870
4871 if (!is_filename_allowed(srv_buf_dump_filename, strlen(srv_buf_dump_filename),
4872 false)) {
4873 log_errlog(ERROR_LEVEL, ER_INNODB_ILLEGAL_COLON_IN_POOL);
4874 return HA_ERR_INITIALIZATION;
4875 }
4876
4877 /* Check that the value of system variable innodb_page_size was
4878 set correctly. Its value was put into srv_page_size. If valid,
4879 return the associated srv_page_size_shift. */
4880 srv_page_size_shift = page_size_validate(srv_page_size);
4881 if (!srv_page_size_shift) {
4882 log_errlog(ERROR_LEVEL, ER_INNODB_INVALID_PAGE_SIZE, srv_page_size);
4883 return HA_ERR_INITIALIZATION;
4884 }
4885
4886 ut_a(srv_log_buffer_size % OS_FILE_LOG_BLOCK_SIZE == 0);
4887 ut_a(srv_log_buffer_size > 0);
4888
4889 ut_a(srv_log_write_ahead_size % OS_FILE_LOG_BLOCK_SIZE == 0);
4890 ut_a(srv_log_write_ahead_size > 0);
4891
4892 assert(innodb_change_buffering <= IBUF_USE_ALL);
4893
4894 /* Check that interdependent parameters have sane values. */
4895 if (srv_max_buf_pool_modified_pct < srv_max_dirty_pages_pct_lwm) {
4896 log_errlog(WARNING_LEVEL, ER_INNODB_DIRTY_WATER_MARK_NOT_LOW,
4897 srv_max_buf_pool_modified_pct);
4898 srv_max_dirty_pages_pct_lwm = srv_max_buf_pool_modified_pct;
4899 }
4900
4901 if (srv_max_io_capacity == SRV_MAX_IO_CAPACITY_DUMMY_DEFAULT) {
4902 if (srv_io_capacity >= SRV_MAX_IO_CAPACITY_LIMIT / 2) {
4903 /* Avoid overflow. */
4904 srv_max_io_capacity = SRV_MAX_IO_CAPACITY_LIMIT;
4905 } else {
4906 /* The user has not set the value. We should
4907 set it based on innodb_io_capacity. */
4908 srv_max_io_capacity = std::max(2 * srv_io_capacity, 2000UL);
4909 }
4910
4911 } else if (srv_max_io_capacity < srv_io_capacity) {
4912 log_errlog(WARNING_LEVEL, ER_INNODB_IO_CAPACITY_EXCEEDS_MAX,
4913 srv_max_io_capacity);
4914 srv_io_capacity = srv_max_io_capacity;
4915 }
4916
4917 if (UNIV_PAGE_SIZE_DEF != srv_page_size) {
4918 ib::warn(ER_IB_MSG_538)
4919 << "innodb-page-size has been changed from the"
4920 " default value "
4921 << UNIV_PAGE_SIZE_DEF << " to " << srv_page_size << ".";
4922 }
4923
4924 if (srv_log_write_ahead_size > srv_page_size) {
4925 srv_log_write_ahead_size = srv_page_size;
4926 } else {
4927 ulong srv_log_write_ahead_size_tmp = OS_FILE_LOG_BLOCK_SIZE;
4928
4929 while (srv_log_write_ahead_size_tmp < srv_log_write_ahead_size) {
4930 srv_log_write_ahead_size_tmp = srv_log_write_ahead_size_tmp * 2;
4931 }
4932 if (srv_log_write_ahead_size_tmp != srv_log_write_ahead_size) {
4933 srv_log_write_ahead_size = srv_log_write_ahead_size_tmp / 2;
4934 }
4935 }
4936
4937 srv_buf_pool_size = srv_buf_pool_curr_size;
4938
4939 innodb_log_checksums_func_update(srv_log_checksums);
4940
4941 #ifdef HAVE_LINUX_LARGE_PAGES
4942 if ((os_use_large_pages = opt_large_pages)) {
4943 os_large_page_size = opt_large_page_size;
4944 }
4945 #endif /* HAVE_LINUX_LARGE_PAGES */
4946
4947 row_rollback_on_timeout = innobase_rollback_on_timeout;
4948
4949 if (innobase_open_files < 10) {
4950 innobase_open_files = 300;
4951 if (srv_file_per_table && table_cache_size > 300) {
4952 innobase_open_files = table_cache_size;
4953 }
4954 }
4955
4956 if (innobase_open_files > (long)open_files_limit) {
4957 ib::warn(ER_IB_MSG_539) << "innodb_open_files should not be greater"
4958 " than the open_files_limit.\n";
4959 if (innobase_open_files > (long)table_cache_size) {
4960 innobase_open_files = table_cache_size;
4961 }
4962 }
4963
4964 srv_innodb_status = innobase_create_status_file;
4965
4966 /* Round up ddl:fts_parser_threads to nearest power of 2 number */
4967 {
4968 ulong n_parser_threads = 1;
4969
4970 while (n_parser_threads < ddl::fts_parser_threads) {
4971 n_parser_threads <<= 1;
4972 }
4973
4974 ddl::fts_parser_threads = n_parser_threads;
4975 }
4976
4977 /* Store the default charset-collation number of this MySQL
4978 installation */
4979
4980 data_mysql_default_charset_coll = (ulint)default_charset_info->number;
4981
4982 innobase_commit_concurrency_init_default();
4983
4984 if (srv_force_recovery == SRV_FORCE_NO_LOG_REDO) {
4985 srv_read_only_mode = true;
4986 }
4987
4988 high_level_read_only =
4989 srv_read_only_mode || srv_force_recovery > SRV_FORCE_NO_TRX_UNDO;
4990
4991 if (srv_read_only_mode) {
4992 ib::info(ER_IB_MSG_540) << "Started in read only mode";
4993
4994 /* There is no write except to intrinsic table and so turn-off
4995 doublewrite mechanism completely. */
4996 dblwr::g_mode = dblwr::Mode::OFF;
4997 }
4998
4999 #ifdef LINUX_NATIVE_AIO
5000 if (srv_use_native_aio) {
5001 ib::info(ER_IB_MSG_541) << "Using Linux native AIO";
5002 }
5003 #elif !defined _WIN32
5004 /* Currently native AIO is supported only on Windows and Linux
5005 and that also when the support is compiled in. In all other
5006 cases, we ignore the setting of innodb_use_native_aio. */
5007 srv_use_native_aio = false;
5008 #endif
5009
5010 #ifndef _WIN32
5011 /* Check if innodb_dedicated_server == ON and O_DIRECT is supported */
5012 if (srv_dedicated_server && sysvar_source_svc != nullptr &&
5013 os_is_o_direct_supported()) {
5014 static const char *variable_name = "innodb_flush_method";
5015 enum enum_variable_source source;
5016
5017 if (!sysvar_source_svc->get(variable_name, strlen(variable_name),
5018 &source)) {
5019 /* If innodb_flush_method is not specified explicitly */
5020 if (source == COMPILED) {
5021 innodb_flush_method = static_cast<ulong>(SRV_UNIX_O_DIRECT_NO_FSYNC);
5022 } else {
5023 ib::warn(ER_IB_MSG_542)
5024 << "Option innodb_dedicated_server"
5025 " is ignored for innodb_flush_method"
5026 "because innodb_flush_method="
5027 << innodb_flush_method_names[innodb_flush_method]
5028 << " is specified explicitly.";
5029 }
5030 }
5031 }
5032
5033 srv_unix_file_flush_method =
5034 static_cast<srv_unix_flush_t>(innodb_flush_method);
5035 ut_ad(innodb_flush_method <= SRV_UNIX_O_DIRECT_NO_FSYNC);
5036 #else
5037 srv_win_file_flush_method = static_cast<srv_win_flush_t>(innodb_flush_method);
5038 ut_ad(innodb_flush_method <= SRV_WIN_IO_NORMAL);
5039 if (srv_use_native_aio) {
5040 ib::info(ER_IB_MSG_541) << "Using Windows native AIO";
5041 }
5042 #endif /* !_WIN32 */
5043
5044 /* Set the maximum number of threads which can wait for a semaphore
5045 inside InnoDB: this is the 'sync wait array' size, as well as the
5046 maximum number of threads that can wait in the 'srv_conc array' for
5047 their time to enter InnoDB. */
5048
5049 srv_max_n_threads = 100 * 1024;
5050
5051 /* This is the first time univ_page_size is used.
5052 It was initialized to 16k pages before srv_page_size was set */
5053 univ_page_size.copy_from(page_size_t(srv_page_size, srv_page_size, false));
5054
5055 srv_sys_space.set_space_id(TRX_SYS_SPACE);
5056
5057 /* Create the filespace flags. */
5058 predefined_flags = fsp_flags_init(univ_page_size, false, false, true, false);
5059 fsp_flags_set_sdi(predefined_flags);
5060
5061 srv_sys_space.set_flags(predefined_flags);
5062
5063 srv_sys_space.set_name(dict_sys_t::s_sys_space_name);
5064 srv_sys_space.set_path(srv_data_home);
5065
5066 /* We set the temporary tablspace id later, after recovery.
5067 The temp tablespace doesn't support raw devices.
5068 Set the name and path. */
5069 srv_tmp_space.set_name(dict_sys_t::s_temp_space_name);
5070 srv_tmp_space.set_path(srv_data_home);
5071
5072 /* Create the filespace flags with the temp flag set. */
5073 uint32_t fsp_flags =
5074 fsp_flags_init(univ_page_size, false, false, false, true);
5075 srv_tmp_space.set_flags(fsp_flags);
5076
5077 /* Set buffer pool size to default for fast startup when mysqld is
5078 run with --help --verbose options. */
5079 ulint srv_buf_pool_size_org = 0;
5080 if (opt_help && opt_verbose && opt_validate_config &&
5081 srv_buf_pool_size > srv_buf_pool_def_size) {
5082 ib::warn(ER_IB_MSG_543) << "Setting innodb_buf_pool_size to "
5083 << srv_buf_pool_def_size << " for fast startup, "
5084 << "when running with --help --verbose options.";
5085 srv_buf_pool_size_org = srv_buf_pool_size;
5086 srv_buf_pool_size = srv_buf_pool_def_size;
5087 }
5088
5089 innodb_buffer_pool_size_init();
5090
5091 innodb_undo_tablespaces_deprecate();
5092
5093 innodb_redo_log_capacity_init();
5094
5095 /* Set the original value back to show in help. */
5096 if (srv_buf_pool_size_org != 0) {
5097 srv_buf_pool_size_org = buf_pool_size_align(srv_buf_pool_size_org);
5098 srv_buf_pool_curr_size = srv_buf_pool_size_org;
5099 }
5100
5101 if (srv_n_page_cleaners > srv_buf_pool_instances) {
5102 /* limit of page_cleaner parallelizability
5103 is number of buffer pool instances. */
5104 srv_n_page_cleaners = srv_buf_pool_instances;
5105 }
5106
5107 srv_lock_table_size = 5 * (srv_buf_pool_size / UNIV_PAGE_SIZE);
5108
5109 return 0;
5110 }
5111
5112 long innobase_get_open_files_limit() { return innobase_open_files; }
5113 void innobase_set_open_files_limit(long new_limit) {
5114 innobase_open_files = new_limit;
5115 }
5116
5117 /** Perform post-commit/rollback cleanup after DDL statement
5118 @param[in,out] thd connection thread */
5119 static void innobase_post_ddl(THD *thd) {
5120 /* During upgrade, etc., the log_ddl may haven't been
5121 initialized and there is nothing to do now. */
5122 if (log_ddl != nullptr) {
5123 DBUG_EXECUTE_IF("DDL_Log_remove_inject_startup_error_3",
5124 srv_inject_too_many_concurrent_trxs = true;);
5125
5126 dberr_t err = log_ddl->post_ddl(thd);
5127
5128 /* If this fails, do not continue startup. */
5129 if (err != DB_SUCCESS) {
5130 ib::fatal(UT_LOCATION_HERE, ER_IB_MSG_DDL_LOG_FAIL_POST_DDL);
5131 }
5132 }
5133 }
5134
5135 /** Initialize the InnoDB storage engine plugin.
5136 @param[in,out] p InnoDB handlerton
5137 @return error code
5138 @retval 0 on success */
5139 static int innodb_init(void *p) {
5140 DBUG_TRACE;
5141
5142 acquire_plugin_services();
5143
5144 handlerton *innobase_hton = (handlerton *)p;
5145 innodb_hton_ptr = innobase_hton;
5146
5147 innobase_hton->state = SHOW_OPTION_YES;
5148 innobase_hton->db_type = DB_TYPE_INNODB;
5149 innobase_hton->savepoint_offset = sizeof(trx_named_savept_t);
5150 innobase_hton->close_connection = innobase_close_connection;
5151 innobase_hton->kill_connection = innobase_kill_connection;
5152 innobase_hton->savepoint_set = innobase_savepoint;
5153 innobase_hton->savepoint_rollback = innobase_rollback_to_savepoint;
5154
5155 innobase_hton->savepoint_rollback_can_release_mdl =
5156 innobase_rollback_to_savepoint_can_release_mdl;
5157
5158 innobase_hton->savepoint_release = innobase_release_savepoint;
5159 innobase_hton->commit = innobase_commit;
5160 innobase_hton->rollback = innobase_rollback;
5161 innobase_hton->prepare = innobase_xa_prepare;
5162 innobase_hton->recover = innobase_xa_recover;
5163 innobase_hton->recover_prepared_in_tc = innobase_xa_recover_prepared_in_tc;
5164 innobase_hton->commit_by_xid = innobase_commit_by_xid;
5165 innobase_hton->rollback_by_xid = innobase_rollback_by_xid;
5166 innobase_hton->set_prepared_in_tc = innobase_set_prepared_in_tc;
5167 innobase_hton->set_prepared_in_tc_by_xid = innobase_set_prepared_in_tc_by_xid;
5168 innobase_hton->create = innobase_create_handler;
5169 innobase_hton->is_valid_tablespace_name = innobase_is_valid_tablespace_name;
5170 innobase_hton->alter_tablespace = innobase_alter_tablespace;
5171 innobase_hton->get_tablespace_filename_ext =
5172 innobase_get_tablespace_filename_ext;
5173 innobase_hton->upgrade_tablespace = dd_upgrade_tablespace;
5174 innobase_hton->upgrade_space_version = upgrade_space_version;
5175 innobase_hton->upgrade_logs = dd_upgrade_logs;
5176 innobase_hton->finish_upgrade = dd_upgrade_finish;
5177 innobase_hton->pre_dd_shutdown = innodb_pre_dd_shutdown;
5178 innobase_hton->panic = innodb_shutdown;
5179 innobase_hton->partition_flags = innobase_partition_flags;
5180
5181 innobase_hton->start_consistent_snapshot =
5182 innobase_start_trx_and_assign_read_view;
5183
5184 innobase_hton->flush_logs = innobase_flush_logs;
5185 innobase_hton->show_status = innobase_show_status;
5186 innobase_hton->lock_hton_log = innobase_lock_hton_log;
5187 innobase_hton->unlock_hton_log = innobase_unlock_hton_log;
5188 innobase_hton->collect_hton_log_info = innobase_collect_hton_log_info;
5189 innobase_hton->fill_is_table = innobase_fill_i_s_table;
5190 innobase_hton->flags = HTON_SUPPORTS_EXTENDED_KEYS |
5191 HTON_SUPPORTS_FOREIGN_KEYS | HTON_SUPPORTS_ATOMIC_DDL |
5192 HTON_CAN_RECREATE | HTON_SUPPORTS_SECONDARY_ENGINE |
5193 HTON_SUPPORTS_TABLE_ENCRYPTION |
5194 HTON_SUPPORTS_GENERATED_INVISIBLE_PK;
5195
5196 innobase_hton->replace_native_transaction_in_thd = innodb_replace_trx_in_thd;
5197 innobase_hton->file_extensions = ha_innobase_exts;
5198 innobase_hton->data = &innodb_api_cb;
5199
5200 innobase_hton->ddse_dict_init = innobase_ddse_dict_init;
5201
5202 innobase_hton->dict_register_dd_table_id = innobase_dict_register_dd_table_id;
5203
5204 innobase_hton->dict_cache_reset = innobase_dict_cache_reset;
5205 innobase_hton->dict_cache_reset_tables_and_tablespaces =
5206 innobase_dict_cache_reset_tables_and_tablespaces;
5207
5208 innobase_hton->dict_recover = innobase_dict_recover;
5209 innobase_hton->dict_get_server_version = innobase_dict_get_server_version;
5210 innobase_hton->dict_set_server_version = innobase_dict_set_server_version;
5211
5212 innobase_hton->post_recover = innobase_post_recover;
5213
5214 innobase_hton->is_supported_system_table = innobase_is_supported_system_table;
5215
5216 innobase_hton->get_table_statistics = innobase_get_table_statistics;
5217
5218 innobase_hton->get_index_column_cardinality =
5219 innobase_get_index_column_cardinality;
5220
5221 innobase_hton->get_tablespace_statistics = innobase_get_tablespace_statistics;
5222 innobase_hton->get_tablespace_type = innobase_get_tablespace_type;
5223 innobase_hton->get_tablespace_type_by_name =
5224 innobase_get_tablespace_type_by_name;
5225
5226 innobase_hton->is_dict_readonly = innobase_is_dict_readonly;
5227
5228 innobase_hton->sdi_create = dict_sdi_create;
5229 innobase_hton->sdi_drop = dict_sdi_drop;
5230 innobase_hton->sdi_get_keys = dict_sdi_get_keys;
5231 innobase_hton->sdi_get = dict_sdi_get;
5232 innobase_hton->sdi_set = dict_sdi_set;
5233 innobase_hton->sdi_delete = dict_sdi_delete;
5234
5235 innobase_hton->rotate_encryption_master_key =
5236 innobase_encryption_key_rotation;
5237
5238 innobase_hton->redo_log_set_state = innobase_redo_set_state;
5239
5240 innobase_hton->post_ddl = innobase_post_ddl;
5241
5242 /* Initialize handler clone interfaces for. */
5243
5244 innobase_hton->clone_interface.clone_capability = innodb_clone_get_capability;
5245 innobase_hton->clone_interface.clone_begin = innodb_clone_begin;
5246 innobase_hton->clone_interface.clone_copy = innodb_clone_copy;
5247 innobase_hton->clone_interface.clone_ack = innodb_clone_ack;
5248 innobase_hton->clone_interface.clone_end = innodb_clone_end;
5249
5250 innobase_hton->clone_interface.clone_apply_begin = innodb_clone_apply_begin;
5251 innobase_hton->clone_interface.clone_apply = innodb_clone_apply;
5252 innobase_hton->clone_interface.clone_apply_end = innodb_clone_apply_end;
5253
5254 innobase_hton->foreign_keys_flags =
5255 HTON_FKS_WITH_PREFIX_PARENT_KEYS |
5256 HTON_FKS_NEED_DIFFERENT_PARENT_AND_SUPPORTING_KEYS |
5257 HTON_FKS_WITH_EXTENDED_PARENT_KEYS;
5258
5259 innobase_hton->check_fk_column_compat = innodb_check_fk_column_compat;
5260 innobase_hton->fk_name_suffix = {STRING_WITH_LEN("_ibfk_")};
5261
5262 innobase_hton->is_reserved_db_name = innobase_check_reserved_file_name;
5263
5264 innobase_hton->page_track.start = innobase_page_track_start;
5265 innobase_hton->page_track.stop = innobase_page_track_stop;
5266 innobase_hton->page_track.purge = innobase_page_track_purge;
5267 innobase_hton->page_track.get_page_ids = innobase_page_track_get_page_ids;
5268 innobase_hton->page_track.get_num_page_ids =
5269 innobase_page_track_get_num_page_ids;
5270 innobase_hton->page_track.get_status = innobase_page_track_get_status;
5271
5272 static_assert(DATA_MYSQL_TRUE_VARCHAR == (ulint)MYSQL_TYPE_VARCHAR);
5273
5274 #ifndef _WIN32
5275 os_file_set_umask(my_umask);
5276 #endif
5277
5278 /* Setup the memory alloc/free tracing mechanisms before calling
5279 any functions that could possibly allocate memory. */
5280 ut_new_boot();
5281
5282 #ifdef HAVE_PSI_INTERFACE
5283 /* Register keys with MySQL performance schema */
5284 int count;
5285
5286 #ifdef UNIV_DEBUG
5287 /** Count of Performance Schema keys that have been registered. */
5288 int global_count = 0;
5289 #endif /* UNIV_DEBUG */
5290
5291 count = static_cast<int>(array_elements(all_pthread_mutexes));
5292 mysql_mutex_register("innodb", all_pthread_mutexes, count);
5293
5294 #ifdef UNIV_DEBUG
5295 global_count += count;
5296 #endif /* UNIV_DEBUG */
5297
5298 #ifdef UNIV_PFS_MEMORY
5299 count = static_cast<int>(array_elements(pfs_instrumented_innodb_memory));
5300 mysql_memory_register("innodb", pfs_instrumented_innodb_memory, count);
5301 #endif /* UNIV_PFS_MEMORY */
5302
5303 #ifdef UNIV_PFS_MUTEX
5304 count = static_cast<int>(array_elements(all_innodb_mutexes));
5305 mysql_mutex_register("innodb", all_innodb_mutexes, count);
5306
5307 #ifdef UNIV_DEBUG
5308 global_count += count;
5309 #endif /* UNIV_DEBUG */
5310
5311 #endif /* UNIV_PFS_MUTEX */
5312
5313 #ifdef UNIV_PFS_RWLOCK
5314 count = static_cast<int>(array_elements(all_innodb_rwlocks));
5315 mysql_rwlock_register("innodb", all_innodb_rwlocks, count);
5316
5317 #ifdef UNIV_DEBUG
5318 global_count += count;
5319 #endif /* UNIV_DEBUG */
5320
5321 #endif /* UNIV_PFS_MUTEX */
5322
5323 #ifdef UNIV_PFS_THREAD
5324 count = static_cast<int>(array_elements(all_innodb_threads));
5325 mysql_thread_register("innodb", all_innodb_threads, count);
5326
5327 #ifdef UNIV_DEBUG
5328 global_count += count;
5329 #endif /* UNIV_DEBUG */
5330
5331 #endif /* UNIV_PFS_THREAD */
5332
5333 #ifdef UNIV_PFS_IO
5334 count = static_cast<int>(array_elements(all_innodb_files));
5335 mysql_file_register("innodb", all_innodb_files, count);
5336
5337 #ifdef UNIV_DEBUG
5338 global_count += count;
5339 #endif /* UNIV_DEBUG */
5340
5341 #endif /* UNIV_PFS_IO */
5342
5343 count = static_cast<int>(array_elements(all_innodb_conds));
5344 mysql_cond_register("innodb", all_innodb_conds, count);
5345
5346 #ifdef UNIV_DEBUG
5347 global_count += count;
5348 #endif /* UNIV_DEBUG */
5349
5350 mysql_data_lock_register(&innodb_data_lock_inspector);
5351
5352 #ifdef UNIV_DEBUG
5353 if (mysql_pfs_key_t::get_count() != global_count) {
5354 ib::error(ER_IB_MSG_544) << "You have created new InnoDB PFS key(s) but "
5355 << mysql_pfs_key_t::get_count() - global_count
5356 << " key(s) is/are not registered with PFS. Please"
5357 << " register the keys in PFS arrays in"
5358 << " ha_innodb.cc.";
5359
5360 return HA_ERR_INITIALIZATION;
5361 }
5362 #endif /* UNIV_DEBUG */
5363
5364 #endif /* HAVE_PSI_INTERFACE */
5365
5366 os_event_global_init();
5367
5368 if (int error = innodb_init_params()) {
5369 return error;
5370 }
5371
5372 /* After this point, error handling has to use
5373 innodb_init_abort(). */
5374
5375 /* Initialize component service handles */
5376 if (innobase::component_services::intitialize_service_handles() == false) {
5377 return innodb_init_abort();
5378 }
5379
5380 if (!srv_sys_space.parse_params(innobase_data_file_path, true)) {
5381 ib::error(ER_IB_MSG_545)
5382 << "Unable to parse innodb_data_file_path=" << innobase_data_file_path;
5383 return innodb_init_abort();
5384 }
5385
5386 if (!srv_tmp_space.parse_params(innobase_temp_data_file_path, false)) {
5387 ib::error(ER_IB_MSG_546) << "Unable to parse innodb_temp_data_file_path="
5388 << innobase_temp_data_file_path;
5389 return innodb_init_abort();
5390 }
5391
5392 /* Perform all sanity check before we take action of deleting files*/
5393 if (srv_sys_space.intersection(&srv_tmp_space)) {
5394 log_errlog(ERROR_LEVEL, ER_INNODB_FILES_SAME, srv_tmp_space.name(),
5395 srv_sys_space.name());
5396 return innodb_init_abort();
5397 }
5398
5399 /* Check for keyring plugin if UNDO/REDO logs are intended to be encrypted */
5400 if ((srv_undo_log_encrypt || srv_redo_log_encrypt) &&
5401 Encryption::check_keyring() == false) {
5402 return innodb_init_abort();
5403 }
5404
5405 return 0;
5406 }
5407
5408 /** De initialize the InnoDB storage engine plugin. */
5409 static int innodb_deinit(MYSQL_PLUGIN plugin_info [[maybe_unused]]) {
5410 release_plugin_services();
5411 return 0;
5412 }
5413
5414 /** Create a hard-coded tablespace file at server initialization.
5415 @param[in] space_id fil_space_t::id
5416 @param[in] filename file name
5417 @retval false on success
5418 @retval true on failure */
5419 static bool dd_create_hardcoded(space_id_t space_id, const char *filename) {
5420 page_no_t pages = FIL_IBD_FILE_INITIAL_SIZE;
5421
5422 dberr_t err = fil_ibd_create(space_id, dict_sys_t::s_dd_space_name, filename,
5423 predefined_flags, pages);
5424
5425 if (err == DB_SUCCESS) {
5426 mtr_t mtr;
5427 mtr.start();
5428
5429 bool ret = fsp_header_init(space_id, pages, &mtr);
5430
5431 mtr.commit();
5432
5433 if (ret) {
5434 btr_sdi_create_index(space_id, false);
5435 return (false);
5436 }
5437 }
5438
5439 return (true);
5440 }
5441
5442 /** Open a hard-coded tablespace file at server initialization.
5443 @param[in] space_id fil_space_t::id
5444 @param[in] filename file name
5445 @retval false on success
5446 @retval true on failure */
5447 static bool dd_open_hardcoded(space_id_t space_id, const char *filename) {
5448 bool fail = false;
5449 fil_space_t *space = fil_space_acquire_silent(space_id);
5450
5451 if (space != nullptr) {
5452 /* ADD SDI flag presence in predefined flags of mysql
5453 tablespace. */
5454
5455 if (strstr(space->files.front().name, filename) != nullptr &&
5456 /* Ignore encryption flag as it might have changed */
5457 !((space->flags ^ predefined_flags) & ~(FSP_FLAGS_MASK_ENCRYPTION))) {
5458 fil_space_open_if_needed(space);
5459
5460 } else {
5461 fail = true;
5462 }
5463
5464 fil_space_release(space);
5465
5466 } else if (fil_ibd_open(true, FIL_TYPE_TABLESPACE, space_id, 0,
5467 dict_sys_t::s_dd_space_name, filename, true,
5468 false) == DB_SUCCESS) {
5469 /* Set fil_space_t::size, which is 0 initially. */
5470 ulint size = fil_space_get_size(space_id);
5471 ut_a(size != ULINT_UNDEFINED);
5472
5473 } else {
5474 fail = true;
5475 }
5476
5477 if (fail) {
5478 my_error(ER_CANT_OPEN_FILE, MYF(0), filename, 0, "");
5479 }
5480
5481 return (fail);
5482 }
5483
5484 /** Open or create InnoDB data files.
5485 @param[in] dict_init_mode whether to create or open the files
5486 @param[in,out] tablespaces predefined tablespaces created by the DDSE
5487 @return 0 on success, 1 on failure */
5488 static int innobase_init_files(dict_init_mode_t dict_init_mode,
5489 List<const Plugin_tablespace> *tablespaces) {
5490 DBUG_TRACE;
5491
5492 ut_ad(dict_init_mode == DICT_INIT_CREATE_FILES ||
5493 dict_init_mode == DICT_INIT_CHECK_FILES ||
5494 dict_init_mode == DICT_INIT_UPGRADE_57_FILES);
5495
5496 bool create = (dict_init_mode == DICT_INIT_CREATE_FILES);
5497
5498 /* Check if the data files exist or not. */
5499 dberr_t err =
5500 srv_sys_space.check_file_spec(create, MIN_EXPECTED_TABLESPACE_SIZE);
5501
5502 if (err != DB_SUCCESS) {
5503 return innodb_init_abort();
5504 }
5505
5506 srv_is_upgrade_mode = (dict_init_mode == DICT_INIT_UPGRADE_57_FILES);
5507
5508 /* Start the InnoDB server. */
5509 err = srv_start(create);
5510
5511 if (err != DB_SUCCESS) {
5512 return innodb_init_abort();
5513 }
5514
5515 if (srv_is_upgrade_mode) {
5516 if (!dict_sys_table_id_build()) {
5517 return innodb_init_abort();
5518 }
5519
5520 if (trx_sys->found_prepared_trx) {
5521 ib::error(ER_DD_UPGRADE_FOUND_PREPARED_XA_TRANSACTION);
5522 return innodb_init_abort();
5523 }
5524
5525 /* Disable AHI when we start loading tables for purge.
5526 These tables are evicted anyway after purge. */
5527
5528 bool old_btr_search_value = btr_search_enabled;
5529 btr_search_enabled = false;
5530
5531 /* Load all tablespaces upfront from InnoDB Dictionary.
5532 This is needed for applying purge and ibuf from 5.7 */
5533 dict_load_tablespaces_for_upgrade();
5534
5535 /* Start purge threads immediately and wait for purge to
5536 become empty. All table_ids will be adjusted by a fixed
5537 offset during upgrade. So purge cannot load a table by
5538 table_id later. Also InnoDB dictionary will be dropped
5539 during the process of upgrade. So apply all the purge
5540 now. */
5541 srv_start_purge_threads();
5542
5543 uint64_t rseg_history_len;
5544 while ((rseg_history_len = trx_sys->rseg_history_len.load()) != 0) {
5545 ib::info(ER_IB_MSG_547)
5546 << "Waiting for purge to become empty:"
5547 << " current purge history len is " << rseg_history_len;
5548 sleep(1);
5549 }
5550
5551 srv_upgrade_old_undo_found = false;
5552
5553 buf_flush_sync_all_buf_pools();
5554
5555 dict_upgrade_evict_tables_cache();
5556
5557 dict_stats_evict_tablespaces();
5558
5559 btr_search_enabled = old_btr_search_value;
5560 }
5561
5562 bool ret;
5563
5564 // For upgrade from 5.7, create mysql.ibd
5565 create |= (dict_init_mode == DICT_INIT_UPGRADE_57_FILES);
5566 ret = create ? dd_create_hardcoded(dict_sys_t::s_dict_space_id,
5567 dict_sys_t::s_dd_space_file_name)
5568 : dd_open_hardcoded(dict_sys_t::s_dict_space_id,
5569 dict_sys_t::s_dd_space_file_name);
5570
5571 /* Once hardcoded tablespace mysql is created or opened,
5572 prepare it along with innodb system tablespace for server.
5573 Tell server that these two hardcoded tablespaces exist. */
5574 if (!ret) {
5575 const size_t len =
5576 30 + sizeof("id=;flags=;server_version=;space_version=;state=normal");
5577 const char *fmt =
5578 "id=%u;flags=%u;server_version=%u;space_version=%u;state=normal";
5579 static char se_private_data_innodb_system[len];
5580 static char se_private_data_dd[len];
5581 snprintf(se_private_data_innodb_system, len, fmt, TRX_SYS_SPACE,
5582 predefined_flags, DD_SPACE_CURRENT_SRV_VERSION,
5583 DD_SPACE_CURRENT_SPACE_VERSION);
5584 snprintf(se_private_data_dd, len, fmt, dict_sys_t::s_dict_space_id,
5585 predefined_flags, DD_SPACE_CURRENT_SRV_VERSION,
5586 DD_SPACE_CURRENT_SPACE_VERSION);
5587
5588 static Plugin_tablespace dd_space(dict_sys_t::s_dd_space_name, "",
5589 se_private_data_dd, "",
5590 innobase_hton_name);
5591 static Plugin_tablespace::Plugin_tablespace_file dd_file(
5592 dict_sys_t::s_dd_space_file_name, "");
5593 dd_space.add_file(&dd_file);
5594 tablespaces->push_back(&dd_space);
5595
5596 static Plugin_tablespace innodb(dict_sys_t::s_sys_space_name, "",
5597 se_private_data_innodb_system, "",
5598 innobase_hton_name);
5599 Tablespace::files_t::const_iterator end = srv_sys_space.m_files.end();
5600 Tablespace::files_t::const_iterator begin = srv_sys_space.m_files.begin();
5601 for (Tablespace::files_t::const_iterator it = begin; it != end; ++it) {
5602 innobase_sys_files.push_back(
5603 ut::new_withkey<Plugin_tablespace::Plugin_tablespace_file>(
5604 UT_NEW_THIS_FILE_PSI_KEY, it->name(), ""));
5605 innodb.add_file(innobase_sys_files.back());
5606 }
5607 tablespaces->push_back(&innodb);
5608
5609 } else {
5610 return innodb_init_abort();
5611 }
5612
5613 innobase_old_blocks_pct = static_cast<uint>(
5614 buf_LRU_old_ratio_update(innobase_old_blocks_pct, true));
5615
5616 ibuf_max_size_update(srv_change_buffer_max_size);
5617
5618 innobase_open_tables = ut::new_<hash_table_t>(200);
5619 mysql_mutex_init(innobase_share_mutex_key.m_value, &innobase_share_mutex,
5620 MY_MUTEX_INIT_FAST);
5621 mysql_mutex_init(commit_cond_mutex_key.m_value, &commit_cond_m,
5622 MY_MUTEX_INIT_FAST);
5623 mysql_cond_init(commit_cond_key.m_value, &commit_cond);
5624 mysql_mutex_init(resume_encryption_cond_mutex_key.m_value,
5625 &resume_encryption_cond_m, MY_MUTEX_INIT_FAST);
5626 mysql_cond_init(resume_encryption_cond_key.m_value, &resume_encryption_cond);
5627 recovery_lock_taken = os_event_create();
5628 innodb_inited = true;
5629 #ifdef MYSQL_DYNAMIC_PLUGIN
5630 if (innobase_hton != p) {
5631 innobase_hton = reinterpret_cast<handlerton *>(p);
5632 *innobase_hton = *innodb_hton_ptr;
5633 }
5634 #endif /* MYSQL_DYNAMIC_PLUGIN */
5635
5636 /* Do this as late as possible so server is fully starts up,
5637 since we might get some initial stats if user choose to turn
5638 on some counters from start up */
5639 if (innobase_enable_monitor_counter) {
5640 innodb_enable_monitor_at_startup(innobase_enable_monitor_counter);
5641 }
5642
5643 /* Turn on monitor counters that are default on */
5644 srv_mon_default_on();
5645
5646 /* Unit Tests */
5647 #ifdef UNIV_ENABLE_UNIT_TEST_GET_PARENT_DIR
5648 unit_test_os_file_get_parent_dir();
5649 #endif /* UNIV_ENABLE_UNIT_TEST_GET_PARENT_DIR */
5650
5651 #ifdef UNIV_ENABLE_UNIT_TEST_MAKE_FILEPATH
5652 test_make_filepath();
5653 #endif /*UNIV_ENABLE_UNIT_TEST_MAKE_FILEPATH */
5654
5655 #ifdef UNIV_ENABLE_DICT_STATS_TEST
5656 test_dict_stats_all();
5657 #endif /*UNIV_ENABLE_DICT_STATS_TEST */
5658
5659 #ifdef UNIV_ENABLE_UNIT_TEST_ROW_RAW_FORMAT_INT
5660 #ifdef HAVE_UT_CHRONO_T
5661 test_row_raw_format_int();
5662 #endif /* HAVE_UT_CHRONO_T */
5663 #endif /* UNIV_ENABLE_UNIT_TEST_ROW_RAW_FORMAT_INT */
5664
5665 return 0;
5666 }
5667
5668 /** Flush InnoDB redo logs to the file system.
5669 @param[in] hton InnoDB handlerton
5670 @param[in] binlog_group_flush true if we got invoked by binlog
5671 group commit during flush stage, false in other cases.
5672 @return false */
5673 static bool innobase_flush_logs(handlerton *hton, bool binlog_group_flush) {
5674 DBUG_TRACE;
5675 assert(hton == innodb_hton_ptr);
5676
5677 if (srv_read_only_mode) {
5678 return false;
5679 }
5680
5681 /* If !binlog_group_flush, we got invoked by FLUSH LOGS or similar.
5682 Else, we got invoked by binlog group commit during flush stage. */
5683
5684 if (binlog_group_flush && srv_flush_log_at_trx_commit == 0) {
5685 /* innodb_flush_log_at_trx_commit=0
5686 (write and sync once per second).
5687 Do not flush the redo log during binlog group commit. */
5688
5689 /* This could be unsafe if we grouped at least one DDL transaction,
5690 and we removed !trx->ddl_must_flush from condition which is checked
5691 inside trx_commit_complete_for_mysql() when we decide if we could
5692 skip the flush. */
5693 return false;
5694 }
5695
5696 /* Signal and wait for all GTIDs to persist on disk. */
5697 if (!binlog_group_flush) {
5698 auto &gtid_persistor = clone_sys->get_gtid_persistor();
5699 gtid_persistor.wait_flush(true, true, nullptr);
5700 }
5701
5702 /* Flush the redo log buffer to the redo log file.
5703 Sync it to disc if we are in FLUSH LOGS, or if
5704 innodb_flush_log_at_trx_commit=1
5705 (write and sync at each commit). */
5706 log_buffer_flush_to_disk(!binlog_group_flush ||
5707 srv_flush_log_at_trx_commit == 1);
5708
5709 return false;
5710 }
5711
5712 /** Commits a transaction in an InnoDB database. */
5713 void innobase_commit_low(trx_t *trx) /*!< in: transaction handle */
5714 {
5715 if (trx_is_started(trx)) {
5716 const dberr_t error [[maybe_unused]] = trx_commit_for_mysql(trx);
5717 // This is ut_ad not ut_a, because previously we did not have an assert
5718 // and nobody has noticed for a long time, so probably there is no much
5719 // harm in silencing this error. OTOH we believe it should no longer happen
5720 // after adding `true` as a second argument to TrxInInnoDB constructor call,
5721 // so we'd like to learn if the error can still happen.
5722 ut_ad(DB_SUCCESS == error);
5723 }
5724 trx->will_lock = 0;
5725 }
5726
5727 /** Creates an InnoDB transaction struct for the thd if it does not yet have
5728 one. Starts a new InnoDB transaction if a transaction is not yet started. And
5729 assigns a new snapshot for a consistent read if the transaction does not yet
5730 have one.
5731 @return 0 */
5732 static int innobase_start_trx_and_assign_read_view(
5733 handlerton *hton, /*!< in: InnoDB handlerton */
5734 THD *thd) /*!< in: MySQL thread handle of the user for
5735 whom the transaction should be committed */
5736 {
5737 DBUG_TRACE;
5738 assert(hton == innodb_hton_ptr);
5739
5740 /* Create a new trx struct for thd, if it does not yet have one */
5741
5742 trx_t *trx = check_trx_exists(thd);
5743
5744 TrxInInnoDB trx_in_innodb(trx);
5745
5746 innobase_srv_conc_force_exit_innodb(trx);
5747
5748 /* The transaction should not be active yet, start it */
5749 ut_ad(!trx_is_started(trx));
5750
5751 trx_start_if_not_started_xa(trx, false, UT_LOCATION_HERE);
5752
5753 /* Assign a read view if the transaction does not have it yet.
5754 Do this only if transaction is using REPEATABLE READ isolation
5755 level. */
5756 trx->isolation_level =
5757 innobase_trx_map_isolation_level(thd_get_trx_isolation(thd));
5758
5759 if (trx->isolation_level == TRX_ISO_REPEATABLE_READ) {
5760 trx_assign_read_view(trx);
5761 } else {
5762 push_warning_printf(thd, Sql_condition::SL_WARNING, HA_ERR_UNSUPPORTED,
5763 "InnoDB: WITH CONSISTENT SNAPSHOT"
5764 " was ignored because this phrase"
5765 " can only be used with"
5766 " REPEATABLE READ isolation level.");
5767 }
5768
5769 /* Set the MySQL flag to mark that there is an active transaction */
5770
5771 innobase_register_trx(hton, current_thd, trx);
5772
5773 return 0;
5774 }
5775
5776 /** Commits a transaction in an InnoDB database or marks an SQL statement
5777 ended.
5778 @return 0 or deadlock error if the transaction was aborted by another
5779 higher priority transaction. */
5780 static int innobase_commit(handlerton *hton, /*!< in: InnoDB handlerton */
5781 THD *thd, /*!< in: MySQL thread handle of the
5782 user for whom the transaction should
5783 be committed */
5784 bool commit_trx) /*!< in: true - commit transaction
5785 false - the current SQL statement
5786 ended */
5787 {
5788 DBUG_TRACE;
5789 assert(hton == innodb_hton_ptr);
5790 DBUG_PRINT("trans", ("ending transaction"));
5791 DEBUG_SYNC_C("transaction_commit_start");
5792
5793 trx_t *trx = check_trx_exists(thd);
5794
5795 /* We are about to check if the transaction is_aborted, and if it is,
5796 then we want to rollback, and otherwise we want to proceed.
5797 However it might happen that a different transaction, which has high priority
5798 will abort our transaction just after we do the test.
5799 To prevent that, we want to set TRX_FORCE_ROLLBACK_DISABLE flag on our trx,
5800 which is checked in RecLock::make_trx_hit_list and prevents high priority
5801 transaction from killing us.
5802 One way to do that is to call TrxInInnoDB with `true` as second argument.
5803 Note that innobase_commit is called not only on "real" COMMIT, but also
5804 after each statement (with commit_trx=false), so we need some logic to decide
5805 if we really plan to perform commit during this call.
5806 */
5807 bool will_commit =
5808 commit_trx ||
5809 (!thd_test_options(thd, OPTION_NOT_AUTOCOMMIT | OPTION_BEGIN));
5810 TrxInInnoDB trx_in_innodb(trx, will_commit);
5811
5812 if (trx_in_innodb.is_aborted()) {
5813 innobase_rollback(hton, thd, commit_trx);
5814
5815 return convert_error_code_to_mysql(DB_FORCED_ABORT, 0, thd);
5816 }
5817
5818 ut_ad(trx->dict_operation_lock_mode == 0);
5819
5820 /* Transaction is deregistered only in a commit or a rollback. If
5821 it is deregistered we know there cannot be resources to be freed
5822 and we could return immediately. For the time being, we play safe
5823 and do the cleanup though there should be nothing to clean up. */
5824
5825 if (!trx_is_registered_for_2pc(trx) && trx_is_started(trx)) {
5826 log_errlog(ERROR_LEVEL, ER_INNODB_UNREGISTERED_TRX_ACTIVE);
5827 }
5828
5829 bool read_only = trx->read_only || trx->id == 0;
5830
5831 if (will_commit) {
5832 /* We were instructed to commit the whole transaction, or
5833 this is an SQL statement end and autocommit is on */
5834
5835 /* We need current binlog position for mysqlbackup to work. */
5836
5837 if (!read_only) {
5838 while (innobase_commit_concurrency > 0) {
5839 mysql_mutex_lock(&commit_cond_m);
5840
5841 ++commit_threads;
5842
5843 if (commit_threads <= innobase_commit_concurrency) {
5844 mysql_mutex_unlock(&commit_cond_m);
5845 break;
5846 }
5847
5848 --commit_threads;
5849
5850 mysql_cond_wait(&commit_cond, &commit_cond_m);
5851
5852 mysql_mutex_unlock(&commit_cond_m);
5853 }
5854
5855 /* The following call reads the binary log position of
5856 the transaction being committed.
5857
5858 Binary logging of other engines is not relevant to
5859 InnoDB as all InnoDB requires is that committing
5860 InnoDB transactions appear in the same order in the
5861 MySQL binary log as they appear in InnoDB logs, which
5862 is guaranteed by the server.
5863
5864 If the binary log is not enabled, or the transaction
5865 is not written to the binary log, the file name will
5866 be a NULL pointer. */
5867 ulonglong pos;
5868
5869 thd_binlog_pos(thd, &trx->mysql_log_file_name, &pos);
5870
5871 trx->mysql_log_offset = static_cast<uint64_t>(pos);
5872
5873 /* Don't do write + flush right now. For group commit
5874 to work we want to do the flush later. */
5875 trx->flush_log_later = true;
5876 }
5877
5878 /* If SE needs to persist GTID we must have a transaction. */
5879 if (thd->se_persists_gtid_explicit()) {
5880 trx_start_if_not_started(trx, true, UT_LOCATION_HERE);
5881 }
5882
5883 innobase_commit_low(trx);
5884
5885 if (!read_only) {
5886 trx->flush_log_later = false;
5887
5888 if (innobase_commit_concurrency > 0) {
5889 mysql_mutex_lock(&commit_cond_m);
5890
5891 ut_ad(commit_threads > 0);
5892 --commit_threads;
5893
5894 mysql_cond_signal(&commit_cond);
5895
5896 mysql_mutex_unlock(&commit_cond_m);
5897 }
5898 }
5899
5900 trx_deregister_from_2pc(trx);
5901
5902 /* Now do a write + flush of logs. */
5903 if (!read_only) {
5904 trx_commit_complete_for_mysql(trx);
5905 }
5906
5907 } else {
5908 /* We just mark the SQL statement ended and do not do a
5909 transaction commit */
5910
5911 /* If we had reserved the auto-inc lock for some
5912 table in this SQL statement we release it now */
5913
5914 if (!read_only) {
5915 lock_unlock_table_autoinc(trx);
5916 }
5917
5918 /* Store the current undo_no of the transaction so that we
5919 know where to roll back if we have to roll back the next
5920 SQL statement */
5921
5922 trx_mark_sql_stat_end(trx);
5923 }
5924
5925 /* Reset the number AUTO-INC rows required */
5926 trx->n_autoinc_rows = 0;
5927
5928 /* This is a statement level variable. */
5929 trx->fts_next_doc_id = 0;
5930
5931 innobase_srv_conc_force_exit_innodb(trx);
5932
5933 return 0;
5934 }
5935
5936 /** Rolls back a transaction or the latest SQL statement.
5937 @return 0 or error number */
5938 static int innobase_rollback(handlerton *hton, /*!< in: InnoDB handlerton */
5939 THD *thd, /*!< in: handle to the MySQL thread
5940 of the user whose transaction should
5941 be rolled back */
5942 bool rollback_trx) /*!< in: true - rollback entire
5943 transaction false - rollback the
5944 current statement only */
5945 {
5946 DBUG_TRACE;
5947 assert(hton == innodb_hton_ptr);
5948 DBUG_PRINT("trans", ("aborting transaction"));
5949
5950 trx_t *trx = check_trx_exists(thd);
5951
5952 TrxInInnoDB trx_in_innodb(trx);
5953
5954 ut_ad(trx_in_innodb.is_aborted() ||
5955 (trx->dict_operation_lock_mode == 0 &&
5956 trx->dict_operation == TRX_DICT_OP_NONE));
5957
5958 innobase_srv_conc_force_exit_innodb(trx);
5959
5960 /* Reset the number AUTO-INC rows required */
5961
5962 trx->n_autoinc_rows = 0;
5963
5964 /* If we had reserved the auto-inc lock for some table (if
5965 we come here to roll back the latest SQL statement) we
5966 release it now before a possibly lengthy rollback */
5967
5968 if (!trx_in_innodb.is_aborted()) {
5969 lock_unlock_table_autoinc(trx);
5970 }
5971
5972 /* This is a statement level variable. */
5973
5974 trx->fts_next_doc_id = 0;
5975
5976 dberr_t error;
5977
5978 if (rollback_trx ||
5979 !thd_test_options(thd, OPTION_NOT_AUTOCOMMIT | OPTION_BEGIN)) {
5980 error = trx_rollback_for_mysql(trx);
5981
5982 ut_ad(trx_can_be_handled_by_current_thread_or_is_hp_victim(trx));
5983 if (trx->state.load(std::memory_order_relaxed) ==
5984 TRX_STATE_FORCED_ROLLBACK) {
5985 #ifdef UNIV_DEBUG
5986 char buffer[1024];
5987
5988 ib::info(ER_IB_MSG_548)
5989 << "Forced rollback : "
5990 << thd_security_context(thd, buffer, sizeof(buffer), 512);
5991 #endif /* UNIV_DEBUG */
5992 trx->state.store(TRX_STATE_NOT_STARTED, std::memory_order_relaxed);
5993 }
5994
5995 trx_deregister_from_2pc(trx);
5996
5997 } else {
5998 error = trx_rollback_last_sql_stat_for_mysql(trx);
5999 }
6000
6001 return convert_error_code_to_mysql(error, 0, trx->mysql_thd);
6002 }
6003
6004 /** Rolls back a transaction
6005 @return 0 or error number */
6006 static int innobase_rollback_trx(trx_t *trx) /*!< in: transaction */
6007 {
6008 dberr_t error = DB_SUCCESS;
6009
6010 DBUG_TRACE;
6011 DBUG_PRINT("trans", ("aborting transaction"));
6012
6013 innobase_srv_conc_force_exit_innodb(trx);
6014
6015 /* If we had reserved the auto-inc lock for some table (if
6016 we come here to roll back the latest SQL statement) we
6017 release it now before a possibly lengthy rollback */
6018 if (!TrxInInnoDB::is_aborted(trx)) {
6019 lock_unlock_table_autoinc(trx);
6020 }
6021
6022 if (trx_is_rseg_updated(trx)) {
6023 error = trx_rollback_for_mysql(trx);
6024 } else {
6025 trx->will_lock = 0;
6026 }
6027
6028 return convert_error_code_to_mysql(error, 0, trx->mysql_thd);
6029 }
6030
6031 /** Rolls back a transaction to a savepoint.
6032 @return 0 if success, HA_ERR_NO_SAVEPOINT if no savepoint with the
6033 given name */
6034 static int innobase_rollback_to_savepoint(
6035 handlerton *hton, /*!< in: InnoDB handlerton */
6036 THD *thd, /*!< in: handle to the MySQL thread
6037 of the user whose transaction should
6038 be rolled back to savepoint */
6039 void *savepoint) /*!< in: savepoint data */
6040 {
6041 DBUG_TRACE;
6042 assert(hton == innodb_hton_ptr);
6043
6044 trx_t *trx = check_trx_exists(thd);
6045
6046 TrxInInnoDB trx_in_innodb(trx);
6047
6048 innobase_srv_conc_force_exit_innodb(trx);
6049
6050 /* TODO: use provided savepoint data area to store savepoint data */
6051
6052 char name[64];
6053
6054 longlong2str((ulint)savepoint, name, 36);
6055
6056 int64_t mysql_binlog_cache_pos;
6057
6058 dberr_t error =
6059 trx_rollback_to_savepoint_for_mysql(trx, name, &mysql_binlog_cache_pos);
6060
6061 if (error == DB_SUCCESS && trx->fts_trx != nullptr) {
6062 fts_savepoint_rollback(trx, name);
6063 }
6064
6065 return convert_error_code_to_mysql(error, 0, nullptr);
6066 }
6067
6068 /** Check whether innodb state allows to safely release MDL locks after
6069 rollback to savepoint.
6070 When binlog is on, MDL locks acquired after savepoint unit are not
6071 released if there are any locks held in InnoDB.
6072 @return true if it is safe, false if its not safe. */
6073 static bool innobase_rollback_to_savepoint_can_release_mdl(
6074 handlerton *hton, /*!< in: InnoDB handlerton */
6075 THD *thd) /*!< in: handle to the MySQL thread
6076 of the user whose transaction should
6077 be rolled back to savepoint */
6078 {
6079 DBUG_TRACE;
6080 assert(hton == innodb_hton_ptr);
6081
6082 trx_t *trx = check_trx_exists(thd);
6083
6084 TrxInInnoDB trx_in_innodb(trx);
6085
6086 ut_ad(thd == current_thd);
6087 ut_ad(trx->lock.wait_lock == nullptr);
6088 return UT_LIST_GET_LEN(trx->lock.trx_locks) == 0;
6089 }
6090
6091 /** Release transaction savepoint name.
6092 @return 0 if success, HA_ERR_NO_SAVEPOINT if no savepoint with the
6093 given name */
6094 static int innobase_release_savepoint(
6095 handlerton *hton, /*!< in: handlerton for InnoDB */
6096 THD *thd, /*!< in: handle to the MySQL thread
6097 of the user whose transaction's
6098 savepoint should be released */
6099 void *savepoint) /*!< in: savepoint data */
6100 {
6101 dberr_t error;
6102 trx_t *trx;
6103 char name[64];
6104
6105 DBUG_TRACE;
6106 assert(hton == innodb_hton_ptr);
6107
6108 trx = check_trx_exists(thd);
6109
6110 TrxInInnoDB trx_in_innodb(trx);
6111
6112 /* TODO: use provided savepoint data area to store savepoint data */
6113
6114 longlong2str((ulint)savepoint, name, 36);
6115
6116 error = trx_release_savepoint_for_mysql(trx, name);
6117
6118 if (error == DB_SUCCESS && trx->fts_trx != nullptr) {
6119 fts_savepoint_release(trx, name);
6120 }
6121
6122 return convert_error_code_to_mysql(error, 0, nullptr);
6123 }
6124
6125 /** Sets a transaction savepoint.
6126 @return always 0, that is, always succeeds */
6127 static int innobase_savepoint(
6128 handlerton *hton, /*!< in: handle to the InnoDB handlerton */
6129 THD *thd, /*!< in: handle to the MySQL thread */
6130 void *savepoint) /*!< in: savepoint data */
6131 {
6132 DBUG_TRACE;
6133 assert(hton == innodb_hton_ptr);
6134
6135 /* In the autocommit mode there is no sense to set a savepoint
6136 (unless we are in sub-statement), so SQL layer ensures that
6137 this method is never called in such situation. */
6138
6139 trx_t *trx = check_trx_exists(thd);
6140
6141 TrxInInnoDB trx_in_innodb(trx);
6142
6143 innobase_srv_conc_force_exit_innodb(trx);
6144
6145 /* Cannot happen outside of transaction */
6146 assert(trx_is_registered_for_2pc(trx));
6147
6148 /* TODO: use provided savepoint data area to store savepoint data */
6149 char name[64];
6150
6151 longlong2str((ulint)savepoint, name, 36);
6152
6153 dberr_t error = trx_savepoint_for_mysql(trx, name, 0);
6154
6155 if (error == DB_SUCCESS && trx->fts_trx != nullptr) {
6156 fts_savepoint_take(trx->fts_trx, name);
6157 }
6158
6159 return convert_error_code_to_mysql(error, 0, nullptr);
6160 }
6161
6162 /** Frees a possible InnoDB trx object associated with the current THD.
6163 @return 0 or error number */
6164 static int innobase_close_connection(
6165 handlerton *hton, /*!< in: innobase handlerton */
6166 THD *thd) /*!< in: handle to the MySQL thread of the user
6167 whose resources should be free'd */
6168 {
6169 DBUG_TRACE;
6170 assert(hton == innodb_hton_ptr);
6171
6172 trx_t *trx = thd_to_trx(thd);
6173 bool free_trx = false;
6174
6175 /* During server initialization MySQL layer will try to open
6176 some of the master-slave tables those residing in InnoDB.
6177 After MySQL layer is done with needed checks these tables
6178 are closed followed by invocation of close_connection on the
6179 associated thd.
6180
6181 close_connection rolls back the trx and then frees it.
6182 Once trx is freed thd should avoid maintaining reference to
6183 it else it can be classified as stale reference.
6184
6185 Re-invocation of innodb_close_connection on same thd should
6186 get trx as NULL. */
6187
6188 if (trx != nullptr) {
6189 ut_ad(trx->mysql_thd == thd);
6190 TrxInInnoDB trx_in_innodb(trx);
6191
6192 if (trx_in_innodb.is_aborted()) {
6193 while (trx_is_started(trx)) {
6194 std::this_thread::sleep_for(std::chrono::microseconds(20));
6195 }
6196 }
6197
6198 if (!trx_is_registered_for_2pc(trx) && trx_is_started(trx)) {
6199 log_errlog(ERROR_LEVEL, ER_INNODB_UNREGISTERED_TRX_ACTIVE);
6200 }
6201
6202 /* Disconnect causes rollback in the following cases:
6203 - trx is not started, or
6204 - trx is in *not* in PREPARED state, or
6205 - trx has not updated any persistent data.
6206 TODO/FIXME: it does not make sense to initiate rollback
6207 in the 1st and 3rd case. */
6208 if (trx_is_started(trx)) {
6209 if (trx_state_eq(trx, TRX_STATE_PREPARED)) {
6210 if (trx_is_redo_rseg_updated(trx)) {
6211 trx_disconnect_prepared(trx);
6212 } else {
6213 trx_rollback_for_mysql(trx);
6214 trx_deregister_from_2pc(trx);
6215 free_trx = true;
6216 }
6217 } else {
6218 log_errlog(WARNING_LEVEL, ER_INNODB_CLOSING_CONNECTION_ROLLS_BACK,
6219 trx->undo_no);
6220 ut_d(ib::warn(ER_IB_MSG_549)
6221 << "trx: " << trx << " started on: "
6222 << innobase_basename(trx->start_file) << ":" << trx->start_line);
6223 innobase_rollback_trx(trx);
6224 free_trx = true;
6225 }
6226 } else {
6227 innobase_rollback_trx(trx);
6228 free_trx = true;
6229 }
6230 }
6231
6232 /* Free trx only after TrxInInnoDB is deleted. */
6233 if (free_trx) {
6234 trx_free_for_mysql(trx);
6235 }
6236
6237 ut::delete_(thd_to_innodb_session(thd));
6238
6239 thd_to_innodb_session(thd) = nullptr;
6240
6241 return 0;
6242 }
6243
6244 /** Cancel any pending lock request associated with the current THD. */
6245 static void innobase_kill_connection(
6246 handlerton *hton, /*!< in: innobase handlerton */
6247 THD *thd) /*!< in: handle to the MySQL thread being
6248 killed */
6249 {
6250 DBUG_TRACE;
6251 assert(hton == innodb_hton_ptr);
6252
6253 trx_t *trx = thd_to_trx(thd);
6254
6255 if (trx != nullptr) {
6256 /* Cancel a pending lock request if there are any */
6257 lock_cancel_if_waiting_and_release({trx});
6258 }
6259 }
6260
6261 /** ** InnoDB database tables
6262 *****************************************************************************/
6263
6264 /** The requested compressed page size (key_block_size)
6265 is given in kilobytes. If it is a valid number, store
6266 that value as the number of log2 shifts from 512 in
6267 zip_ssize. Zero means it is not compressed. */
6268 static uint32_t get_zip_shift_size(ulint key_block_size) {
6269 uint32_t zssize; /* Zip Shift Size */
6270 uint32_t kbsize; /* Key Block Size */
6271 const uint32_t zip_ssize_max =
6272 std::min(static_cast<uint32_t>(UNIV_PAGE_SSIZE_MAX),
6273 static_cast<uint32_t>(PAGE_ZIP_SSIZE_MAX));
6274 for (zssize = kbsize = 1; zssize <= zip_ssize_max; zssize++, kbsize <<= 1) {
6275 if (kbsize == key_block_size) {
6276 return (zssize);
6277 }
6278 }
6279 return (0);
6280 }
6281
6282 /** Get real row type for the table created based on one specified by user,
6283 CREATE TABLE options and SE capabilities.
6284
6285 @note The current code in this method is redundant with/copy of code from
6286 create_table_info_t::innobase_table_flags(). This is temporary workaround.
6287 In future this method will always return ROW_TYPE_DYNAMIC
6288 (which is suitable for intrinsic temporary tables)
6289 and rely on adjusting row format in table definition at ha_innobase::create()
6290 or ha_innobase::prepare_inplace_alter_table() time.
6291 */
6292 enum row_type ha_innobase::get_real_row_type(
6293 const HA_CREATE_INFO *create_info) const {
6294 const bool is_temp = create_info->options & HA_LEX_CREATE_TMP_TABLE;
6295 row_type rt = create_info->row_type;
6296
6297 if (is_temp && (create_info->options & HA_LEX_CREATE_INTERNAL_TMP_TABLE)) {
6298 return (ROW_TYPE_DYNAMIC);
6299 }
6300
6301 if (rt == ROW_TYPE_DEFAULT && create_info->key_block_size &&
6302 get_zip_shift_size(create_info->key_block_size) && !is_temp &&
6303 (srv_file_per_table || tablespace_is_shared_space(create_info))) {
6304 rt = ROW_TYPE_COMPRESSED;
6305 }
6306
6307 switch (rt) {
6308 case ROW_TYPE_REDUNDANT:
6309 case ROW_TYPE_DYNAMIC:
6310 case ROW_TYPE_COMPACT:
6311 return (rt);
6312 case ROW_TYPE_COMPRESSED:
6313 if (!is_temp &&
6314 (srv_file_per_table || tablespace_is_shared_space(create_info))) {
6315 return (rt);
6316 } else {
6317 return (ROW_TYPE_DYNAMIC);
6318 }
6319 case ROW_TYPE_NOT_USED:
6320 case ROW_TYPE_FIXED:
6321 case ROW_TYPE_PAGED:
6322 return (ROW_TYPE_DYNAMIC);
6323 case ROW_TYPE_DEFAULT:
6324 default:
6325 switch (innodb_default_row_format) {
6326 case DEFAULT_ROW_FORMAT_REDUNDANT:
6327 return (ROW_TYPE_REDUNDANT);
6328 case DEFAULT_ROW_FORMAT_COMPACT:
6329 return (ROW_TYPE_COMPACT);
6330 case DEFAULT_ROW_FORMAT_DYNAMIC:
6331 return (ROW_TYPE_DYNAMIC);
6332 default:
6333 ut_d(ut_error);
6334 ut_o(return (ROW_TYPE_DYNAMIC));
6335 }
6336 }
6337 }
6338
6339 /** Get the table flags to use for the statement.
6340 @return table flags */
6341
6342 handler::Table_flags ha_innobase::table_flags() const {
6343 THD *thd = ha_thd();
6344 handler::Table_flags flags = m_int_table_flags;
6345
6346 /* If querying the table flags when no table_share is given,
6347 then we must check if the table to be created/checked is partitioned.
6348 */
6349 if (table_share == nullptr && thd_get_work_part_info(thd) != nullptr) {
6350 /* Currently ha_innopart does not support
6351 all InnoDB features such as GEOMETRY, FULLTEXT etc. */
6352 flags &= ~(HA_INNOPART_DISABLED_TABLE_FLAGS);
6353 }
6354
6355 /* Temporary table provides accurate record count */
6356 if (table_share != nullptr &&
6357 table_share->table_category == TABLE_CATEGORY_TEMPORARY) {
6358 flags |= HA_STATS_RECORDS_IS_EXACT;
6359 }
6360
6361 /* Need to use tx_isolation here since table flags is (also)
6362 called before prebuilt is inited. */
6363
6364 ulong const tx_isolation = thd_tx_isolation(thd);
6365
6366 if (tx_isolation <= ISO_READ_COMMITTED) {
6367 return (flags);
6368 }
6369
6370 return (flags | HA_BINLOG_STMT_CAPABLE);
6371 }
6372
6373 /** Returns the table type (storage engine name).
6374 @return table type */
6375
6376 const char *ha_innobase::table_type() const { return (innobase_hton_name); }
6377
6378 /** Returns the operations supported for indexes.
6379 @return flags of supported operations */
6380
6381 ulong ha_innobase::index_flags(uint key, uint, bool) const {
6382 if (table_share->key_info[key].algorithm == HA_KEY_ALG_FULLTEXT) {
6383 return (0);
6384 }
6385
6386 ulong flags = HA_READ_NEXT | HA_READ_PREV | HA_READ_ORDER | HA_READ_RANGE |
6387 HA_KEYREAD_ONLY | HA_DO_INDEX_COND_PUSHDOWN;
6388
6389 /* For spatial index, we don't support descending scan
6390 and ICP so far. */
6391 if (table_share->key_info[key].flags & HA_SPATIAL) {
6392 flags = HA_READ_NEXT | HA_READ_ORDER | HA_READ_RANGE | HA_KEYREAD_ONLY |
6393 HA_KEY_SCAN_NOT_ROR;
6394 return (flags);
6395 }
6396
6397 /* For dd tables mysql.*, we disable ICP for them,
6398 it's for avoiding recursively access same page. */
6399 /* TODO: Remove these code once the recursiveely access issue which
6400 caused by ICP fixed. */
6401 const char *dbname = table_share->db.str;
6402 if (dbname && strstr(dbname, dict_sys_t::s_dd_space_name) != nullptr &&
6403 strlen(dbname) == 5) {
6404 flags = HA_READ_NEXT | HA_READ_PREV | HA_READ_ORDER | HA_READ_RANGE |
6405 HA_KEYREAD_ONLY;
6406 }
6407
6408 /* Multi-valued keys don't support ordered retrieval, neither they're
6409 suitable for keyread only retrieval. */
6410 if (table_share->key_info[key].flags & HA_MULTI_VALUED_KEY) {
6411 flags &= ~(HA_READ_ORDER | HA_KEYREAD_ONLY);
6412 }
6413
6414 return (flags);
6415 }
6416
6417 /** Returns the maximum number of keys.
6418 @return MAX_KEY */
6419
6420 uint ha_innobase::max_supported_keys() const { return (MAX_KEY); }
6421
6422 /** Returns the maximum key length.
6423 @return maximum supported key length, in bytes */
6424
6425 uint ha_innobase::max_supported_key_length() const {
6426 /* An InnoDB page must store >= 2 keys; a secondary key record
6427 must also contain the primary key value. Therefore, if both
6428 the primary key and the secondary key are at this maximum length,
6429 it must be less than 1/4th of the free space on a page including
6430 record overhead.
6431
6432 MySQL imposes its own limit to this number; MAX_KEY_LENGTH = 3072.
6433
6434 For page sizes = 16k, InnoDB historically reported 3500 bytes here,
6435 But the MySQL limit of 3072 was always used through the handler
6436 interface. */
6437
6438 switch (UNIV_PAGE_SIZE) {
6439 case 4096:
6440 return (768);
6441 case 8192:
6442 return (1536);
6443 default:
6444 return (3500);
6445 }
6446 }
6447
6448 /** Determines if the primary key is clustered index.
6449 @return true */
6450
6451 bool ha_innobase::primary_key_is_clustered() const { return (true); }
6452
6453 bool create_table_info_t::normalize_table_name(char *norm_name,
6454 const char *name) {
6455 const char *name_ptr;
6456 ulint name_len;
6457 const char *db_ptr;
6458 ulint db_len;
6459 const char *ptr;
6460 ulint norm_len;
6461
6462 /* Scan name from the end */
6463
6464 ptr = strend(name) - 1;
6465
6466 /* seek to the last path separator */
6467 while (ptr >= name && *ptr != '\\' && *ptr != '/') {
6468 ptr--;
6469 }
6470
6471 name_ptr = ptr + 1;
6472 name_len = strlen(name_ptr);
6473
6474 /* skip any number of path separators */
6475 while (ptr >= name && (*ptr == '\\' || *ptr == '/')) {
6476 ptr--;
6477 }
6478
6479 assert(ptr >= name);
6480
6481 /* seek to the last but one path separator or one char before
6482 the beginning of name */
6483 db_len = 0;
6484 while (ptr >= name && *ptr != '\\' && *ptr != '/') {
6485 ptr--;
6486 db_len++;
6487 }
6488
6489 db_ptr = ptr + 1;
6490
6491 norm_len = db_len + name_len + sizeof "/";
6492
6493 if (norm_len >= FN_REFLEN - 1) {
6494 /* purecov: begin assert */
6495 ut_d(ut_error);
6496 ut_o(return (false));
6497 /* purecov: end */
6498 }
6499
6500 memcpy(norm_name, db_ptr, db_len);
6501
6502 norm_name[db_len] = '/';
6503
6504 /* Copy the name and null-byte. */
6505 memcpy(norm_name + db_len + 1, name_ptr, name_len + 1);
6506
6507 if (lower_case_file_system) {
6508 ut_ad(lower_case_table_names != 0);
6509 innobase_casedn_str(norm_name);
6510 }
6511 return (true);
6512 }
6513
6514 #ifdef UNIV_DEBUG
6515 /*********************************************************************
6516 Test normalize_table_name(). */
6517 static void test_normalize_table_name() {
6518 char norm_name[FN_REFLEN];
6519 const char *test_data[][2] = {
6520 /* input, expected result */
6521 {"./mysqltest/t1", "mysqltest/t1"},
6522 {"./test/#sql-842b_2", "test/#sql-842b_2"},
6523 {"./test/#sql-85a3_10", "test/#sql-85a3_10"},
6524 {"./test/#sql2-842b-2", "test/#sql2-842b-2"},
6525 {"./test/bug29807", "test/bug29807"},
6526 {"./test/foo", "test/foo"},
6527 {"./test/innodb_bug52663", "test/innodb_bug52663"},
6528 {"./test/t", "test/t"},
6529 {"./test/t1", "test/t1"},
6530 {"./test/t10", "test/t10"},
6531 {"/a/b/db/table", "db/table"},
6532 {"/a/b/db///////table", "db/table"},
6533 {"/a/b////db///////table", "db/table"},
6534 {"/var/tmp/mysqld.1/#sql842b_2_10", "mysqld.1/#sql842b_2_10"},
6535 {"db/table", "db/table"},
6536 {"ddd/t", "ddd/t"},
6537 {"d/ttt", "d/ttt"},
6538 {"d/t", "d/t"},
6539 {".\\mysqltest\\t1", "mysqltest/t1"},
6540 {".\\test\\#sql-842b_2", "test/#sql-842b_2"},
6541 {".\\test\\#sql-85a3_10", "test/#sql-85a3_10"},
6542 {".\\test\\#sql2-842b-2", "test/#sql2-842b-2"},
6543 {".\\test\\bug29807", "test/bug29807"},
6544 {".\\test\\foo", "test/foo"},
6545 {".\\test\\innodb_bug52663", "test/innodb_bug52663"},
6546 {".\\test\\t", "test/t"},
6547 {".\\test\\t1", "test/t1"},
6548 {".\\test\\t10", "test/t10"},
6549 {"C:\\a\\b\\db\\table", "db/table"},
6550 {"C:\\a\\b\\db\\\\\\\\\\\\\\table", "db/table"},
6551 {"C:\\a\\b\\\\\\\\db\\\\\\\\\\\\\\table", "db/table"},
6552 {"C:\\var\\tmp\\mysqld.1\\#sql842b_2_10", "mysqld.1/#sql842b_2_10"},
6553 {"db\\table", "db/table"},
6554 {"ddd\\t", "ddd/t"},
6555 {"d\\ttt", "d/ttt"},
6556 {"d\\t", "d/t"},
6557 };
6558
6559 for (size_t i = 0; i < UT_ARR_SIZE(test_data); i++) {
6560 printf(
6561 "test_normalize_table_name():"
6562 " testing \"%s\", expected \"%s\"... ",
6563 test_data[i][0], test_data[i][1]);
6564
6565 create_table_info_t::normalize_table_name(norm_name, test_data[i][0]);
6566
6567 if (strcmp(norm_name, test_data[i][1]) == 0) {
6568 printf("ok\n");
6569 } else {
6570 printf("got \"%s\"\n", norm_name);
6571 ut_error;
6572 }
6573 }
6574 }
6575
6576 /*********************************************************************
6577 Test ut_format_name(). */
6578 static void test_ut_format_name() {
6579 char buf[NAME_LEN * 3];
6580
6581 struct {
6582 const char *name;
6583 ulint buf_size;
6584 const char *expected;
6585 } test_data[] = {
6586 {"test/t1", sizeof(buf), "`test`.`t1`"},
6587 {"test/t1", 12, "`test`.`t1`"},
6588 {"test/t1", 11, "`test`.`t1"},
6589 {"test/t1", 10, "`test`.`t"},
6590 {"test/t1", 9, "`test`.`"},
6591 {"test/t1", 8, "`test`."},
6592 {"test/t1", 7, "`test`"},
6593 {"test/t1", 6, "`test"},
6594 {"test/t1", 5, "`tes"},
6595 {"test/t1", 4, "`te"},
6596 {"test/t1", 3, "`t"},
6597 {"test/t1", 2, "`"},
6598 {"test/t1", 1, ""},
6599 {"test/t1", 0, "BUF_NOT_CHANGED"},
6600 {"table", sizeof(buf), "`table`"},
6601 {"ta'le", sizeof(buf), "`ta'le`"},
6602 {"ta\"le", sizeof(buf), "`ta\"le`"},
6603 {"ta`le", sizeof(buf), "`ta``le`"},
6604 };
6605
6606 for (size_t i = 0; i < UT_ARR_SIZE(test_data); i++) {
6607 memcpy(buf, "BUF_NOT_CHANGED", strlen("BUF_NOT_CHANGED") + 1);
6608
6609 char *ret;
6610
6611 ret = ut_format_name(test_data[i].name, buf, test_data[i].buf_size);
6612
6613 ut_a(ret == buf);
6614
6615 if (strcmp(buf, test_data[i].expected) == 0) {
6616 ib::info(ER_IB_MSG_550) << "ut_format_name(" << test_data[i].name
6617 << ", buf, " << test_data[i].buf_size
6618 << "),"
6619 " expected "
6620 << test_data[i].expected << ", OK";
6621 } else {
6622 ib::error(ER_IB_MSG_551)
6623 << "ut_format_name(" << test_data[i].name << ", buf, "
6624 << test_data[i].buf_size
6625 << "),"
6626 " expected "
6627 << test_data[i].expected << ", ERROR: got " << buf;
6628 ut_error;
6629 }
6630 }
6631 }
6632 #endif /* UNIV_DEBUG */
6633
6634 /** Match index columns between MySQL and InnoDB.
6635 This function checks whether the index column information
6636 is consistent between KEY info from mysql and that from innodb index.
6637 @param[in] key_info Index info from mysql
6638 @param[in] index_info Index info from InnoDB
6639 @return true if all column types match. */
6640 bool innobase_match_index_columns(const KEY *key_info,
6641 const dict_index_t *index_info) {
6642 const KEY_PART_INFO *key_part;
6643 const KEY_PART_INFO *key_end;
6644 const dict_field_t *innodb_idx_fld;
6645 const dict_field_t *innodb_idx_fld_end;
6646
6647 DBUG_TRACE;
6648
6649 /* Check whether user defined index column count matches */
6650 if (key_info->user_defined_key_parts != index_info->n_user_defined_cols) {
6651 return false;
6652 }
6653
6654 key_part = key_info->key_part;
6655 key_end = key_part + key_info->user_defined_key_parts;
6656 innodb_idx_fld = index_info->fields;
6657 innodb_idx_fld_end = index_info->fields + index_info->n_fields;
6658
6659 /* Check each index column's datatype. We do not check
6660 column name because there exists case that index
6661 column name got modified in mysql but such change does not
6662 propagate to InnoDB.
6663 One hidden assumption here is that the index column sequences
6664 are matched up between those in mysql and InnoDB. */
6665 for (; key_part != key_end; ++key_part) {
6666 ulint col_type;
6667 ulint is_unsigned;
6668 ulint mtype = innodb_idx_fld->col->mtype;
6669
6670 /* Need to translate to InnoDB column type before
6671 comparison. */
6672 col_type = get_innobase_type_from_mysql_type(&is_unsigned, key_part->field);
6673
6674 /* Ignore InnoDB specific system columns. */
6675 while (mtype == DATA_SYS) {
6676 innodb_idx_fld++;
6677
6678 if (innodb_idx_fld >= innodb_idx_fld_end) {
6679 return false;
6680 }
6681 }
6682
6683 if ((bool)innodb_idx_fld->is_ascending !=
6684 !(key_part->key_part_flag & HA_REVERSE_SORT)) {
6685 /* Column Type mismatches */
6686 return false;
6687 }
6688
6689 if (col_type != mtype) {
6690 /* If the col_type we get from mysql type is a geometry
6691 data type, we should check if mtype is a legacy type
6692 from 5.6, either upgraded to DATA_GEOMETRY or not.
6693 This is indeed not an accurate check, but should be
6694 safe, since DATA_BLOB would be upgraded once we create
6695 spatial index on it and we intend to use DATA_GEOMETRY
6696 for legacy GIS data types which are of var-length. */
6697 switch (col_type) {
6698 case DATA_POINT:
6699 case DATA_VAR_POINT:
6700 if (DATA_POINT_MTYPE(mtype) || mtype == DATA_GEOMETRY ||
6701 mtype == DATA_BLOB) {
6702 break;
6703 }
6704 [[fallthrough]];
6705 case DATA_GEOMETRY:
6706 if (mtype == DATA_BLOB) {
6707 break;
6708 }
6709 [[fallthrough]];
6710 default:
6711 /* Column type mismatches */
6712 return false;
6713 }
6714 }
6715
6716 innodb_idx_fld++;
6717 }
6718
6719 return true;
6720 }
6721
6722 /** Build a template for a base column for a virtual column
6723 @param[in] table MySQL TABLE
6724 @param[in] clust_index InnoDB clustered index
6725 @param[in] field field in MySQL table
6726 @param[in] col InnoDB column
6727 @param[in,out] templ template to fill
6728 @param[in] col_no field index for virtual col
6729 */
6730 static void innobase_vcol_build_templ(const TABLE *table,
6731 const dict_index_t *clust_index,
6732 Field *field, const dict_col_t *col,
6733 mysql_row_templ_t *templ, ulint col_no) {
6734 if (col->is_virtual()) {
6735 templ->is_virtual = true;
6736 templ->col_no = col_no;
6737 templ->clust_rec_field_no = ULINT_UNDEFINED;
6738 templ->rec_field_no = col->ind;
6739 } else {
6740 templ->is_virtual = false;
6741 templ->col_no = col_no;
6742 templ->clust_rec_field_no = dict_col_get_clust_pos(col, clust_index);
6743 ut_a(templ->clust_rec_field_no != ULINT_UNDEFINED);
6744
6745 templ->rec_field_no = templ->clust_rec_field_no;
6746 }
6747
6748 templ->icp_rec_field_no = ULINT_UNDEFINED;
6749
6750 if (field->is_nullable()) {
6751 templ->mysql_null_byte_offset = field->null_offset();
6752
6753 templ->mysql_null_bit_mask = (ulint)field->null_bit;
6754 } else {
6755 templ->mysql_null_bit_mask = 0;
6756 }
6757
6758 templ->mysql_col_offset = static_cast<ulint>(get_field_offset(table, field));
6759 templ->mysql_col_len = static_cast<ulint>(field->pack_length());
6760 /* The multi-value index indexes attribute values in a JSON doc, so its
6761 index field length could be different from the actual column data length */
6762 if (templ->is_virtual && innobase_is_multi_value_fld(field)) {
6763 templ->mysql_mvidx_len = static_cast<ulint>(field->key_length());
6764 templ->is_multi_val = true;
6765 } else {
6766 templ->mysql_mvidx_len = 0;
6767 templ->is_multi_val = false;
6768 }
6769
6770 templ->type = col->mtype;
6771 templ->mysql_type = static_cast<ulint>(field->type());
6772
6773 if (templ->mysql_type == DATA_MYSQL_TRUE_VARCHAR) {
6774 templ->mysql_length_bytes = field->get_length_bytes();
6775 }
6776
6777 templ->charset = dtype_get_charset_coll(col->prtype);
6778 templ->mbminlen = col->get_mbminlen();
6779 templ->mbmaxlen = col->get_mbmaxlen();
6780 templ->is_unsigned = col->prtype & DATA_UNSIGNED;
6781 }
6782
6783 /** Callback used by MySQL server layer to initialize
6784 the table virtual columns' template
6785 @param[in] table MySQL TABLE
6786 @param[in,out] ib_table InnoDB table */
6787 void innobase_build_v_templ_callback(const TABLE *table, void *ib_table) {
6788 const dict_table_t *t_table = static_cast<dict_table_t *>(ib_table);
6789
6790 innobase_build_v_templ(table, t_table, t_table->vc_templ, nullptr, true,
6791 nullptr);
6792 }
6793
6794 /** Build template for the virtual columns and their base columns. This
6795 is done when the table first opened.
6796 @param[in] table MySQL TABLE
6797 @param[in] ib_table InnoDB dict_table_t
6798 @param[in,out] s_templ InnoDB template structure
6799 @param[in] add_v new virtual columns added along with
6800 add index call
6801 @param[in] locked true if dict_sys mutex is held
6802 @param[in] share_tbl_name original MySQL table name */
6803 void innobase_build_v_templ(const TABLE *table, const dict_table_t *ib_table,
6804 dict_vcol_templ_t *s_templ,
6805 const dict_add_v_col_t *add_v, bool locked,
6806 const char *share_tbl_name) {
6807 ulint ncol = ib_table->n_cols - DATA_N_SYS_COLS;
6808 ulint n_v_col = ib_table->n_v_cols;
6809 bool marker[REC_MAX_N_FIELDS];
6810
6811 ut_ad(ncol < REC_MAX_N_FIELDS);
6812
6813 if (add_v != nullptr) {
6814 n_v_col += add_v->n_v_col;
6815 }
6816
6817 ut_ad(n_v_col > 0);
6818
6819 if (!locked) {
6820 dict_sys_mutex_enter();
6821 }
6822
6823 if (s_templ->vtempl) {
6824 if (!locked) {
6825 dict_sys_mutex_exit();
6826 }
6827 return;
6828 }
6829
6830 memset(marker, 0, sizeof(bool) * ncol);
6831
6832 s_templ->vtempl = static_cast<mysql_row_templ_t **>(ut::zalloc_withkey(
6833 UT_NEW_THIS_FILE_PSI_KEY, (ncol + n_v_col) * sizeof *s_templ->vtempl));
6834 s_templ->n_col = ncol;
6835 s_templ->n_v_col = n_v_col;
6836 s_templ->rec_len = table->s->reclength;
6837 s_templ->default_rec = static_cast<byte *>(
6838 ut::malloc_withkey(UT_NEW_THIS_FILE_PSI_KEY, table->s->reclength));
6839 memcpy(s_templ->default_rec, table->s->default_values, table->s->reclength);
6840
6841 /* Mark those columns could be base columns */
6842 for (ulint i = 0; i < ib_table->n_v_cols; i++) {
6843 const dict_v_col_t *vcol = dict_table_get_nth_v_col(ib_table, i);
6844
6845 for (ulint j = 0; j < vcol->num_base; j++) {
6846 ulint col_no = vcol->base_col[j]->ind;
6847 marker[col_no] = true;
6848 }
6849 }
6850
6851 if (add_v) {
6852 for (ulint i = 0; i < add_v->n_v_col; i++) {
6853 const dict_v_col_t *vcol = &add_v->v_col[i];
6854
6855 for (ulint j = 0; j < vcol->num_base; j++) {
6856 ulint col_no = vcol->base_col[j]->ind;
6857 marker[col_no] = true;
6858 }
6859 }
6860 }
6861
6862 ulint j = 0;
6863 ulint z = 0;
6864
6865 const dict_index_t *clust_index = ib_table->first_index();
6866
6867 for (ulint i = 0; i < table->s->fields; i++) {
6868 Field *field = table->field[i];
6869
6870 /* Build template for virtual columns */
6871 if (innobase_is_v_fld(field)) {
6872 #ifdef UNIV_DEBUG
6873 const char *name;
6874
6875 if (z >= ib_table->n_v_def) {
6876 name = add_v->v_col_name[z - ib_table->n_v_def];
6877 } else {
6878 name = dict_table_get_v_col_name(ib_table, z);
6879 }
6880
6881 ut_ad(!ut_strcmp(name, field->field_name));
6882 #endif
6883 const dict_v_col_t *vcol;
6884
6885 if (z >= ib_table->n_v_def) {
6886 vcol = &add_v->v_col[z - ib_table->n_v_def];
6887 } else {
6888 vcol = dict_table_get_nth_v_col(ib_table, z);
6889 }
6890
6891 s_templ->vtempl[z + s_templ->n_col] =
6892 static_cast<mysql_row_templ_t *>(ut::malloc_withkey(
6893 UT_NEW_THIS_FILE_PSI_KEY, sizeof *s_templ->vtempl[j]));
6894
6895 innobase_vcol_build_templ(table, clust_index, field, &vcol->m_col,
6896 s_templ->vtempl[z + s_templ->n_col], z);
6897 z++;
6898 continue;
6899 }
6900
6901 ut_ad(j < ncol);
6902
6903 /* Build template for base columns */
6904 if (marker[j]) {
6905 dict_col_t *col = ib_table->get_col(j);
6906
6907 #ifdef UNIV_DEBUG
6908 const char *name = ib_table->get_col_name(j);
6909
6910 ut_ad(!ut_strcmp(name, field->field_name));
6911 #endif
6912
6913 s_templ->vtempl[j] = static_cast<mysql_row_templ_t *>(ut::malloc_withkey(
6914 UT_NEW_THIS_FILE_PSI_KEY, sizeof *s_templ->vtempl[j]));
6915
6916 innobase_vcol_build_templ(table, clust_index, field, col,
6917 s_templ->vtempl[j], j);
6918 }
6919
6920 j++;
6921 }
6922
6923 if (!locked) {
6924 dict_sys_mutex_exit();
6925 }
6926
6927 s_templ->db_name = table->s->db.str;
6928 s_templ->tb_name = table->s->table_name.str;
6929
6930 if (share_tbl_name) {
6931 s_templ->share_name = share_tbl_name;
6932 }
6933 }
6934
6935 /** This function builds a translation table in INNOBASE_SHARE
6936 structure for fast index location with mysql array number from its
6937 table->key_info structure. This also provides the necessary translation
6938 between the key order in mysql key_info and InnoDB ib_table->indexes if
6939 they are not fully matched with each other.
6940 Note we do not have any mutex protecting the translation table
6941 building based on the assumption that there is no concurrent
6942 index creation/drop and DMLs that requires index lookup. All table
6943 handle will be closed before the index creation/drop.
6944 @return true if index translation table built successfully */
6945 static bool innobase_build_index_translation(
6946 const TABLE *table, /*!< in: table in MySQL data
6947 dictionary */
6948 dict_table_t *ib_table, /*!< in: table in InnoDB data
6949 dictionary */
6950 INNOBASE_SHARE *share) /*!< in/out: share structure
6951 where index translation table
6952 will be constructed in. */
6953 {
6954 DBUG_TRACE;
6955
6956 bool ret = true;
6957
6958 dict_sys_mutex_enter();
6959
6960 ulint mysql_num_index = table->s->keys;
6961 ulint ib_num_index = UT_LIST_GET_LEN(ib_table->indexes);
6962 dict_index_t **index_mapping = share->idx_trans_tbl.index_mapping;
6963
6964 /* If there exists inconsistency between MySQL and InnoDB dictionary
6965 (metadata) information, the number of index defined in MySQL
6966 could exceed that in InnoDB, do not build index translation
6967 table in such case */
6968 if (ib_num_index < mysql_num_index) {
6969 ret = false;
6970 goto func_exit;
6971 }
6972
6973 /* If index entry count is non-zero, nothing has
6974 changed since last update, directly return true */
6975 if (share->idx_trans_tbl.index_count) {
6976 /* Index entry count should still match mysql_num_index */
6977 ut_a(share->idx_trans_tbl.index_count == mysql_num_index);
6978 goto func_exit;
6979 }
6980
6981 /* The number of index increased, rebuild the mapping table */
6982 if (mysql_num_index > share->idx_trans_tbl.array_size) {
6983 index_mapping = reinterpret_cast<dict_index_t **>(
6984 ut::realloc_withkey(UT_NEW_THIS_FILE_PSI_KEY, index_mapping,
6985 mysql_num_index * sizeof(*index_mapping)));
6986
6987 if (index_mapping == nullptr) {
6988 /* Report an error if index_mapping continues to be
6989 NULL and mysql_num_index is a non-zero value */
6990 log_errlog(ERROR_LEVEL, ER_INNODB_TRX_XLATION_TABLE_OOM, mysql_num_index,
6991 share->idx_trans_tbl.array_size);
6992 ret = false;
6993 goto func_exit;
6994 }
6995
6996 share->idx_trans_tbl.array_size = mysql_num_index;
6997 }
6998
6999 /* For each index in the mysql key_info array, fetch its
7000 corresponding InnoDB index pointer into index_mapping
7001 array. */
7002 for (ulint count = 0; count < mysql_num_index; count++) {
7003 /* Fetch index pointers into index_mapping according to mysql
7004 index sequence */
7005 index_mapping[count] =
7006 dict_table_get_index_on_name(ib_table, table->key_info[count].name);
7007
7008 if (index_mapping[count] == nullptr) {
7009 log_errlog(ERROR_LEVEL, ER_INNODB_CANT_FIND_INDEX_IN_INNODB_DD,
7010 table->key_info[count].name);
7011 ret = false;
7012 goto func_exit;
7013 }
7014
7015 /* Double check fetched index has the same
7016 column info as those in mysql key_info. */
7017 if (!innobase_match_index_columns(&table->key_info[count],
7018 index_mapping[count])) {
7019 log_errlog(ERROR_LEVEL, ER_INNODB_INDEX_COLUMN_INFO_UNLIKE_MYSQLS,
7020 table->key_info[count].name);
7021 ret = false;
7022 goto func_exit;
7023 }
7024 }
7025
7026 /* Successfully built the translation table */
7027 share->idx_trans_tbl.index_count = mysql_num_index;
7028
7029 func_exit:
7030 if (!ret) {
7031 /* Build translation table failed. */
7032 ut::free(index_mapping);
7033
7034 share->idx_trans_tbl.array_size = 0;
7035 share->idx_trans_tbl.index_count = 0;
7036 index_mapping = nullptr;
7037 }
7038
7039 share->idx_trans_tbl.index_mapping = index_mapping;
7040
7041 dict_sys_mutex_exit();
7042
7043 return ret;
7044 }
7045
7046 /** This function uses index translation table to quickly locate the
7047 requested index structure.
7048 Note we do not have mutex protection for the index translation table
7049 access, it is based on the assumption that there is no concurrent
7050 translation table rebuild (fter create/drop index) and DMLs that
7051 require index lookup.
7052 @return dict_index_t structure for requested index. NULL if
7053 fail to locate the index structure. */
7054 static dict_index_t *innobase_index_lookup(
7055 INNOBASE_SHARE *share, /*!< in: share structure for index
7056 translation table. */
7057 uint keynr) /*!< in: index number for the requested
7058 index */
7059 {
7060 if (share->idx_trans_tbl.index_mapping == nullptr ||
7061 keynr >= share->idx_trans_tbl.index_count) {
7062 return (nullptr);
7063 }
7064
7065 return (share->idx_trans_tbl.index_mapping[keynr]);
7066 }
7067
7068 /** Set the autoinc column max value. This should only be called from
7069 ha_innobase::open, therefore there's no need for a covering lock. */
7070 void ha_innobase::innobase_initialize_autoinc() {
7071 ulonglong auto_inc;
7072 const Field *field = table->found_next_number_field;
7073
7074 if (field != nullptr) {
7075 auto_inc = field->get_max_int_value();
7076
7077 /* autoinc column cannot be virtual column */
7078 ut_ad(!innobase_is_v_fld(field));
7079 } else {
7080 /* We have no idea what's been passed in to us as the
7081 autoinc column. We set it to the 0, effectively disabling
7082 updates to the table. */
7083 auto_inc = 0;
7084
7085 ib::info(ER_IB_MSG_552) << "Unable to determine the AUTOINC column name";
7086 }
7087
7088 if (srv_force_recovery >= SRV_FORCE_NO_IBUF_MERGE) {
7089 /* If the recovery level is set so high that writes
7090 are disabled we force the AUTOINC counter to 0
7091 value effectively disabling writes to the table.
7092 Secondly, we avoid reading the table in case the read
7093 results in failure due to a corrupted table/index.
7094
7095 We will not return an error to the client, so that the
7096 tables can be dumped with minimal hassle. If an error
7097 were returned in this case, the first attempt to read
7098 the table would fail and subsequent SELECTs would succeed. */
7099 auto_inc = 0;
7100 } else if (field == nullptr) {
7101 /* This is a far more serious error, best to avoid
7102 opening the table and return failure. */
7103 my_error(ER_AUTOINC_READ_FAILED, MYF(0));
7104 } else {
7105 dict_index_t *index = nullptr;
7106 const char *col_name;
7107 uint64_t read_auto_inc;
7108 ulint err;
7109
7110 update_thd(ha_thd());
7111
7112 col_name = field->field_name;
7113
7114 read_auto_inc = dict_table_autoinc_read(m_prebuilt->table);
7115
7116 if (read_auto_inc == 0) {
7117 index = innobase_get_index(table->s->next_number_index);
7118
7119 /* Execute SELECT MAX(col_name) FROM TABLE;
7120 This is necessary when an imported tablespace
7121 doesn't have a correct cfg file so autoinc
7122 has not been initialized, or the table is empty. */
7123 err = row_search_max_autoinc(index, col_name, &read_auto_inc);
7124
7125 if (read_auto_inc > 0) {
7126 ib::warn(ER_IB_MSG_553)
7127 << "Reading max(auto_inc_col) = " << read_auto_inc << " for table "
7128 << index->table->name << ", because there was an IMPORT"
7129 << " without cfg file.";
7130 }
7131
7132 } else {
7133 err = DB_SUCCESS;
7134 }
7135
7136 switch (err) {
7137 case DB_SUCCESS: {
7138 ulonglong col_max_value;
7139
7140 col_max_value = field->get_max_int_value();
7141
7142 /* At the this stage we do not know the increment
7143 nor the offset, so use a default increment of 1. */
7144
7145 auto_inc = innobase_next_autoinc(read_auto_inc, 1, 1, 0, col_max_value);
7146
7147 break;
7148 }
7149 case DB_RECORD_NOT_FOUND:
7150 ib::error(ER_IB_MSG_554) << "MySQL and InnoDB data dictionaries are"
7151 " out of sync. Unable to find the AUTOINC"
7152 " column "
7153 << col_name
7154 << " in the InnoDB"
7155 " table "
7156 << index->table->name
7157 << ". We set"
7158 " the next AUTOINC column value to 0, in"
7159 " effect disabling the AUTOINC next value"
7160 " generation.";
7161
7162 ib::info(ER_IB_MSG_555) << "You can either set the next AUTOINC"
7163 " value explicitly using ALTER TABLE or fix"
7164 " the data dictionary by recreating the"
7165 " table.";
7166
7167 /* This will disable the AUTOINC generation. */
7168 auto_inc = 0;
7169
7170 /* We want the open to succeed, so that the user can
7171 take corrective action. ie. reads should succeed but
7172 updates should fail. */
7173 err = DB_SUCCESS;
7174 break;
7175 default:
7176 /* row_search_max_autoinc() should only return
7177 one of DB_SUCCESS or DB_RECORD_NOT_FOUND. */
7178 ut_error;
7179 }
7180 }
7181
7182 dict_table_autoinc_initialize(m_prebuilt->table, auto_inc);
7183 }
7184
7185 /** Open an InnoDB table.
7186 @param[in] name table name
7187 @param[in] open_flags flags for opening table from SQL-layer.
7188 @param[in] table_def dd::Table object describing table to be opened
7189 @retval 1 if error
7190 @retval 0 if success */
7191 int ha_innobase::open(const char *name, int, uint open_flags,
7192 const dd::Table *table_def) {
7193 dict_table_t *ib_table;
7194 char norm_name[FN_REFLEN];
7195 THD *thd;
7196 bool cached = false;
7197
7198 DBUG_TRACE;
7199 assert(table_share == table->s);
7200
7201 thd = ha_thd();
7202
7203 if (!normalize_table_name(norm_name, name)) {
7204 /* purecov: begin inspected */
7205 ut_d(ut_error);
7206 ut_o(return (HA_ERR_TOO_LONG_PATH));
7207 /* purecov: end */
7208 }
7209
7210 m_user_thd = nullptr;
7211 m_share = nullptr;
7212
7213 /* Will be allocated if it is needed in ::update_row() */
7214 m_upd_buf = nullptr;
7215 m_upd_buf_size = 0;
7216
7217 /* Get pointer to a table object in InnoDB dictionary cache.
7218 For intrinsic table, get it from session private data */
7219 ib_table = thd_to_innodb_session(thd)->lookup_table_handler(norm_name);
7220
7221 if (ib_table == nullptr) {
7222 dict_sys_mutex_enter();
7223 ib_table = dict_table_check_if_in_cache_low(norm_name);
7224 if (ib_table != nullptr) {
7225 if (ib_table->is_corrupted()) {
7226 /* Optionally remove this corrupted table from cache now
7227 if no other thread is still using it. If not, the corrupted bit
7228 will keep it from being used.*/
7229 if (ib_table->get_ref_count() == 0) {
7230 dict_table_remove_from_cache(ib_table);
7231 }
7232 ib_table = nullptr;
7233 cached = true;
7234 } else if (ib_table->refresh_fk) {
7235 ib_table->acquire_with_lock();
7236
7237 dict_names_t fk_tables;
7238 dict_sys_mutex_exit();
7239 dd::cache::Dictionary_client *client = dd::get_dd_client(thd);
7240 dd::cache::Dictionary_client::Auto_releaser releaser(client);
7241
7242 dberr_t err = dd_table_load_fk(
7243 client, ib_table->name.m_name, nullptr, ib_table,
7244 &table_def->table(), thd, false,
7245 !thd_test_options(thd, OPTION_NO_FOREIGN_KEY_CHECKS), &fk_tables);
7246
7247 dict_sys_mutex_enter();
7248 ib_table->refresh_fk = false;
7249
7250 if (err != DB_SUCCESS) {
7251 ib_table->release();
7252 goto reload;
7253 }
7254
7255 cached = true;
7256 } else if (ib_table->discard_after_ddl) {
7257 reload:
7258 btr_drop_ahi_for_table(ib_table);
7259 dict_table_remove_from_cache(ib_table);
7260 ib_table = nullptr;
7261 } else {
7262 cached = true;
7263 if (!dd_table_match(ib_table, table_def)) {
7264 dict_set_corrupted(ib_table->first_index());
7265 dict_table_remove_from_cache(ib_table);
7266 ib_table = nullptr;
7267 } else {
7268 ib_table->acquire_with_lock();
7269 }
7270 }
7271
7272 /* If the table is in-memory, always get the latest
7273 version, in case this is open table after DDL */
7274 if (ib_table != nullptr && table_def != nullptr) {
7275 ib_table->version = dd_get_version(table_def);
7276 }
7277
7278 if (ib_table != nullptr) {
7279 dict_table_ddl_release(ib_table);
7280 }
7281 }
7282
7283 dict_sys_mutex_exit();
7284
7285 if (!cached) {
7286 dd::cache::Dictionary_client *client = dd::get_dd_client(thd);
7287 dd::cache::Dictionary_client::Auto_releaser releaser(client);
7288
7289 ib_table = dd_open_table(client, table, norm_name, table_def, thd);
7290 if (!ib_table) {
7291 set_my_errno(ENOENT);
7292 return HA_ERR_NO_SUCH_TABLE;
7293 }
7294 }
7295 } else {
7296 ib_table->acquire();
7297 ut_ad(ib_table->is_intrinsic());
7298 }
7299
7300 if (ib_table != nullptr) {
7301 /* Make sure table->is_dd_table is set */
7302 std::string db_str;
7303 std::string tbl_str;
7304 dict_name::get_table(ib_table->name.m_name, db_str, tbl_str);
7305
7306 ib_table->is_dd_table =
7307 dd::get_dictionary()->is_dd_table_name(db_str.c_str(), tbl_str.c_str());
7308 }
7309
7310 /* m_share might hold pointers to dict table indexes without any pin.
7311 We must always allocate m_share after opening the dict_table_t object
7312 and free it before de-allocating dict_table_t to avoid race. */
7313 if (ib_table != nullptr) {
7314 m_share = get_share(name);
7315 if (m_share == nullptr) {
7316 dict_table_close(ib_table, false, false);
7317 return HA_ERR_SE_OUT_OF_MEMORY;
7318 }
7319 }
7320
7321 if (ib_table != nullptr &&
7322 ((!DICT_TF2_FLAG_IS_SET(ib_table, DICT_TF2_FTS_HAS_DOC_ID) &&
7323 table->s->fields != dict_table_get_n_tot_u_cols(ib_table)) ||
7324 (DICT_TF2_FLAG_IS_SET(ib_table, DICT_TF2_FTS_HAS_DOC_ID) &&
7325 (table->s->fields != dict_table_get_n_tot_u_cols(ib_table) - 1)))) {
7326 ib::warn(ER_IB_MSG_556)
7327 << "Table " << norm_name << " contains " << ib_table->get_n_user_cols()
7328 << " user"
7329 " defined columns in InnoDB, but "
7330 << table->s->fields
7331 << " columns in MySQL. Please check"
7332 " INFORMATION_SCHEMA.INNODB_COLUMNS and " REFMAN
7333 "innodb-troubleshooting.html for how to resolve the"
7334 " issue.";
7335
7336 /* Mark this table as corrupted, so the drop table
7337 or force recovery can still use it, but not others. */
7338 ib_table->first_index()->type |= DICT_CORRUPT;
7339 free_share(m_share);
7340 dict_table_close(ib_table, false, false);
7341 ib_table = nullptr;
7342 }
7343
7344 /* For encrypted table, check if the encryption info in data
7345 file can't be retrieved properly, mark it as corrupted. */
7346 if (ib_table != nullptr && dd_is_table_in_encrypted_tablespace(ib_table) &&
7347 ib_table->ibd_file_missing && !dict_table_is_discarded(ib_table)) {
7348 /* Mark this table as corrupted, so the drop table
7349 or force recovery can still use it, but not others. */
7350
7351 free_share(m_share);
7352 dict_table_close(ib_table, false, false);
7353 ib_table = nullptr;
7354
7355 my_error(ER_CANNOT_FIND_KEY_IN_KEYRING, MYF(0));
7356
7357 return HA_ERR_TABLE_CORRUPT;
7358 }
7359
7360 if (nullptr == ib_table) {
7361 ib::warn(ER_IB_MSG_557)
7362 << "Cannot open table " << norm_name << TROUBLESHOOTING_MSG;
7363
7364 set_my_errno(ENOENT);
7365
7366 return HA_ERR_NO_SUCH_TABLE;
7367 }
7368
7369 innobase_copy_frm_flags_from_table_share(ib_table, table->s);
7370
7371 dict_stats_init(ib_table);
7372
7373 MONITOR_INC(MONITOR_TABLE_OPEN);
7374
7375 bool no_tablespace;
7376
7377 if (dict_table_is_discarded(ib_table)) {
7378 /* If the op is an IMPORT, open the space without this warning. */
7379 if (thd_tablespace_op(thd) != Alter_info::ALTER_IMPORT_TABLESPACE) {
7380 ib_senderrf(thd, IB_LOG_LEVEL_WARN, ER_TABLESPACE_DISCARDED,
7381 table->s->table_name.str);
7382 }
7383
7384 /* Allow an open because a proper DISCARD should have set
7385 all the flags and index root page numbers to FIL_NULL that
7386 should prevent any DML from running but it should allow DDL
7387 operations. */
7388 no_tablespace = false;
7389
7390 } else if (ib_table->ibd_file_missing) {
7391 ib_senderrf(thd, IB_LOG_LEVEL_WARN, ER_TABLESPACE_MISSING, norm_name);
7392
7393 /* This means we have no idea what happened to the tablespace
7394 file, best to play it safe. */
7395
7396 no_tablespace = true;
7397 } else {
7398 no_tablespace = false;
7399 }
7400
7401 if (!thd_tablespace_op(thd) && no_tablespace) {
7402 free_share(m_share);
7403 set_my_errno(ENOENT);
7404
7405 dict_table_close(ib_table, false, false);
7406
7407 return HA_ERR_TABLESPACE_MISSING;
7408 }
7409
7410 m_prebuilt = row_create_prebuilt(ib_table, table->s->reclength);
7411
7412 m_prebuilt->default_rec = table->s->default_values;
7413 ut_ad(m_prebuilt->default_rec);
7414
7415 m_prebuilt->m_mysql_table = table;
7416 m_prebuilt->m_mysql_handler = this;
7417
7418 if (ib_table->is_intrinsic()) {
7419 ut_ad(open_flags & HA_OPEN_INTERNAL_TABLE);
7420
7421 m_prebuilt->m_temp_read_shared = table_share->ref_count() >= 2;
7422
7423 if (m_prebuilt->m_temp_read_shared) {
7424 if (ib_table->temp_prebuilt == nullptr) {
7425 ib_table->temp_prebuilt =
7426 ut::new_withkey<temp_prebuilt_vec>(UT_NEW_THIS_FILE_PSI_KEY);
7427 }
7428
7429 ib_table->temp_prebuilt->push_back(m_prebuilt);
7430 }
7431 m_prebuilt->m_temp_tree_modified = false;
7432 }
7433
7434 key_used_on_scan = table_share->primary_key;
7435
7436 if (ib_table->n_v_cols) {
7437 dict_sys_mutex_enter();
7438 if (ib_table->vc_templ == nullptr) {
7439 ib_table->vc_templ =
7440 ut::new_withkey<dict_vcol_templ_t>(UT_NEW_THIS_FILE_PSI_KEY);
7441 ib_table->vc_templ->vtempl = nullptr;
7442 } else if (ib_table->get_ref_count() == 1) {
7443 /* Clean and refresh the template if no one else
7444 get hold on it */
7445 dict_free_vc_templ(ib_table->vc_templ);
7446 ib_table->vc_templ->vtempl = nullptr;
7447 }
7448
7449 if (ib_table->vc_templ->vtempl == nullptr) {
7450 innobase_build_v_templ(table, ib_table, ib_table->vc_templ, nullptr, true,
7451 m_share->table_name);
7452 }
7453
7454 dict_sys_mutex_exit();
7455 }
7456
7457 if (!innobase_build_index_translation(table, ib_table, m_share)) {
7458 log_errlog(ERROR_LEVEL, ER_INNODB_CANT_BUILD_INDEX_XLATION_TABLE_FOR, name);
7459 }
7460
7461 /* Allocate a buffer for a 'row reference'. A row reference is
7462 a string of bytes of length ref_length which uniquely specifies
7463 a row in our table. Note that MySQL may also compare two row
7464 references for equality by doing a simple memcmp on the strings
7465 of length ref_length! */
7466
7467 if (!row_table_got_default_clust_index(ib_table)) {
7468 m_prebuilt->clust_index_was_generated = false;
7469
7470 if (table_share->is_missing_primary_key()) {
7471 log_errlog(ERROR_LEVEL, ER_INNODB_PK_NOT_IN_MYSQL, name);
7472
7473 /* This mismatch could cause further problems
7474 if not attended, bring this to the user's attention
7475 by printing a warning in addition to log a message
7476 in the errorlog */
7477 push_warning_printf(thd, Sql_condition::SL_WARNING, ER_NO_SUCH_INDEX,
7478 "InnoDB: Table %s has a"
7479 " primary key in InnoDB data"
7480 " dictionary, but not in"
7481 " MySQL!",
7482 name);
7483
7484 /* If table_share->is_missing_primary_key(),
7485 the table_share->primary_key
7486 value could be out of bound if continue to index
7487 into key_info[] array. Find InnoDB primary index,
7488 and assign its key_length to ref_length.
7489 In addition, since MySQL indexes are sorted starting
7490 with primary index, unique index etc., initialize
7491 ref_length to the first index key length in
7492 case we fail to find InnoDB cluster index.
7493
7494 Please note, this will not resolve the primary
7495 index mismatch problem, other side effects are
7496 possible if users continue to use the table.
7497 However, we allow this table to be opened so
7498 that user can adopt necessary measures for the
7499 mismatch while still being accessible to the table
7500 date. */
7501 if (!table->key_info) {
7502 ut_ad(!table->s->keys);
7503 ref_length = 0;
7504 } else {
7505 ref_length = table->key_info[0].key_length;
7506 }
7507
7508 /* Find corresponding cluster index
7509 key length in MySQL's key_info[] array */
7510 for (uint i = 0; i < table->s->keys; i++) {
7511 dict_index_t *index;
7512 index = innobase_get_index(i);
7513 if (index->is_clustered()) {
7514 ref_length = table->key_info[i].key_length;
7515 }
7516 }
7517 } else {
7518 /* MySQL allocates the buffer for ref.
7519 key_info->key_length includes space for all key
7520 columns + one byte for each column that may be
7521 NULL. ref_length must be as exact as possible to
7522 save space, because all row reference buffers are
7523 allocated based on ref_length. */
7524
7525 ref_length = table->key_info[table_share->primary_key].key_length;
7526 }
7527 } else {
7528 if (!table_share->is_missing_primary_key()) {
7529 log_errlog(ERROR_LEVEL, ER_INNODB_PK_ONLY_IN_MYSQL, name);
7530
7531 /* This mismatch could cause further problems
7532 if not attended, bring this to the user attention
7533 by printing a warning in addition to log a message
7534 in the errorlog */
7535 push_warning_printf(thd, Sql_condition::SL_WARNING, ER_NO_SUCH_INDEX,
7536 "InnoDB: Table %s has no"
7537 " primary key in InnoDB data"
7538 " dictionary, but has one in"
7539 " MySQL!",
7540 name);
7541 }
7542
7543 m_prebuilt->clust_index_was_generated = true;
7544
7545 ref_length = DATA_ROW_ID_LEN;
7546
7547 /* If we automatically created the clustered index, then
7548 MySQL does not know about it, and MySQL must NOT be aware
7549 of the index used on scan, to make it avoid checking if we
7550 update the column of the index. That is why we assert below
7551 that key_used_on_scan is the undefined value MAX_KEY.
7552 The column is the row id in the automatic generation case,
7553 and it will never be updated anyway. */
7554
7555 if (key_used_on_scan != MAX_KEY) {
7556 log_errlog(WARNING_LEVEL, ER_INNODB_CLUSTERED_INDEX_PRIVATE, name,
7557 (ulong)key_used_on_scan);
7558 }
7559 }
7560
7561 /* Index block size in InnoDB: used by MySQL in query optimization */
7562 stats.block_size = UNIV_PAGE_SIZE;
7563
7564 /* Only if the table has an AUTOINC column. */
7565 if (m_prebuilt->table != nullptr && !m_prebuilt->table->ibd_file_missing &&
7566 table->found_next_number_field != nullptr) {
7567 dict_table_t *ib_table = m_prebuilt->table;
7568
7569 dict_table_autoinc_lock(ib_table);
7570
7571 uint64_t autoinc = dict_table_autoinc_read(ib_table);
7572 uint64_t autoinc_persisted = 0;
7573
7574 mutex_enter(ib_table->autoinc_persisted_mutex);
7575 autoinc_persisted = ib_table->autoinc_persisted;
7576 mutex_exit(ib_table->autoinc_persisted_mutex);
7577
7578 /* Since a table can already be "open" in InnoDB's internal
7579 data dictionary, we only init the autoinc counter once, the
7580 first time the table is loaded. We can safely reuse the
7581 autoinc value from a previous MySQL open. */
7582 if (autoinc == 0 || autoinc == autoinc_persisted) {
7583 /* If autoinc is 0, it means the counter was never
7584 used or imported from a tablespace without .cfg file.
7585 We have to search the index to get proper counter.
7586 If only the second condition is true, it means it's
7587 the first time open for the table, we just want to
7588 calculate the next counter */
7589 innobase_initialize_autoinc();
7590 }
7591
7592 dict_table_autoinc_set_col_pos(
7593 ib_table, table->found_next_number_field->field_index());
7594 ut_ad(dict_table_has_autoinc_col(ib_table));
7595
7596 dict_table_autoinc_unlock(ib_table);
7597 }
7598
7599 /* Set plugin parser for fulltext index */
7600 for (uint i = 0; i < table->s->keys; i++) {
7601 if (table->key_info[i].flags & HA_USES_PARSER) {
7602 dict_index_t *index = innobase_get_index(i);
7603 plugin_ref parser = table->key_info[i].parser;
7604
7605 ut_ad(index->type & DICT_FTS);
7606 index->parser =
7607 static_cast<st_mysql_ftparser *>(plugin_decl(parser)->info);
7608
7609 index->is_ngram = strncmp(plugin_name(parser)->str, FTS_NGRAM_PARSER_NAME,
7610 plugin_name(parser)->length) == 0;
7611
7612 DBUG_EXECUTE_IF("fts_instrument_use_default_parser",
7613 index->parser = &fts_default_parser;);
7614 }
7615 }
7616
7617 info(HA_STATUS_NO_LOCK | HA_STATUS_VARIABLE | HA_STATUS_CONST);
7618
7619 dberr_t err =
7620 dict_set_compression(m_prebuilt->table, table->s->compress.str, false);
7621
7622 switch (err) {
7623 case DB_NOT_FOUND:
7624 case DB_UNSUPPORTED:
7625 /* We will do another check before the create
7626 table and push the error to the client there. */
7627 break;
7628
7629 case DB_IO_NO_PUNCH_HOLE_TABLESPACE:
7630 /* We did the check in the 'if' above. */
7631
7632 case DB_IO_NO_PUNCH_HOLE_FS:
7633 /* During open we can't check whether the FS supports
7634 punch hole or not, at least on Linux. */
7635 break;
7636
7637 default:
7638 ut_error;
7639
7640 case DB_SUCCESS:
7641 break;
7642 }
7643
7644 #ifdef UNIV_DEBUG
7645 fts_aux_table_t aux_table;
7646
7647 if (fts_is_aux_table_name(&aux_table, norm_name, strlen(norm_name))) {
7648 ut_ad(m_prebuilt->table->is_fts_aux());
7649 }
7650 #endif /* UNIV_DEBUG */
7651
7652 if (m_prebuilt->table->is_fts_aux()) {
7653 dict_table_close(m_prebuilt->table, false, false);
7654 }
7655
7656 return 0;
7657 }
7658
7659 handler *ha_innobase::clone(const char *name, /*!< in: table name */
7660 MEM_ROOT *mem_root) /*!< in: memory context */
7661 {
7662 DBUG_TRACE;
7663
7664 ha_innobase *new_handler =
7665 dynamic_cast<ha_innobase *>(handler::clone(name, mem_root));
7666
7667 if (new_handler != nullptr) {
7668 assert(new_handler->m_prebuilt != nullptr);
7669
7670 new_handler->m_prebuilt->select_lock_type = m_prebuilt->select_lock_type;
7671 }
7672
7673 return new_handler;
7674 }
7675
7676 uint ha_innobase::max_supported_key_part_length(
7677 HA_CREATE_INFO *create_info) const {
7678 /* A table format specific index column length check will be performed
7679 at ha_innobase::add_index() and row_create_index_for_mysql() */
7680 switch (create_info->row_type) {
7681 case ROW_TYPE_REDUNDANT:
7682 case ROW_TYPE_COMPACT:
7683 return (REC_ANTELOPE_MAX_INDEX_COL_LEN - 1);
7684 break;
7685 default:
7686 return (REC_VERSION_56_MAX_INDEX_COL_LEN);
7687 }
7688 }
7689
7690 /** Closes a handle to an InnoDB table.
7691 @return 0 */
7692
7693 int ha_innobase::close() {
7694 DBUG_TRACE;
7695
7696 if (m_prebuilt->m_temp_read_shared) {
7697 temp_prebuilt_vec *vec = m_prebuilt->table->temp_prebuilt;
7698 ut_ad(m_prebuilt->table->is_intrinsic());
7699 vec->erase(std::remove(vec->begin(), vec->end(), m_prebuilt), vec->end());
7700 }
7701
7702 free_share(m_share);
7703
7704 row_prebuilt_free(m_prebuilt, false);
7705
7706 if (m_upd_buf != nullptr) {
7707 ut_ad(m_upd_buf_size != 0);
7708 my_free(m_upd_buf);
7709 m_upd_buf = nullptr;
7710 m_upd_buf_size = 0;
7711 }
7712
7713 MONITOR_INC(MONITOR_TABLE_CLOSE);
7714
7715 /* Tell InnoDB server that there might be work for
7716 utility threads: */
7717
7718 srv_active_wake_master_thread();
7719
7720 return 0;
7721 }
7722
7723 /* The following accessor functions should really be inside MySQL code! */
7724
7725 /** Gets field offset for a field in a table.
7726 @param[in] table MySQL table object
7727 @param[in] field MySQL field object
7728 @return offset */
7729 static inline uint get_field_offset(const TABLE *table, const Field *field) {
7730 return field->offset(table->record[0]);
7731 }
7732
7733 /** Compare two character string according to their charset.
7734 @param[in] cs Character set
7735 @param[in] p1 Key
7736 @param[in] p2 Node */
7737 extern int innobase_fts_text_cmp(const void *cs, const void *p1,
7738 const void *p2) {
7739 const CHARSET_INFO *charset = (const CHARSET_INFO *)cs;
7740 const fts_string_t *s1 = (const fts_string_t *)p1;
7741 const fts_string_t *s2 = (const fts_string_t *)p2;
7742
7743 return (ha_compare_text(charset, s1->f_str, static_cast<uint>(s1->f_len),
7744 s2->f_str, static_cast<uint>(s2->f_len), false));
7745 }
7746
7747 /** Compare two FTS character strings case insensitively according to their
7748 charset. This assumes that s1 is already in lower case.
7749 @param[in] cs character set
7750 @param[in] s1 key
7751 @param[in] s2 node
7752 @return 0 if the two strings are equal */
7753 int innobase_fts_nocase_compare(const CHARSET_INFO *cs, const fts_string_t *s1,
7754 const fts_string_t *s2) {
7755 ulint newlen;
7756
7757 my_casedn_str(cs, (char *)s2->f_str);
7758
7759 newlen = strlen((const char *)s2->f_str);
7760
7761 return (ha_compare_text(cs, s1->f_str, static_cast<uint>(s1->f_len),
7762 s2->f_str, static_cast<uint>(newlen), false));
7763 }
7764
7765 #endif /* UNIV_HOTBACKUP */
7766
7767 /** Compare two character strings case insensitively according to their
7768 charset.
7769 @param[in] cs character set
7770 @param[in] s1 string 1
7771 @param[in] s2 string 2
7772 @return 0 if the two strings are equal */
7773 int innobase_nocase_compare(const void *cs, const char *s1, const char *s2) {
7774 const CHARSET_INFO *charset = static_cast<const CHARSET_INFO *>(cs);
7775 const uchar *str1 = reinterpret_cast<const uchar *>(s1);
7776 const uchar *str2 = reinterpret_cast<const uchar *>(s2);
7777 uint len1 = static_cast<uint>(strlen(s1));
7778 uint len2 = static_cast<uint>(strlen(s2));
7779
7780 /* This function returns zero if the two strings are equal. */
7781 return (ha_compare_text(charset, str1, len1, str2, len2, false));
7782 }
7783
7784 #ifndef UNIV_HOTBACKUP
7785
7786 ulint innobase_strnxfrm(const CHARSET_INFO *cs, const uchar *str,
7787 const ulint len) {
7788 uchar mystr[2];
7789 ulint value;
7790
7791 if (!str || len == 0) {
7792 return (0);
7793 }
7794
7795 my_strnxfrm(cs, (uchar *)mystr, 2, str, len);
7796
7797 value = mach_read_from_2(mystr);
7798
7799 if (value > 255) {
7800 value = value / 256;
7801 }
7802
7803 return (value);
7804 }
7805
7806 /** Compare two character string according to their charset.
7807 @param[in] cs Character set
7808 @param[in] p1 Key
7809 @param[in] p2 Node */
7810 extern int innobase_fts_text_cmp_prefix(const void *cs, const void *p1,
7811 const void *p2) {
7812 const CHARSET_INFO *charset = (const CHARSET_INFO *)cs;
7813 const fts_string_t *s1 = (const fts_string_t *)p1;
7814 const fts_string_t *s2 = (const fts_string_t *)p2;
7815 int result;
7816
7817 result = ha_compare_text(charset, s2->f_str, static_cast<uint>(s2->f_len),
7818 s1->f_str, static_cast<uint>(s1->f_len), true);
7819
7820 /* We switched s1, s2 position in ha_compare_text. So we need
7821 to negate the result */
7822 return (-result);
7823 }
7824
7825 /** Makes all characters in a string lower case.
7826 @param[in] cs Character set
7827 @param[in] src String to put in lower case
7828 @param[in] src_len Input string length
7829 @param[in] dst Buffer for result string
7830 @param[in] dst_len Buffer size */
7831 extern size_t innobase_fts_casedn_str(CHARSET_INFO *cs, char *src,
7832 size_t src_len, char *dst,
7833 size_t dst_len) {
7834 if (cs->casedn_multiply == 1) {
7835 memcpy(dst, src, src_len);
7836 dst[src_len] = 0;
7837 my_casedn_str(cs, dst);
7838
7839 return (strlen(dst));
7840 } else {
7841 return (cs->cset->casedn(cs, src, src_len, dst, dst_len));
7842 }
7843 }
7844
7845 inline bool true_word_char(int c, uchar ch) {
7846 return c & (_MY_U | _MY_L | _MY_NMR) || ch == '_';
7847 }
7848
7849 /** Get the next token from the given string and store it in *token.
7850 It is mostly copied from MyISAM's doc parsing function ft_simple_get_word()
7851 @return length of string processed */
7852 ulint innobase_mysql_fts_get_token(
7853 CHARSET_INFO *cs, /*!< in: Character set */
7854 const byte *start, /*!< in: start of text */
7855 const byte *end, /*!< in: one character past end of
7856 text */
7857 fts_string_t *token) /*!< out: token's text */
7858 {
7859 int mbl;
7860 const uchar *doc = start;
7861
7862 ut_a(cs);
7863
7864 token->f_n_char = token->f_len = 0;
7865 token->f_str = nullptr;
7866
7867 for (;;) {
7868 if (doc >= end) {
7869 return (doc - start);
7870 }
7871
7872 int ctype;
7873
7874 mbl = cs->cset->ctype(cs, &ctype, doc, (const uchar *)end);
7875
7876 if (true_word_char(ctype, *doc)) {
7877 break;
7878 }
7879
7880 doc += mbl > 0 ? mbl : (mbl < 0 ? -mbl : 1);
7881 }
7882
7883 ulint length = 0;
7884
7885 token->f_str = const_cast<byte *>(doc);
7886
7887 while (doc < end) {
7888 int ctype;
7889
7890 mbl = cs->cset->ctype(cs, &ctype, (uchar *)doc, (uchar *)end);
7891 if (!true_word_char(ctype, *doc)) {
7892 break;
7893 }
7894
7895 ++length;
7896
7897 doc += mbl > 0 ? mbl : (mbl < 0 ? -mbl : 1);
7898 }
7899
7900 token->f_len = (uint)(doc - token->f_str);
7901 token->f_n_char = length;
7902
7903 return (doc - start);
7904 }
7905
7906 /** Converts a MySQL type to an InnoDB type. Note that this function returns
7907 the 'mtype' of InnoDB. InnoDB differentiates between MySQL's old <= 4.1
7908 VARCHAR and the new true VARCHAR in >= 5.0.3 by the 'prtype'.
7909 @param[out] unsigned_flag DATA_UNSIGNED if an 'unsigned type'; at least
7910 ENUM and SET, and unsigned integer types are 'unsigned types'
7911 @param[in] f MySQL Field
7912 @return DATA_BINARY, DATA_VARCHAR, ... */
7913 ulint get_innobase_type_from_mysql_type(ulint *unsigned_flag, const void *f) {
7914 const class Field *field = reinterpret_cast<const class Field *>(f);
7915
7916 /* The following asserts try to check that the MySQL type code fits in
7917 8 bits: this is used in ibuf and also when DATA_NOT_NULL is ORed to
7918 the type */
7919
7920 assert((ulint)MYSQL_TYPE_STRING < 256);
7921 assert((ulint)MYSQL_TYPE_VAR_STRING < 256);
7922 assert((ulint)MYSQL_TYPE_DOUBLE < 256);
7923 assert((ulint)MYSQL_TYPE_FLOAT < 256);
7924 assert((ulint)MYSQL_TYPE_DECIMAL < 256);
7925
7926 if (field->is_flag_set(UNSIGNED_FLAG)) {
7927 *unsigned_flag = DATA_UNSIGNED;
7928 } else {
7929 *unsigned_flag = 0;
7930 }
7931
7932 if (field->real_type() == MYSQL_TYPE_ENUM ||
7933 field->real_type() == MYSQL_TYPE_SET) {
7934 /* MySQL has field->type() a string type for these, but the
7935 data is actually internally stored as an unsigned integer
7936 code! */
7937
7938 *unsigned_flag = DATA_UNSIGNED; /* MySQL has its own unsigned
7939 flag set to zero, even though
7940 internally this is an unsigned
7941 integer type */
7942 return (DATA_INT);
7943 }
7944
7945 switch (field->type()) {
7946 /* NOTE that we only allow string types in DATA_MYSQL and
7947 DATA_VARMYSQL */
7948 case MYSQL_TYPE_VAR_STRING: /* old <= 4.1 VARCHAR */
7949 case MYSQL_TYPE_VARCHAR: /* new >= 5.0.3 true VARCHAR */
7950 if (field->binary()) {
7951 return (DATA_BINARY);
7952 } else if (field->charset() == &my_charset_latin1) {
7953 return (DATA_VARCHAR);
7954 } else {
7955 return (DATA_VARMYSQL);
7956 }
7957 case MYSQL_TYPE_BIT:
7958 case MYSQL_TYPE_STRING:
7959 if (field->binary()) {
7960 return (DATA_FIXBINARY);
7961 } else if (field->charset() == &my_charset_latin1) {
7962 return (DATA_CHAR);
7963 } else {
7964 return (DATA_MYSQL);
7965 }
7966 case MYSQL_TYPE_NEWDECIMAL:
7967 return (DATA_FIXBINARY);
7968 case MYSQL_TYPE_LONG:
7969 case MYSQL_TYPE_LONGLONG:
7970 case MYSQL_TYPE_TINY:
7971 case MYSQL_TYPE_SHORT:
7972 case MYSQL_TYPE_INT24:
7973 case MYSQL_TYPE_DATE:
7974 case MYSQL_TYPE_YEAR:
7975 case MYSQL_TYPE_NEWDATE:
7976 case MYSQL_TYPE_BOOL:
7977 return (DATA_INT);
7978 case MYSQL_TYPE_TIME:
7979 case MYSQL_TYPE_DATETIME:
7980 case MYSQL_TYPE_TIMESTAMP:
7981 case MYSQL_TYPE_TIME2:
7982 case MYSQL_TYPE_DATETIME2:
7983 case MYSQL_TYPE_TIMESTAMP2:
7984 switch (field->real_type()) {
7985 case MYSQL_TYPE_TIME:
7986 case MYSQL_TYPE_DATETIME:
7987 case MYSQL_TYPE_TIMESTAMP:
7988 return (DATA_INT);
7989 default:
7990 assert((ulint)MYSQL_TYPE_DECIMAL < 256);
7991 [[fallthrough]];
7992 case MYSQL_TYPE_TIME2:
7993 case MYSQL_TYPE_DATETIME2:
7994 case MYSQL_TYPE_TIMESTAMP2:
7995 return (DATA_FIXBINARY);
7996 }
7997 case MYSQL_TYPE_FLOAT:
7998 return (DATA_FLOAT);
7999 case MYSQL_TYPE_DOUBLE:
8000 return (DATA_DOUBLE);
8001 case MYSQL_TYPE_DECIMAL:
8002 return (DATA_DECIMAL);
8003 case MYSQL_TYPE_GEOMETRY:
8004 return (DATA_GEOMETRY);
8005 case MYSQL_TYPE_TINY_BLOB:
8006 case MYSQL_TYPE_MEDIUM_BLOB:
8007 case MYSQL_TYPE_BLOB:
8008 case MYSQL_TYPE_LONG_BLOB:
8009 case MYSQL_TYPE_JSON: // JSON fields are stored as BLOBs
8010 return (DATA_BLOB);
8011 case MYSQL_TYPE_NULL:
8012 /* MySQL currently accepts "NULL" datatype, but will
8013 reject such datatype in the next release. We will cope
8014 with it and not trigger assertion failure in 5.1 */
8015 break;
8016 default:
8017 ut_error;
8018 }
8019
8020 return (0);
8021 }
8022
8023 /** Converts a MySQL data-dictionary type to an InnoDB type. Also returns
8024 a few attributes which are useful for precise type calculation.
8025
8026 @note This function is version of get_innobase_type_from_mysql_type() with
8027 added knowledge about how additional attributes calculated (e.g. in
8028 create_table_info_t::create_table_def()) and about behavior of Field
8029 class and its descendats.
8030
8031 @note It allows to get InnoDB generic and precise types directly from MySQL
8032 data-dictionary info, bypassing expensive construction of Field objects.
8033
8034 @param[out] unsigned_flag DATA_UNSIGNED if an 'unsigned type'.
8035 @param[out] binary_type DATA_BINARY_TYPE if a 'binary type'.
8036 @param[out] charset_no Collation id for string types.
8037 @param[in] dd_type MySQL data-dictionary type.
8038 @param[in] field_charset Charset.
8039 @param[in] is_unsigned MySQL data-dictionary unsigned flag.
8040
8041 @return DATA_BINARY, DATA_VARCHAR, ... */
8042 ulint get_innobase_type_from_mysql_dd_type(ulint *unsigned_flag,
8043 ulint *binary_type,
8044 ulint *charset_no,
8045 dd::enum_column_types dd_type,
8046 const CHARSET_INFO *field_charset,
8047 bool is_unsigned) {
8048 /* InnoDB's unsigned flag is based on UNSIGNED_FLAG bit in Field::flags.
8049 This bit is unset for Field objects by default. */
8050 *unsigned_flag = 0;
8051 /* InnoDB's binary type flag is based on result of Field::binary() call.
8052 The latter returns true by default. */
8053 *binary_type = DATA_BINARY_TYPE;
8054 /* InnoDB takes into account charset numbers only for columns which it
8055 considers of string type. */
8056 *charset_no = 0;
8057
8058 switch (dd_type) {
8059 case dd::enum_column_types::ENUM:
8060 case dd::enum_column_types::SET:
8061 /* SQL-layer has its own unsigned flag set to zero, even though
8062 internally this is an unsigned integer type. */
8063 *unsigned_flag = DATA_UNSIGNED;
8064 /* ENUM and SET are handled as string types by SQL-layer,
8065 hence the charset check. */
8066 if (field_charset != &my_charset_bin) *binary_type = 0;
8067 return (DATA_INT);
8068 case dd::enum_column_types::VAR_STRING: /* old <= 4.1 VARCHAR. */
8069 case dd::enum_column_types::VARCHAR: /* new >= 5.0.3 true VARCHAR. */
8070 *charset_no = field_charset->number;
8071 if (field_charset == &my_charset_bin) {
8072 return (DATA_BINARY);
8073 } else {
8074 *binary_type = 0;
8075 if (field_charset == &my_charset_latin1) {
8076 return (DATA_VARCHAR);
8077 } else {
8078 return (DATA_VARMYSQL);
8079 }
8080 }
8081 case dd::enum_column_types::BIT:
8082 /* MySQL always sets unsigned flag for both its BIT types. */
8083 *unsigned_flag = DATA_UNSIGNED;
8084 *charset_no = my_charset_bin.number;
8085 return (DATA_FIXBINARY);
8086 case dd::enum_column_types::STRING:
8087 *charset_no = field_charset->number;
8088 if (field_charset == &my_charset_bin) {
8089 return (DATA_FIXBINARY);
8090 } else {
8091 *binary_type = 0;
8092 if (field_charset == &my_charset_latin1) {
8093 return (DATA_CHAR);
8094 } else {
8095 return (DATA_MYSQL);
8096 }
8097 }
8098 case dd::enum_column_types::DECIMAL:
8099 case dd::enum_column_types::FLOAT:
8100 case dd::enum_column_types::DOUBLE:
8101 case dd::enum_column_types::NEWDECIMAL:
8102 case dd::enum_column_types::LONG:
8103 case dd::enum_column_types::LONGLONG:
8104 case dd::enum_column_types::TINY:
8105 case dd::enum_column_types::SHORT:
8106 case dd::enum_column_types::INT24:
8107 /* Types based on Field_num set unsigned flag from value stored
8108 in the data-dictionary (YEAR being the exception). */
8109 if (is_unsigned) *unsigned_flag = DATA_UNSIGNED;
8110 switch (dd_type) {
8111 case dd::enum_column_types::DECIMAL:
8112 return (DATA_DECIMAL);
8113 case dd::enum_column_types::FLOAT:
8114 return (DATA_FLOAT);
8115 case dd::enum_column_types::DOUBLE:
8116 return (DATA_DOUBLE);
8117 case dd::enum_column_types::NEWDECIMAL:
8118 *charset_no = my_charset_bin.number;
8119 return (DATA_FIXBINARY);
8120 default:
8121 break;
8122 }
8123 return (DATA_INT);
8124 case dd::enum_column_types::DATE:
8125 case dd::enum_column_types::NEWDATE:
8126 case dd::enum_column_types::TIME:
8127 case dd::enum_column_types::DATETIME:
8128 return (DATA_INT);
8129 case dd::enum_column_types::YEAR:
8130 case dd::enum_column_types::TIMESTAMP:
8131 /* MySQL always sets unsigned flag for YEAR and old TIMESTAMP type. */
8132 *unsigned_flag = DATA_UNSIGNED;
8133 return (DATA_INT);
8134 case dd::enum_column_types::TIME2:
8135 case dd::enum_column_types::DATETIME2:
8136 case dd::enum_column_types::TIMESTAMP2:
8137 *charset_no = my_charset_bin.number;
8138 return (DATA_FIXBINARY);
8139 case dd::enum_column_types::GEOMETRY:
8140 /* Field_geom::binary() is always true. */
8141 return (DATA_GEOMETRY);
8142 case dd::enum_column_types::TINY_BLOB:
8143 case dd::enum_column_types::MEDIUM_BLOB:
8144 case dd::enum_column_types::BLOB:
8145 case dd::enum_column_types::LONG_BLOB:
8146 *charset_no = field_charset->number;
8147 if (field_charset != &my_charset_bin) *binary_type = 0;
8148 return (DATA_BLOB);
8149 case dd::enum_column_types::JSON:
8150 /* JSON fields are stored as BLOBs.
8151 Field_json::binary() always returns true even though data in
8152 such columns are stored in UTF8. */
8153 *charset_no = my_charset_utf8mb4_bin.number;
8154 return (DATA_BLOB);
8155 case dd::enum_column_types::TYPE_NULL:
8156 /* Compatibility with get_innobase_type_from_mysql_type(). */
8157 *charset_no = field_charset->number;
8158 if (field_charset != &my_charset_bin) *binary_type = 0;
8159 break;
8160 default:
8161 ut_error;
8162 }
8163
8164 return (0);
8165 }
8166
8167 /** Reads an unsigned integer value < 64k from 2 bytes, in the little-endian
8168 storage format.
8169 @return value */
8170 static inline uint innobase_read_from_2_little_endian(
8171 const uchar *buf) /*!< in: from where to read */
8172 {
8173 return ((uint)((ulint)(buf[0]) + 256 * ((ulint)(buf[1]))));
8174 }
8175
8176 /** Determines if a field is needed in a m_prebuilt struct 'template'.
8177 @return field to use, or NULL if the field is not needed */
8178 static const Field *build_template_needs_field(
8179 bool index_contains, /*!< in:
8180 dict_index_contains_col_or_prefix(
8181 index, i) */
8182 bool read_just_key, /*!< in: true when MySQL calls
8183 ha_innobase::extra with the
8184 argument HA_EXTRA_KEYREAD; it is enough
8185 to read just columns defined in
8186 the index (i.e., no read of the
8187 clustered index record necessary) */
8188 bool fetch_all_in_key,
8189 /*!< in: true=fetch all fields in
8190 the index */
8191 bool fetch_primary_key_cols,
8192 /*!< in: true=fetch the
8193 primary key columns */
8194 dict_index_t *index, /*!< in: InnoDB index to use */
8195 const TABLE *table, /*!< in: MySQL table object */
8196 ulint i, /*!< in: field index in InnoDB table */
8197 ulint num_v) /*!< in: num virtual column so far */
8198 {
8199 const Field *field = table->field[i];
8200
8201 if (!index_contains) {
8202 if (read_just_key) {
8203 /* If this is a 'key read', we do not need
8204 columns that are not in the key */
8205
8206 return (nullptr);
8207 }
8208 } else if (fetch_all_in_key) {
8209 /* This field is needed in the query */
8210
8211 return (field);
8212 }
8213
8214 if (bitmap_is_set(table->read_set, static_cast<uint>(i)) ||
8215 bitmap_is_set(table->write_set, static_cast<uint>(i))) {
8216 /* This field is needed in the query */
8217
8218 return (field);
8219 }
8220
8221 ut_ad(i >= num_v);
8222 if (fetch_primary_key_cols &&
8223 dict_table_col_in_clustered_key(index->table, i - num_v)) {
8224 /* This field is needed in the query */
8225
8226 return (field);
8227 }
8228
8229 /* This field is not needed in the query, skip it */
8230
8231 return (nullptr);
8232 }
8233
8234 /** Determines if a field is needed in a m_prebuilt struct 'template'.
8235 @return whether the field is needed for index condition pushdown */
8236 inline bool build_template_needs_field_in_icp(
8237 const dict_index_t *index, /*!< in: InnoDB index */
8238 const row_prebuilt_t *prebuilt, /*!< in: row fetch template */
8239 bool contains, /*!< in: whether the index contains
8240 column i */
8241 ulint i, /*!< in: column number */
8242 bool is_virtual)
8243 /*!< in: a virtual column or not */
8244 {
8245 ut_ad(contains == dict_index_contains_col_or_prefix(index, i, is_virtual));
8246
8247 return (index == prebuilt->index ? contains
8248 : dict_index_contains_col_or_prefix(
8249 prebuilt->index, i, is_virtual));
8250 }
8251
8252 /** Adds a field to a m_prebuilt struct 'template'.
8253 @return the field template */
8254 static mysql_row_templ_t *build_template_field(
8255 row_prebuilt_t *prebuilt, /*!< in/out: template */
8256 dict_index_t *clust_index, /*!< in: InnoDB clustered index */
8257 dict_index_t *index, /*!< in: InnoDB index to use */
8258 TABLE *table, /*!< in: MySQL table object */
8259 const Field *field, /*!< in: field in MySQL table */
8260 ulint i, /*!< in: field index in InnoDB table */
8261 ulint v_no) /*!< in: field index for virtual col */
8262 {
8263 mysql_row_templ_t *templ;
8264 const dict_col_t *col;
8265
8266 ut_ad(clust_index->table == index->table);
8267
8268 templ = prebuilt->mysql_template + prebuilt->n_template++;
8269 UNIV_MEM_INVALID(templ, sizeof *templ);
8270
8271 if (innobase_is_v_fld(field)) {
8272 templ->is_virtual = true;
8273 col = &dict_table_get_nth_v_col(index->table, v_no)->m_col;
8274 } else {
8275 templ->is_virtual = false;
8276 col = index->table->get_col(i);
8277 }
8278
8279 if (!templ->is_virtual) {
8280 templ->col_no = i;
8281 templ->clust_rec_field_no = dict_col_get_clust_pos(col, clust_index);
8282 ut_a(templ->clust_rec_field_no != ULINT_UNDEFINED);
8283
8284 if (index->is_clustered()) {
8285 templ->rec_field_no = templ->clust_rec_field_no;
8286 } else {
8287 templ->rec_field_no = index->get_col_pos(i);
8288 }
8289 } else {
8290 templ->clust_rec_field_no = v_no;
8291 if (index->is_clustered()) {
8292 templ->rec_field_no = templ->clust_rec_field_no;
8293 } else {
8294 templ->rec_field_no = index->get_col_pos(v_no, false, true);
8295 }
8296 }
8297
8298 /* Set in set_templ_icp(). */
8299 templ->icp_rec_field_no = ULINT_UNDEFINED;
8300
8301 if (field->is_nullable()) {
8302 templ->mysql_null_byte_offset = field->null_offset();
8303
8304 templ->mysql_null_bit_mask = (ulint)field->null_bit;
8305 } else {
8306 templ->mysql_null_bit_mask = 0;
8307 }
8308
8309 templ->mysql_col_offset = (ulint)get_field_offset(table, field);
8310 templ->mysql_col_len = (ulint)field->pack_length();
8311 if (templ->is_virtual && innobase_is_multi_value_fld(field)) {
8312 templ->mysql_mvidx_len = static_cast<ulint>(field->key_length());
8313 templ->is_multi_val = true;
8314 } else {
8315 templ->mysql_mvidx_len = 0;
8316 templ->is_multi_val = false;
8317 }
8318 templ->type = col->mtype;
8319 templ->mysql_type = (ulint)field->type();
8320
8321 if (templ->mysql_type == DATA_MYSQL_TRUE_VARCHAR) {
8322 templ->mysql_length_bytes = field->get_length_bytes();
8323 } else {
8324 templ->mysql_length_bytes = 0;
8325 }
8326
8327 templ->charset = dtype_get_charset_coll(col->prtype);
8328 templ->mbminlen = col->get_mbminlen();
8329 templ->mbmaxlen = col->get_mbmaxlen();
8330 templ->is_unsigned = col->prtype & DATA_UNSIGNED;
8331
8332 if (!index->is_clustered() && templ->rec_field_no == ULINT_UNDEFINED) {
8333 prebuilt->need_to_access_clustered = true;
8334 }
8335
8336 /* For spatial index, we need to access cluster index. */
8337 if (dict_index_is_spatial(index)) {
8338 prebuilt->need_to_access_clustered = true;
8339 }
8340
8341 if (prebuilt->mysql_prefix_len <
8342 templ->mysql_col_offset + templ->mysql_col_len) {
8343 prebuilt->mysql_prefix_len = templ->mysql_col_offset + templ->mysql_col_len;
8344 }
8345
8346 if (DATA_LARGE_MTYPE(templ->type)) {
8347 prebuilt->templ_contains_blob = true;
8348 }
8349
8350 if (templ->type == DATA_POINT) {
8351 /* We set this only when it's DATA_POINT, but not
8352 DATA_VAR_POINT */
8353 prebuilt->templ_contains_fixed_point = true;
8354 }
8355
8356 return (templ);
8357 }
8358
8359 /** Set Index Condition Push down (ICP) field number in template.
8360 @param[in,out] templ mysql column template
8361 @param[in] index index used to build the template
8362 @param[in] scan_index active index for current scan
8363 @param[in] col_position position of current column */
8364 static void set_templ_icp(mysql_row_templ_t *templ, const dict_index_t *index,
8365 const dict_index_t *scan_index, ulint col_position) {
8366 if (scan_index == nullptr || templ == nullptr) {
8367 return;
8368 }
8369
8370 bool is_virtual = templ->is_virtual;
8371 auto icp_field_no = templ->rec_field_no;
8372
8373 if (scan_index != index) {
8374 /* First, try to find the column position without prefix. */
8375 icp_field_no = scan_index->get_col_pos(col_position, false, is_virtual);
8376 }
8377
8378 /* Try any prefix of the column. Used in end_range comparison. */
8379 if (icp_field_no == ULINT_UNDEFINED) {
8380 ut_ad(!scan_index->is_clustered());
8381 icp_field_no = scan_index->get_col_pos(col_position, true, is_virtual);
8382 }
8383 templ->icp_rec_field_no = icp_field_no;
8384 }
8385
8386 /** Builds a 'template' to the m_prebuilt struct. The template is used in fast
8387 retrieval of just those column values MySQL needs in its processing.
8388 @param[in] whole_row true if access is needed to a whole row, false if accessing
8389 individual fields is enough */
8390 void ha_innobase::build_template(bool whole_row) {
8391 dict_index_t *index;
8392 dict_index_t *clust_index;
8393 ulint n_fields;
8394 bool fetch_all_in_key = false;
8395 bool fetch_primary_key_cols = false;
8396 ulint i;
8397
8398 if (m_prebuilt->select_lock_type == LOCK_X) {
8399 /* We always retrieve the whole clustered index record if we
8400 use exclusive row level locks, for example, if the read is
8401 done in an UPDATE statement. */
8402
8403 whole_row = true;
8404 } else if (!whole_row) {
8405 if (m_prebuilt->hint_need_to_fetch_extra_cols == ROW_RETRIEVE_ALL_COLS) {
8406 /* We know we must at least fetch all columns in the
8407 key, or all columns in the table */
8408
8409 if (m_prebuilt->read_just_key) {
8410 /* MySQL has instructed us that it is enough
8411 to fetch the columns in the key; looks like
8412 MySQL can set this flag also when there is
8413 only a prefix of the column in the key: in
8414 that case we retrieve the whole column from
8415 the clustered index */
8416
8417 fetch_all_in_key = true;
8418 } else {
8419 whole_row = true;
8420 }
8421 } else if (m_prebuilt->hint_need_to_fetch_extra_cols ==
8422 ROW_RETRIEVE_PRIMARY_KEY) {
8423 /* We must at least fetch all primary key cols. Note
8424 that if the clustered index was internally generated
8425 by InnoDB on the row id (no primary key was
8426 defined), then row_search_for_mysql() will always
8427 retrieve the row id to a special buffer in the
8428 m_prebuilt struct. */
8429
8430 fetch_primary_key_cols = true;
8431 }
8432 }
8433
8434 clust_index = m_prebuilt->table->first_index();
8435
8436 index = whole_row ? clust_index : m_prebuilt->index;
8437
8438 m_prebuilt->need_to_access_clustered = (index == clust_index);
8439
8440 /* Either m_prebuilt->index should be a secondary index, or it
8441 should be the clustered index. */
8442 ut_ad(index->is_clustered() == (index == clust_index));
8443
8444 /* Below we check column by column if we need to access
8445 the clustered index. */
8446
8447 n_fields = (ulint)table->s->fields; /* number of columns */
8448
8449 if (!m_prebuilt->mysql_template) {
8450 m_prebuilt->mysql_template = (mysql_row_templ_t *)ut::malloc_withkey(
8451 UT_NEW_THIS_FILE_PSI_KEY, n_fields * sizeof(mysql_row_templ_t));
8452 }
8453
8454 #if defined(UNIV_DEBUG) && !defined(UNIV_DEBUG_VALGRIND)
8455 /* zero-filling for compare contents for debug */
8456 memset(m_prebuilt->mysql_template, 0, n_fields * sizeof(mysql_row_templ_t));
8457 #endif /* UNIV_DEBUG && !UNIV_DEBUG_VALGRIND */
8458
8459 m_prebuilt->template_type =
8460 whole_row ? ROW_MYSQL_WHOLE_ROW : ROW_MYSQL_REC_FIELDS;
8461 m_prebuilt->null_bitmap_len = table->s->null_bytes;
8462
8463 /* Prepare to build m_prebuilt->mysql_template[]. */
8464 m_prebuilt->templ_contains_blob = false;
8465 m_prebuilt->templ_contains_fixed_point = false;
8466 m_prebuilt->mysql_prefix_len = 0;
8467 m_prebuilt->n_template = 0;
8468 m_prebuilt->idx_cond_n_cols = 0;
8469
8470 /* Note that in InnoDB, i is the column number in the table.
8471 MySQL calls columns 'fields'. */
8472
8473 if (active_index != MAX_KEY && active_index == pushed_idx_cond_keyno) {
8474 ulint num_v = 0;
8475
8476 /* Push down an index condition or an end_range check. */
8477 for (i = 0; i < n_fields; i++) {
8478 bool index_contains;
8479
8480 if (innobase_is_v_fld(table->field[i])) {
8481 index_contains = dict_index_contains_col_or_prefix(index, num_v, true);
8482 } else {
8483 index_contains =
8484 dict_index_contains_col_or_prefix(index, i - num_v, false);
8485 }
8486
8487 /* Test if an end_range or an index condition
8488 refers to the field. Note that "index" and
8489 "index_contains" may refer to the clustered index.
8490 Index condition pushdown is relative to
8491 m_prebuilt->index (the index that is being
8492 looked up first). */
8493
8494 /* When join_read_always_key() invokes this
8495 code via handler::ha_index_init() and
8496 ha_innobase::index_init(), end_range is not
8497 yet initialized. Because of that, we must
8498 always check for index_contains, instead of
8499 the subset
8500 field->part_of_key.is_set(active_index)
8501 which would be acceptable if end_range==NULL. */
8502 bool is_v = innobase_is_v_fld(table->field[i]);
8503 if (build_template_needs_field_in_icp(index, m_prebuilt, index_contains,
8504 is_v ? num_v : i - num_v, is_v)) {
8505 /* Needed in ICP */
8506 const Field *field;
8507 mysql_row_templ_t *templ;
8508
8509 if (whole_row) {
8510 field = table->field[i];
8511 } else {
8512 field = build_template_needs_field(
8513 index_contains, m_prebuilt->read_just_key, fetch_all_in_key,
8514 fetch_primary_key_cols, index, table, i, num_v);
8515 if (!field) {
8516 if (innobase_is_v_fld(table->field[i])) {
8517 num_v++;
8518 }
8519 continue;
8520 }
8521 }
8522
8523 templ = build_template_field(m_prebuilt, clust_index, index, table,
8524 field, i - num_v, 0);
8525
8526 ut_ad(!templ->is_virtual);
8527
8528 m_prebuilt->idx_cond_n_cols++;
8529 ut_ad(m_prebuilt->idx_cond_n_cols == m_prebuilt->n_template);
8530
8531 auto column_position = i - num_v;
8532
8533 set_templ_icp(templ, index, m_prebuilt->index, column_position);
8534
8535 ut_ad(templ->icp_rec_field_no != ULINT_UNDEFINED);
8536
8537 /* Index condition pushdown can be used on
8538 all columns of a secondary index, and on
8539 the PRIMARY KEY columns. On the clustered
8540 index, it must never be used on other than
8541 PRIMARY KEY columns, because those columns
8542 may be stored off-page, and we will not
8543 fetch externally stored columns before
8544 checking the index condition. */
8545 /* TODO: test the above with an assertion
8546 like this. Note that index conditions are
8547 currently pushed down as part of the
8548 "optimizer phase" while end_range is done
8549 as part of the execution phase. Therefore,
8550 we were unable to use an accurate condition
8551 for end_range in the "if" condition above,
8552 and the following assertion would fail.
8553 ut_ad(!(m_prebuilt->index->is_clustered())
8554 || templ->rec_field_no
8555 < m_prebuilt->index->n_uniq);
8556 */
8557 }
8558
8559 if (innobase_is_v_fld(table->field[i])) {
8560 num_v++;
8561 }
8562 }
8563
8564 ut_ad(m_prebuilt->idx_cond_n_cols > 0);
8565 ut_ad(m_prebuilt->idx_cond_n_cols == m_prebuilt->n_template);
8566
8567 num_v = 0;
8568
8569 /* Include the fields that are not needed in index condition
8570 pushdown. */
8571 for (i = 0; i < n_fields; i++) {
8572 mysql_row_templ_t *templ;
8573 bool index_contains;
8574
8575 if (innobase_is_v_fld(table->field[i])) {
8576 index_contains = dict_index_contains_col_or_prefix(index, num_v, true);
8577 } else {
8578 index_contains =
8579 dict_index_contains_col_or_prefix(index, i - num_v, false);
8580 }
8581
8582 bool is_v = innobase_is_v_fld(table->field[i]);
8583
8584 if (!build_template_needs_field_in_icp(index, m_prebuilt, index_contains,
8585 is_v ? num_v : i - num_v, is_v)) {
8586 /* Not needed in ICP */
8587 const Field *field;
8588
8589 if (whole_row) {
8590 field = table->field[i];
8591 } else {
8592 field = build_template_needs_field(
8593 index_contains, m_prebuilt->read_just_key, fetch_all_in_key,
8594 fetch_primary_key_cols, index, table, i, num_v);
8595 if (!field) {
8596 if (innobase_is_v_fld(table->field[i])) {
8597 num_v++;
8598 }
8599 continue;
8600 }
8601 }
8602
8603 templ = build_template_field(m_prebuilt, clust_index, index, table,
8604 field, i - num_v, num_v);
8605
8606 if (templ->is_virtual) {
8607 num_v++;
8608 }
8609 }
8610 }
8611
8612 m_prebuilt->idx_cond = true;
8613 } else {
8614 mysql_row_templ_t *templ;
8615 ulint num_v = 0;
8616 /* No index condition pushdown */
8617 m_prebuilt->idx_cond = false;
8618
8619 for (i = 0; i < n_fields; i++) {
8620 const Field *field;
8621 bool is_virtual = innobase_is_v_fld(table->field[i]);
8622
8623 if (whole_row) {
8624 /* Even this is whole_row, if the search is
8625 on a virtual column, and read_just_key is
8626 set, and field is not in this index, we
8627 will not try to fill the value since they
8628 are not stored in such index nor in the
8629 cluster index. */
8630 if (is_virtual && m_prebuilt->read_just_key &&
8631 !dict_index_contains_col_or_prefix(m_prebuilt->index, num_v,
8632 true)) {
8633 /* Turn off ROW_MYSQL_WHOLE_ROW */
8634 m_prebuilt->template_type = ROW_MYSQL_REC_FIELDS;
8635 num_v++;
8636 continue;
8637 }
8638
8639 field = table->field[i];
8640 } else {
8641 bool contain;
8642
8643 if (innobase_is_v_fld(table->field[i])) {
8644 contain = dict_index_contains_col_or_prefix(index, num_v, true);
8645 } else {
8646 contain = dict_index_contains_col_or_prefix(index, i - num_v, false);
8647 }
8648
8649 field = build_template_needs_field(
8650 contain, m_prebuilt->read_just_key, fetch_all_in_key,
8651 fetch_primary_key_cols, index, table, i, num_v);
8652 if (!field) {
8653 if (is_virtual) {
8654 num_v++;
8655 }
8656 continue;
8657 }
8658 }
8659
8660 templ = build_template_field(m_prebuilt, clust_index, index, table, field,
8661 i - num_v, num_v);
8662
8663 /* Virtual columns may have to be read from the secondary index before
8664 evaluating an end-range condition in row_search_end_range_check(). Set
8665 ICP field number for virtual column. */
8666 auto scan_index = m_prebuilt->index;
8667 bool is_sec_idx = (scan_index != nullptr && !scan_index->is_clustered());
8668
8669 if (is_virtual && is_sec_idx) {
8670 set_templ_icp(templ, index, scan_index, num_v);
8671 }
8672
8673 if (templ->is_virtual) {
8674 num_v++;
8675 }
8676 }
8677 }
8678
8679 if (index != clust_index && m_prebuilt->need_to_access_clustered) {
8680 /* Change rec_field_no's to correspond to the clustered index
8681 record */
8682 for (i = 0; i < m_prebuilt->n_template; i++) {
8683 mysql_row_templ_t *templ = &m_prebuilt->mysql_template[i];
8684
8685 templ->rec_field_no = templ->clust_rec_field_no;
8686 }
8687 }
8688 }
8689
8690 /** This special handling is really to overcome the limitations of MySQL's
8691 binlogging. We need to eliminate the non-determinism that will arise in
8692 INSERT ... SELECT type of statements, since MySQL binlog only stores the
8693 min value of the autoinc interval. Once that is fixed we can get rid of
8694 the special lock handling.
8695 @return DB_SUCCESS if all OK else error code */
8696
8697 dberr_t ha_innobase::innobase_lock_autoinc(void) {
8698 DBUG_TRACE;
8699 dberr_t error = DB_SUCCESS;
8700 long lock_mode = innobase_autoinc_lock_mode;
8701
8702 ut_ad(!srv_read_only_mode || m_prebuilt->table->is_intrinsic());
8703
8704 if (m_prebuilt->table->is_intrinsic() || m_prebuilt->no_autoinc_locking) {
8705 /* Intrinsic table are not shared across connection
8706 so there is no need to AUTOINC lock the table.
8707 Also we won't use AUTOINC lock if this was requested
8708 explicitly. */
8709 lock_mode = AUTOINC_NO_LOCKING;
8710 }
8711
8712 switch (lock_mode) {
8713 case AUTOINC_NO_LOCKING:
8714 /* Acquire only the AUTOINC mutex. */
8715 dict_table_autoinc_lock(m_prebuilt->table);
8716 break;
8717
8718 case AUTOINC_NEW_STYLE_LOCKING:
8719 /* For simple (single/multi) row INSERTs, we fallback to the
8720 old style only if another transaction has already acquired
8721 the AUTOINC lock on behalf of a LOAD FILE or INSERT ... SELECT
8722 etc. type of statement. */
8723 if (thd_sql_command(m_user_thd) == SQLCOM_INSERT ||
8724 thd_sql_command(m_user_thd) == SQLCOM_REPLACE) {
8725 dict_table_t *ib_table = m_prebuilt->table;
8726
8727 /* Acquire the AUTOINC mutex. */
8728 dict_table_autoinc_lock(ib_table);
8729
8730 /* We need to check that another transaction isn't
8731 already holding the AUTOINC lock on the table. */
8732 if (ib_table->count_by_mode[LOCK_AUTO_INC]) {
8733 /* Release the mutex to avoid deadlocks. */
8734 dict_table_autoinc_unlock(ib_table);
8735 } else {
8736 break;
8737 }
8738 }
8739 /* Fall through to old style locking. */
8740 [[fallthrough]];
8741
8742 case AUTOINC_OLD_STYLE_LOCKING:
8743 DBUG_EXECUTE_IF("die_if_autoinc_old_lock_style_used", ut_d(ut_error););
8744 error = row_lock_table_autoinc_for_mysql(m_prebuilt);
8745
8746 if (error == DB_SUCCESS) {
8747 /* Acquire the AUTOINC mutex. */
8748 dict_table_autoinc_lock(m_prebuilt->table);
8749 }
8750 break;
8751
8752 default:
8753 ut_error;
8754 }
8755
8756 return error;
8757 }
8758
8759 /** Store the autoinc value in the table. The autoinc value is only set if
8760 it's greater than the existing autoinc value in the table.
8761 @return DB_SUCCESS if all went well else error code */
8762
8763 dberr_t ha_innobase::innobase_set_max_autoinc(
8764 ulonglong auto_inc) /*!< in: value to store */
8765 {
8766 dberr_t error;
8767
8768 error = innobase_lock_autoinc();
8769
8770 if (error == DB_SUCCESS) {
8771 dict_table_autoinc_update_if_greater(m_prebuilt->table, auto_inc);
8772
8773 dict_table_autoinc_unlock(m_prebuilt->table);
8774 }
8775
8776 return (error);
8777 }
8778
8779 /** Write Row interface optimized for intrinisc table.
8780 @param[in] record a row in MySQL format.
8781 @return 0 on success or error code */
8782 int ha_innobase::intrinsic_table_write_row(uchar *record) {
8783 dberr_t err;
8784
8785 /* No auto-increment support for intrinsic table. */
8786 ut_ad(!(table->next_number_field && record == table->record[0]));
8787
8788 if (m_prebuilt->mysql_template == nullptr ||
8789 m_prebuilt->template_type != ROW_MYSQL_WHOLE_ROW) {
8790 /* Build the template used in converting quickly between
8791 the two database formats */
8792 build_template(true);
8793 }
8794
8795 err = row_insert_for_mysql((byte *)record, m_prebuilt);
8796
8797 return (
8798 convert_error_code_to_mysql(err, m_prebuilt->table->flags, m_user_thd));
8799 }
8800
8801 /** Parse out multi-value and store in a multi_value_data struct
8802 @param[in] bv JSON binary that has the mult-value
8803 @param[out] valuep store the parsed out value
8804 @param[in] fld Array Field for the data
8805 @param[in] dfield InnoDB indexed field struct
8806 @param[in] comp if this is new InnoDB row type
8807 @param[in,out] heap heap memory */
8808 static void innobase_store_multi_value_low(json_binary::Value *bv,
8809 multi_value_data **valuep,
8810 Field_typed_array *fld,
8811 dfield_t *dfield, ulint comp,
8812 mem_heap_t *heap) {
8813 multi_value_data *value = *valuep;
8814 byte *buf;
8815
8816 /* Even for single values, there will be an array with 1 element */
8817 ut_ad(bv->type() == json_binary::Value::ARRAY);
8818 uint32_t elements = bv->element_count();
8819
8820 ut_ad(elements > 0);
8821
8822 if (value == nullptr) {
8823 ut_ad(heap != nullptr);
8824 value =
8825 static_cast<multi_value_data *>(mem_heap_zalloc(heap, sizeof(*value)));
8826 }
8827
8828 if (elements > value->num_alc) {
8829 value->alloc(elements, false, heap);
8830 }
8831
8832 buf = reinterpret_cast<byte *>(value->conv_buf);
8833
8834 value->num_v = elements;
8835
8836 ulint col_len = fld->key_length();
8837
8838 for (uint i = 0; i < elements; i++) {
8839 const byte *mysql_data = nullptr;
8840 const dtype_t *dtype = dfield_get_type(dfield);
8841 ulint type = dtype->mtype;
8842 int64_t val;
8843
8844 json_binary::Value elt = bv->element(i);
8845 if (elt.type() == json_binary::Value::LITERAL_NULL) {
8846 dfield_set_data(dfield, nullptr, UNIV_SQL_NULL);
8847 } else if (type == DATA_INT) {
8848 byte data[8];
8849 if (elt.type() == json_binary::Value::OPAQUE) {
8850 if (elt.field_type() == MYSQL_TYPE_TIME ||
8851 elt.field_type() == MYSQL_TYPE_DATETIME ||
8852 elt.field_type() == MYSQL_TYPE_TIMESTAMP) {
8853 /* Newer Mysql temporal types use DATA_FIXBINARY Innodb type */
8854 ut_d(ut_error); /* purecov: inspected */
8855 } else if (elt.field_type() == MYSQL_TYPE_DATE) {
8856 /* Temporal data has at most 8 bytes length */
8857 Json_datetime::from_packed_to_key(elt.get_data(), elt.field_type(),
8858 data, fld->decimals());
8859 mysql_data = data;
8860 } else {
8861 mysql_data = reinterpret_cast<const byte *>(elt.get_data());
8862 }
8863 } else {
8864 /* Both signed and unsigned ints are handled here. Because there is
8865 an assumption the data passed from server should be always
8866 little-endian one, so need to convert it explicitly here.
8867 @see Field_longlong::store() */
8868 if (fld->is_unsigned()) {
8869 val = static_cast<int64_t>(elt.get_uint64());
8870 } else {
8871 val = elt.get_int64();
8872 }
8873 #ifdef WORDS_BIGENDIAN
8874 if (fld->table->s->db_low_byte_first) {
8875 int8store(data, val);
8876 } else
8877 #endif
8878 {
8879 longlongstore(data, val);
8880 }
8881 mysql_data = data;
8882 }
8883 row_mysql_store_col_in_innobase_format(dfield, buf, true, mysql_data,
8884 col_len, comp);
8885 } else if (type == DATA_CHAR || type == DATA_VARCHAR ||
8886 type == DATA_VARMYSQL) {
8887 mysql_data = (byte *)elt.get_data();
8888 col_len = (ulint)elt.get_data_length();
8889 dfield_set_data(dfield, mysql_data, col_len);
8890 } else if (type == DATA_BINARY || type == DATA_FIXBINARY) {
8891 if (elt.type() == json_binary::Value::OPAQUE) {
8892 switch (elt.field_type()) {
8893 case MYSQL_TYPE_VARCHAR: {
8894 mysql_data = reinterpret_cast<const byte *>(elt.get_data());
8895 dfield_set_data(dfield,
8896 reinterpret_cast<const byte *>(elt.get_data()),
8897 elt.get_data_length());
8898 break;
8899 }
8900 case MYSQL_TYPE_NEWDECIMAL: {
8901 ut_d(my_decimal d);
8902 /* Ensure correct decimal value */
8903 ut_ad(!Json_decimal::convert_from_binary(
8904 elt.get_data(), elt.get_data_length(), &d));
8905 /* Ensure binary is of the expected size */
8906 ut_ad(Json_decimal::get_encoded_binary_len(elt.get_data_length()) ==
8907 dfield->type.len);
8908 dfield_set_data(dfield,
8909 Json_decimal::get_encoded_binary(elt.get_data()),
8910 dfield->type.len);
8911 break;
8912 }
8913 case MYSQL_TYPE_TIME:
8914 case MYSQL_TYPE_DATE:
8915 case MYSQL_TYPE_DATETIME:
8916 case MYSQL_TYPE_TIMESTAMP: {
8917 /* Temporal data has at most 8 bytes length */
8918 Json_datetime::from_packed_to_key(elt.get_data(), elt.field_type(),
8919 buf, fld->decimals());
8920
8921 dfield_set_data(dfield, buf, dfield->type.len);
8922 break;
8923 }
8924 default:
8925 /* Shouldn't happen */
8926 ut_d(ut_error); /* purecov: inspected */
8927 }
8928 }
8929 } else {
8930 /* not supported */
8931 ut_d(ut_error); /* purecov: inspected */
8932 }
8933
8934 value->datap[i] = dfield->data;
8935 value->data_len[i] = dfield->len;
8936 buf += sizeof(uint64_t);
8937 }
8938
8939 *valuep = value;
8940 }
8941
8942 /** Handle the multi-value array, parse the values and store them
8943 @param[in] v JSON binary that has the mult-value
8944 @param[out] value store the parsed out value
8945 @param[in] fld array Field for the data
8946 @param[in] dfield InnoDB indexed field struct
8947 @param[in] comp if this is new InnoDB row type
8948 @param[in,out] heap heap memory
8949 @return true if values are valid and stored, otherwise false */
8950 static inline bool innobase_store_multi_value(json_binary::Value &v,
8951 multi_value_data *value,
8952 Field_typed_array *fld,
8953 dfield_t *dfield, bool comp,
8954 mem_heap_t *heap) {
8955 if (v.type() == json_binary::Value::ERROR) {
8956 /* purecov: begin inspected */
8957 my_error(ER_INVALID_JSON_BINARY_DATA, MYF(0));
8958 return (false);
8959 /* purecov: end */
8960 } else if (v.type() == json_binary::Value::LITERAL_NULL) {
8961 /* When field is null, json parser creates LETERAL_NULL value.
8962 JSON NULL shouldn't get here in any other way */
8963 ut_ad(fld->is_null());
8964 dfield_set_null(dfield);
8965 } else if (v.element_count() == 0) {
8966 dfield_set_data(dfield, nullptr, UNIV_NO_INDEX_VALUE);
8967 } else {
8968 innobase_store_multi_value_low(&v, &value, fld, dfield, comp, heap);
8969 dfield_set_data(dfield, value, UNIV_MULTI_VALUE_ARRAY_MARKER);
8970 ut_ad(!value->duplicate());
8971 }
8972
8973 return (true);
8974 }
8975
8976 /** Parse out multi-values from a MySQL record
8977 @param[in] mysql_table MySQL table structure
8978 @param[in] f_idx field index of the multi-value column
8979 @param[in,out] dfield field structure to store parsed multi-value
8980 @param[in,out] value nullptr or the multi-value structure
8981 to store the parsed values
8982 @param[in] old_val old value if exists
8983 @param[in] comp true if InnoDB table uses compact row format
8984 @param[in,out] heap memory heap */
8985 void innobase_get_multi_value(const TABLE *mysql_table, ulint f_idx,
8986 dfield_t *dfield, multi_value_data *value,
8987 uint old_val, ulint comp, mem_heap_t *heap) {
8988 Field_typed_array *fld;
8989 uint length;
8990 const char *ptr;
8991
8992 ut_ad(dfield_check_typed(dfield));
8993
8994 fld = down_cast<Field_typed_array *>(mysql_table->field[f_idx]);
8995
8996 if (old_val) {
8997 length = fld->data_length(old_val);
8998 ptr = fld->get_binary(old_val);
8999 } else {
9000 length = fld->data_length();
9001 ptr = fld->get_binary();
9002 }
9003
9004 json_binary::Value v(json_binary::parse_binary(ptr, length));
9005 ut_ad(v.type() == json_binary::Value::ARRAY ||
9006 v.type() == json_binary::Value::LITERAL_NULL);
9007
9008 ut_d(bool succ =)
9009 innobase_store_multi_value(v, value, fld, dfield, comp, heap);
9010 ut_ad(succ);
9011 }
9012
9013 /** Stores a row in an InnoDB database, to the table specified in this
9014 handle.
9015 @return error code */
9016
9017 int ha_innobase::write_row(uchar *record) /*!< in: a row in MySQL format */
9018 {
9019 dberr_t error;
9020 int error_result = 0;
9021 bool auto_inc_used = false;
9022
9023 DBUG_TRACE;
9024
9025 /* Increase the write count of handler */
9026 ha_statistic_increment(&System_status_var::ha_write_count);
9027
9028 if (m_prebuilt->table->is_intrinsic()) {
9029 return intrinsic_table_write_row(record);
9030 }
9031
9032 trx_t *trx = thd_to_trx(m_user_thd);
9033
9034 TrxInInnoDB trx_in_innodb(trx);
9035
9036 if (!m_prebuilt->table->is_intrinsic() && trx_in_innodb.is_aborted()) {
9037 innobase_rollback(ht, m_user_thd, false);
9038
9039 return convert_error_code_to_mysql(DB_FORCED_ABORT, 0, m_user_thd);
9040 }
9041
9042 /* Validation checks before we commence write_row operation. */
9043 if (high_level_read_only) {
9044 ib_senderrf(ha_thd(), IB_LOG_LEVEL_WARN, ER_READ_ONLY_MODE);
9045 return HA_ERR_TABLE_READONLY;
9046 } else if (m_prebuilt->trx != trx) {
9047 ib::error(ER_IB_MSG_558) << "The transaction object for the table handle is"
9048 " at "
9049 << static_cast<const void *>(m_prebuilt->trx)
9050 << ", but for the current thread it is at "
9051 << static_cast<const void *>(trx);
9052
9053 fputs("InnoDB: Dump of 200 bytes around m_prebuilt: ", stderr);
9054 ut_print_buf(stderr, ((const byte *)m_prebuilt) - 100, 200);
9055 fputs("\nInnoDB: Dump of 200 bytes around ha_data: ", stderr);
9056 ut_print_buf(stderr, ((const byte *)trx) - 100, 200);
9057 putc('\n', stderr);
9058 ut_error;
9059 } else if (!trx_is_started(trx)) {
9060 ++trx->will_lock;
9061 }
9062
9063 /* Handling of Auto-Increment Columns. */
9064 if (table->next_number_field && record == table->record[0]) {
9065 /* Reset the error code before calling
9066 innobase_get_auto_increment(). */
9067 m_prebuilt->autoinc_error = DB_SUCCESS;
9068
9069 error_result = update_auto_increment();
9070 if (error_result) {
9071 /* We don't want to mask autoinc overflow errors. */
9072
9073 /* Handle the case where the AUTOINC sub-system
9074 failed during initialization. */
9075 if (m_prebuilt->autoinc_error == DB_UNSUPPORTED) {
9076 error_result = ER_AUTOINC_READ_FAILED;
9077 /* Set the error message to report too. */
9078 my_error(ER_AUTOINC_READ_FAILED, MYF(0));
9079 goto func_exit;
9080 } else if (m_prebuilt->autoinc_error != DB_SUCCESS) {
9081 error = m_prebuilt->autoinc_error;
9082 goto report_error;
9083 }
9084
9085 /* MySQL errors are passed straight back. */
9086 goto func_exit;
9087 }
9088
9089 auto_inc_used = true;
9090 }
9091
9092 /* Prepare INSERT graph that will be executed for actual INSERT
9093 (This is a one time operation) */
9094 if (m_prebuilt->mysql_template == nullptr ||
9095 m_prebuilt->template_type != ROW_MYSQL_WHOLE_ROW) {
9096 /* Build the template used in converting quickly between
9097 the two database formats */
9098
9099 build_template(true);
9100 }
9101
9102 error = innobase_srv_conc_enter_innodb(m_prebuilt);
9103
9104 if (error != DB_SUCCESS) {
9105 goto report_error;
9106 }
9107
9108 /* Execute insert graph that will result in actual insert. */
9109 error = row_insert_for_mysql((byte *)record, m_prebuilt);
9110
9111 DEBUG_SYNC(m_user_thd, "ib_after_row_insert");
9112
9113 /* Handling of errors related to auto-increment. */
9114 if (auto_inc_used) {
9115 ulonglong auto_inc;
9116 ulonglong col_max_value;
9117
9118 /* Note the number of rows processed for this statement, used
9119 by get_auto_increment() to determine the number of AUTO-INC
9120 values to reserve. This is only useful for a mult-value INSERT
9121 and is a statement level counter. */
9122 if (trx->n_autoinc_rows > 0) {
9123 --trx->n_autoinc_rows;
9124 }
9125
9126 /* We need the upper limit of the col type to check for
9127 whether we update the table autoinc counter or not. */
9128 col_max_value = table->next_number_field->get_max_int_value();
9129
9130 /* Get the value that MySQL attempted to store in the table. */
9131 auto_inc = table->next_number_field->val_int();
9132
9133 switch (error) {
9134 case DB_DUPLICATE_KEY:
9135
9136 /* A REPLACE command and LOAD DATA INFILE REPLACE
9137 handle a duplicate key error themselves, but we
9138 must update the autoinc counter if we are performing
9139 those statements. */
9140
9141 switch (thd_sql_command(m_user_thd)) {
9142 case SQLCOM_LOAD:
9143 if (!m_prebuilt->allow_duplicates()) {
9144 break;
9145 }
9146
9147 case SQLCOM_REPLACE:
9148 case SQLCOM_INSERT_SELECT:
9149 case SQLCOM_REPLACE_SELECT:
9150 goto set_max_autoinc;
9151
9152 default:
9153 break;
9154 }
9155
9156 break;
9157
9158 case DB_SUCCESS:
9159 /* If the actual value inserted is greater than
9160 the upper limit of the interval, then we try and
9161 update the table upper limit. Note: last_value
9162 will be 0 if get_auto_increment() was not called. */
9163
9164 if (auto_inc >= m_prebuilt->autoinc_last_value) {
9165 set_max_autoinc:
9166 /* This should filter out the negative
9167 values set explicitly by the user. */
9168 if (auto_inc <= col_max_value) {
9169 ut_a(m_prebuilt->autoinc_increment > 0);
9170
9171 ulonglong offset;
9172 ulonglong increment;
9173 dberr_t err;
9174
9175 offset = m_prebuilt->autoinc_offset;
9176 increment = m_prebuilt->autoinc_increment;
9177
9178 auto_inc = innobase_next_autoinc(auto_inc, 1, increment, offset,
9179 col_max_value);
9180
9181 err = innobase_set_max_autoinc(auto_inc);
9182
9183 if (err != DB_SUCCESS) {
9184 error = err;
9185 }
9186 }
9187 }
9188 break;
9189 default:
9190 break;
9191 }
9192 }
9193
9194 innobase_srv_conc_exit_innodb(m_prebuilt);
9195
9196 report_error:
9197 /* Cleanup and exit. */
9198 if (error == DB_TABLESPACE_DELETED) {
9199 ib_senderrf(trx->mysql_thd, IB_LOG_LEVEL_ERROR, ER_TABLESPACE_DISCARDED,
9200 table->s->table_name.str);
9201 }
9202
9203 error_result =
9204 convert_error_code_to_mysql(error, m_prebuilt->table->flags, m_user_thd);
9205
9206 if (error_result == HA_FTS_INVALID_DOCID) {
9207 my_error(HA_FTS_INVALID_DOCID, MYF(0));
9208 }
9209
9210 func_exit:
9211
9212 innobase_active_small();
9213
9214 return error_result;
9215 }
9216
9217 /** Fill the update vector's "old_vrow" field for those non-updated,
9218 but indexed columns. Such columns could still present in the virtual
9219 index rec fields even if they are not updated (some other fields updated),
9220 so needs to be logged.
9221 @param[in] prebuilt InnoDB prebuilt struct
9222 @param[in,out] vfield field to filled
9223 @param[in] o_len actual column length
9224 @param[in] old_mysql_row_col MySQL old field ptr
9225 @param[in] col_pack_len MySQL field col length
9226 @param[in,out] buf buffer for a converted integer value
9227 @return used buffer ptr from row_mysql_store_col_in_innobase_format() */
9228 static byte *innodb_fill_old_vcol_val(row_prebuilt_t *prebuilt,
9229 dfield_t *vfield, ulint o_len,
9230 const byte *old_mysql_row_col,
9231 ulint col_pack_len, byte *buf) {
9232 ut_ad(dfield_check_typed(vfield));
9233
9234 if (o_len != UNIV_SQL_NULL) {
9235 buf = row_mysql_store_col_in_innobase_format(
9236 vfield, buf, true, old_mysql_row_col, col_pack_len,
9237 dict_table_is_comp(prebuilt->table));
9238 } else {
9239 dfield_set_null(vfield);
9240 }
9241
9242 return (buf);
9243 }
9244
9245 /** Parse out multi-values from both old and new MySQL records,
9246 at the meantime, calculate the difference between two records.
9247 @param[in] mysql_table MySQL table structure
9248 @param[in] field_idx field index of the multi-value column
9249 @param[in,out] old_field field structure to store the parsed old value
9250 @param[in,out] new_field field structure to store the parsed new value
9251 @param[in] old_value old value to parse
9252 @param[in] comp true if InnoDB table uses compact row format
9253 @param[in,out] heap memory heap */
9254 static void innobase_get_multi_value_and_diff(
9255 const TABLE *mysql_table, ulint field_idx, dfield_t *old_field,
9256 dfield_t *new_field, uint old_value, ulint comp, mem_heap_t *heap) {
9257 Field_typed_array *fld;
9258 const char *old_ptr = nullptr;
9259 const char *new_ptr = nullptr;
9260 uint old_len;
9261 uint new_len;
9262
9263 fld = down_cast<Field_typed_array *>(mysql_table->field[field_idx]);
9264
9265 old_ptr = fld->get_binary(old_value);
9266 old_len = fld->get_length(old_value);
9267 new_ptr = fld->get_binary();
9268 new_len = fld->get_length();
9269
9270 json_binary::Value old_v(json_binary::parse_binary(old_ptr, old_len));
9271 json_binary::Value new_v(json_binary::parse_binary(new_ptr, new_len));
9272 ut_ad(old_v.type() == json_binary::Value::ARRAY);
9273 ut_ad(new_v.type() == json_binary::Value::ARRAY);
9274
9275 ut_d(bool succ1 =)
9276 innobase_store_multi_value(old_v, nullptr, fld, old_field, comp, heap);
9277 ut_ad(succ1);
9278 ut_d(bool succ2 =)
9279 innobase_store_multi_value(new_v, nullptr, fld, new_field, comp, heap);
9280 ut_ad(succ2);
9281
9282 ut_ad(!dfield_is_null(old_field));
9283 ut_ad(!dfield_is_null(new_field));
9284 /* If no indexed value, then no need to get the difference */
9285 if (old_field->len == UNIV_NO_INDEX_VALUE ||
9286 new_field->len == UNIV_NO_INDEX_VALUE) {
9287 return;
9288 }
9289
9290 /* Now old_field and new_field are having both multi-value data, in the
9291 same sequence with data in old_v and new_v, which are also sorted in
9292 ascending order. */
9293
9294 uint old_counter = 0;
9295 uint new_counter = 0;
9296 multi_value_data *old_mv = static_cast<multi_value_data *>(old_field->data);
9297 multi_value_data *new_mv = static_cast<multi_value_data *>(new_field->data);
9298
9299 old_mv->alloc_bitset(heap);
9300 new_mv->alloc_bitset(heap);
9301
9302 while (old_counter < old_v.element_count() &&
9303 new_counter < new_v.element_count()) {
9304 ut_ad(old_counter < old_mv->num_v);
9305 ut_ad(new_counter < new_mv->num_v);
9306
9307 int res = old_v.element(old_counter).eq(new_v.element(new_counter));
9308 if (res == 0) {
9309 old_mv->bitset->set(old_counter++, false);
9310 new_mv->bitset->set(new_counter++, false);
9311 } else if (res < 0) {
9312 ++old_counter;
9313 } else {
9314 ++new_counter;
9315 }
9316 }
9317 }
9318
9319 /** Checks which fields have changed in a row and stores information
9320 of them to an update vector for the table's clustered index.
9321 @return DB_SUCCESS or error code */
9322 static dberr_t calc_row_difference(
9323 upd_t *uvect, /*!< in/out: update vector for the
9324 clustered index */
9325 const uchar *old_row, /*!< in: old row in MySQL format */
9326 uchar *new_row, /*!< in: new row in MySQL format */
9327 TABLE *table, /*!< in: table in MySQL data
9328 dictionary */
9329 uchar *upd_buff, /*!< in: buffer to use */
9330 ulint buff_len, /*!< in: buffer length */
9331 row_prebuilt_t *prebuilt, /*!< in: InnoDB prebuilt struct */
9332 THD *thd) /*!< in: user thread */
9333 {
9334 uchar *original_upd_buff = upd_buff;
9335 Field *field;
9336 enum_field_types field_mysql_type;
9337 uint n_fields;
9338 ulint o_len;
9339 ulint n_len;
9340 ulint col_pack_len;
9341 const byte *new_mysql_row_col;
9342 const byte *old_mysql_row_col;
9343 const byte *o_ptr;
9344 const byte *n_ptr;
9345 byte *buf;
9346 upd_field_t *ufield;
9347 ulint col_type;
9348 ulint n_changed = 0;
9349 dfield_t dfield;
9350 dict_index_t *clust_index;
9351 uint i;
9352 bool changes_fts_column = false;
9353 bool changes_fts_doc_col = false;
9354 trx_t *trx = thd_to_trx(thd);
9355 doc_id_t doc_id = FTS_NULL_DOC_ID;
9356 ulint comp = 0;
9357 ulint num_v = 0;
9358
9359 ut_ad(!srv_read_only_mode || prebuilt->table->is_intrinsic());
9360
9361 comp = dict_table_is_comp(prebuilt->table);
9362
9363 n_fields = table->s->fields;
9364 clust_index = prebuilt->table->first_index();
9365
9366 /* We use upd_buff to convert changed fields */
9367 buf = (byte *)upd_buff;
9368
9369 for (i = 0; i < n_fields; i++) {
9370 dfield.reset();
9371
9372 field = table->field[i];
9373 bool is_virtual = innobase_is_v_fld(field);
9374 bool is_multi_value = innobase_is_multi_value_fld(field);
9375 dict_col_t *col;
9376
9377 if (is_virtual) {
9378 col = &prebuilt->table->v_cols[num_v].m_col;
9379 } else {
9380 col = &prebuilt->table->cols[i - num_v];
9381 }
9382
9383 o_ptr = (const byte *)old_row + get_field_offset(table, field);
9384 n_ptr = (const byte *)new_row + get_field_offset(table, field);
9385
9386 /* Use new_mysql_row_col and col_pack_len save the values */
9387
9388 new_mysql_row_col = n_ptr;
9389 old_mysql_row_col = o_ptr;
9390 col_pack_len = field->pack_length();
9391
9392 o_len = col_pack_len;
9393 n_len = col_pack_len;
9394
9395 /* We use o_ptr and n_ptr to dig up the actual data for
9396 comparison. */
9397
9398 field_mysql_type = field->type();
9399
9400 col_type = col->mtype;
9401
9402 /* Reset the type to BLOB for multi-value field, since server may
9403 keep it as non-BLOB one. */
9404 if (is_multi_value) {
9405 col_type = DATA_BLOB;
9406 }
9407
9408 switch (col_type) {
9409 case DATA_BLOB:
9410 case DATA_POINT:
9411 case DATA_VAR_POINT:
9412 case DATA_GEOMETRY:
9413 o_ptr = row_mysql_read_blob_ref(&o_len, o_ptr, o_len);
9414 n_ptr = row_mysql_read_blob_ref(&n_len, n_ptr, n_len);
9415
9416 break;
9417
9418 case DATA_VARCHAR:
9419 case DATA_BINARY:
9420 case DATA_VARMYSQL:
9421 if (field_mysql_type == MYSQL_TYPE_VARCHAR) {
9422 /* This is a >= 5.0.3 type true VARCHAR where
9423 the real payload data length is stored in
9424 1 or 2 bytes */
9425
9426 o_ptr = row_mysql_read_true_varchar(&o_len, o_ptr,
9427 (ulint)field->get_length_bytes());
9428
9429 n_ptr = row_mysql_read_true_varchar(&n_len, n_ptr,
9430 (ulint)field->get_length_bytes());
9431 }
9432
9433 break;
9434 default:;
9435 }
9436
9437 if (field_mysql_type == MYSQL_TYPE_LONGLONG && prebuilt->table->fts &&
9438 innobase_strcasecmp(field->field_name, FTS_DOC_ID_COL_NAME) == 0) {
9439 doc_id = (doc_id_t)mach_read_from_n_little_endian(n_ptr, 8);
9440 if (doc_id == 0) {
9441 return (DB_FTS_INVALID_DOCID);
9442 }
9443 }
9444
9445 if (field->is_nullable()) {
9446 if (field->is_null_in_record(old_row)) {
9447 o_len = UNIV_SQL_NULL;
9448 }
9449
9450 if (field->is_null_in_record(new_row)) {
9451 n_len = UNIV_SQL_NULL;
9452 }
9453 }
9454
9455 #ifdef UNIV_DEBUG
9456 bool online_ord_part = false;
9457 #endif
9458
9459 if (is_virtual) {
9460 /* If the virtual column is not indexed,
9461 we shall ignore it for update */
9462 if (!col->ord_part) {
9463 /* Check whether there is a table-rebuilding
9464 online ALTER TABLE in progress, and this
9465 virtual column could be newly indexed, thus
9466 it will be materialized. Then we will have
9467 to log its update.
9468 Note, we do not support online dropping virtual
9469 column while adding new index, nor with
9470 online alter column order while adding index,
9471 so the virtual column sequence must not change
9472 if it is online operation */
9473 if (dict_index_is_online_ddl(clust_index) &&
9474 row_log_col_is_indexed(clust_index, num_v)) {
9475 #ifdef UNIV_DEBUG
9476 online_ord_part = true;
9477 #endif
9478 } else {
9479 num_v++;
9480 continue;
9481 }
9482 }
9483
9484 if (!uvect->old_vrow) {
9485 uvect->old_vrow =
9486 dtuple_create_with_vcol(uvect->heap, 0, prebuilt->table->n_v_cols);
9487 for (uint j = 0; j < prebuilt->table->n_v_cols; j++) {
9488 dfield_t *field = dtuple_get_nth_v_field(uvect->old_vrow, j);
9489 /* In case a multi-value field checking read uninitialized value */
9490 dfield_get_type(field)->prtype = 0;
9491 dfield_set_len(field, UNIV_SQL_NULL);
9492 }
9493 }
9494
9495 ulint max_field_len = DICT_MAX_FIELD_LEN_BY_FORMAT(prebuilt->table);
9496
9497 /* for virtual columns, we only materialize
9498 its index, and index field length would not
9499 exceed max_field_len. So continue if the
9500 first max_field_len bytes are matched up */
9501 if (o_len != UNIV_SQL_NULL && n_len != UNIV_SQL_NULL &&
9502 o_len >= max_field_len && n_len >= max_field_len &&
9503 memcmp(o_ptr, n_ptr, max_field_len) == 0) {
9504 dfield_t *vfield = dtuple_get_nth_v_field(uvect->old_vrow, num_v);
9505 col->copy_type(dfield_get_type(vfield));
9506
9507 if (is_multi_value) {
9508 innobase_get_multi_value(prebuilt->m_mysql_table, i, vfield, nullptr,
9509 static_cast<uint>(old_row - new_row), comp,
9510 uvect->per_stmt_heap);
9511 } else {
9512 buf = innodb_fill_old_vcol_val(prebuilt, vfield, o_len,
9513 old_mysql_row_col, col_pack_len, buf);
9514 }
9515 num_v++;
9516 continue;
9517 }
9518 }
9519
9520 if (o_len != n_len || (o_len != UNIV_SQL_NULL && o_len != 0 &&
9521 0 != memcmp(o_ptr, n_ptr, o_len))) {
9522 /* The field has changed */
9523 bool multi_value_calc_by_diff = false;
9524 dfield_t old_field, new_field;
9525
9526 ufield = uvect->fields + n_changed;
9527
9528 const auto old_old_v_val = ufield->old_v_val;
9529
9530 UNIV_MEM_INVALID(ufield, sizeof *ufield);
9531
9532 /* Let us use a dummy dfield to make the conversion
9533 from the MySQL column format to the InnoDB format */
9534
9535 /* If the length of new geometry object is 0, means
9536 this object is invalid geometry object, we need
9537 to block it. */
9538 if (DATA_GEOMETRY_MTYPE(col_type) && o_len != 0 && n_len == 0) {
9539 return (DB_CANT_CREATE_GEOMETRY_OBJECT);
9540 }
9541
9542 if (is_multi_value && n_len != UNIV_SQL_NULL &&
9543 !field->is_null_in_record(old_row)) {
9544 /* Multi-value field and both old and new are not NULL,
9545 parse the value separately and also calculate the difference */
9546 ut_ad(is_virtual);
9547
9548 col->copy_type(dfield_get_type(&old_field));
9549 col->copy_type(dfield_get_type(&new_field));
9550
9551 innobase_get_multi_value_and_diff(
9552 prebuilt->m_mysql_table, i, &old_field, &new_field,
9553 static_cast<uint>(old_row - new_row), comp, uvect->per_stmt_heap);
9554
9555 multi_value_calc_by_diff = true;
9556 }
9557
9558 if (n_len != UNIV_SQL_NULL) {
9559 col->copy_type(dfield_get_type(&dfield));
9560
9561 if (is_multi_value && !multi_value_calc_by_diff) {
9562 innobase_get_multi_value(prebuilt->m_mysql_table, i, &dfield, nullptr,
9563 0, comp, uvect->per_stmt_heap);
9564 } else {
9565 buf = row_mysql_store_col_in_innobase_format(&dfield, (byte *)buf,
9566 true, new_mysql_row_col,
9567 col_pack_len, comp);
9568 }
9569
9570 if (multi_value_calc_by_diff) {
9571 dfield_copy(&ufield->new_val, &new_field);
9572 } else {
9573 dfield_copy(&ufield->new_val, &dfield);
9574 }
9575 } else {
9576 col->copy_type(dfield_get_type(&ufield->new_val));
9577 dfield_set_null(&ufield->new_val);
9578 }
9579
9580 ufield->exp = nullptr;
9581 ufield->orig_len = 0;
9582 ufield->mysql_field = field;
9583
9584 if (is_virtual) {
9585 dfield_t *vfield = dtuple_get_nth_v_field(uvect->old_vrow, num_v);
9586 upd_fld_set_virtual_col(ufield);
9587 /* Set ufield->field_no to store the position of virtual column. */
9588 ufield->field_no = num_v;
9589
9590 ut_ad(col->ord_part || online_ord_part);
9591 if (old_old_v_val == nullptr) {
9592 ufield->old_v_val = static_cast<dfield_t *>(
9593 mem_heap_alloc(uvect->heap, sizeof *ufield->old_v_val));
9594 } else {
9595 UNIV_MEM_VALID(ufield, sizeof *ufield);
9596 ufield->old_v_val->reset();
9597 }
9598
9599 if (!field->is_null_in_record(old_row)) {
9600 if (n_len == UNIV_SQL_NULL) {
9601 col->copy_type(dfield_get_type(&dfield));
9602 }
9603
9604 if (is_multi_value && !multi_value_calc_by_diff) {
9605 innobase_get_multi_value(prebuilt->m_mysql_table, i, &dfield,
9606 nullptr,
9607 static_cast<uint>(old_row - new_row), comp,
9608 uvect->per_stmt_heap);
9609 } else {
9610 buf = row_mysql_store_col_in_innobase_format(
9611 &dfield, (byte *)buf, true, old_mysql_row_col, col_pack_len,
9612 comp);
9613 }
9614
9615 if (multi_value_calc_by_diff) {
9616 dfield_copy(ufield->old_v_val, &old_field);
9617 dfield_copy(vfield, &old_field);
9618 } else {
9619 dfield_copy(ufield->old_v_val, &dfield);
9620 dfield_copy(vfield, &dfield);
9621 }
9622 } else {
9623 col->copy_type(dfield_get_type(ufield->old_v_val));
9624 dfield_set_null(ufield->old_v_val);
9625 dfield_set_null(vfield);
9626 }
9627 num_v++;
9628 } else {
9629 /* Set ufield->field_no to store the position of column in
9630 clustered index. */
9631 ufield->field_no = dict_col_get_clust_pos(
9632 &prebuilt->table->cols[i - num_v], clust_index);
9633 #ifdef UNIV_DEBUG
9634 if (clust_index->has_row_versions()) {
9635 dict_col_t *col = &prebuilt->table->cols[i - num_v];
9636 ufield->field_phy_pos = col->get_col_phy_pos();
9637 }
9638 #endif
9639 ufield->old_v_val = nullptr;
9640 }
9641 n_changed++;
9642
9643 /* If an FTS indexed column was changed by this
9644 UPDATE then we need to inform the FTS sub-system.
9645
9646 NOTE: Currently we re-index all FTS indexed columns
9647 even if only a subset of the FTS indexed columns
9648 have been updated. That is the reason we are
9649 checking only once here. Later we will need to
9650 note which columns have been updated and do
9651 selective processing. */
9652 if (prebuilt->table->fts != nullptr && !is_virtual) {
9653 ulint offset;
9654 dict_table_t *innodb_table;
9655
9656 innodb_table = prebuilt->table;
9657
9658 if (!changes_fts_column) {
9659 offset = row_upd_changes_fts_column(innodb_table, ufield);
9660
9661 if (offset != ULINT_UNDEFINED) {
9662 changes_fts_column = true;
9663 }
9664 }
9665
9666 if (!changes_fts_doc_col) {
9667 changes_fts_doc_col = row_upd_changes_doc_id(innodb_table, ufield);
9668 }
9669 }
9670 } else if (is_virtual) {
9671 dfield_t *vfield = dtuple_get_nth_v_field(uvect->old_vrow, num_v);
9672 col->copy_type(dfield_get_type(vfield));
9673
9674 if (is_multi_value) {
9675 innobase_get_multi_value(prebuilt->m_mysql_table, i, vfield, nullptr,
9676 static_cast<uint>(old_row - new_row), comp,
9677 uvect->per_stmt_heap);
9678 } else {
9679 buf = innodb_fill_old_vcol_val(prebuilt, vfield, o_len,
9680 old_mysql_row_col, col_pack_len, buf);
9681 }
9682
9683 ut_ad(col->ord_part || online_ord_part);
9684 num_v++;
9685 }
9686 }
9687
9688 /* If the update changes a column with an FTS index on it, we
9689 then add an update column node with a new document id to the
9690 other changes. We piggy back our changes on the normal UPDATE
9691 to reduce processing and IO overhead. */
9692 if (!prebuilt->table->fts) {
9693 trx->fts_next_doc_id = 0;
9694 } else if (changes_fts_column || changes_fts_doc_col) {
9695 dict_table_t *innodb_table = prebuilt->table;
9696
9697 ufield = uvect->fields + n_changed;
9698
9699 if (!DICT_TF2_FLAG_IS_SET(innodb_table, DICT_TF2_FTS_HAS_DOC_ID)) {
9700 /* If Doc ID is managed by user, and if any
9701 FTS indexed column has been updated, its corresponding
9702 Doc ID must also be updated. Otherwise, return
9703 error */
9704 if (changes_fts_column && !changes_fts_doc_col) {
9705 ib::warn(ER_IB_MSG_559) << "A new Doc ID must be supplied"
9706 " while updating FTS indexed columns.";
9707 return DB_FTS_INVALID_DOCID;
9708 }
9709
9710 /* Doc ID must monotonically increase */
9711 ut_ad(innodb_table->fts->cache);
9712 if (doc_id < prebuilt->table->fts->cache->next_doc_id) {
9713 ib::warn(ER_IB_MSG_560) << "FTS Doc ID must be larger than "
9714 << innodb_table->fts->cache->next_doc_id - 1
9715 << " for table " << innodb_table->name;
9716
9717 return DB_FTS_INVALID_DOCID;
9718 } else if ((doc_id - prebuilt->table->fts->cache->next_doc_id) >=
9719 FTS_DOC_ID_MAX_STEP) {
9720 ib::warn(ER_IB_MSG_561)
9721 << "Doc ID " << doc_id
9722 << " is too"
9723 " big. Its difference with largest"
9724 " Doc ID used "
9725 << prebuilt->table->fts->cache->next_doc_id - 1
9726 << " cannot exceed or equal to " << FTS_DOC_ID_MAX_STEP;
9727 }
9728
9729 trx->fts_next_doc_id = doc_id;
9730 } else {
9731 /* If the Doc ID is a hidden column, it can't be
9732 changed by user */
9733 ut_ad(!changes_fts_doc_col);
9734
9735 /* Doc ID column is hidden, a new Doc ID will be
9736 generated by following fts_update_doc_id() call */
9737 trx->fts_next_doc_id = 0;
9738 }
9739
9740 fts_update_doc_id(innodb_table, ufield, &trx->fts_next_doc_id);
9741
9742 ++n_changed;
9743 } else {
9744 /* We have a Doc ID column, but none of FTS indexed
9745 columns are touched, nor the Doc ID column, so set
9746 fts_next_doc_id to UINT64_UNDEFINED, which means do not
9747 update the Doc ID column */
9748 trx->fts_next_doc_id = UINT64_UNDEFINED;
9749 }
9750
9751 uvect->n_fields = n_changed;
9752 uvect->info_bits = 0;
9753
9754 ut_a(buf <= (byte *)original_upd_buff + buff_len);
9755
9756 ut_d(uvect->validate_for_index(clust_index));
9757 return DB_SUCCESS;
9758 }
9759
9760 /**
9761 Updates a row given as a parameter to a new value. Note that we are given
9762 whole rows, not just the fields which are updated: this incurs some
9763 overhead for CPU when we check which fields are actually updated.
9764 TODO: currently InnoDB does not prevent the 'Halloween problem':
9765 in a searched update a single row can get updated several times
9766 if its index columns are updated!
9767 @param[in] old_row Old row contents in MySQL format
9768 @param[out] new_row Updated row contents in MySQL format
9769 @return error number or 0 */
9770
9771 int ha_innobase::update_row(const uchar *old_row, uchar *new_row) {
9772 int err;
9773
9774 dberr_t error;
9775 trx_t *trx = thd_to_trx(m_user_thd);
9776 uint64_t new_counter = 0;
9777
9778 DBUG_TRACE;
9779
9780 ut_a(m_prebuilt->trx == trx);
9781
9782 if (high_level_read_only && !m_prebuilt->table->is_intrinsic()) {
9783 ib_senderrf(ha_thd(), IB_LOG_LEVEL_WARN, ER_READ_ONLY_MODE);
9784 return HA_ERR_TABLE_READONLY;
9785 } else if (!trx_is_started(trx)) {
9786 ++trx->will_lock;
9787 }
9788
9789 if (m_upd_buf == nullptr) {
9790 ut_ad(m_upd_buf_size == 0);
9791
9792 /* Create a buffer for packing the fields of a record. Why
9793 table->reclength did not work here? Obviously, because char
9794 fields when packed actually became 1 byte longer, when we also
9795 stored the string length as the first byte. */
9796
9797 m_upd_buf_size =
9798 table->s->reclength + table->s->max_key_length + MAX_REF_PARTS * 3;
9799
9800 m_upd_buf = reinterpret_cast<uchar *>(
9801 my_malloc(PSI_INSTRUMENT_ME, m_upd_buf_size, MYF(MY_WME)));
9802
9803 if (m_upd_buf == nullptr) {
9804 m_upd_buf_size = 0;
9805 return HA_ERR_OUT_OF_MEM;
9806 }
9807 }
9808
9809 ha_statistic_increment(&System_status_var::ha_update_count);
9810
9811 upd_t *uvect;
9812
9813 if (m_prebuilt->upd_node) {
9814 uvect = m_prebuilt->upd_node->update;
9815 } else {
9816 uvect = row_get_prebuilt_update_vector(m_prebuilt);
9817 }
9818
9819 uvect->table = m_prebuilt->table;
9820 uvect->mysql_table = table;
9821
9822 /* Build an update vector from the modified fields in the rows
9823 (uses m_upd_buf of the handle) */
9824
9825 error = calc_row_difference(uvect, old_row, new_row, table, m_upd_buf,
9826 m_upd_buf_size, m_prebuilt, m_user_thd);
9827
9828 if (error != DB_SUCCESS) {
9829 goto func_exit;
9830 }
9831
9832 if (!m_prebuilt->table->is_intrinsic() && TrxInInnoDB::is_aborted(trx)) {
9833 innobase_rollback(ht, m_user_thd, false);
9834
9835 return convert_error_code_to_mysql(DB_FORCED_ABORT, 0, m_user_thd);
9836 }
9837
9838 /* This is not a delete */
9839 m_prebuilt->upd_node->is_delete = false;
9840
9841 error = innobase_srv_conc_enter_innodb(m_prebuilt);
9842
9843 if (error != DB_SUCCESS) {
9844 goto func_exit;
9845 }
9846
9847 error = row_update_for_mysql((byte *)old_row, m_prebuilt);
9848
9849 if (dict_table_has_autoinc_col(m_prebuilt->table)) {
9850 new_counter = row_upd_get_new_autoinc_counter(
9851 uvect, m_prebuilt->table->autoinc_field_no);
9852 } else {
9853 new_counter = 0;
9854 }
9855
9856 /* We should handle the case if the AUTOINC counter has been
9857 updated, we want to update the counter accordingly.
9858
9859 We need to do some special AUTOINC handling for the following case:
9860
9861 INSERT INTO t (c1,c2) VALUES(x,y) ON DUPLICATE KEY UPDATE ...
9862
9863 We need to use the AUTOINC counter that was actually used by
9864 MySQL in the UPDATE statement, which can be different from the
9865 value used in the INSERT statement. */
9866
9867 if (error == DB_SUCCESS &&
9868 (new_counter != 0 ||
9869 (table->next_number_field && new_row == table->record[0] &&
9870 thd_sql_command(m_user_thd) == SQLCOM_INSERT &&
9871 m_prebuilt->allow_duplicates()))) {
9872 ulonglong auto_inc;
9873 ulonglong col_max_value;
9874
9875 if (new_counter != 0) {
9876 auto_inc = new_counter;
9877 } else {
9878 ut_ad(table->next_number_field != nullptr);
9879 auto_inc = table->next_number_field->val_int();
9880 }
9881
9882 /* We need the upper limit of the col type to check for
9883 whether we update the table autoinc counter or not. */
9884 col_max_value = table->found_next_number_field->get_max_int_value();
9885
9886 if (auto_inc <= col_max_value && auto_inc != 0) {
9887 ulonglong offset;
9888 ulonglong increment;
9889
9890 offset = m_prebuilt->autoinc_offset;
9891 increment = m_prebuilt->autoinc_increment;
9892
9893 auto_inc =
9894 innobase_next_autoinc(auto_inc, 1, increment, offset, col_max_value);
9895
9896 error = innobase_set_max_autoinc(auto_inc);
9897 }
9898 }
9899
9900 innobase_srv_conc_exit_innodb(m_prebuilt);
9901
9902 func_exit:
9903
9904 err =
9905 convert_error_code_to_mysql(error, m_prebuilt->table->flags, m_user_thd);
9906
9907 /* If success and no columns were updated. */
9908 if (err == 0 && uvect->n_fields == 0) {
9909 /* This is the same as success, but instructs
9910 MySQL that the row is not really updated and it
9911 should not increase the count of updated rows.
9912 This is fix for http://bugs.mysql.com/29157 */
9913 err = HA_ERR_RECORD_IS_THE_SAME;
9914 } else if (err == HA_FTS_INVALID_DOCID) {
9915 my_error(HA_FTS_INVALID_DOCID, MYF(0));
9916 }
9917
9918 /* Tell InnoDB server that there might be work for
9919 utility threads: */
9920
9921 innobase_active_small();
9922
9923 return err;
9924 }
9925
9926 /** Deletes a row given as the parameter.
9927 @return error number or 0 */
9928
9929 int ha_innobase::delete_row(
9930 const uchar *record) /*!< in: a row in MySQL format */
9931 {
9932 dberr_t error;
9933 trx_t *trx = thd_to_trx(m_user_thd);
9934 TrxInInnoDB trx_in_innodb(trx);
9935
9936 DBUG_TRACE;
9937
9938 if (!m_prebuilt->table->is_intrinsic() && trx_in_innodb.is_aborted()) {
9939 innobase_rollback(ht, m_user_thd, false);
9940
9941 return convert_error_code_to_mysql(DB_FORCED_ABORT, 0, m_user_thd);
9942 }
9943
9944 ut_a(m_prebuilt->trx == trx);
9945
9946 if (high_level_read_only && !m_prebuilt->table->is_intrinsic()) {
9947 ib_senderrf(ha_thd(), IB_LOG_LEVEL_WARN, ER_READ_ONLY_MODE);
9948 return HA_ERR_TABLE_READONLY;
9949 } else if (!trx_is_started(trx)) {
9950 ++trx->will_lock;
9951 }
9952
9953 ha_statistic_increment(&System_status_var::ha_delete_count);
9954
9955 if (!m_prebuilt->upd_node) {
9956 row_get_prebuilt_update_vector(m_prebuilt);
9957 }
9958
9959 /* This is a delete */
9960
9961 m_prebuilt->upd_node->is_delete = true;
9962
9963 error = innobase_srv_conc_enter_innodb(m_prebuilt);
9964
9965 if (error == DB_SUCCESS) {
9966 error = row_update_for_mysql((byte *)record, m_prebuilt);
9967 innobase_srv_conc_exit_innodb(m_prebuilt);
9968 }
9969
9970 /* Tell the InnoDB server that there might be work for
9971 utility threads: */
9972
9973 innobase_active_small();
9974
9975 return convert_error_code_to_mysql(error, m_prebuilt->table->flags,
9976 m_user_thd);
9977 }
9978
9979 /** Delete all rows from the table.
9980 @retval HA_ERR_WRONG_COMMAND if the table is transactional
9981 @retval 0 on success */
9982 int ha_innobase::delete_all_rows() {
9983 DBUG_TRACE;
9984
9985 if (!m_prebuilt->table->is_intrinsic()) {
9986 /* Transactional tables should use truncate(). */
9987 return HA_ERR_WRONG_COMMAND;
9988 }
9989
9990 row_delete_all_rows(m_prebuilt->table);
9991
9992 dict_stats_update(m_prebuilt->table, DICT_STATS_EMPTY_TABLE);
9993
9994 return 0;
9995 }
9996
9997 /** Removes a new lock set on a row, if it was not read optimistically. This can
9998 be called after a row has been read in the processing of an UPDATE or a DELETE
9999 query, when the record doesn't match the WHERE condition. */
10000
10001 void ha_innobase::unlock_row(void) {
10002 DBUG_TRACE;
10003
10004 /* Consistent read does not take any locks, thus there is
10005 nothing to unlock. There is no locking for intrinsic table. */
10006
10007 if (m_prebuilt->select_lock_type == LOCK_NONE ||
10008 m_prebuilt->table->is_intrinsic()) {
10009 return;
10010 }
10011
10012 TrxInInnoDB trx_in_innodb(m_prebuilt->trx);
10013
10014 if (trx_in_innodb.is_aborted()) {
10015 return;
10016 }
10017
10018 ut_ad(!m_prebuilt->table->is_intrinsic());
10019
10020 /* Ideally, this assert must be in the beginning of the function.
10021 But there are some calls to this function from the SQL layer when the
10022 transaction is in state TRX_STATE_NOT_STARTED. The check on
10023 m_prebuilt->select_lock_type above gets around this issue. */
10024
10025 ut_ad(trx_state_eq(m_prebuilt->trx, TRX_STATE_ACTIVE) ||
10026 trx_state_eq(m_prebuilt->trx, TRX_STATE_FORCED_ROLLBACK));
10027
10028 /* The purpose of unlock_row() is to release locks held on non-matching row
10029 found during most recent row_search_mvcc() call.
10030 In higher isolation levels row_try_unlock() is a no-op, as we only set the
10031 m_prebuilt->new_rec_lock[i] when trx->releases_non_matching_rows().
10032 In lower isolation levels row_try_unlock() will remove the record locks which
10033 were newly created during the most recent row_search_mvcc() (the record locks
10034 which were merely reused, are not released as they are still needed).
10035 @see handler::was_semi_consistent_read() for great explanation of what
10036 semi-consistent read mode is all about and why we don't call row_try_unlock()
10037 in case of ROW_READ_DID_SEMI_CONSISTENT, and reset the flag instead; in short
10038 a successful semi-consistent read means we didn't acquire any lock, so don't
10039 need to unlock anything if the row doesn't match the query. */
10040 if (m_prebuilt->row_read_type == ROW_READ_DID_SEMI_CONSISTENT) {
10041 ut_ad(m_prebuilt->new_rec_locks_count() == 0);
10042 m_prebuilt->row_read_type = ROW_READ_TRY_SEMI_CONSISTENT;
10043 }
10044 m_prebuilt->try_unlock(false);
10045 }
10046
10047 /* See handler.h and row0mysql.h for docs on this function. */
10048
10049 bool ha_innobase::was_semi_consistent_read(void) {
10050 return (m_prebuilt->row_read_type == ROW_READ_DID_SEMI_CONSISTENT);
10051 }
10052
10053 /* See handler.h and row0mysql.h for docs on this function. */
10054
10055 void ha_innobase::try_semi_consistent_read(bool yes) {
10056 ut_a(m_prebuilt->trx == thd_to_trx(ha_thd()));
10057
10058 if (yes && m_prebuilt->trx->allow_semi_consistent()) {
10059 m_prebuilt->row_read_type = ROW_READ_TRY_SEMI_CONSISTENT;
10060
10061 } else {
10062 m_prebuilt->row_read_type = ROW_READ_WITH_LOCKS;
10063 }
10064 }
10065
10066 /** Initializes a handle to use an index.
10067 @return 0 or error number */
10068 int ha_innobase::index_init(uint keynr, /*!< in: key (index) number */
10069 bool) /*!< in: 1 if result
10070 MUST be sorted
10071 according to index */
10072 {
10073 DBUG_TRACE;
10074
10075 return change_active_index(keynr);
10076 }
10077
10078 /** Currently does nothing.
10079 @return 0 */
10080
10081 int ha_innobase::index_end(void) {
10082 DBUG_TRACE;
10083
10084 if (m_prebuilt->index->last_sel_cur) {
10085 m_prebuilt->index->last_sel_cur->release();
10086 }
10087
10088 active_index = MAX_KEY;
10089
10090 in_range_check_pushed_down = false;
10091
10092 m_ds_mrr.dsmrr_close();
10093
10094 return 0;
10095 }
10096
10097 /** Converts a search mode flag understood by MySQL to a flag understood
10098 by InnoDB. */
10099 page_cur_mode_t convert_search_mode_to_innobase(ha_rkey_function find_flag) {
10100 switch (find_flag) {
10101 case HA_READ_KEY_EXACT:
10102 /* this does not require the index to be UNIQUE */
10103 case HA_READ_KEY_OR_NEXT:
10104 return (PAGE_CUR_GE);
10105 case HA_READ_AFTER_KEY:
10106 return (PAGE_CUR_G);
10107 case HA_READ_BEFORE_KEY:
10108 return (PAGE_CUR_L);
10109 case HA_READ_KEY_OR_PREV:
10110 case HA_READ_PREFIX_LAST:
10111 case HA_READ_PREFIX_LAST_OR_PREV:
10112 return (PAGE_CUR_LE);
10113 case HA_READ_MBR_CONTAIN:
10114 return (PAGE_CUR_CONTAIN);
10115 case HA_READ_MBR_INTERSECT:
10116 return (PAGE_CUR_INTERSECT);
10117 case HA_READ_MBR_WITHIN:
10118 return (PAGE_CUR_WITHIN);
10119 case HA_READ_MBR_DISJOINT:
10120 return (PAGE_CUR_DISJOINT);
10121 case HA_READ_MBR_EQUAL:
10122 return (PAGE_CUR_MBR_EQUAL);
10123 case HA_READ_PREFIX:
10124 return (PAGE_CUR_UNSUPP);
10125 case HA_READ_INVALID:
10126 return (PAGE_CUR_UNSUPP);
10127 /* do not use "default:" in order to produce a gcc warning:
10128 enumeration value '...' not handled in switch
10129 (if -Wswitch or -Wall is used) */
10130 }
10131
10132 my_error(ER_CHECK_NOT_IMPLEMENTED, MYF(0), "this functionality");
10133
10134 return (PAGE_CUR_UNSUPP);
10135 }
10136
10137 /*
10138 BACKGROUND INFO: HOW A SELECT SQL QUERY IS EXECUTED
10139 ---------------------------------------------------
10140 The following does not cover all the details, but explains how we determine
10141 the start of a new SQL statement, and what is associated with it.
10142
10143 For each table in the database the MySQL interpreter may have several
10144 table handle instances in use, also in a single SQL query. For each table
10145 handle instance there is an InnoDB 'm_prebuilt' struct which contains most
10146 of the InnoDB data associated with this table handle instance.
10147
10148 A) if the user has not explicitly set any MySQL table level locks:
10149
10150 1) MySQL calls ::external_lock to set an 'intention' table level lock on
10151 the table of the handle instance. There we set
10152 m_prebuilt->sql_stat_start = true. The flag sql_stat_start should be set
10153 true if we are taking this table handle instance to use in a new SQL
10154 statement issued by the user. We also increment trx->n_mysql_tables_in_use.
10155
10156 2) If m_prebuilt->sql_stat_start == true we 'pre-compile' the MySQL search
10157 instructions to m_prebuilt->template of the table handle instance in
10158 ::index_read. The template is used to save CPU time in large joins.
10159
10160 3) In row_search_for_mysql, if m_prebuilt->sql_stat_start is true, we
10161 allocate a new consistent read view for the trx if it does not yet have one,
10162 or in the case of a locking read, set an InnoDB 'intention' table level
10163 lock on the table.
10164
10165 4) We do the SELECT. MySQL may repeatedly call ::index_read for the
10166 same table handle instance, if it is a join.
10167
10168 5) When the SELECT ends, MySQL removes its intention table level locks
10169 in ::external_lock. When trx->n_mysql_tables_in_use drops to zero,
10170 (a) we execute a COMMIT there if the autocommit is on,
10171 (b) we also release possible 'SQL statement level resources' InnoDB may
10172 have for this SQL statement. The MySQL interpreter does NOT execute
10173 autocommit for pure read transactions, though it should. That is why the
10174 table handler in that case has to execute the COMMIT in ::external_lock.
10175
10176 B) If the user has explicitly set MySQL table level locks, then MySQL
10177 does NOT call ::external_lock at the start of the statement. To determine
10178 when we are at the start of a new SQL statement we at the start of
10179 ::index_read also compare the query id to the latest query id where the
10180 table handle instance was used. If it has changed, we know we are at the
10181 start of a new SQL statement. Since the query id can theoretically
10182 overwrap, we use this test only as a secondary way of determining the
10183 start of a new SQL statement. */
10184
10185 /** Positions an index cursor to the index specified in the handle. Fetches the
10186 row if any.
10187 @return 0, HA_ERR_KEY_NOT_FOUND, or error number */
10188
10189 int ha_innobase::index_read(
10190 uchar *buf, /*!< in/out: buffer for the returned
10191 row */
10192 const uchar *key_ptr, /*!< in: key value; if this is NULL
10193 we position the cursor at the
10194 start or end of index; this can
10195 also contain an InnoDB row id, in
10196 which case key_len is the InnoDB
10197 row id length; the key value can
10198 also be a prefix of a full key value,
10199 and the last column can be a prefix
10200 of a full column */
10201 uint key_len, /*!< in: key value length */
10202 enum ha_rkey_function find_flag) /*!< in: search flags from my_base.h */
10203 {
10204 DBUG_TRACE;
10205 DEBUG_SYNC_C("ha_innobase_index_read_begin");
10206
10207 ut_a(m_prebuilt->trx == thd_to_trx(m_user_thd));
10208 ut_ad(key_len != 0 || find_flag != HA_READ_KEY_EXACT);
10209
10210 ha_statistic_increment(&System_status_var::ha_read_key_count);
10211
10212 dict_index_t *index = m_prebuilt->index;
10213
10214 if (index == nullptr || index->is_corrupted()) {
10215 m_prebuilt->index_usable = false;
10216 return HA_ERR_CRASHED;
10217 }
10218
10219 if (!m_prebuilt->index_usable) {
10220 return index->is_corrupted() ? HA_ERR_INDEX_CORRUPT
10221 : HA_ERR_TABLE_DEF_CHANGED;
10222 }
10223
10224 if (index->type & DICT_FTS) {
10225 return HA_ERR_KEY_NOT_FOUND;
10226 }
10227
10228 /* For R-Tree index, we will always place the page lock to
10229 pages being searched */
10230 if (dict_index_is_spatial(index)) {
10231 ++m_prebuilt->trx->will_lock;
10232 }
10233
10234 /* Note that if the index for which the search template is built is not
10235 necessarily m_prebuilt->index, but can also be the clustered index */
10236
10237 if (m_prebuilt->sql_stat_start && !can_reuse_mysql_template()) {
10238 build_template(false);
10239 }
10240
10241 #if defined(UNIV_DEBUG) && !defined(UNIV_DEBUG_VALGRIND)
10242 /* valgrind complains about some of uninitialized bytes. skip it for now. */
10243 if (m_prebuilt->sql_stat_start && can_reuse_mysql_template()) {
10244 /* confirm mysql_template contents are same */
10245 const auto n_template_save = m_prebuilt->n_template;
10246 mysql_row_templ_t *mysql_template_save = m_prebuilt->mysql_template;
10247 m_prebuilt->mysql_template = nullptr;
10248 build_template(false);
10249 ut_a(m_prebuilt->n_template == n_template_save);
10250 ut_a(!memcmp(m_prebuilt->mysql_template, mysql_template_save,
10251 m_prebuilt->n_template * sizeof(mysql_row_templ_t)));
10252 ut::free(m_prebuilt->mysql_template);
10253 m_prebuilt->mysql_template = mysql_template_save;
10254 }
10255 #endif /* UNIV_DEBUG && !UNIV_DEBUG_VALGRIND */
10256
10257 if (key_ptr != nullptr) {
10258 /* Convert the search key value to InnoDB format into
10259 m_prebuilt->search_tuple */
10260
10261 row_sel_convert_mysql_key_to_innobase(
10262 m_prebuilt->search_tuple, m_prebuilt->srch_key_val1,
10263 m_prebuilt->srch_key_val_len, index, key_ptr, key_len);
10264
10265 assert(m_prebuilt->search_tuple->n_fields > 0);
10266 } else {
10267 /* We position the cursor to the last or the first entry
10268 in the index */
10269
10270 dtuple_set_n_fields(m_prebuilt->search_tuple, 0);
10271 }
10272
10273 ut_ad(m_prebuilt->m_mysql_handler == this);
10274 m_prebuilt->m_stop_tuple_found = false;
10275 if (end_range != nullptr && m_prebuilt->is_reading_range()) {
10276 row_sel_convert_mysql_key_to_innobase(
10277 m_prebuilt->m_stop_tuple, m_prebuilt->srch_key_val2,
10278 m_prebuilt->srch_key_val_len, index, end_range->key, end_range->length);
10279 } else {
10280 dtuple_set_n_fields(m_prebuilt->m_stop_tuple, 0);
10281 }
10282
10283 page_cur_mode_t mode = convert_search_mode_to_innobase(find_flag);
10284
10285 ulint match_mode = 0;
10286
10287 if (find_flag == HA_READ_KEY_EXACT) {
10288 match_mode = ROW_SEL_EXACT;
10289
10290 } else if (find_flag == HA_READ_PREFIX_LAST) {
10291 match_mode = ROW_SEL_EXACT_PREFIX;
10292 }
10293
10294 m_last_match_mode = (uint)match_mode;
10295
10296 dberr_t ret;
10297
10298 if (mode != PAGE_CUR_UNSUPP) {
10299 ret = innobase_srv_conc_enter_innodb(m_prebuilt);
10300
10301 if (ret != DB_SUCCESS) {
10302 return convert_error_code_to_mysql(ret, m_prebuilt->table->flags,
10303 m_user_thd);
10304 }
10305
10306 if (!m_prebuilt->table->is_intrinsic()) {
10307 if (TrxInInnoDB::is_aborted(m_prebuilt->trx)) {
10308 innobase_rollback(ht, m_user_thd, false);
10309
10310 return convert_error_code_to_mysql(DB_FORCED_ABORT, 0, m_user_thd);
10311 }
10312
10313 m_prebuilt->ins_sel_stmt = thd_is_ins_sel_stmt(m_user_thd);
10314
10315 ret = row_search_mvcc(buf, mode, m_prebuilt, match_mode, 0);
10316
10317 } else {
10318 m_prebuilt->session = thd_to_innodb_session(m_user_thd);
10319
10320 ret = row_search_no_mvcc(buf, mode, m_prebuilt, match_mode, 0);
10321 }
10322
10323 innobase_srv_conc_exit_innodb(m_prebuilt);
10324 } else {
10325 ret = DB_UNSUPPORTED;
10326 }
10327
10328 DBUG_EXECUTE_IF("ib_select_query_failure", ret = DB_ERROR;);
10329
10330 int error;
10331
10332 switch (ret) {
10333 case DB_SUCCESS:
10334 error = 0;
10335 if (m_prebuilt->table->is_system_table) {
10336 srv_stats.n_system_rows_read.add(
10337 thd_get_thread_id(m_prebuilt->trx->mysql_thd), 1);
10338 } else {
10339 srv_stats.n_rows_read.add(thd_get_thread_id(m_prebuilt->trx->mysql_thd),
10340 1);
10341 }
10342 break;
10343
10344 case DB_RECORD_NOT_FOUND:
10345 error = HA_ERR_KEY_NOT_FOUND;
10346 break;
10347
10348 case DB_END_OF_INDEX:
10349 error = HA_ERR_KEY_NOT_FOUND;
10350 break;
10351
10352 case DB_TABLESPACE_DELETED:
10353 ib_senderrf(m_prebuilt->trx->mysql_thd, IB_LOG_LEVEL_ERROR,
10354 ER_TABLESPACE_DISCARDED, table->s->table_name.str);
10355
10356 error = HA_ERR_NO_SUCH_TABLE;
10357 break;
10358
10359 case DB_TABLESPACE_NOT_FOUND:
10360
10361 ib_senderrf(m_prebuilt->trx->mysql_thd, IB_LOG_LEVEL_ERROR,
10362 ER_TABLESPACE_MISSING, table->s->table_name.str);
10363
10364 error = HA_ERR_TABLESPACE_MISSING;
10365 break;
10366
10367 default:
10368 error = convert_error_code_to_mysql(ret, m_prebuilt->table->flags,
10369 m_user_thd);
10370
10371 break;
10372 }
10373
10374 return error;
10375 }
10376
10377 /** The following functions works like index_read, but it find the last
10378 row with the current key value or prefix.
10379 @return 0, HA_ERR_KEY_NOT_FOUND, or an error code */
10380
10381 int ha_innobase::index_read_last(
10382 uchar *buf, /*!< out: fetched row */
10383 const uchar *key_ptr, /*!< in: key value, or a prefix of a full
10384 key value */
10385 uint key_len) /*!< in: length of the key val or prefix
10386 in bytes */
10387 {
10388 return (index_read(buf, key_ptr, key_len, HA_READ_PREFIX_LAST));
10389 }
10390
10391 /** Get the index for a handle. Does not change active index.
10392 @return NULL or index instance. */
10393
10394 dict_index_t *ha_innobase::innobase_get_index(
10395 uint keynr) /*!< in: use this index; MAX_KEY means always
10396 clustered index, even if it was internally
10397 generated by InnoDB */
10398 {
10399 KEY *key;
10400 dict_index_t *index;
10401
10402 DBUG_TRACE;
10403
10404 if (keynr != MAX_KEY && table->s->keys > 0) {
10405 key = table->key_info + keynr;
10406
10407 index = innobase_index_lookup(m_share, keynr);
10408
10409 if (index != nullptr) {
10410 ut_a(ut_strcmp(index->name, key->name) == 0);
10411 } else {
10412 /* Can't find index with keynr in the translation
10413 table. Only print message if the index translation
10414 table exists */
10415 if (m_share->idx_trans_tbl.index_mapping != nullptr) {
10416 log_errlog(WARNING_LEVEL, ER_INNODB_FAILED_TO_FIND_IDX_WITH_KEY_NO,
10417 key ? key->name : "NULL", keynr,
10418 m_prebuilt->table->name.m_name);
10419 }
10420
10421 index = dict_table_get_index_on_name(m_prebuilt->table, key->name);
10422 }
10423 } else {
10424 key = nullptr;
10425 index = m_prebuilt->table->first_index();
10426 }
10427
10428 if (index == nullptr) {
10429 log_errlog(ERROR_LEVEL, ER_INNODB_FAILED_TO_FIND_IDX_FROM_DICT_CACHE, keynr,
10430 key ? key->name : "NULL", m_prebuilt->table->name.m_name);
10431 }
10432
10433 return index;
10434 }
10435
10436 /** Changes the active index of a handle.
10437 @return 0 or error code */
10438 int ha_innobase::change_active_index(
10439 uint keynr) /*!< in: use this index; MAX_KEY means always clustered
10440 index, even if it was internally generated by
10441 InnoDB */
10442 {
10443 DBUG_TRACE;
10444
10445 ut_ad(m_user_thd == ha_thd());
10446 ut_a(m_prebuilt->trx == thd_to_trx(m_user_thd));
10447
10448 TrxInInnoDB trx_in_innodb(m_prebuilt->trx);
10449
10450 if (!m_prebuilt->table->is_intrinsic() && trx_in_innodb.is_aborted()) {
10451 innobase_rollback(ht, m_user_thd, false);
10452
10453 return convert_error_code_to_mysql(DB_FORCED_ABORT, 0, m_user_thd);
10454 }
10455
10456 active_index = keynr;
10457
10458 m_prebuilt->index = innobase_get_index(keynr);
10459
10460 if (m_prebuilt->index == nullptr) {
10461 log_errlog(WARNING_LEVEL, ER_INNODB_ACTIVE_INDEX_CHANGE_FAILED, keynr);
10462 m_prebuilt->index_usable = false;
10463 return 1;
10464 }
10465
10466 m_prebuilt->index_usable = m_prebuilt->index->is_usable(m_prebuilt->trx);
10467
10468 if (!m_prebuilt->index_usable) {
10469 if (m_prebuilt->index->is_corrupted()) {
10470 char table_name[MAX_FULL_NAME_LEN + 1];
10471
10472 innobase_format_name(table_name, sizeof table_name,
10473 m_prebuilt->index->table->name.m_name);
10474
10475 if (m_prebuilt->index->is_clustered()) {
10476 ut_ad(m_prebuilt->table->is_corrupted());
10477 push_warning_printf(m_user_thd, Sql_condition::SL_WARNING,
10478 HA_ERR_TABLE_CORRUPT,
10479 "InnoDB: Table %s is corrupted.", table_name);
10480 return HA_ERR_TABLE_CORRUPT;
10481 } else {
10482 push_warning_printf(m_user_thd, Sql_condition::SL_WARNING,
10483 HA_ERR_INDEX_CORRUPT,
10484 "InnoDB: Index %s for table %s is"
10485 " marked as corrupted",
10486 m_prebuilt->index->name(), table_name);
10487 my_error(ER_INDEX_CORRUPT, MYF(0), m_prebuilt->index->name());
10488 return HA_ERR_INDEX_CORRUPT;
10489 }
10490 } else {
10491 push_warning_printf(m_user_thd, Sql_condition::SL_WARNING,
10492 HA_ERR_TABLE_DEF_CHANGED,
10493 "InnoDB: insufficient history for index %u", keynr);
10494 }
10495
10496 /* The caller seems to ignore this. Thus, we must check
10497 this again in row_search_for_mysql(). */
10498 return HA_ERR_TABLE_DEF_CHANGED;
10499 }
10500
10501 ut_a(m_prebuilt->search_tuple != nullptr);
10502 ut_a(m_prebuilt->m_stop_tuple != nullptr);
10503
10504 /* Initialization of search_tuple is not needed for FT index
10505 since FT search returns rank only. In addition engine should
10506 be able to retrieve FTS_DOC_ID column value if necessary. */
10507 if ((m_prebuilt->index->type & DICT_FTS)) {
10508 if (table->fts_doc_id_field &&
10509 bitmap_is_set(table->read_set,
10510 table->fts_doc_id_field->field_index()) &&
10511 m_prebuilt->read_just_key) {
10512 m_prebuilt->fts_doc_id_in_read_set = true;
10513 }
10514 } else {
10515 m_prebuilt->init_search_tuples_types();
10516
10517 /* If it's FTS query and FTS_DOC_ID exists FTS_DOC_ID field is
10518 always added to read_set. */
10519 m_prebuilt->fts_doc_id_in_read_set =
10520 (m_prebuilt->read_just_key && table->fts_doc_id_field &&
10521 m_prebuilt->in_fts_query);
10522 }
10523
10524 /* MySQL changes the active index for a handle also during some
10525 queries, for example SELECT MAX(a), SUM(a) first retrieves the MAX()
10526 and then calculates the sum. Previously we played safe and used
10527 the flag ROW_MYSQL_WHOLE_ROW below, but that caused unnecessary
10528 copying. Starting from MySQL-4.1 we use a more efficient flag here. */
10529
10530 build_template(false);
10531
10532 return 0;
10533 }
10534
10535 /** Reads the next or previous row from a cursor, which must have previously
10536 been positioned using index_read.
10537 @return 0, HA_ERR_END_OF_FILE, or error number */
10538
10539 int ha_innobase::general_fetch(
10540 uchar *buf, /*!< in/out: buffer for next row in MySQL
10541 format */
10542 uint direction, /*!< in: ROW_SEL_NEXT or ROW_SEL_PREV */
10543 uint match_mode) /*!< in: 0, ROW_SEL_EXACT, or
10544 ROW_SEL_EXACT_PREFIX */
10545 {
10546 DBUG_TRACE;
10547
10548 const trx_t *trx = m_prebuilt->trx;
10549
10550 ut_ad(trx == thd_to_trx(m_user_thd));
10551
10552 bool intrinsic = m_prebuilt->table->is_intrinsic();
10553
10554 if (!intrinsic && TrxInInnoDB::is_aborted(trx)) {
10555 innobase_rollback(ht, m_user_thd, false);
10556
10557 return convert_error_code_to_mysql(DB_FORCED_ABORT, 0, m_user_thd);
10558 }
10559
10560 auto ret = innobase_srv_conc_enter_innodb(m_prebuilt);
10561
10562 if (ret != DB_SUCCESS) {
10563 return convert_error_code_to_mysql(DB_FORCED_ABORT, 0, m_user_thd);
10564 }
10565
10566 if (!intrinsic) {
10567 ret = row_search_mvcc(buf, PAGE_CUR_UNSUPP, m_prebuilt, match_mode,
10568 direction);
10569
10570 } else {
10571 ret = row_search_no_mvcc(buf, PAGE_CUR_UNSUPP, m_prebuilt, match_mode,
10572 direction);
10573 }
10574
10575 innobase_srv_conc_exit_innodb(m_prebuilt);
10576
10577 int error;
10578
10579 switch (ret) {
10580 case DB_SUCCESS:
10581 error = 0;
10582 if (m_prebuilt->table->is_system_table) {
10583 srv_stats.n_system_rows_read.add(
10584 thd_get_thread_id(m_prebuilt->trx->mysql_thd), 1);
10585 } else {
10586 srv_stats.n_rows_read.add(thd_get_thread_id(m_prebuilt->trx->mysql_thd),
10587 1);
10588 }
10589 break;
10590 case DB_RECORD_NOT_FOUND:
10591 error = HA_ERR_END_OF_FILE;
10592 break;
10593 case DB_END_OF_INDEX:
10594 error = HA_ERR_END_OF_FILE;
10595 break;
10596 case DB_TABLESPACE_DELETED:
10597 ib_senderrf(trx->mysql_thd, IB_LOG_LEVEL_ERROR, ER_TABLESPACE_DISCARDED,
10598 table->s->table_name.str);
10599
10600 error = HA_ERR_NO_SUCH_TABLE;
10601 break;
10602 case DB_TABLESPACE_NOT_FOUND:
10603
10604 ib_senderrf(trx->mysql_thd, IB_LOG_LEVEL_ERROR, ER_TABLESPACE_MISSING,
10605 table->s->table_name.str);
10606
10607 error = HA_ERR_TABLESPACE_MISSING;
10608 break;
10609 default:
10610 error = convert_error_code_to_mysql(ret, m_prebuilt->table->flags,
10611 m_user_thd);
10612
10613 break;
10614 }
10615
10616 return error;
10617 }
10618
10619 /** Reads the next row from a cursor, which must have previously been
10620 positioned using index_read.
10621 @return 0, HA_ERR_END_OF_FILE, or error number */
10622
10623 int ha_innobase::index_next(uchar *buf) /*!< in/out: buffer for next row in
10624 MySQL format */
10625 {
10626 ha_statistic_increment(&System_status_var::ha_read_next_count);
10627
10628 return (general_fetch(buf, ROW_SEL_NEXT, 0));
10629 }
10630
10631 /** Reads the next row matching to the key value given as the parameter.
10632 @return 0, HA_ERR_END_OF_FILE, or error number */
10633
10634 int ha_innobase::index_next_same(uchar *buf, /*!< in/out: buffer for the row */
10635 const uchar *, /*!< in: key value */
10636 uint) /*!< in: key value length */
10637 {
10638 ha_statistic_increment(&System_status_var::ha_read_next_count);
10639
10640 return (general_fetch(buf, ROW_SEL_NEXT, m_last_match_mode));
10641 }
10642
10643 /** Reads the previous row from a cursor, which must have previously been
10644 positioned using index_read.
10645 @return 0, HA_ERR_END_OF_FILE, or error number */
10646
10647 int ha_innobase::index_prev(
10648 uchar *buf) /*!< in/out: buffer for previous row in MySQL format */
10649 {
10650 ha_statistic_increment(&System_status_var::ha_read_prev_count);
10651
10652 return (general_fetch(buf, ROW_SEL_PREV, 0));
10653 }
10654
10655 /** Positions a cursor on the first record in an index and reads the
10656 corresponding row to buf.
10657 @return 0, HA_ERR_END_OF_FILE, or error code */
10658
10659 int ha_innobase::index_first(uchar *buf) /*!< in/out: buffer for the row */
10660 {
10661 DBUG_TRACE;
10662
10663 ha_statistic_increment(&System_status_var::ha_read_first_count);
10664
10665 int error = index_read(buf, nullptr, 0, HA_READ_AFTER_KEY);
10666
10667 /* MySQL does not seem to allow this to return HA_ERR_KEY_NOT_FOUND */
10668
10669 if (error == HA_ERR_KEY_NOT_FOUND) {
10670 error = HA_ERR_END_OF_FILE;
10671 }
10672
10673 return error;
10674 }
10675
10676 /** Positions a cursor on the last record in an index and reads the
10677 corresponding row to buf.
10678 @return 0, HA_ERR_END_OF_FILE, or error code */
10679
10680 int ha_innobase::index_last(uchar *buf) /*!< in/out: buffer for the row */
10681 {
10682 DBUG_TRACE;
10683
10684 ha_statistic_increment(&System_status_var::ha_read_last_count);
10685
10686 int error = index_read(buf, nullptr, 0, HA_READ_BEFORE_KEY);
10687
10688 /* MySQL does not seem to allow this to return HA_ERR_KEY_NOT_FOUND */
10689
10690 if (error == HA_ERR_KEY_NOT_FOUND) {
10691 error = HA_ERR_END_OF_FILE;
10692 }
10693
10694 return error;
10695 }
10696
10697 int ha_innobase::sample_init(void *&scan_ctx, double sampling_percentage,
10698 int sampling_seed,
10699 enum_sampling_method sampling_method,
10700 const bool tablesample) {
10701 ut_ad(table_share->is_missing_primary_key() ==
10702 (bool)m_prebuilt->clust_index_was_generated);
10703
10704 ut_ad(sampling_percentage >= 0.0);
10705 ut_ad(sampling_percentage <= 100.0);
10706 ut_ad(sampling_method == enum_sampling_method::SYSTEM);
10707
10708 if (sampling_percentage <= 0.0 || sampling_percentage > 100.0 ||
10709 sampling_method != enum_sampling_method::SYSTEM) {
10710 return 0;
10711 }
10712
10713 if (dict_table_is_discarded(m_prebuilt->table)) {
10714 ib_senderrf(ha_thd(), IB_LOG_LEVEL_ERROR, ER_TABLESPACE_DISCARDED,
10715 m_prebuilt->table->name.m_name);
10716
10717 return HA_ERR_NO_SUCH_TABLE;
10718 }
10719
10720 int err = change_active_index(table_share->primary_key);
10721
10722 if (err != 0) {
10723 return err;
10724 }
10725
10726 trx_t *trx{nullptr};
10727
10728 if (tablesample) {
10729 update_thd();
10730
10731 trx = m_prebuilt->trx;
10732 trx_start_if_not_started_xa(trx, false, UT_LOCATION_HERE);
10733
10734 if (trx->isolation_level > TRX_ISO_READ_UNCOMMITTED) {
10735 trx_assign_read_view(trx);
10736 }
10737 }
10738
10739 /* Parallel read is not currently supported for sampling. */
10740 size_t max_threads = Parallel_reader::available_threads(1, false);
10741
10742 if (max_threads == 0) {
10743 return HA_ERR_SAMPLING_INIT_FAILED;
10744 }
10745
10746 Histogram_sampler *sampler = ut::new_withkey<Histogram_sampler>(
10747 UT_NEW_THIS_FILE_PSI_KEY, max_threads, sampling_seed, sampling_percentage,
10748 sampling_method);
10749
10750 if (sampler == nullptr) {
10751 Parallel_reader::release_threads(max_threads);
10752 return HA_ERR_OUT_OF_MEM;
10753 }
10754
10755 scan_ctx = static_cast<void *>(sampler);
10756
10757 auto index = m_prebuilt->table->first_index();
10758
10759 auto success = sampler->init(trx, index, m_prebuilt);
10760
10761 if (!success) {
10762 return (HA_ERR_SAMPLING_INIT_FAILED);
10763 }
10764
10765 dberr_t db_err = sampler->run();
10766
10767 if (db_err != DB_SUCCESS) {
10768 return (convert_error_code_to_mysql(db_err, 0, ha_thd()));
10769 }
10770
10771 return (0);
10772 }
10773
10774 int ha_innobase::sample_next(void *scan_ctx, uchar *buf) {
10775 dberr_t err = DB_SUCCESS;
10776
10777 Histogram_sampler *sampler = static_cast<Histogram_sampler *>(scan_ctx);
10778
10779 sampler->set(buf);
10780
10781 /** Buffer rows one by one */
10782 err = sampler->buffer_next();
10783
10784 if (err == DB_END_OF_INDEX) {
10785 return HA_ERR_END_OF_FILE;
10786 }
10787
10788 return (convert_error_code_to_mysql(err, 0, ha_thd()));
10789 }
10790
10791 int ha_innobase::sample_end(void *scan_ctx) {
10792 Histogram_sampler *sampler = static_cast<Histogram_sampler *>(scan_ctx);
10793
10794 ut::delete_(sampler);
10795
10796 return 0;
10797 }
10798
10799 int ha_innobase::read_range_first(const key_range *start_key,
10800 const key_range *end_key, bool eq_range_arg,
10801 bool sorted) {
10802 auto guard = m_prebuilt->get_is_reading_range_guard();
10803 return handler::read_range_first(start_key, end_key, eq_range_arg, sorted);
10804 }
10805
10806 int ha_innobase::read_range_next() {
10807 auto guard = m_prebuilt->get_is_reading_range_guard();
10808 return (handler::read_range_next());
10809 }
10810
10811 /** Initialize a table scan.
10812 @param[in] scan whether this is a second call to rnd_init()
10813 without rnd_end() in between
10814 @return 0 or error number */
10815 int ha_innobase::rnd_init(bool scan) {
10816 DBUG_TRACE;
10817 assert(table_share->is_missing_primary_key() ==
10818 (bool)m_prebuilt->clust_index_was_generated);
10819
10820 int err = change_active_index(table_share->primary_key);
10821
10822 /* Don't use semi-consistent read in random row reads (by position).
10823 This means we must disable semi_consistent_read if scan is false */
10824
10825 if (!scan) {
10826 m_prebuilt->row_read_type = ROW_READ_WITH_LOCKS;
10827 }
10828
10829 m_start_of_scan = true;
10830 return err;
10831 }
10832
10833 /** Ends a table scan.
10834 @return 0 or error number */
10835
10836 int ha_innobase::rnd_end(void) { return (index_end()); }
10837
10838 /** Reads the next row in a table scan (also used to read the FIRST row
10839 in a table scan).
10840 @return 0, HA_ERR_END_OF_FILE, or error number */
10841
10842 int ha_innobase::rnd_next(uchar *buf) /*!< in/out: returns the row in this
10843 buffer, in MySQL format */
10844 {
10845 int error;
10846
10847 DBUG_TRACE;
10848
10849 if (m_user_thd->transaction_rollback_request) return HA_ERR_GENERIC;
10850
10851 ha_statistic_increment(&System_status_var::ha_read_rnd_next_count);
10852
10853 if (m_start_of_scan) {
10854 error = index_first(buf);
10855
10856 if (error == HA_ERR_KEY_NOT_FOUND) {
10857 error = HA_ERR_END_OF_FILE;
10858 }
10859
10860 m_start_of_scan = false;
10861 } else {
10862 error = general_fetch(buf, ROW_SEL_NEXT, 0);
10863 }
10864
10865 return error;
10866 }
10867
10868 /** Fetches a row from the table based on a row reference.
10869 @return 0, HA_ERR_KEY_NOT_FOUND, or error code */
10870
10871 int ha_innobase::rnd_pos(
10872 uchar *buf, /*!< in/out: buffer for the row */
10873 uchar *pos) /*!< in: primary key value of the row in the
10874 MySQL format, or the row id if the clustered
10875 index was internally generated by InnoDB; the
10876 length of data in pos has to be ref_length */
10877 {
10878 DBUG_TRACE;
10879 DBUG_DUMP("key", pos, ref_length);
10880
10881 ha_statistic_increment(&System_status_var::ha_read_rnd_count);
10882
10883 ut_a(m_prebuilt->trx == thd_to_trx(ha_thd()));
10884
10885 /* Note that we assume the length of the row reference is fixed
10886 for the table, and it is == ref_length */
10887
10888 int error = index_read(buf, pos, ref_length, HA_READ_KEY_EXACT);
10889
10890 if (error != 0) {
10891 DBUG_PRINT("error", ("Got error: %d", error));
10892 } else {
10893 m_start_of_scan = false;
10894 }
10895
10896 return error;
10897 }
10898
10899 /** Initialize FT index scan
10900 @return 0 or error number */
10901
10902 int ha_innobase::ft_init() {
10903 DBUG_TRACE;
10904
10905 trx_t *trx = check_trx_exists(ha_thd());
10906
10907 /* FTS queries are not treated as autocommit non-locking selects.
10908 This is because the FTS implementation can acquire locks behind
10909 the scenes. This has not been verified but it is safer to treat
10910 them as regular read only transactions for now. */
10911
10912 if (!trx_is_started(trx)) {
10913 ++trx->will_lock;
10914 }
10915
10916 return rnd_init(false);
10917 }
10918
10919 /** Initialize FT index scan
10920 @return FT_INFO structure if successful or NULL */
10921
10922 FT_INFO *ha_innobase::ft_init_ext(uint flags, /* in: */
10923 uint keynr, /* in: */
10924 String *key) /* in: */
10925 {
10926 NEW_FT_INFO *fts_hdl = nullptr;
10927 dict_index_t *index;
10928 fts_result_t *result;
10929 char buf_tmp[8192];
10930 ulint buf_tmp_used;
10931 uint num_errors;
10932 ulint query_len = key->length();
10933 const CHARSET_INFO *char_set = key->charset();
10934 const char *query = key->ptr();
10935
10936 if (fts_enable_diag_print) {
10937 {
10938 ib::info out(ER_IB_MSG_1220);
10939 out << "keynr=" << keynr << ", '";
10940 out.write(key->ptr(), key->length());
10941 }
10942
10943 if (flags & FT_BOOL) {
10944 ib::info(ER_IB_MSG_562) << "BOOL search";
10945 } else {
10946 ib::info(ER_IB_MSG_563) << "NL search";
10947 }
10948 }
10949
10950 /* FIXME: utf32 and utf16 are not compatible with some
10951 string function used. So to convert them to uft8 before
10952 we proceed. */
10953 if (strcmp(char_set->csname, "utf32") == 0 ||
10954 strcmp(char_set->csname, "utf16") == 0) {
10955 buf_tmp_used = innobase_convert_string(
10956 buf_tmp, sizeof(buf_tmp) - 1, &my_charset_utf8mb3_general_ci, query,
10957 query_len, (CHARSET_INFO *)char_set, &num_errors);
10958
10959 buf_tmp[buf_tmp_used] = 0;
10960 query = buf_tmp;
10961 query_len = buf_tmp_used;
10962 }
10963
10964 trx_t *trx = m_prebuilt->trx;
10965
10966 TrxInInnoDB trx_in_innodb(trx);
10967
10968 if (trx_in_innodb.is_aborted()) {
10969 innobase_rollback(ht, m_user_thd, false);
10970
10971 int err;
10972 err = convert_error_code_to_mysql(DB_FORCED_ABORT, 0, m_user_thd);
10973
10974 my_error(err, MYF(0));
10975
10976 return (nullptr);
10977 }
10978
10979 /* FTS queries are not treated as autocommit non-locking selects.
10980 This is because the FTS implementation can acquire locks behind
10981 the scenes. This has not been verified but it is safer to treat
10982 them as regular read only transactions for now. */
10983
10984 if (!trx_is_started(trx)) {
10985 ++trx->will_lock;
10986 }
10987
10988 dict_table_t *ft_table = m_prebuilt->table;
10989
10990 /* Table does not have an FTS index */
10991 if (!ft_table->fts || ib_vector_is_empty(ft_table->fts->indexes)) {
10992 my_error(ER_TABLE_HAS_NO_FT, MYF(0));
10993 return (nullptr);
10994 }
10995
10996 /* If tablespace is discarded, we should return here */
10997 if (dict_table_is_discarded(ft_table)) {
10998 my_error(ER_NO_SUCH_TABLE, MYF(0), table->s->db.str,
10999 table->s->table_name.str);
11000 return (nullptr);
11001 }
11002
11003 if (keynr == NO_SUCH_KEY) {
11004 /* FIXME: Investigate the NO_SUCH_KEY usage */
11005 index = reinterpret_cast<dict_index_t *>(
11006 ib_vector_getp(ft_table->fts->indexes, 0));
11007 } else {
11008 index = innobase_get_index(keynr);
11009 }
11010
11011 if (index == nullptr || index->type != DICT_FTS) {
11012 my_error(ER_TABLE_HAS_NO_FT, MYF(0));
11013 return (nullptr);
11014 }
11015
11016 if (!(ft_table->fts->fts_status & ADDED_TABLE_SYNCED)) {
11017 fts_init_index(ft_table, false);
11018
11019 ft_table->fts->fts_status |= ADDED_TABLE_SYNCED;
11020 }
11021
11022 const byte *q = reinterpret_cast<const byte *>(const_cast<char *>(query));
11023
11024 dberr_t error = fts_query(trx, index, flags, q, query_len, &result,
11025 m_prebuilt->m_fts_limit);
11026
11027 if (error != DB_SUCCESS) {
11028 my_error(convert_error_code_to_mysql(error, 0, nullptr), MYF(0));
11029 return (nullptr);
11030 }
11031
11032 /* Allocate FTS handler, and instantiate it before return */
11033 fts_hdl = reinterpret_cast<NEW_FT_INFO *>(
11034 my_malloc(PSI_INSTRUMENT_ME, sizeof(NEW_FT_INFO), MYF(0)));
11035
11036 fts_hdl->please = const_cast<_ft_vft *>(&ft_vft_result);
11037 fts_hdl->could_you = const_cast<_ft_vft_ext *>(&ft_vft_ext_result);
11038 fts_hdl->ft_prebuilt = m_prebuilt;
11039 fts_hdl->ft_result = result;
11040
11041 /* FIXME: Re-evaluate the condition when Bug 14469540 is resolved */
11042 m_prebuilt->in_fts_query = true;
11043
11044 return (reinterpret_cast<FT_INFO *>(fts_hdl));
11045 }
11046
11047 /** Initialize FT index scan
11048 @return FT_INFO structure if successful or NULL */
11049
11050 FT_INFO *ha_innobase::ft_init_ext_with_hints(uint keynr, /* in: key num */
11051 String *key, /* in: key */
11052 Ft_hints *hints) /* in: hints */
11053 {
11054 /* TODO Implement function properly working with FT hint. */
11055 if (hints->get_flags() & FT_NO_RANKING) {
11056 m_prebuilt->m_fts_limit = hints->get_limit();
11057 } else {
11058 m_prebuilt->m_fts_limit = ULONG_UNDEFINED;
11059 }
11060
11061 return (ft_init_ext(hints->get_flags(), keynr, key));
11062 }
11063
11064 /** Set up search tuple for a query through FTS_DOC_ID_INDEX on
11065 supplied Doc ID. This is used by MySQL to retrieve the documents
11066 once the search result (Doc IDs) is available */
11067 static void innobase_fts_create_doc_id_key(
11068 dtuple_t *tuple, /* in/out: m_prebuilt->search_tuple */
11069 const dict_index_t *index, /* in: index (FTS_DOC_ID_INDEX) */
11070 doc_id_t *doc_id) /* in/out: doc id to search, value
11071 could be changed to storage format
11072 used for search. */
11073 {
11074 doc_id_t temp_doc_id;
11075 dfield_t *dfield = dtuple_get_nth_field(tuple, 0);
11076
11077 ut_a(dict_index_get_n_unique(index) == 1);
11078
11079 dtuple_set_n_fields(tuple, index->n_fields);
11080 dict_index_copy_types(tuple, index, index->n_fields);
11081
11082 #ifdef UNIV_DEBUG
11083 /* The unique Doc ID field should be an eight-bytes integer */
11084 dict_field_t *field = index->get_field(0);
11085 ut_a(field->col->mtype == DATA_INT);
11086 ut_ad(sizeof(*doc_id) == field->fixed_len);
11087 ut_ad(!strcmp(index->name, FTS_DOC_ID_INDEX_NAME));
11088 #endif /* UNIV_DEBUG */
11089
11090 /* Convert to storage byte order */
11091 mach_write_to_8(reinterpret_cast<byte *>(&temp_doc_id), *doc_id);
11092 *doc_id = temp_doc_id;
11093 dfield_set_data(dfield, doc_id, sizeof(*doc_id));
11094
11095 dtuple_set_n_fields_cmp(tuple, 1);
11096
11097 for (ulint i = 1; i < index->n_fields; i++) {
11098 dfield = dtuple_get_nth_field(tuple, i);
11099 dfield_set_null(dfield);
11100 }
11101 }
11102
11103 /** Fetch next result from the FT result set
11104 @return error code */
11105
11106 int ha_innobase::ft_read(uchar *buf) /*!< in/out: buf contain result row */
11107 {
11108 TrxInInnoDB trx_in_innodb(m_prebuilt->trx);
11109
11110 if (trx_in_innodb.is_aborted()) {
11111 innobase_rollback(ht, m_user_thd, false);
11112
11113 return (convert_error_code_to_mysql(DB_FORCED_ABORT, 0, m_user_thd));
11114 }
11115
11116 row_prebuilt_t *ft_prebuilt;
11117
11118 ft_prebuilt = reinterpret_cast<NEW_FT_INFO *>(ft_handler)->ft_prebuilt;
11119
11120 ut_a(ft_prebuilt == m_prebuilt);
11121
11122 fts_result_t *result;
11123
11124 result = reinterpret_cast<NEW_FT_INFO *>(ft_handler)->ft_result;
11125
11126 if (result->current == nullptr) {
11127 /* This is the case where the FTS query did not
11128 contain and matching documents. */
11129 if (result->rankings_by_id != nullptr) {
11130 /* Now that we have the complete result, we
11131 need to sort the document ids on their rank
11132 calculation. */
11133
11134 fts_query_sort_result_on_rank(result);
11135
11136 result->current =
11137 const_cast<ib_rbt_node_t *>(rbt_first(result->rankings_by_rank));
11138 } else {
11139 ut_a(result->current == nullptr);
11140 }
11141 } else {
11142 result->current = const_cast<ib_rbt_node_t *>(
11143 rbt_next(result->rankings_by_rank, result->current));
11144 }
11145
11146 next_record:
11147
11148 if (result->current != nullptr) {
11149 doc_id_t search_doc_id;
11150 dtuple_t *tuple = m_prebuilt->search_tuple;
11151
11152 /* If we only need information from result we can return
11153 without fetching the table row */
11154 if (ft_prebuilt->read_just_key) {
11155 const fts_ranking_t *ranking = rbt_value(fts_ranking_t, result->current);
11156 m_prebuilt->fts_doc_id = ranking->doc_id;
11157 if (m_prebuilt->fts_doc_id_in_read_set) {
11158 innobase_fts_store_docid(table, ranking->doc_id);
11159 }
11160 return (0);
11161 }
11162
11163 dict_index_t *index;
11164
11165 index = m_prebuilt->table->fts_doc_id_index;
11166
11167 /* Must find the index */
11168 ut_a(index != nullptr);
11169
11170 /* Switch to the FTS doc id index */
11171 m_prebuilt->index = index;
11172
11173 fts_ranking_t *ranking = rbt_value(fts_ranking_t, result->current);
11174
11175 search_doc_id = ranking->doc_id;
11176
11177 /* We pass a pointer of search_doc_id because it will be
11178 converted to storage byte order used in the search
11179 tuple. */
11180 innobase_fts_create_doc_id_key(tuple, index, &search_doc_id);
11181
11182 auto ret = innobase_srv_conc_enter_innodb(m_prebuilt);
11183
11184 if (ret == DB_SUCCESS) {
11185 ret = row_search_for_mysql((byte *)buf, PAGE_CUR_GE, m_prebuilt,
11186 ROW_SEL_EXACT, 0);
11187 innobase_srv_conc_exit_innodb(m_prebuilt);
11188 }
11189
11190 int error;
11191
11192 switch (ret) {
11193 case DB_SUCCESS:
11194 error = 0;
11195 break;
11196 case DB_RECORD_NOT_FOUND:
11197 result->current = const_cast<ib_rbt_node_t *>(
11198 rbt_next(result->rankings_by_rank, result->current));
11199
11200 if (!result->current) {
11201 /* exhaust the result set, should return
11202 HA_ERR_END_OF_FILE just like
11203 ha_innobase::general_fetch() and/or
11204 ha_innobase::index_first() etc. */
11205 error = HA_ERR_END_OF_FILE;
11206 } else {
11207 goto next_record;
11208 }
11209 break;
11210 case DB_END_OF_INDEX:
11211 error = HA_ERR_END_OF_FILE;
11212 break;
11213 case DB_TABLESPACE_DELETED:
11214
11215 ib_senderrf(m_prebuilt->trx->mysql_thd, IB_LOG_LEVEL_ERROR,
11216 ER_TABLESPACE_DISCARDED, table->s->table_name.str);
11217
11218 error = HA_ERR_NO_SUCH_TABLE;
11219 break;
11220 case DB_TABLESPACE_NOT_FOUND:
11221
11222 ib_senderrf(m_prebuilt->trx->mysql_thd, IB_LOG_LEVEL_ERROR,
11223 ER_TABLESPACE_MISSING, table->s->table_name.str);
11224
11225 error = HA_ERR_TABLESPACE_MISSING;
11226 break;
11227 default:
11228 error = convert_error_code_to_mysql(ret, 0, m_user_thd);
11229
11230 break;
11231 }
11232
11233 return (error);
11234 }
11235
11236 return (HA_ERR_END_OF_FILE);
11237 }
11238
11239 /*************************************************************************
11240 */
11241
11242 void ha_innobase::ft_end() {
11243 ib::info(ER_IB_MSG_564) << "ft_end()";
11244
11245 rnd_end();
11246 }
11247
11248 /**
11249 Store a reference to the current row to 'ref' field of the handle.
11250 Note that in the case where we have generated the clustered index for the
11251 table, the function parameter is illogical: we MUST ASSUME that 'record'
11252 is the current 'position' of the handle, because if row ref is actually
11253 the row id internally generated in InnoDB, then 'record' does not contain
11254 it. We just guess that the row id must be for the record where the handle
11255 was positioned the last time.
11256 @param[in] record row in MySQL format */
11257 void ha_innobase::position(const uchar *record) {
11258 uint len;
11259
11260 DBUG_TRACE;
11261 assert(m_prebuilt->trx == thd_to_trx(ha_thd()));
11262 assert(table_share->is_missing_primary_key() ==
11263 (bool)m_prebuilt->clust_index_was_generated);
11264
11265 if (m_prebuilt->clust_index_was_generated) {
11266 /* No primary key was defined for the table and we
11267 generated the clustered index from row id: the
11268 row reference will be the row id, not any key value
11269 that MySQL knows of */
11270
11271 len = DATA_ROW_ID_LEN;
11272
11273 memcpy(ref, m_prebuilt->row_id, len);
11274 } else {
11275 /* Copy primary key as the row reference */
11276 KEY *key_info = table->key_info + table_share->primary_key;
11277 key_copy(ref, (uchar *)record, key_info, key_info->key_length);
11278 len = key_info->key_length;
11279 }
11280
11281 /* We assume that the 'ref' value len is always fixed for the same
11282 table. */
11283
11284 if (len != ref_length) {
11285 log_errlog(ERROR_LEVEL, ER_INNODB_DIFF_IN_REF_LEN, (ulong)len,
11286 (ulong)ref_length);
11287 }
11288 }
11289
11290 /** Set up base columns for virtual column
11291 @param[in] table the InnoDB table
11292 @param[in] field MySQL field
11293 @param[in,out] v_col virtual column to be set up */
11294 void innodb_base_col_setup(dict_table_t *table, const Field *field,
11295 dict_v_col_t *v_col) {
11296 int n = 0;
11297
11298 for (uint i = 0; i < field->table->s->fields; ++i) {
11299 const Field *base_field = field->table->field[i];
11300
11301 if (!base_field->is_virtual_gcol() &&
11302 bitmap_is_set(&field->gcol_info->base_columns_map, i)) {
11303 ulint z;
11304
11305 for (z = 0; z < table->n_cols; z++) {
11306 const char *name = table->get_col_name(z);
11307 if (!innobase_strcasecmp(name, base_field->field_name)) {
11308 break;
11309 }
11310 }
11311
11312 ut_ad(z != table->n_cols);
11313
11314 v_col->base_col[n] = table->get_col(z);
11315 ut_ad(v_col->base_col[n]->ind == z);
11316 n++;
11317 }
11318 }
11319 }
11320
11321 /** Set up base columns for stored column
11322 @param[in] table InnoDB table
11323 @param[in] field MySQL field
11324 @param[in,out] s_col stored column */
11325 void innodb_base_col_setup_for_stored(const dict_table_t *table,
11326 const Field *field, dict_s_col_t *s_col) {
11327 ulint n = 0;
11328
11329 for (uint i = 0; i < field->table->s->fields; ++i) {
11330 const Field *base_field = field->table->field[i];
11331
11332 if (!innobase_is_v_fld(base_field) &&
11333 bitmap_is_set(&field->gcol_info->base_columns_map, i)) {
11334 ulint z;
11335 for (z = 0; z < table->n_cols; z++) {
11336 const char *name = table->get_col_name(z);
11337 if (!innobase_strcasecmp(name, base_field->field_name)) {
11338 break;
11339 }
11340 }
11341
11342 ut_ad(z != table->n_cols);
11343
11344 s_col->base_col[n] = table->get_col(z);
11345 n++;
11346
11347 if (n == s_col->num_base) {
11348 break;
11349 }
11350 }
11351 }
11352 }
11353
11354 /** Create a table definition to an InnoDB database.
11355 @param[in] dd_table dd::Table or nullptr for intrinsic table
11356 @param[in] old_part_table dd::Table from an old partition for partitioned
11357 table, NULL otherwise.
11358 @return HA_* level error */
11359 [[nodiscard]] inline int create_table_info_t::create_table_def(
11360 const dd::Table *dd_table, const dd::Table *old_part_table) {
11361 dict_table_t *table;
11362 ulint n_cols;
11363 dberr_t err;
11364 ulint col_type;
11365 ulint col_len;
11366 ulint i;
11367 ulint j = 0;
11368 ulint doc_id_col = 0;
11369 bool has_doc_id_col = false;
11370 mem_heap_t *heap;
11371 ulint num_v = 0;
11372 ulint num_m_v = 0;
11373 space_id_t space_id = 0;
11374 dd::Object_id dd_space_id = dd::INVALID_OBJECT_ID;
11375 ulint actual_n_cols;
11376
11377 uint32_t i_c = 0;
11378 uint32_t c_c = 0;
11379 uint32_t t_c = 0;
11380 uint32_t c_r_v = 0;
11381
11382 DBUG_TRACE;
11383 DBUG_PRINT("enter", ("table_name: %s", m_table_name));
11384
11385 assert(m_trx->mysql_thd == m_thd);
11386
11387 bool part_table_with_instant_cols =
11388 (old_part_table != nullptr && dd_table_has_row_versions(*old_part_table));
11389
11390 /* MySQL does the name length check. But we do additional check
11391 on the name length here */
11392 const size_t table_name_len = strlen(m_table_name);
11393 if (table_name_len > MAX_FULL_NAME_LEN) {
11394 push_warning_printf(m_thd, Sql_condition::SL_WARNING, ER_WRONG_TABLE_NAME,
11395 "InnoDB: Table Name or Database Name is too long");
11396
11397 return HA_ERR_WRONG_TABLE_NAME;
11398 }
11399
11400 /* Make sure that the table name is acceptable. */
11401 if (m_table_name[table_name_len - 1] == '/') {
11402 push_warning_printf(m_thd, Sql_condition::SL_WARNING, ER_WRONG_TABLE_NAME,
11403 "InnoDB: Table name is empty");
11404
11405 return HA_ERR_WRONG_TABLE_NAME;
11406 }
11407
11408 fts_aux_table_t aux_table;
11409 if (fts_is_aux_table_name(&aux_table, m_table_name, strlen(m_table_name))) {
11410 push_warning_printf(
11411 m_thd, Sql_condition::SL_WARNING, ER_WRONG_TABLE_NAME,
11412 "Invalid table name. `%s` has the form of an FTS auxiliary table name",
11413 m_table_name);
11414 return HA_ERR_WRONG_TABLE_NAME;
11415 }
11416
11417 n_cols = m_form->s->fields;
11418
11419 /* Find out any virtual column */
11420 for (i = 0; i < n_cols; i++) {
11421 Field *field = m_form->field[i];
11422
11423 ut_ad(!(!innobase_is_v_fld(field) && innobase_is_multi_value_fld(field)));
11424
11425 if (innobase_is_v_fld(field)) {
11426 num_v++;
11427
11428 if (innobase_is_multi_value_fld(field)) {
11429 num_m_v++;
11430 }
11431 }
11432 }
11433
11434 /* Check whether there already exists a FTS_DOC_ID column */
11435 if (create_table_check_doc_id_col(m_trx->mysql_thd, m_form, &doc_id_col)) {
11436 /* Raise error if the Doc ID column is of wrong type or name */
11437 if (doc_id_col == ULINT_UNDEFINED) {
11438 err = DB_ERROR;
11439 goto error_ret;
11440 } else {
11441 has_doc_id_col = true;
11442 }
11443 }
11444
11445 /* For single-table tablespaces, we pass 0 as the space id, and then
11446 determine the actual space id when the tablespace is created. */
11447 if (DICT_TF_HAS_SHARED_SPACE(m_flags)) {
11448 ut_ad(m_tablespace != nullptr && m_tablespace[0] != '\0');
11449
11450 space_id = fil_space_get_id_by_name(m_tablespace);
11451 dd_space_id = (dd_table != nullptr ? dd_table->tablespace_id()
11452 : dd::INVALID_OBJECT_ID);
11453 }
11454
11455 /* Adjust the number of columns for the FTS hidden field */
11456 actual_n_cols = n_cols;
11457 if (m_flags2 & (DICT_TF2_FTS | DICT_TF2_FTS_ADD_DOC_ID) && !has_doc_id_col) {
11458 actual_n_cols += 1;
11459 }
11460
11461 if (part_table_with_instant_cols) {
11462 dd_table_get_column_counters(*old_part_table, i_c, c_c, t_c, c_r_v);
11463 }
11464
11465 table = dict_mem_table_create(m_table_name, space_id, actual_n_cols, num_v,
11466 num_m_v, m_flags, m_flags2, t_c - c_c);
11467
11468 /* Set dd tablespace id */
11469 table->dd_space_id = dd_space_id;
11470
11471 /* Set the hidden doc_id column. */
11472 if (m_flags2 & (DICT_TF2_FTS | DICT_TF2_FTS_ADD_DOC_ID)) {
11473 table->fts->doc_col = has_doc_id_col ? doc_id_col : n_cols - num_v;
11474 }
11475
11476 if (DICT_TF_HAS_DATA_DIR(m_flags)) {
11477 ut_a(strlen(m_remote_path) != 0);
11478
11479 table->data_dir_path = mem_heap_strdup(table->heap, m_remote_path);
11480
11481 } else {
11482 table->data_dir_path = nullptr;
11483 }
11484
11485 if (DICT_TF_HAS_SHARED_SPACE(m_flags)) {
11486 ut_ad(strlen(m_tablespace));
11487 table->tablespace = mem_heap_strdup(table->heap, m_tablespace);
11488 } else {
11489 table->tablespace = nullptr;
11490 }
11491
11492 /* Initialize row version and column counts for new table */
11493 if (!part_table_with_instant_cols) {
11494 table->current_row_version = 0;
11495 table->initial_col_count = n_cols - num_v;
11496 table->current_col_count = table->initial_col_count;
11497 table->total_col_count = table->initial_col_count;
11498 } else {
11499 /* This is a new partition getting created. We need to inherit INSTANT
11500 instant metadata from old partition table */
11501 table->initial_col_count = i_c;
11502 table->current_col_count = c_c;
11503 table->total_col_count = t_c;
11504 table->current_row_version = c_r_v;
11505 table->discard_after_ddl = true;
11506
11507 #ifdef UNIV_DEBUG
11508 /* Get and set current row version for table */
11509 uint32_t v = 0;
11510 for (auto col : old_part_table->columns()) {
11511 if (dd_column_is_dropped(col)) {
11512 uint32_t value = dd_column_get_version_dropped(col);
11513 v = std::max(v, value);
11514 continue;
11515 }
11516
11517 if (dd_column_is_added(col)) {
11518 uint32_t value = dd_column_get_version_added(col);
11519 v = std::max(v, value);
11520 continue;
11521 }
11522 }
11523 ut_ad(dd_is_valid_row_version(v));
11524 ut_ad(table->current_row_version == v);
11525 #endif
11526 }
11527
11528 heap = mem_heap_create(1000, UT_LOCATION_HERE);
11529
11530 for (i = 0; i < n_cols; i++) {
11531 ulint nulls_allowed;
11532 ulint unsigned_type;
11533 ulint binary_type;
11534 ulint long_true_varchar;
11535 ulint charset_no;
11536 ulint is_virtual;
11537 ulint is_multi_val;
11538 bool is_stored = false;
11539
11540 Field *field = m_form->field[i];
11541
11542 /* Generate a unique column name by pre-pending table-name for
11543 intrinsic tables. For other tables (including normal
11544 temporary) column names are unique. If not, MySQL layer will
11545 block such statement.
11546 This is work-around fix till Optimizer can handle this issue
11547 (probably 5.7.4+). */
11548 char field_name[MAX_FULL_NAME_LEN + 2 + 10];
11549
11550 if (table->is_intrinsic() && field->table) {
11551 snprintf(field_name, sizeof(field_name), "%s_%s_" ULINTPF,
11552 field->table->alias, field->field_name, i);
11553
11554 } else {
11555 snprintf(field_name, sizeof(field_name), "%s", field->field_name);
11556 }
11557
11558 col_type = get_innobase_type_from_mysql_type(&unsigned_type, field);
11559
11560 if (!col_type) {
11561 push_warning_printf(m_thd, Sql_condition::SL_WARNING,
11562 ER_CANT_CREATE_TABLE,
11563 "Error creating table '%s' with"
11564 " column '%s'. Please check its"
11565 " column type and try to re-create"
11566 " the table with an appropriate"
11567 " column type.",
11568 table->name.m_name, field->field_name);
11569 goto err_col;
11570 }
11571
11572 nulls_allowed = field->is_nullable() ? 0 : DATA_NOT_NULL;
11573 binary_type = field->binary() ? DATA_BINARY_TYPE : 0;
11574
11575 charset_no = 0;
11576
11577 if (dtype_is_string_type(col_type)) {
11578 charset_no = (ulint)field->charset()->number;
11579
11580 DBUG_EXECUTE_IF("simulate_max_char_col",
11581 charset_no = MAX_CHAR_COLL_NUM + 1;);
11582
11583 if (charset_no > MAX_CHAR_COLL_NUM) {
11584 /* in data0type.h we assume that the
11585 number fits in one byte in prtype */
11586 push_warning_printf(m_thd, Sql_condition::SL_WARNING,
11587 ER_CANT_CREATE_TABLE,
11588 "In InnoDB, charset-collation codes"
11589 " must be below 256."
11590 " Unsupported code %lu.",
11591 (ulong)charset_no);
11592 mem_heap_free(heap);
11593 dict_mem_table_free(table);
11594
11595 return ER_CANT_CREATE_TABLE;
11596 }
11597 }
11598
11599 col_len = field->pack_length();
11600
11601 /* The MySQL pack length contains 1 or 2 bytes length field
11602 for a true VARCHAR. Let us subtract that, so that the InnoDB
11603 column length in the InnoDB data dictionary is the real
11604 maximum byte length of the actual data. */
11605
11606 long_true_varchar = 0;
11607
11608 if (field->type() == MYSQL_TYPE_VARCHAR) {
11609 col_len -= field->get_length_bytes();
11610
11611 if (field->get_length_bytes() == 2) {
11612 long_true_varchar = DATA_LONG_TRUE_VARCHAR;
11613 }
11614 }
11615
11616 if (col_type == DATA_POINT) {
11617 col_len = DATA_POINT_LEN;
11618 }
11619
11620 is_virtual = (innobase_is_v_fld(field)) ? DATA_VIRTUAL : 0;
11621 is_stored = innobase_is_s_fld(field);
11622
11623 is_multi_val = innobase_is_multi_value_fld(field) ? DATA_MULTI_VALUE : 0;
11624
11625 /* First check whether the column to be added has a
11626 system reserved name. */
11627 if (dict_col_name_is_reserved(field_name)) {
11628 my_error(ER_WRONG_COLUMN_NAME, MYF(0), field_name);
11629 err_col:
11630 dict_mem_table_free(table);
11631 mem_heap_free(heap);
11632
11633 err = DB_ERROR;
11634 goto error_ret;
11635 }
11636
11637 if (!is_virtual) {
11638 uint32_t v_added = UINT32_UNDEFINED;
11639 uint32_t v_dropped = UINT32_UNDEFINED;
11640 uint32_t phy_pos = UINT32_UNDEFINED;
11641
11642 if (part_table_with_instant_cols) {
11643 const dd::Column *old_part_col =
11644 dd_find_column(old_part_table, field_name);
11645 ut_ad(old_part_col != nullptr);
11646
11647 /* Get version added */
11648 v_added = dd_column_get_version_added(old_part_col);
11649
11650 /* This columns must be present */
11651 ut_ad(!dd_column_is_dropped(old_part_col));
11652
11653 /* Get physical pos */
11654 const char *s = dd_column_key_strings[DD_INSTANT_PHYSICAL_POS];
11655 ut_ad(old_part_col->se_private_data().exists(s));
11656 old_part_col->se_private_data().get(s, &phy_pos);
11657 }
11658
11659 dict_mem_table_add_col(
11660 table, heap, field_name, col_type,
11661 dtype_form_prtype((ulint)field->type() | nulls_allowed |
11662 unsigned_type | binary_type | long_true_varchar,
11663 charset_no),
11664 col_len, !field->is_hidden_by_system(), phy_pos, v_added, v_dropped);
11665
11666 if (dd_is_valid_row_version(v_added)) {
11667 mem_heap_t *instant_heap = mem_heap_create(1000, UT_LOCATION_HERE);
11668 const dd::Column *old_part_col =
11669 dd_find_column(old_part_table, field_name);
11670 ut_ad(old_part_col != nullptr);
11671 dict_col_t *col = table->get_col(table->n_def - 1);
11672 dd_parse_default_value(old_part_col->se_private_data(), col, heap);
11673 mem_heap_free(instant_heap);
11674 }
11675 } else {
11676 if (is_multi_val) {
11677 col_len = field->key_length();
11678 }
11679 dict_mem_table_add_v_col(
11680 table, heap, field_name, col_type,
11681 dtype_form_prtype((ulint)field->type() | nulls_allowed |
11682 unsigned_type | binary_type |
11683 long_true_varchar | is_virtual | is_multi_val,
11684 charset_no),
11685 col_len, i, field->gcol_info->non_virtual_base_columns(),
11686 !field->is_hidden_by_system());
11687 }
11688
11689 if (is_stored) {
11690 ut_ad(!is_virtual);
11691 /* Added stored column in m_s_cols list. */
11692 dict_mem_table_add_s_col(table,
11693 field->gcol_info->non_virtual_base_columns());
11694 }
11695 }
11696
11697 if (num_v) {
11698 for (i = 0; i < n_cols; i++) {
11699 dict_v_col_t *v_col;
11700
11701 Field *field = m_form->field[i];
11702
11703 if (!innobase_is_v_fld(field)) {
11704 continue;
11705 }
11706
11707 v_col = dict_table_get_nth_v_col(table, j);
11708
11709 j++;
11710
11711 innodb_base_col_setup(table, field, v_col);
11712 }
11713 }
11714
11715 /** Fill base columns for the stored column present in the list. */
11716 if (table->s_cols && table->s_cols->size()) {
11717 for (i = 0; i < n_cols; i++) {
11718 Field *field = m_form->field[i];
11719
11720 if (!innobase_is_s_fld(field)) {
11721 continue;
11722 }
11723
11724 dict_s_col_list::iterator it;
11725 for (it = table->s_cols->begin(); it != table->s_cols->end(); ++it) {
11726 dict_s_col_t s_col = *it;
11727
11728 if (s_col.s_pos == i) {
11729 innodb_base_col_setup_for_stored(table, field, &s_col);
11730 break;
11731 }
11732 }
11733 }
11734 }
11735
11736 /* Add the FTS doc_id hidden column. */
11737 if (m_flags2 & (DICT_TF2_FTS | DICT_TF2_FTS_ADD_DOC_ID) && !has_doc_id_col) {
11738 fts_add_doc_id_column(table, heap);
11739 }
11740
11741 if (table->is_temporary()) {
11742 if (m_create_info->compress.length > 0) {
11743 push_warning_printf(m_thd, Sql_condition::SL_WARNING, HA_ERR_UNSUPPORTED,
11744 "InnoDB: Compression not supported for "
11745 "temporary tables");
11746
11747 err = DB_UNSUPPORTED;
11748 dict_mem_table_free(table);
11749 } else if (m_create_info->encrypt_type.length > 0 &&
11750 !Encryption::is_none(m_create_info->encrypt_type.str)) {
11751 my_error(ER_TABLESPACE_CANNOT_ENCRYPT, MYF(0));
11752 err = DB_UNSUPPORTED;
11753 dict_mem_table_free(table);
11754 } else {
11755 /* Get a new table ID */
11756 dict_table_assign_new_id(table);
11757
11758 /* Create temp tablespace if configured. */
11759 err = dict_build_tablespace_for_table(table, m_create_info, m_trx);
11760
11761 if (err == DB_SUCCESS) {
11762 /* Temp-table are maintained in memory and so
11763 can_be_evicted is false. */
11764 mem_heap_t *temp_table_heap;
11765
11766 temp_table_heap = mem_heap_create(256, UT_LOCATION_HERE);
11767
11768 /* For intrinsic table (given that they are
11769 not shared beyond session scope), add
11770 it to session specific THD structure
11771 instead of adding it to dictionary cache. */
11772 if (table->is_intrinsic()) {
11773 add_table_to_thread_cache(table, temp_table_heap, m_thd);
11774
11775 } else {
11776 dict_table_add_system_columns(table, temp_table_heap);
11777
11778 dict_sys_mutex_enter();
11779 dict_table_add_to_cache(table, false);
11780 dict_sys_mutex_exit();
11781 }
11782
11783 DBUG_EXECUTE_IF("ib_ddl_crash_during_create2", DBUG_SUICIDE(););
11784
11785 mem_heap_free(temp_table_heap);
11786 } else {
11787 dict_mem_table_free(table);
11788 }
11789 }
11790
11791 } else {
11792 const char *algorithm = m_create_info->compress.str;
11793
11794 err = DB_SUCCESS;
11795
11796 if (!(m_flags2 & DICT_TF2_USE_FILE_PER_TABLE) &&
11797 m_create_info->compress.length > 0 &&
11798 !Compression::is_none(algorithm)) {
11799 push_warning_printf(m_thd, Sql_condition::SL_WARNING, HA_ERR_UNSUPPORTED,
11800 "InnoDB: Compression not supported for "
11801 "shared tablespaces");
11802
11803 algorithm = nullptr;
11804
11805 err = DB_UNSUPPORTED;
11806 dict_mem_table_free(table);
11807
11808 } else if (Compression::validate(algorithm) != DB_SUCCESS ||
11809 m_form->s->row_type == ROW_TYPE_COMPRESSED ||
11810 m_create_info->key_block_size > 0) {
11811 algorithm = nullptr;
11812 }
11813
11814 if (err == DB_SUCCESS) {
11815 const char *encrypt = m_create_info->encrypt_type.str;
11816 if (!Encryption::is_none(encrypt) &&
11817 (m_flags2 & DICT_TF2_USE_FILE_PER_TABLE)) {
11818 /* Set the encryption flag. */
11819 byte *master_key = nullptr;
11820 uint32_t master_key_id;
11821
11822 /* Check if keyring is ready. */
11823 Encryption::get_master_key(&master_key_id, &master_key);
11824
11825 if (master_key == nullptr) {
11826 my_error(ER_CANNOT_FIND_KEY_IN_KEYRING, MYF(0));
11827 err = DB_UNSUPPORTED;
11828 dict_mem_table_free(table);
11829 } else {
11830 my_free(master_key);
11831 /* This flag will be used for setting
11832 encryption flag for file-per-table
11833 tablespace. */
11834 DICT_TF2_FLAG_SET(table, DICT_TF2_ENCRYPTION_FILE_PER_TABLE);
11835 }
11836 }
11837 }
11838
11839 if (err == DB_SUCCESS) {
11840 err = row_create_table_for_mysql(table, algorithm, m_create_info, m_trx,
11841 heap);
11842
11843 if (err == DB_IO_NO_PUNCH_HOLE_FS) {
11844 ut_ad(!dict_table_in_shared_tablespace(table));
11845 my_error(ER_INNODB_COMPRESSION_FAILURE, MYF(0),
11846 "Punch hole not supported by the filesystem or the tablespace "
11847 "page size is not large enough.");
11848 }
11849
11850 if (err == DB_SUCCESS && part_table_with_instant_cols) {
11851 /* Set phy_pos for system cols */
11852
11853 auto fn = [&](uint32_t sys_col, const char *name) {
11854 uint32_t phy_pos = UINT32_UNDEFINED;
11855 dict_col_t *col = table->get_sys_col(sys_col);
11856 const dd::Column *old_part_col = dd_find_column(old_part_table, name);
11857 if (old_part_col == nullptr) {
11858 /* If PK exists, DB_ROW_ID won't be part of table definition. */
11859 ut_ad(strcmp(name, "DB_ROW_ID") == 0);
11860 return;
11861 }
11862
11863 const char *s = dd_column_key_strings[DD_INSTANT_PHYSICAL_POS];
11864 ut_ad(old_part_col->se_private_data().exists(s));
11865 old_part_col->se_private_data().get(s, &phy_pos);
11866 col->set_phy_pos(phy_pos);
11867 };
11868
11869 fn(DATA_ROW_ID, "DB_ROW_ID");
11870 fn(DATA_TRX_ID, "DB_TRX_ID");
11871 fn(DATA_ROLL_PTR, "DB_ROLL_PTR");
11872
11873 /* Add INSTANT DROP columns metadata */
11874 IF_DEBUG(uint32_t row_version = 0;)
11875 fill_dict_dropped_columns(old_part_table, table,
11876 IF_DEBUG(row_version, ) heap);
11877 ut_ad(row_version <= table->current_row_version);
11878 }
11879 }
11880
11881 DBUG_EXECUTE_IF("ib_crash_during_create_for_encryption", DBUG_SUICIDE(););
11882 }
11883
11884 mem_heap_free(heap);
11885
11886 DBUG_EXECUTE_IF("ib_create_err_tablespace_exist",
11887 err = DB_TABLESPACE_EXISTS;);
11888
11889 if (err == DB_DUPLICATE_KEY || err == DB_TABLESPACE_EXISTS) {
11890 char display_name[FN_REFLEN];
11891 char *buf_end =
11892 innobase_convert_identifier(display_name, sizeof(display_name) - 1,
11893 m_table_name, strlen(m_table_name), m_thd);
11894
11895 *buf_end = '\0';
11896
11897 my_error(
11898 err == DB_DUPLICATE_KEY ? ER_TABLE_EXISTS_ERROR : ER_TABLESPACE_EXISTS,
11899 MYF(0), display_name);
11900
11901 if (err == DB_DUPLICATE_KEY) {
11902 /* 'this' may not be ready for get_dup_key(), see same
11903 error tweaking in rename_table(). */
11904 err = DB_ERROR;
11905 }
11906 }
11907
11908 if (err == DB_SUCCESS && (m_flags2 & DICT_TF2_FTS)) {
11909 dict_sys_mutex_enter();
11910 fts_optimize_add_table(table);
11911 dict_sys_mutex_exit();
11912 }
11913
11914 if (err == DB_SUCCESS) {
11915 m_table = table;
11916 }
11917
11918 error_ret:
11919 return convert_error_code_to_mysql(err, m_flags, m_thd);
11920 }
11921
11922 template <typename Index>
11923 const dd::Index *get_my_dd_index(const Index *index);
11924
11925 template <>
11926 const dd::Index *get_my_dd_index<dd::Index>(const dd::Index *dd_index) {
11927 return dd_index;
11928 }
11929
11930 template <>
11931 const dd::Index *get_my_dd_index<dd::Partition_index>(
11932 const dd::Partition_index *dd_index) {
11933 return (dd_index != nullptr) ? &dd_index->index() : nullptr;
11934 }
11935
11936 /** Creates an index in an InnoDB database. */
11937 inline int create_index(
11938 trx_t *trx, /*!< in: InnoDB transaction handle */
11939 const TABLE *form, /*!< in: information on table
11940 columns and indexes */
11941 uint32_t flags, /*!< in: InnoDB table flags */
11942 const char *table_name, /*!< in: table name */
11943 uint key_num, /*!< in: index number */
11944 const dd::Table *dd_table) /*!< in: dd::Table for the table*/
11945 {
11946 dict_index_t *index;
11947 int error;
11948 const KEY *key;
11949 ulint ind_type;
11950 ulint *field_lengths;
11951 uint32_t srid = 0;
11952 bool has_srid = false;
11953 bool multi_val_idx = false;
11954
11955 DBUG_TRACE;
11956
11957 key = form->key_info + key_num;
11958
11959 /* Assert that "GEN_CLUST_INDEX" cannot be used as non-primary index */
11960 ut_a(innobase_strcasecmp(key->name, innobase_index_reserve_name) != 0);
11961
11962 if (key->key_length == 0) {
11963 my_error(ER_WRONG_KEY_COLUMN, MYF(0), key->key_part->field->field_name);
11964 return ER_WRONG_KEY_COLUMN;
11965 }
11966 ind_type = 0;
11967 if (key->flags & HA_SPATIAL) {
11968 ind_type = DICT_SPATIAL;
11969 } else if (key->flags & HA_FULLTEXT) {
11970 ind_type = DICT_FTS;
11971 }
11972
11973 if (ind_type == DICT_SPATIAL) {
11974 ulint dd_index_num = key_num + ((form->s->primary_key == MAX_KEY) ? 1 : 0);
11975
11976 const auto *dd_index_auto = dd_table->indexes()[dd_index_num];
11977
11978 const dd::Index *dd_index = get_my_dd_index(dd_index_auto);
11979 ut_ad(dd_index->name() == key->name);
11980
11981 size_t geom_col_idx;
11982 for (geom_col_idx = 0; geom_col_idx < dd_index->elements().size();
11983 ++geom_col_idx) {
11984 if (!dd_index->elements()[geom_col_idx]->column().is_se_hidden()) break;
11985 }
11986 const dd::Column &col = dd_index->elements()[geom_col_idx]->column();
11987 has_srid = col.srs_id().has_value();
11988 srid = has_srid ? col.srs_id().value() : 0;
11989 }
11990
11991 if (ind_type != 0) {
11992 index = dict_mem_index_create(table_name, key->name, 0, ind_type,
11993 key->user_defined_key_parts);
11994
11995 for (ulint i = 0; i < key->user_defined_key_parts; i++) {
11996 KEY_PART_INFO *key_part = key->key_part + i;
11997
11998 /* We do not support special (Fulltext or Spatial)
11999 index on virtual columns */
12000 if (innobase_is_v_fld(key_part->field)) {
12001 ut_d(ut_error);
12002 ut_o(return HA_ERR_UNSUPPORTED);
12003 }
12004
12005 index->add_field(key_part->field->field_name, 0,
12006 !(key_part->key_part_flag & HA_REVERSE_SORT));
12007 }
12008
12009 if (ind_type == DICT_SPATIAL) {
12010 index->srid_is_valid = has_srid;
12011 index->srid = srid;
12012 index->rtr_srs.reset(fetch_srs(index->srid));
12013 }
12014
12015 return convert_error_code_to_mysql(
12016 row_create_index_for_mysql(index, trx, nullptr, nullptr), flags,
12017 nullptr);
12018 }
12019
12020 ind_type = 0;
12021
12022 if (key_num == form->s->primary_key) {
12023 ind_type |= DICT_CLUSTERED;
12024 }
12025
12026 if (key->flags & HA_NOSAME) {
12027 ind_type |= DICT_UNIQUE;
12028 }
12029
12030 field_lengths = (ulint *)my_malloc(
12031 PSI_INSTRUMENT_ME, key->user_defined_key_parts * sizeof *field_lengths,
12032 MYF(MY_FAE));
12033
12034 /* We pass 0 as the space id, and determine at a lower level the space
12035 id where to store the table */
12036
12037 index = dict_mem_index_create(table_name, key->name, 0, ind_type,
12038 key->user_defined_key_parts);
12039
12040 innodb_session_t *&priv = thd_to_innodb_session(trx->mysql_thd);
12041 dict_table_t *handler = priv->lookup_table_handler(table_name);
12042
12043 if (handler != nullptr) {
12044 /* This setting will enforce SQL NULL == SQL NULL.
12045 For now this is turned-on for intrinsic tables
12046 only but can be turned on for other tables if needed arises. */
12047 index->nulls_equal = (key->flags & HA_NULL_ARE_EQUAL) ? true : false;
12048
12049 /* Disable use of AHI for intrinsic table indexes as AHI
12050 validates the predicated entry using index-id which has to be
12051 system-wide unique that is not the case with indexes of
12052 intrinsic table for performance reason.
12053 Also given the lifetime of these tables and frequent delete
12054 and update AHI would not help on performance front as it does
12055 with normal tables. */
12056 index->disable_ahi = true;
12057 }
12058
12059 for (ulint i = 0; i < key->user_defined_key_parts; i++) {
12060 KEY_PART_INFO *key_part = key->key_part + i;
12061 ulint prefix_len;
12062 ulint col_type;
12063 ulint is_unsigned;
12064
12065 /* (The flag HA_PART_KEY_SEG denotes in MySQL a
12066 column prefix field in an index: we only store a
12067 specified number of first bytes of the column to
12068 the index field.) The flag does not seem to be
12069 properly set by MySQL. Let us fall back on testing
12070 the length of the key part versus the column.
12071 We first reach to the table's column; if the index is on a
12072 prefix, key_part->field is not the table's column (it's a
12073 "fake" field forged in open_table_from_share() with length
12074 equal to the length of the prefix); so we have to go to
12075 form->field. */
12076 Field *field = form->field[key_part->field->field_index()];
12077 if (field == nullptr) ut_error;
12078
12079 const char *field_name = key_part->field->field_name;
12080 if (handler != nullptr && handler->is_intrinsic()) {
12081 ut_ad(!innobase_is_v_fld(key_part->field));
12082 ulint col_no =
12083 dict_col_get_no(handler->get_col(key_part->field->field_index()));
12084 field_name = handler->get_col_name(col_no);
12085 }
12086
12087 col_type = get_innobase_type_from_mysql_type(&is_unsigned, key_part->field);
12088
12089 /* Multi-value prefix index is not supported. */
12090 if (!innobase_is_multi_value_fld(key_part->field) &&
12091 (DATA_LARGE_MTYPE(col_type) ||
12092 (key_part->length < field->pack_length() &&
12093 field->type() != MYSQL_TYPE_VARCHAR) ||
12094 (field->type() == MYSQL_TYPE_VARCHAR &&
12095 key_part->length <
12096 field->pack_length() - field->get_length_bytes()))) {
12097 switch (col_type) {
12098 default:
12099 prefix_len = key_part->length;
12100 break;
12101 case DATA_INT:
12102 case DATA_FLOAT:
12103 case DATA_DOUBLE:
12104 case DATA_DECIMAL:
12105 log_errlog(ERROR_LEVEL, ER_WRONG_TYPE_FOR_COLUMN_PREFIX_IDX_FLD,
12106 table_name, key_part->field->field_name);
12107
12108 prefix_len = 0;
12109 }
12110 } else {
12111 prefix_len = 0;
12112 }
12113
12114 field_lengths[i] = key_part->length;
12115
12116 ut_ad(!(!innobase_is_v_fld(key_part->field) &&
12117 innobase_is_multi_value_fld(key_part->field)));
12118
12119 if (innobase_is_v_fld(key_part->field)) {
12120 index->type |= DICT_VIRTUAL;
12121
12122 if (innobase_is_multi_value_fld(key_part->field)) {
12123 index->type |= DICT_MULTI_VALUE;
12124 }
12125 }
12126
12127 index->add_field(field_name, prefix_len,
12128 !(key_part->key_part_flag & HA_REVERSE_SORT));
12129 }
12130
12131 ut_ad(key->flags & HA_FULLTEXT || !(index->type & DICT_FTS));
12132
12133 multi_val_idx = ((index->type & DICT_MULTI_VALUE) == DICT_MULTI_VALUE);
12134
12135 /* Even though we've defined max_supported_key_part_length, we
12136 still do our own checking using field_lengths to be absolutely
12137 sure we don't create too long indexes. */
12138
12139 error = convert_error_code_to_mysql(
12140 row_create_index_for_mysql(index, trx, field_lengths, handler), flags,
12141 nullptr);
12142
12143 /* For multi-value virtual index, we need to adjust indexed col length */
12144 if (error == 0 && multi_val_idx) {
12145 dict_table_t *new_table = dd_table_open_on_name_in_mem(table_name, false);
12146
12147 dict_index_t *last_index = UT_LIST_GET_LAST(new_table->indexes);
12148 for (unsigned int i = 0; i < last_index->n_fields; i++) {
12149 if (last_index->fields[i].col->is_multi_value() &&
12150 (last_index->fields[i].fixed_len != 0)) {
12151 last_index->fields[i].fixed_len = field_lengths[i];
12152 }
12153 }
12154
12155 dd_table_close(new_table, nullptr, nullptr, false);
12156 }
12157
12158 if (error && handler != nullptr) {
12159 priv->unregister_table_handler(table_name);
12160 }
12161
12162 my_free(field_lengths);
12163
12164 return error;
12165 }
12166
12167 /** Creates an index to an InnoDB table when the user has defined no
12168 primary index. */
12169 inline int create_clustered_index_when_no_primary(
12170 trx_t *trx, /*!< in: InnoDB transaction handle */
12171 uint32_t flags, /*!< in: InnoDB table flags */
12172 const char *table_name) /*!< in: table name */
12173 {
12174 dict_index_t *index;
12175 dberr_t error;
12176
12177 /* We pass 0 as the space id, and determine at a lower level the space
12178 id where to store the table */
12179 index = dict_mem_index_create(table_name, innobase_index_reserve_name, 0,
12180 DICT_CLUSTERED, 0);
12181
12182 innodb_session_t *&priv = thd_to_innodb_session(trx->mysql_thd);
12183
12184 dict_table_t *handler = priv->lookup_table_handler(table_name);
12185
12186 if (handler != nullptr) {
12187 /* Disable use of AHI for intrinsic table indexes as AHI
12188 validates the predicated entry using index-id which has to be
12189 system-wide unique that is not the case with indexes of
12190 intrinsic table for performance reason.
12191 Also given the lifetime of these tables and frequent delete
12192 and update AHI would not help on performance front as it does
12193 with normal tables. */
12194 index->disable_ahi = true;
12195 }
12196
12197 error = row_create_index_for_mysql(index, trx, nullptr, handler);
12198
12199 if (error != DB_SUCCESS && handler != nullptr) {
12200 priv->unregister_table_handler(table_name);
12201 }
12202
12203 return (convert_error_code_to_mysql(error, flags, nullptr));
12204 }
12205
12206 void create_table_info_t::log_error_invalid_location(std::string &msg,
12207 bool ignore) {
12208 if (ignore) {
12209 THD *thd = current_thd;
12210
12211 constexpr char ignored_msg[] =
12212 " The DATA DIRECTORY location will be ignored and the"
12213 " file will be put into the default datadir location.";
12214
12215 msg.append(ignored_msg);
12216 push_warning_printf(thd, Sql_condition::SL_WARNING, ER_WRONG_FILE_NAME,
12217 "%s", msg.c_str());
12218
12219 ib::warn(ER_IB_MSG_INVALID_LOCATION_FOR_TABLE, m_table_name, msg.c_str());
12220 } else {
12221 my_printf_error(ER_WRONG_FILE_NAME, "%s", MYF(0), msg.c_str());
12222
12223 ib::error(ER_IB_MSG_INVALID_LOCATION_FOR_TABLE, m_table_name, msg.c_str());
12224 }
12225 }
12226
12227 bool create_table_info_t::create_option_data_directory_is_valid(bool ignore) {
12228 bool is_valid = true;
12229
12230 ut_ad(m_create_info->data_file_name != nullptr &&
12231 *m_create_info->data_file_name != '\0');
12232
12233 /* Use DATA DIRECTORY only with file-per-table. */
12234 if (!m_use_shared_space && !m_allow_file_per_table) {
12235 push_warning(m_thd, Sql_condition::SL_WARNING, ER_ILLEGAL_HA_CREATE_OPTION,
12236 "InnoDB: DATA DIRECTORY requires"
12237 " innodb_file_per_table.");
12238 is_valid = false;
12239 }
12240
12241 /* Do not use DATA DIRECTORY with TEMPORARY TABLE. */
12242 if (m_create_info->options & HA_LEX_CREATE_TMP_TABLE) {
12243 push_warning(m_thd, Sql_condition::SL_WARNING, ER_ILLEGAL_HA_CREATE_OPTION,
12244 "InnoDB: DATA DIRECTORY cannot be used"
12245 " for TEMPORARY tables.");
12246 is_valid = false;
12247 }
12248
12249 /* We checked previously for a conflicting DATA DIRECTORY mixed
12250 with TABLESPACE in create_option_tablespace_is_valid().
12251 An ALTER TABLE statement might have both if it is being moved.
12252 So if m_tablespace is set, don't check the existing data_file_name. */
12253 if (m_create_info->tablespace != nullptr) {
12254 return (is_valid);
12255 }
12256
12257 #ifndef UNIV_HOTBACKUP
12258 /* Validate the directory location. */
12259 bool suffixed_table_name = !m_partition;
12260 char *filepath = Fil_path::make(m_create_info->data_file_name, m_table_name,
12261 IBD, suffixed_table_name);
12262 size_t dirname_len = dirname_length(filepath);
12263 Fil_path dirpath(filepath, dirname_len, true);
12264
12265 /* Do not allow the file to be created in a unique undo directory. */
12266 if (MySQL_undo_path_is_unique && (MySQL_undo_path.is_same_as(dirpath) ||
12267 MySQL_undo_path.is_ancestor(dirpath))) {
12268 std::string msg(
12269 "The DATA DIRECTORY location cannot be the undo directory.");
12270
12271 log_error_invalid_location(msg, ignore);
12272
12273 is_valid = false;
12274 }
12275
12276 /* Do not allow a file-per-table tablespace in the datadir.
12277 In order to be located in the datadir, one must use a schama name
12278 identical to the datadir directory and the datadir parent must be
12279 used as the DATA DIRECTORY.*/
12280 bool in_datadir = MySQL_datadir_path.is_same_as(dirpath);
12281 if (in_datadir) {
12282 std::string msg("The DATA DIRECTORY location cannot be the datadir.");
12283
12284 log_error_invalid_location(msg, ignore);
12285
12286 is_valid = false;
12287 }
12288
12289 /* Do not allow a datafile outside the known directories. */
12290 bool under_datadir = MySQL_datadir_path.is_ancestor(dirpath);
12291 bool in_known_location =
12292 (in_datadir || under_datadir) ? true : fil_path_is_known(dirpath.path());
12293
12294 if (!in_known_location) {
12295 std::string msg(
12296 "The DATA DIRECTORY location must be in a known directory.");
12297
12298 log_error_invalid_location(msg, ignore);
12299
12300 is_valid = false;
12301 }
12302
12303 ut::free(filepath);
12304 #endif /* UNIV_HOTBACKUP */
12305
12306 return (is_valid);
12307 }
12308
12309 /** Validate the tablespace name provided for a tablespace DDL
12310 @param[in] ts_command tablespace command type
12311 @param[in] name A proposed tablespace name
12312 @return MySQL handler error code like HA_... */
12313 static int validate_tablespace_name(ts_command_type ts_command,
12314 const char *name) {
12315 int err = 0;
12316
12317 /* This prefix is reserved by InnoDB for use in internal tablespace
12318 names. */
12319 const char reserved_space_name_prefix[] = "innodb_";
12320
12321 /* Validation at the SQL layer should already be completed at this
12322 stage. Re-assert that the length is valid. */
12323 if (validate_tablespace_name_length(name)) {
12324 my_printf_error(ER_WRONG_TABLESPACE_NAME,
12325 "InnoDB: Tablespace name `%s` is too long.", MYF(0), name);
12326 return (HA_WRONG_CREATE_OPTION);
12327 }
12328
12329 /* The tablespace name cannot start with `innodb_`. */
12330 if (strlen(name) >= sizeof(reserved_space_name_prefix) - 1 &&
12331 0 == memcmp(name, reserved_space_name_prefix,
12332 sizeof(reserved_space_name_prefix) - 1)) {
12333 /* Use a different message for reserved names */
12334 if (0 == strcmp(name, dict_sys_t::s_file_per_table_name) ||
12335 0 == strcmp(name, dict_sys_t::s_sys_space_name) ||
12336 0 == strcmp(name, dict_sys_t::s_temp_space_name)) {
12337 /* Allow these names if the caller is putting a
12338 table into one of these by CREATE/ALTER TABLE */
12339 if (ts_command != TS_CMD_NOT_DEFINED) {
12340 my_printf_error(ER_WRONG_TABLESPACE_NAME,
12341 "InnoDB: `%s` is a reserved"
12342 " tablespace name.",
12343 MYF(0), name);
12344 err = HA_WRONG_CREATE_OPTION;
12345 }
12346 } else {
12347 /* Allow any undo tablespace to be set active or inactive.
12348 And any undo tablespace can be dropped except the default two
12349 implicit spaces. All other DDL should not work on tablespaces
12350 that start with "innodb_". */
12351 bool allow =
12352 (ts_command == ALTER_UNDO_TABLESPACE ||
12353 (ts_command == DROP_UNDO_TABLESPACE &&
12354 0 != strcmp(name, dict_sys_t::s_default_undo_space_name_1) &&
12355 0 != strcmp(name, dict_sys_t::s_default_undo_space_name_2)));
12356 if (!allow) {
12357 my_printf_error(ER_WRONG_TABLESPACE_NAME,
12358 "InnoDB: Tablespace names starting"
12359 " with `%s` are reserved.",
12360 MYF(0), reserved_space_name_prefix);
12361 err = HA_WRONG_CREATE_OPTION;
12362 }
12363 }
12364 } else if (0 == strcmp(name, dict_sys_t::s_dd_space_name)) {
12365 /* mysql tablespace can't be created or dropped */
12366 if (ts_command == CREATE_TABLESPACE || ts_command == DROP_TABLESPACE) {
12367 my_printf_error(ER_WRONG_TABLESPACE_NAME,
12368 "InnoDB: `mysql` is a reserved"
12369 " tablespace name.",
12370 MYF(0));
12371 err = HA_WRONG_CREATE_OPTION;
12372 }
12373 }
12374
12375 /* The tablespace name cannot contain a '/'. */
12376 if (memchr(name, '/', strlen(name)) != nullptr) {
12377 my_printf_error(ER_WRONG_TABLESPACE_NAME,
12378 "InnoDB: A general tablespace name cannot"
12379 " contain '/'.",
12380 MYF(0));
12381 err = HA_WRONG_CREATE_OPTION;
12382 }
12383
12384 return (err);
12385 }
12386
12387 bool innobase_is_valid_tablespace_name(ts_command_type ts_cmd,
12388 const char *name) {
12389 return (0 == validate_tablespace_name(ts_cmd, name));
12390 }
12391
12392 /** Validate TABLESPACE option.
12393 @return true if valid, false if not. */
12394 bool create_table_info_t::create_option_tablespace_is_valid() {
12395 bool is_temp = m_create_info->options & HA_LEX_CREATE_TMP_TABLE;
12396 bool is_file_per_table = tablespace_is_file_per_table(m_create_info);
12397 bool is_general_space = tablespace_is_general_space(m_create_info);
12398 bool is_temp_space =
12399 (m_create_info->tablespace &&
12400 strcmp(m_create_info->tablespace, dict_sys_t::s_temp_space_name) == 0);
12401
12402 /* Do not allow creation of a temp table
12403 with innodb_file_per_table or innodb_temporary option. */
12404 if (is_temp && (is_file_per_table || is_temp_space)) {
12405 if (THDVAR(m_thd, strict_mode) && is_file_per_table) {
12406 my_printf_error(ER_ILLEGAL_HA_CREATE_OPTION,
12407 "InnoDB: TABLESPACE=%s option"
12408 " is disallowed for temporary tables"
12409 " with INNODB_STRICT_MODE=ON. This option is"
12410 " deprecated and will be removed in a future release",
12411 MYF(0), m_create_info->tablespace);
12412 return false;
12413 }
12414
12415 /* STRICT mode turned off. Proceed with the execution with
12416 a deprecation warning */
12417 push_warning_printf(
12418 m_thd, Sql_condition::SL_WARNING, ER_ILLEGAL_HA_CREATE_OPTION,
12419 "InnoDB: TABLESPACE=%s option is ignored. All temporary tables"
12420 " are created in a session temporary tablespace. This option"
12421 " is deprecated and will be removed in a future release.",
12422 m_create_info->tablespace);
12423 }
12424
12425 /* Check the encryption option validity. */
12426 if (m_create_info->encrypt_type.str != nullptr &&
12427 Encryption::validate(m_create_info->encrypt_type.str) == DB_UNSUPPORTED) {
12428 my_error(ER_INVALID_ENCRYPTION_OPTION, MYF(0));
12429 return false;
12430 }
12431
12432 if (!m_use_shared_space) {
12433 if (!m_use_file_per_table) {
12434 /* System tablespace is being used for table */
12435 if (m_create_info->encrypt_type.str != nullptr &&
12436 !Encryption::is_none(m_create_info->encrypt_type.str)) {
12437 /* Encryption is not allowed for system tablespace. */
12438 my_printf_error(ER_ILLEGAL_HA_CREATE_OPTION,
12439 "InnoDB : ENCRYPTION=Y is not accepted"
12440 " for system tablespace.",
12441 MYF(0));
12442 return false;
12443 }
12444
12445 if (m_create_info->m_implicit_tablespace_autoextend_size > 0) {
12446 /* AUTOEXTEND_SIZE is not allowed for system tablespace. */
12447 my_printf_error(ER_ILLEGAL_HA_CREATE_OPTION,
12448 "InnoDB : AUTOEXTEND_SIZE is not accepted"
12449 " for system tablespace.",
12450 MYF(0));
12451 return false;
12452 }
12453 }
12454
12455 /* Validate autoextend_size attribute value. */
12456 if (m_create_info->m_implicit_tablespace_autoextend_size > 0 &&
12457 validate_autoextend_size_value(
12458 m_create_info->m_implicit_tablespace_autoextend_size) !=
12459 DB_SUCCESS) {
12460 return false;
12461 }
12462 return true;
12463 }
12464
12465 if (m_use_shared_space && !is_general_space) {
12466 /* System tablespace is being used for table */
12467 if (m_create_info->encrypt_type.str != nullptr &&
12468 !Encryption::is_none(m_create_info->encrypt_type.str)) {
12469 /* Encryption is not allowed for system tablespace. */
12470 my_printf_error(ER_ILLEGAL_HA_CREATE_OPTION,
12471 "InnoDB : ENCRYPTION=Y is not accepted"
12472 " for system tablespace.",
12473 MYF(0));
12474 return false;
12475 }
12476
12477 if (m_create_info->m_implicit_tablespace_autoextend_size_change &&
12478 m_create_info->m_implicit_tablespace_autoextend_size > 0) {
12479 /* AUTOEXTEND_SIZE is not allowed for system tablespace. */
12480 my_printf_error(ER_ILLEGAL_HA_CREATE_OPTION,
12481 "InnoDB : AUTOEXTEND_SIZE is not accepted"
12482 " for system tablespace.",
12483 MYF(0));
12484 return false;
12485 }
12486 }
12487
12488 /* ALTER TABLE ... AUTOEXTEND_SIZE is not allowed if the tablespace is
12489 a general tablespace. */
12490 if (!is_temp && is_general_space && m_use_shared_space) {
12491 if (m_create_info->m_implicit_tablespace_autoextend_size_change &&
12492 m_create_info->m_implicit_tablespace_autoextend_size > 0) {
12493 my_error(ER_INNODB_INCOMPATIBLE_WITH_TABLESPACE, MYF(0),
12494 "AUTOEXTEND_SIZE");
12495 return false;
12496 }
12497 }
12498
12499 /* Validate autoextend_size attribute value. */
12500 if (m_create_info->m_implicit_tablespace_autoextend_size > 0 &&
12501 validate_autoextend_size_value(
12502 m_create_info->m_implicit_tablespace_autoextend_size) != DB_SUCCESS) {
12503 return false;
12504 }
12505
12506 /* Name validation should be ensured from the SQL layer. */
12507 ut_ad(0 == validate_tablespace_name(TS_CMD_NOT_DEFINED,
12508 m_create_info->tablespace));
12509
12510 /* Look up the tablespace name in the fil_system. */
12511 space_id_t space_id = fil_space_get_id_by_name(m_create_info->tablespace);
12512
12513 if (space_id == SPACE_UNKNOWN) {
12514 my_printf_error(ER_TABLESPACE_MISSING,
12515 "InnoDB: A general tablespace named"
12516 " `%s` cannot be found.",
12517 MYF(0), m_create_info->tablespace);
12518 return false;
12519 }
12520
12521 if (fsp_is_undo_tablespace(space_id)) {
12522 my_printf_error(ER_WRONG_TABLESPACE_NAME,
12523 "InnoDB: An undo tablespace cannot contain tables.",
12524 MYF(0));
12525
12526 return false;
12527 }
12528
12529 /* Cannot add a second table to a file-per-table tablespace. */
12530 uint32_t fsp_flags = fil_space_get_flags(space_id);
12531 if (fsp_is_file_per_table(space_id, fsp_flags)) {
12532 my_printf_error(ER_ILLEGAL_HA_CREATE_OPTION,
12533 "InnoDB: Tablespace `%s` is file-per-table so no"
12534 " other table can be added to it.",
12535 MYF(0), m_create_info->tablespace);
12536 return false;
12537 }
12538
12539 bool is_create_table = (thd_sql_command(m_thd) == SQLCOM_CREATE_TABLE);
12540
12541 /* Tables in shared tablespace should not have encryption options */
12542 if (is_shared_tablespace(m_create_info->tablespace)) {
12543 m_create_info->encrypt_type.str = nullptr;
12544 m_create_info->encrypt_type.length = 0;
12545 }
12546
12547 /* If TABLESPACE=innodb_file_per_table this function is not called
12548 since tablespace_is_shared_space() will return false. Any other
12549 tablespace is incompatible with the DATA DIRECTORY phrase.
12550 On any ALTER TABLE that contains a DATA DIRECTORY, MySQL will issue
12551 a warning like "<DATA DIRECTORY> option ignored." The check below is
12552 needed for CREATE TABLE only. ALTER TABLE may be moving remote
12553 file-per-table table to a general tablespace, in which case the
12554 create_info->data_file_name is not null. */
12555 if (is_create_table && m_create_info->data_file_name != nullptr &&
12556 *m_create_info->data_file_name != '\0') {
12557 my_printf_error(ER_ILLEGAL_HA_CREATE_OPTION,
12558 "InnoDB: DATA DIRECTORY cannot be used"
12559 " with a TABLESPACE assignment.",
12560 MYF(0));
12561 return false;
12562 }
12563
12564 /* Temp tables only belong in temp tablespaces. */
12565 if (m_create_info->options & HA_LEX_CREATE_TMP_TABLE) {
12566 if (!FSP_FLAGS_GET_TEMPORARY(fsp_flags)) {
12567 my_printf_error(ER_ILLEGAL_HA_CREATE_OPTION,
12568 "InnoDB: Tablespace `%s` cannot contain"
12569 " TEMPORARY tables.",
12570 MYF(0), m_create_info->tablespace);
12571 return false;
12572 }
12573
12574 /* Restrict Compressed Temporary General tablespaces. */
12575 if (m_create_info->key_block_size ||
12576 m_create_info->row_type == ROW_TYPE_COMPRESSED) {
12577 my_printf_error(ER_ILLEGAL_HA_CREATE_OPTION,
12578 "InnoDB: Temporary tablespace `%s` cannot"
12579 " contain COMPRESSED tables.",
12580 MYF(0), m_create_info->tablespace);
12581 return false;
12582 }
12583 } else if (FSP_FLAGS_GET_TEMPORARY(fsp_flags)) {
12584 my_printf_error(ER_ILLEGAL_HA_CREATE_OPTION,
12585 "InnoDB: Tablespace `%s` can only contain"
12586 " TEMPORARY tables.",
12587 MYF(0), m_create_info->tablespace);
12588 return false;
12589 }
12590
12591 /* Make sure the physical page size of the table matches the
12592 file block size of the tablespace. */
12593 ulint block_size_needed;
12594 bool table_is_compressed;
12595 if (m_create_info->key_block_size) {
12596 block_size_needed = m_create_info->key_block_size * 1024;
12597 table_is_compressed = true;
12598 } else if (m_create_info->row_type == ROW_TYPE_COMPRESSED) {
12599 block_size_needed =
12600 std::min(UNIV_PAGE_SIZE / 2, static_cast<ulint>(UNIV_ZIP_SIZE_MAX));
12601 table_is_compressed = true;
12602 } else {
12603 block_size_needed = UNIV_PAGE_SIZE;
12604 table_is_compressed = false;
12605 }
12606
12607 const page_size_t page_size(fsp_flags);
12608
12609 /* The compression code needs some work in order for a general
12610 tablespace to contain both compressed and non-compressed tables
12611 together in the same tablespace. The problem seems to be that
12612 each page is either compressed or not based on the fsp flags,
12613 which is shared by all tables in that general tablespace. */
12614 if (table_is_compressed && page_size.physical() == UNIV_PAGE_SIZE) {
12615 my_printf_error(ER_ILLEGAL_HA_CREATE_OPTION,
12616 "InnoDB: Tablespace `%s` cannot contain a"
12617 " COMPRESSED table",
12618 MYF(0), m_create_info->tablespace);
12619 return false;
12620 }
12621
12622 if (block_size_needed != page_size.physical()) {
12623 my_printf_error(ER_ILLEGAL_HA_CREATE_OPTION,
12624 "InnoDB: Tablespace `%s` uses block size %zu"
12625 " and cannot contain a table with physical"
12626 " page size " ULINTPF,
12627 MYF(0), m_create_info->tablespace, page_size.physical(),
12628 block_size_needed);
12629 return false;
12630 }
12631
12632 return true;
12633 }
12634
12635 /** Validate the COPMRESSION option.
12636 @return true if valid, false if not. */
12637 bool create_table_info_t::create_option_compression_is_valid() {
12638 dberr_t err;
12639 Compression compression;
12640
12641 if (m_create_info->compress.length == 0) {
12642 return (true);
12643 }
12644
12645 err = Compression::check(m_create_info->compress.str, &compression);
12646
12647 if (err == DB_UNSUPPORTED) {
12648 push_warning_printf(m_thd, Sql_condition::SL_WARNING,
12649 ER_UNSUPPORTED_EXTENSION,
12650 "InnoDB: Unsupported compression algorithm '%s'",
12651 m_create_info->compress.str);
12652 return (false);
12653 }
12654
12655 /* Allow Compression=NONE on any tablespace or row format. */
12656 if (compression.m_type == Compression::NONE) {
12657 return (true);
12658 }
12659
12660 static char intro[] = "InnoDB: Page Compression is not supported";
12661
12662 if (m_create_info->key_block_size != 0 ||
12663 m_create_info->row_type == ROW_TYPE_COMPRESSED) {
12664 push_warning_printf(m_thd, Sql_condition::SL_WARNING,
12665 ER_UNSUPPORTED_EXTENSION,
12666 "%s with row_format=compressed or"
12667 " key_block_size > 0",
12668 intro);
12669 return (false);
12670 }
12671
12672 if (m_create_info->options & HA_LEX_CREATE_TMP_TABLE) {
12673 push_warning_printf(m_thd, Sql_condition::SL_WARNING, HA_ERR_UNSUPPORTED,
12674 "%s for temporary tables", intro);
12675 return (false);
12676 }
12677
12678 if (tablespace_is_general_space(m_create_info)) {
12679 push_warning_printf(m_thd, Sql_condition::SL_WARNING, HA_ERR_UNSUPPORTED,
12680 "%s for shared general tablespaces", intro);
12681 return (false);
12682 }
12683
12684 /* The only non-file-per-table tablespace left is the system space. */
12685 if (!m_use_file_per_table) {
12686 push_warning_printf(m_thd, Sql_condition::SL_WARNING, HA_ERR_UNSUPPORTED,
12687 "%s for the system tablespace", intro);
12688 return (false);
12689 }
12690
12691 return (true);
12692 }
12693
12694 /** Validate the create options. Check that the options KEY_BLOCK_SIZE,
12695 ROW_FORMAT, DATA DIRECTORY, TEMPORARY & TABLESPACE are compatible with
12696 each other and other settings. These CREATE OPTIONS are not validated
12697 here unless innodb_strict_mode is on. With strict mode, this function
12698 will report each problem it finds using a custom message with error
12699 code ER_ILLEGAL_HA_CREATE_OPTION, not its built-in message.
12700 @return NULL if valid, string name of bad option if not. */
12701 const char *create_table_info_t::create_options_are_invalid() {
12702 bool has_key_block_size = (m_create_info->key_block_size != 0);
12703 bool is_temp = m_create_info->options & HA_LEX_CREATE_TMP_TABLE;
12704
12705 const char *ret = nullptr;
12706 enum row_type row_format = m_create_info->row_type;
12707
12708 ut_ad(m_thd != nullptr);
12709 ut_ad(m_create_info != nullptr);
12710
12711 /* The TABLESPACE designation on a CREATE TABLE is not subject to
12712 non-strict-mode. If it is incorrect or is incompatible with other
12713 options, then we will return an error. Make sure the tablespace exists
12714 and is compatible with this table */
12715 if (!create_option_tablespace_is_valid()) {
12716 return ("TABLESPACE");
12717 }
12718
12719 /* If innodb_strict_mode is not set don't do any more validation.
12720 Also, if this table is being put into a shared general tablespace
12721 we ALWAYS act like strict mode is ON.
12722 Or if caller explicitly asks for skipping strict mode check (if
12723 tablespace is not a shared general tablespace), then skip */
12724 if (!m_use_shared_space && (!(THDVAR(m_thd, strict_mode)) || skip_strict())) {
12725 return (nullptr);
12726 }
12727
12728 /* Check if a non-zero KEY_BLOCK_SIZE was specified. */
12729 if (has_key_block_size) {
12730 if (is_temp) {
12731 my_error(ER_UNSUPPORT_COMPRESSED_TEMPORARY_TABLE, MYF(0));
12732 return ("KEY_BLOCK_SIZE");
12733 }
12734
12735 switch (m_create_info->key_block_size) {
12736 ulint kbs_max;
12737 case 1:
12738 case 2:
12739 case 4:
12740 case 8:
12741 case 16:
12742 /* The maximum KEY_BLOCK_SIZE (KBS) is
12743 UNIV_PAGE_SIZE_MAX. But if UNIV_PAGE_SIZE is
12744 smaller than UNIV_PAGE_SIZE_MAX, the maximum
12745 KBS is also smaller. */
12746 kbs_max = std::min(1 << (UNIV_PAGE_SSIZE_MAX - 1),
12747 1 << (PAGE_ZIP_SSIZE_MAX - 1));
12748 if (m_create_info->key_block_size > kbs_max) {
12749 push_warning_printf(m_thd, Sql_condition::SL_WARNING,
12750 ER_ILLEGAL_HA_CREATE_OPTION,
12751 "InnoDB: KEY_BLOCK_SIZE=%" PRIu32
12752 " cannot be larger than " ULINTPF ".",
12753 m_create_info->key_block_size, kbs_max);
12754 ret = "KEY_BLOCK_SIZE";
12755 }
12756
12757 /* The following checks do not apply to shared tablespaces */
12758 if (m_use_shared_space) {
12759 break;
12760 }
12761
12762 /* Valid KEY_BLOCK_SIZE, check its dependencies. */
12763 if (!m_allow_file_per_table) {
12764 push_warning(m_thd, Sql_condition::SL_WARNING,
12765 ER_ILLEGAL_HA_CREATE_OPTION,
12766 "InnoDB: KEY_BLOCK_SIZE requires"
12767 " innodb_file_per_table.");
12768 ret = "KEY_BLOCK_SIZE";
12769 }
12770 break;
12771 default:
12772 push_warning_printf(m_thd, Sql_condition::SL_WARNING,
12773 ER_ILLEGAL_HA_CREATE_OPTION,
12774 "InnoDB: invalid KEY_BLOCK_SIZE = %" PRIu32
12775 ". Valid values are [1, 2, 4, 8, 16]",
12776 m_create_info->key_block_size);
12777 ret = "KEY_BLOCK_SIZE";
12778 break;
12779 }
12780 }
12781
12782 /* Check for a valid InnoDB ROW_FORMAT specifier and
12783 other incompatibilities. */
12784 switch (row_format) {
12785 case ROW_TYPE_COMPRESSED:
12786 if (is_temp) {
12787 my_error(ER_UNSUPPORT_COMPRESSED_TEMPORARY_TABLE, MYF(0));
12788 return ("ROW_FORMAT");
12789 }
12790 if (!m_use_shared_space && !m_allow_file_per_table) {
12791 push_warning_printf(m_thd, Sql_condition::SL_WARNING,
12792 ER_ILLEGAL_HA_CREATE_OPTION,
12793 "InnoDB: %s requires innodb_file_per_table.",
12794 get_row_format_name(row_format));
12795 ret = "ROW_FORMAT";
12796 }
12797 break;
12798 case ROW_TYPE_DYNAMIC:
12799 case ROW_TYPE_COMPACT:
12800 case ROW_TYPE_REDUNDANT:
12801 if (has_key_block_size) {
12802 push_warning_printf(m_thd, Sql_condition::SL_WARNING,
12803 ER_ILLEGAL_HA_CREATE_OPTION,
12804 "InnoDB: cannot specify %s"
12805 " with KEY_BLOCK_SIZE.",
12806 get_row_format_name(row_format));
12807 ret = "KEY_BLOCK_SIZE";
12808 }
12809 break;
12810 case ROW_TYPE_DEFAULT:
12811 break;
12812 case ROW_TYPE_FIXED:
12813 case ROW_TYPE_PAGED:
12814 case ROW_TYPE_NOT_USED:
12815 push_warning(m_thd, Sql_condition::SL_WARNING,
12816 ER_ILLEGAL_HA_CREATE_OPTION,
12817 "InnoDB: invalid ROW_FORMAT specifier.");
12818 ret = "ROW_TYPE";
12819 break;
12820 }
12821
12822 if (m_create_info->data_file_name != nullptr &&
12823 *m_create_info->data_file_name != '\0' && m_table_name != nullptr &&
12824 !create_option_data_directory_is_valid()) {
12825 ret = "DATA DIRECTORY";
12826 }
12827
12828 /* Do not allow INDEX_DIRECTORY */
12829 if (m_create_info->index_file_name) {
12830 push_warning_printf(m_thd, Sql_condition::SL_WARNING,
12831 ER_ILLEGAL_HA_CREATE_OPTION,
12832 "InnoDB: INDEX DIRECTORY is not supported");
12833 ret = "INDEX DIRECTORY";
12834 }
12835
12836 /* Don't support compressed table when page size > 16k. */
12837 if ((has_key_block_size || row_format == ROW_TYPE_COMPRESSED) &&
12838 UNIV_PAGE_SIZE > UNIV_PAGE_SIZE_DEF) {
12839 push_warning(m_thd, Sql_condition::SL_WARNING, ER_ILLEGAL_HA_CREATE_OPTION,
12840 "InnoDB: Cannot create a COMPRESSED table"
12841 " when innodb_page_size > 16k.");
12842
12843 if (has_key_block_size) {
12844 ret = "KEY_BLOCK_SIZE";
12845 } else {
12846 ret = "ROW_TYPE";
12847 }
12848 }
12849
12850 /* Validate the page compression parameter. */
12851 if (!create_option_compression_is_valid()) {
12852 return ("COMPRESSION");
12853 }
12854
12855 /* Check the encryption option. */
12856 if (ret == nullptr && m_create_info->encrypt_type.str != nullptr) {
12857 dberr_t err;
12858
12859 err = Encryption::validate(m_create_info->encrypt_type.str);
12860
12861 if (err == DB_UNSUPPORTED) {
12862 my_error(ER_INVALID_ENCRYPTION_OPTION, MYF(0));
12863 ret = "ENCRYPTION";
12864 }
12865 }
12866
12867 return (ret);
12868 }
12869
12870 /** Update create_info. Used in SHOW CREATE TABLE et al. */
12871
12872 void ha_innobase::update_create_info(
12873 HA_CREATE_INFO *create_info) /*!< in/out: create info */
12874 {
12875 if (!(create_info->used_fields & HA_CREATE_USED_AUTO)) {
12876 info(HA_STATUS_AUTO);
12877 create_info->auto_increment_value = stats.auto_increment_value;
12878 }
12879
12880 /* Update the DATA DIRECTORY name. */
12881 dd_get_and_save_data_dir_path<dd::Table>(m_prebuilt->table, nullptr, false);
12882
12883 if (m_prebuilt->table->data_dir_path != nullptr) {
12884 create_info->data_file_name = m_prebuilt->table->data_dir_path;
12885 }
12886
12887 /* Update the TABLESPACE name from the Data Dictionary. */
12888 dict_get_and_save_space_name(m_prebuilt->table);
12889
12890 /* Put this tablespace name into the create_info structure so that
12891 SHOW CREATE TABLE will display TABLESPACE=name. This also affects
12892 an ALTER TABLE which must know the current TABLESPACE so that the
12893 table will stay there. */
12894 if (m_prebuilt->table->tablespace != nullptr &&
12895 create_info->tablespace == nullptr) {
12896 create_info->tablespace = m_prebuilt->table->tablespace;
12897 }
12898 }
12899
12900 /** Initialize the table FTS stopword list
12901 @return true if success */
12902 bool innobase_fts_load_stopword(
12903 dict_table_t *table, /*!< in: Table has the FTS */
12904 trx_t *trx, /*!< in: transaction */
12905 THD *thd) /*!< in: current thread */
12906 {
12907 ut_ad(!dict_sys_mutex_own());
12908
12909 return (fts_load_stopword(table, trx, innobase_server_stopword_table,
12910 THDVAR(thd, ft_user_stopword_table),
12911 THDVAR(thd, ft_enable_stopword), false));
12912 }
12913
12914 static bool innobase_ddse_dict_init(
12915 dict_init_mode_t dict_init_mode, uint, List<const dd::Object_table> *tables,
12916 List<const Plugin_tablespace> *tablespaces) {
12917 DBUG_TRACE;
12918
12919 LogErr(SYSTEM_LEVEL, ER_IB_MSG_INNODB_START_INITIALIZE);
12920
12921 assert(tables && tables->is_empty());
12922 assert(tablespaces && tablespaces->is_empty());
12923
12924 if (dblwr::is_enabled()) {
12925 if (innobase_doublewrite_dir != nullptr && *innobase_doublewrite_dir != 0) {
12926 dblwr::dir.assign(innobase_doublewrite_dir);
12927 switch (dblwr::dir.front()) {
12928 case '#':
12929 case '.':
12930 break;
12931 default:
12932 if (!Fil_path::is_absolute_path(dblwr::dir)) {
12933 dblwr::dir.insert(0, "#");
12934 }
12935 }
12936 ib::info(ER_IB_MSG_DBLWR_1325)
12937 << "Using " << dblwr::dir << " as doublewrite directory";
12938 } else {
12939 dblwr::dir.assign(".");
12940 }
12941 ib::info(ER_IB_MSG_DBLWR_1304) << "Atomic write enabled";
12942 } else {
12943 ib::info(ER_IB_MSG_DBLWR_1305) << "Atomic write disabled";
12944 }
12945
12946 if (innobase_init_files(dict_init_mode, tablespaces)) {
12947 return true;
12948 }
12949
12950 /* Instantiate table defs only if we are successful so far. */
12951 dd::Object_table *innodb_dynamic_metadata =
12952 dd::Object_table::create_object_table();
12953 innodb_dynamic_metadata->set_hidden(true);
12954 dd::Object_table_definition *def =
12955 innodb_dynamic_metadata->target_table_definition();
12956 def->set_table_name("innodb_dynamic_metadata");
12957 def->add_field(0, "table_id", "table_id BIGINT UNSIGNED NOT NULL");
12958 def->add_field(1, "version", "version BIGINT UNSIGNED NOT NULL");
12959 def->add_field(2, "metadata", "metadata BLOB NOT NULL");
12960 def->add_index(0, "index_pk", "PRIMARY KEY (table_id)");
12961 /* Options and tablespace are set at the SQL layer. */
12962
12963 /* Changing these values would change the specification of innodb statistics
12964 tables. */
12965 static constexpr size_t DB_NAME_FIELD_SIZE = 64;
12966 static constexpr size_t TABLE_NAME_FIELD_SIZE = 199;
12967
12968 static_assert(DB_NAME_FIELD_SIZE == dict_name::MAX_DB_CHAR_LEN,
12969 "dict_name::MAX_DB_CHAR_LEN mismatch with db column");
12970
12971 static_assert(TABLE_NAME_FIELD_SIZE == dict_name::MAX_TABLE_CHAR_LEN,
12972 "dict_name::MAX_TABLE_CHAR_LEN mismatch with table column");
12973
12974 /* Set length for database name field. */
12975 std::ostringstream db_name_field;
12976 db_name_field << "database_name VARCHAR(" << DB_NAME_FIELD_SIZE
12977 << ") NOT NULL";
12978 std::string db_field = db_name_field.str();
12979
12980 /* Set length for table name field. */
12981 std::ostringstream table_name_field;
12982 table_name_field << "table_name VARCHAR(" << TABLE_NAME_FIELD_SIZE
12983 << ") NOT NULL";
12984 std::string table_field = table_name_field.str();
12985
12986 dd::Object_table *innodb_table_stats =
12987 dd::Object_table::create_object_table();
12988 innodb_table_stats->set_hidden(false);
12989 def = innodb_table_stats->target_table_definition();
12990 def->set_table_name("innodb_table_stats");
12991 def->add_field(0, "database_name", db_field.c_str());
12992 def->add_field(1, "table_name", table_field.c_str());
12993 def->add_field(2, "last_update",
12994 "last_update TIMESTAMP NOT NULL \n"
12995 " DEFAULT CURRENT_TIMESTAMP \n"
12996 " ON UPDATE CURRENT_TIMESTAMP");
12997 def->add_field(3, "n_rows", "n_rows BIGINT UNSIGNED NOT NULL");
12998 def->add_field(4, "clustered_index_size",
12999 "clustered_index_size BIGINT UNSIGNED NOT NULL");
13000 def->add_field(5, "sum_of_other_index_sizes",
13001 "sum_of_other_index_sizes BIGINT UNSIGNED NOT NULL");
13002 def->add_index(0, "index_pk", "PRIMARY KEY (database_name, table_name)");
13003 /* Options and tablespace are set at the SQL layer. */
13004
13005 dd::Object_table *innodb_index_stats =
13006 dd::Object_table::create_object_table();
13007 innodb_index_stats->set_hidden(false);
13008 def = innodb_index_stats->target_table_definition();
13009 def->set_table_name("innodb_index_stats");
13010 def->add_field(0, "database_name", db_field.c_str());
13011 def->add_field(1, "table_name", table_field.c_str());
13012 def->add_field(2, "index_name", "index_name VARCHAR(64) NOT NULL");
13013 def->add_field(3, "last_update",
13014 "last_update TIMESTAMP NOT NULL"
13015 " DEFAULT CURRENT_TIMESTAMP"
13016 " ON UPDATE CURRENT_TIMESTAMP");
13017 /*
13018 There are at least: stat_name='size'
13019 stat_name='n_leaf_pages'
13020 stat_name='n_diff_pfx%'
13021 */
13022 def->add_field(4, "stat_name", "stat_name VARCHAR(64) NOT NULL");
13023 def->add_field(5, "stat_value", "stat_value BIGINT UNSIGNED NOT NULL");
13024 def->add_field(6, "sample_size", "sample_size BIGINT UNSIGNED");
13025 def->add_field(7, "stat_description",
13026 "stat_description VARCHAR(1024) NOT NULL");
13027 def->add_index(0, "index_pk",
13028 "PRIMARY KEY (database_name, table_name, "
13029 "index_name, stat_name)");
13030 /* Options and tablespace are set at the SQL layer. */
13031
13032 dd::Object_table *innodb_ddl_log = dd::Object_table::create_object_table();
13033 innodb_ddl_log->set_hidden(true);
13034 def = innodb_ddl_log->target_table_definition();
13035 def->set_table_name("innodb_ddl_log");
13036 def->add_field(0, "id", "id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT");
13037 def->add_field(1, "thread_id", "thread_id BIGINT UNSIGNED NOT NULL");
13038 def->add_field(2, "type", "type INT UNSIGNED NOT NULL");
13039 def->add_field(3, "space_id", "space_id INT UNSIGNED");
13040 def->add_field(4, "page_no", "page_no INT UNSIGNED");
13041 def->add_field(5, "index_id", "index_id BIGINT UNSIGNED");
13042 def->add_field(6, "table_id", "table_id BIGINT UNSIGNED");
13043 def->add_field(7, "old_file_path",
13044 "old_file_path VARCHAR(512) COLLATE UTF8MB3_BIN");
13045 def->add_field(8, "new_file_path",
13046 "new_file_path VARCHAR(512) COLLATE UTF8MB3_BIN");
13047 def->add_index(0, "index_pk", "PRIMARY KEY(id)");
13048 def->add_index(1, "index_k_thread_id", "KEY(thread_id)");
13049 /* Options and tablespace are set at the SQL layer. */
13050
13051 tables->push_back(innodb_dynamic_metadata);
13052 tables->push_back(innodb_table_stats);
13053 tables->push_back(innodb_index_stats);
13054 tables->push_back(innodb_ddl_log);
13055
13056 LogErr(SYSTEM_LEVEL, ER_IB_MSG_INNODB_END_INITIALIZE);
13057
13058 return false;
13059 }
13060
13061 /** Initialize the set of hard coded DD table ids.
13062 @param[in] dd_table_id Table id of DD table. */
13063 static void innobase_dict_register_dd_table_id(dd::Object_id dd_table_id) {
13064 dict_sys_t::s_dd_table_ids.insert(dd_table_id);
13065 }
13066
13067 /** Parse the table name into normal name and remote path if needed.
13068 @param[in] name Table name (db/table or full path).
13069 @return 0 if successful, otherwise, error number */
13070 int create_table_info_t::parse_table_name(const char *name) {
13071 DBUG_TRACE;
13072
13073 #ifdef _WIN32
13074 /* Names passed in from server are in two formats:
13075 1. <database_name>/<table_name>: for normal table creation
13076 2. full path: for temp table creation, or DATA DIRECTORY.
13077
13078 When srv_file_per_table is on,
13079 check for full path pattern, i.e.
13080 X:\dir\..., X is a driver letter, or
13081 \\dir1\dir2\..., UNC path
13082 returns error if it is in full path format, but not creating a temp.
13083 table. Currently InnoDB does not support symbolic link on Windows. */
13084
13085 if (m_innodb_file_per_table &&
13086 !(m_create_info->options & HA_LEX_CREATE_TMP_TABLE)) {
13087 if (name[1] == ':' || (name[0] == '\\' && name[1] == '\\')) {
13088 log_errlog(ERROR_LEVEL, ER_INNODB_CANNOT_CREATE_TABLE, name);
13089 return HA_ERR_GENERIC;
13090 }
13091 }
13092 #endif /* _WIN32 */
13093
13094 if (!normalize_table_name(m_table_name, name)) {
13095 /* purecov: begin inspected */
13096 ut_d(ut_error);
13097 ut_o(return (HA_ERR_TOO_LONG_PATH));
13098 /* purecov: end */
13099 }
13100
13101 m_remote_path[0] = '\0';
13102 m_tablespace[0] = '\0';
13103
13104 /* Set the remote path if DATA DIRECTORY is valid. If not,
13105 we ignore the DATA DIRECTORY. In strict mode, a non-valid
13106 value would have already been rejected. */
13107 if (m_create_info->data_file_name != nullptr &&
13108 *m_create_info->data_file_name != '\0' && m_table_name != nullptr) {
13109 if (!create_option_data_directory_is_valid(true)) {
13110 push_warning_printf(m_thd, Sql_condition::SL_WARNING, WARN_OPTION_IGNORED,
13111 ER_DEFAULT(WARN_OPTION_IGNORED), "DATA DIRECTORY");
13112 m_flags &= ~DICT_TF_MASK_DATA_DIR;
13113 } else {
13114 strncpy(m_remote_path, m_create_info->data_file_name, FN_REFLEN - 1);
13115 }
13116 }
13117
13118 if (m_create_info->index_file_name) {
13119 push_warning_printf(m_thd, Sql_condition::SL_WARNING, WARN_OPTION_IGNORED,
13120 ER_DEFAULT(WARN_OPTION_IGNORED), "INDEX DIRECTORY");
13121 }
13122
13123 /* The TABLESPACE designation has already been validated by
13124 create_option_tablespace_is_valid() regardless of strict-mode.
13125 So it only needs to be copied now. */
13126 if (m_use_shared_space) {
13127 strncpy(m_tablespace, m_create_info->tablespace, NAME_LEN - 1);
13128 }
13129
13130 return 0;
13131 }
13132
13133 /** Determine InnoDB table flags.
13134 If strict_mode=OFF, this will adjust the flags to what should be assumed.
13135 However, if an existing general tablespace is being targeted, we will NOT
13136 assume anything or adjust these flags.
13137 @retval true if successful, false if error */
13138 bool create_table_info_t::innobase_table_flags() {
13139 DBUG_TRACE;
13140
13141 const char *fts_doc_id_index_bad = nullptr;
13142 uint32_t zip_ssize = 0;
13143 const bool is_temp = m_create_info->options & HA_LEX_CREATE_TMP_TABLE;
13144 bool zip_allowed = !is_temp;
13145
13146 const uint32_t zip_ssize_max =
13147 std::min<uint32_t>((UNIV_PAGE_SSIZE_MAX), (PAGE_ZIP_SSIZE_MAX));
13148
13149 m_flags = 0;
13150 m_flags2 = 0;
13151
13152 /* Validate the page compression parameter. */
13153 if (!create_option_compression_is_valid()) {
13154 /* No need to do anything. Warnings were issued.
13155 The compression setting will be ignored later.
13156 If inodb_strict_mode=ON, this is called twice unless
13157 there was a problem before.
13158 If inodb_strict_mode=OFF, this is the only call. */
13159 }
13160
13161 /* Validate the page encryption parameter. */
13162 if (m_create_info->encrypt_type.length > 0) {
13163 const char *encryption = m_create_info->encrypt_type.str;
13164
13165 if (Encryption::validate(encryption) != DB_SUCCESS) {
13166 /* Incorrect encryption option */
13167 my_error(ER_INVALID_ENCRYPTION_OPTION, MYF(0));
13168 return false;
13169 }
13170 }
13171
13172 /* Check if there are any FTS indexes defined on this table. */
13173 for (uint i = 0; i < m_form->s->keys; i++) {
13174 const KEY *key = &m_form->key_info[i];
13175
13176 if (key->flags & HA_FULLTEXT) {
13177 m_flags2 |= DICT_TF2_FTS;
13178
13179 /* We don't support FTS indexes in temporary
13180 tables. */
13181 if (is_temp) {
13182 my_error(ER_INNODB_NO_FT_TEMP_TABLE, MYF(0));
13183 return false;
13184 }
13185
13186 if (fts_doc_id_index_bad) {
13187 goto index_bad;
13188 }
13189 } else if (key->flags & HA_SPATIAL) {
13190 assert(~m_create_info->options &
13191 (HA_LEX_CREATE_TMP_TABLE | HA_LEX_CREATE_INTERNAL_TMP_TABLE));
13192 }
13193
13194 if (innobase_strcasecmp(key->name, FTS_DOC_ID_INDEX_NAME)) {
13195 continue;
13196 }
13197
13198 /* Do a pre-check on FTS DOC ID index */
13199 if (!(key->flags & HA_NOSAME)
13200 /* For now, we do not allow a descending index,
13201 because fts_doc_fetch_by_doc_id() uses the
13202 InnODB SQL interpreter to look up FTS_DOC_ID.*/
13203 || (key->key_part[0].key_part_flag & HA_REVERSE_SORT) ||
13204 strcmp(key->name, FTS_DOC_ID_INDEX_NAME) ||
13205 strcmp(key->key_part[0].field->field_name, FTS_DOC_ID_COL_NAME)) {
13206 fts_doc_id_index_bad = key->name;
13207 }
13208
13209 if (fts_doc_id_index_bad && (m_flags2 & DICT_TF2_FTS)) {
13210 index_bad:
13211 my_error(ER_INNODB_FT_WRONG_DOCID_INDEX, MYF(0), fts_doc_id_index_bad);
13212 return false;
13213 }
13214 }
13215
13216 if (is_temp && m_create_info->key_block_size > 0) {
13217 push_warning(m_thd, Sql_condition::SL_WARNING, ER_ILLEGAL_HA_CREATE_OPTION,
13218 "InnoDB: KEY_BLOCK_SIZE is ignored"
13219 " for TEMPORARY TABLE.");
13220 zip_allowed = false;
13221 } else if (m_create_info->key_block_size > 0) {
13222 zip_ssize = get_zip_shift_size(m_create_info->key_block_size);
13223
13224 /* Make sure compressed row format is allowed. */
13225 if (is_temp) {
13226 push_warning(m_thd, Sql_condition::SL_WARNING,
13227 ER_ILLEGAL_HA_CREATE_OPTION,
13228 "InnoDB: KEY_BLOCK_SIZE is ignored"
13229 " for TEMPORARY TABLE.");
13230 zip_allowed = false;
13231 } else if (!m_allow_file_per_table && !m_use_shared_space) {
13232 push_warning(m_thd, Sql_condition::SL_WARNING,
13233 ER_ILLEGAL_HA_CREATE_OPTION,
13234 "InnoDB: KEY_BLOCK_SIZE requires"
13235 " innodb_file_per_table.");
13236 zip_allowed = false;
13237 }
13238
13239 if (!zip_allowed || (!zip_ssize && m_create_info->key_block_size)) {
13240 push_warning_printf(m_thd, Sql_condition::SL_WARNING,
13241 ER_ILLEGAL_HA_CREATE_OPTION,
13242 "InnoDB: ignoring KEY_BLOCK_SIZE=%" PRIu32 ".",
13243 m_create_info->key_block_size);
13244 }
13245 }
13246
13247 enum row_type row_type = m_form->s->row_type;
13248
13249 if (zip_ssize && zip_allowed) {
13250 /* if ROW_FORMAT is set to default,
13251 automatically change it to COMPRESSED. */
13252 if (row_type == ROW_TYPE_DEFAULT) {
13253 row_type = ROW_TYPE_COMPRESSED;
13254 } else if (row_type != ROW_TYPE_COMPRESSED) {
13255 /* ROW_FORMAT other than COMPRESSED
13256 ignores KEY_BLOCK_SIZE. It does not
13257 make sense to reject conflicting
13258 KEY_BLOCK_SIZE and ROW_FORMAT, because
13259 such combinations can be obtained
13260 with ALTER TABLE anyway. */
13261 push_warning_printf(m_thd, Sql_condition::SL_WARNING,
13262 ER_ILLEGAL_HA_CREATE_OPTION,
13263 "InnoDB: ignoring KEY_BLOCK_SIZE=%" PRIu32
13264 " as ROW_FORMAT is not COMPRESSED.",
13265 m_create_info->key_block_size);
13266 zip_allowed = false;
13267 }
13268 } else {
13269 /* zip_ssize == 0 means no KEY_BLOCK_SIZE. */
13270 if (row_type == ROW_TYPE_COMPRESSED && zip_allowed) {
13271 /* ROW_FORMAT=COMPRESSED without KEY_BLOCK_SIZE
13272 implies half the maximum KEY_BLOCK_SIZE(*1k) or
13273 UNIV_PAGE_SIZE, whichever is less. */
13274 zip_ssize = zip_ssize_max - 1;
13275 }
13276 }
13277
13278 rec_format_t innodb_row_format = get_row_format(innodb_default_row_format);
13279 switch (row_type) {
13280 case ROW_TYPE_REDUNDANT:
13281 innodb_row_format = REC_FORMAT_REDUNDANT;
13282 break;
13283 case ROW_TYPE_COMPACT:
13284 innodb_row_format = REC_FORMAT_COMPACT;
13285 break;
13286
13287 case ROW_TYPE_COMPRESSED:
13288 if (is_temp) {
13289 push_warning_printf(m_thd, Sql_condition::SL_WARNING,
13290 ER_ILLEGAL_HA_CREATE_OPTION,
13291 "InnoDB: %s is ignored for TEMPORARY TABLE.",
13292 get_row_format_name(row_type));
13293
13294 /* DYNAMIC row format is closer to COMPRESSED
13295 in that it supports better for large BLOBs. */
13296 push_warning(m_thd, Sql_condition::SL_WARNING,
13297 ER_ILLEGAL_HA_CREATE_OPTION,
13298 "InnoDB: assuming ROW_FORMAT=DYNAMIC.");
13299
13300 row_type = ROW_TYPE_DYNAMIC;
13301 innodb_row_format = REC_FORMAT_DYNAMIC;
13302 break;
13303 }
13304
13305 /* ROW_FORMAT=COMPRESSED requires file_per_table unless
13306 there is a target tablespace. */
13307 if (!m_allow_file_per_table && !m_use_shared_space) {
13308 push_warning_printf(m_thd, Sql_condition::SL_WARNING,
13309 ER_ILLEGAL_HA_CREATE_OPTION,
13310 "InnoDB: %s requires innodb_file_per_table.",
13311 get_row_format_name(row_type));
13312 } else {
13313 /* We can use this row_format. */
13314 innodb_row_format = REC_FORMAT_COMPRESSED;
13315 break;
13316 }
13317 zip_allowed = false;
13318 /* fall through to set row_type = DYNAMIC */
13319 [[fallthrough]];
13320 case ROW_TYPE_NOT_USED:
13321 case ROW_TYPE_FIXED:
13322 case ROW_TYPE_PAGED:
13323 push_warning(m_thd, Sql_condition::SL_WARNING,
13324 ER_ILLEGAL_HA_CREATE_OPTION,
13325 "InnoDB: assuming ROW_FORMAT=DYNAMIC.");
13326 [[fallthrough]];
13327 case ROW_TYPE_DYNAMIC:
13328 innodb_row_format = REC_FORMAT_DYNAMIC;
13329 break;
13330 case ROW_TYPE_DEFAULT: {
13331 /* Consider the real_row_type if already set. */
13332 switch (m_form->s->real_row_type) {
13333 case ROW_TYPE_REDUNDANT:
13334 innodb_row_format = REC_FORMAT_REDUNDANT;
13335 break;
13336 case ROW_TYPE_COMPACT:
13337 innodb_row_format = REC_FORMAT_COMPACT;
13338 break;
13339 case ROW_TYPE_COMPRESSED:
13340 innodb_row_format = REC_FORMAT_COMPRESSED;
13341 break;
13342 case ROW_TYPE_DYNAMIC:
13343 innodb_row_format = REC_FORMAT_DYNAMIC;
13344 break;
13345 default:
13346 break;
13347 }
13348 break;
13349 }
13350 default:
13351 ut_d(ut_error);
13352 }
13353
13354 /* Don't support compressed table when page size > 16k. */
13355 if (zip_allowed && zip_ssize && UNIV_PAGE_SIZE > UNIV_PAGE_SIZE_DEF) {
13356 push_warning(m_thd, Sql_condition::SL_WARNING, ER_ILLEGAL_HA_CREATE_OPTION,
13357 "InnoDB: Cannot create a COMPRESSED table"
13358 " when innodb_page_size > 16k."
13359 " Assuming ROW_FORMAT=DYNAMIC.");
13360 zip_allowed = false;
13361 }
13362
13363 ut_ad(!is_temp || !zip_allowed);
13364 ut_ad(!is_temp || row_type != ROW_TYPE_COMPRESSED);
13365 ut_ad(!is_temp || innodb_row_format != REC_FORMAT_COMPRESSED);
13366
13367 /* Set the table flags */
13368 if (!zip_allowed) {
13369 zip_ssize = 0;
13370 }
13371
13372 if (is_temp) {
13373 m_flags2 |= DICT_TF2_TEMPORARY;
13374
13375 if (m_create_info->options & HA_LEX_CREATE_INTERNAL_TMP_TABLE) {
13376 /* Intrinsic tables reside only in the shared temporary
13377 tablespace and we will always use ROW_FORMAT=DYNAMIC. */
13378 /* We do not allow compressed intrinsic temporary tables. */
13379 ut_ad(zip_ssize == 0);
13380 innodb_row_format = REC_FORMAT_DYNAMIC;
13381 m_flags2 |= DICT_TF2_INTRINSIC;
13382 }
13383 if (m_use_shared_space && m_create_info->tablespace != nullptr &&
13384 strcmp(m_create_info->tablespace, dict_sys_t::s_temp_space_name) == 0) {
13385 /* This is possible only with innodb_strict_mode=OFF and we warned that
13386 that tablespace=innodb_temporary is ignored. We should instead use
13387 session temporary tablespaces */
13388 m_use_shared_space = false;
13389 }
13390
13391 } else if (m_use_file_per_table) {
13392 ut_ad(!m_use_shared_space);
13393 m_flags2 |= DICT_TF2_USE_FILE_PER_TABLE;
13394 }
13395
13396 /* Set the table flags */
13397 dict_tf_set(&m_flags, innodb_row_format, zip_ssize, m_use_data_dir,
13398 m_use_shared_space);
13399
13400 return true;
13401 }
13402
13403 /** Detach the just created table and its auxiliary tables if exist */
13404 void create_table_info_t::detach() {
13405 ut_ad(!dict_sys_mutex_own());
13406 dict_sys_mutex_enter();
13407
13408 ut_ad(m_table != nullptr);
13409 ut_ad(!m_table->can_be_evicted);
13410 ut_ad(!m_table->is_temporary());
13411
13412 if (!m_table->explicitly_non_lru) {
13413 dict_table_allow_eviction(m_table);
13414 }
13415
13416 if ((m_table->flags2 & (DICT_TF2_FTS | DICT_TF2_FTS_ADD_DOC_ID)) ||
13417 m_table->fts != nullptr) {
13418 fts_detach_aux_tables(m_table, true);
13419 }
13420
13421 dict_sys_mutex_exit();
13422 }
13423
13424 /** Parse MERGE_THRESHOLD value from the string.
13425 @param[in] thd connection
13426 @param[in] str string which might include 'MERGE_THRESHOLD='
13427 @return value parsed. 0 means not found or invalid value. */
13428 static ulint innobase_parse_merge_threshold(THD *thd, const char *str) {
13429 static const char *label = "MERGE_THRESHOLD=";
13430 static const size_t label_len = strlen(label);
13431 const char *pos = str;
13432
13433 pos = strstr(str, label);
13434
13435 if (pos == nullptr) {
13436 return (0);
13437 }
13438
13439 pos += label_len;
13440
13441 lint ret = atoi(pos);
13442
13443 if (ret > 0 && ret <= 50) {
13444 return (static_cast<ulint>(ret));
13445 }
13446
13447 push_warning_printf(
13448 thd, Sql_condition::SL_WARNING, ER_ILLEGAL_HA_CREATE_OPTION,
13449 "InnoDB: Invalid value for MERGE_THRESHOLD in the CREATE TABLE"
13450 " statement. The value is ignored.");
13451
13452 return (0);
13453 }
13454
13455 /** Parse hint for table and its indexes, and update the information
13456 in dictionary.
13457 @param[in] thd Connection thread
13458 @param[in,out] table Target table
13459 @param[in] table_share Table definition */
13460 void innobase_parse_hint_from_comment(THD *thd, dict_table_t *table,
13461 const TABLE_SHARE *table_share) {
13462 ulint merge_threshold_table;
13463 ulint merge_threshold_index[MAX_KEY];
13464 bool is_found[MAX_KEY];
13465
13466 if (table_share->comment.str != nullptr) {
13467 merge_threshold_table =
13468 innobase_parse_merge_threshold(thd, table_share->comment.str);
13469 } else {
13470 merge_threshold_table = DICT_INDEX_MERGE_THRESHOLD_DEFAULT;
13471 }
13472
13473 if (merge_threshold_table == 0) {
13474 merge_threshold_table = DICT_INDEX_MERGE_THRESHOLD_DEFAULT;
13475 }
13476
13477 for (uint i = 0; i < table_share->keys; i++) {
13478 KEY *key_info = &table_share->key_info[i];
13479
13480 ut_ad(i < sizeof(merge_threshold_index) / sizeof(merge_threshold_index[0]));
13481
13482 if (key_info->flags & HA_USES_COMMENT && key_info->comment.str != nullptr) {
13483 merge_threshold_index[i] =
13484 innobase_parse_merge_threshold(thd, key_info->comment.str);
13485 } else {
13486 merge_threshold_index[i] = merge_threshold_table;
13487 }
13488
13489 if (merge_threshold_index[i] == 0) {
13490 merge_threshold_index[i] = merge_threshold_table;
13491 }
13492 }
13493
13494 for (uint i = 0; i < table_share->keys; i++) {
13495 is_found[i] = false;
13496 }
13497
13498 /* update in memory */
13499 for (auto index : table->indexes) {
13500 if (dict_index_is_auto_gen_clust(index)) {
13501 /* GEN_CLUST_INDEX should use merge_threshold_table */
13502
13503 /* x-lock index is needed to exclude concurrent
13504 pessimistic tree operations */
13505 rw_lock_x_lock(dict_index_get_lock(index), UT_LOCATION_HERE);
13506 index->merge_threshold = merge_threshold_table;
13507 rw_lock_x_unlock(dict_index_get_lock(index));
13508
13509 continue;
13510 }
13511
13512 for (uint i = 0; i < table_share->keys; i++) {
13513 if (is_found[i]) {
13514 continue;
13515 }
13516
13517 KEY *key_info = &table_share->key_info[i];
13518
13519 if (innobase_strcasecmp(index->name, key_info->name) == 0) {
13520 /* x-lock index is needed to exclude concurrent
13521 pessimistic tree operations */
13522 rw_lock_x_lock(dict_index_get_lock(index), UT_LOCATION_HERE);
13523 index->merge_threshold = merge_threshold_index[i];
13524 rw_lock_x_unlock(dict_index_get_lock(index));
13525 is_found[i] = true;
13526
13527 break;
13528 }
13529 }
13530 }
13531 }
13532
13533 /** Set m_use_* flags. */
13534 void create_table_info_t::set_tablespace_type(
13535 bool table_being_altered_is_file_per_table) {
13536 /* Note whether this table will be created using a shared,
13537 general or system tablespace. */
13538 m_use_shared_space = tablespace_is_shared_space(m_create_info);
13539
13540 /** Allow file_per_table for this table either because:
13541 1) the setting innodb_file_per_table=on,
13542 2) the table being altered is currently file_per_table
13543 3) explicitly requested by tablespace=innodb_file_per_table. */
13544 m_allow_file_per_table = m_innodb_file_per_table ||
13545 table_being_altered_is_file_per_table ||
13546 tablespace_is_file_per_table(m_create_info);
13547
13548 bool is_temp = m_create_info->options & HA_LEX_CREATE_TMP_TABLE;
13549
13550 /* Ignore the current innodb_file_per_table setting if we are
13551 creating a temporary table or if the
13552 TABLESPACE= phrase is using an existing shared tablespace. */
13553 m_use_file_per_table =
13554 m_allow_file_per_table && !is_temp && !m_use_shared_space;
13555
13556 /* DATA DIRECTORY must have m_use_file_per_table. */
13557 m_use_data_dir = m_use_file_per_table &&
13558 (m_create_info->data_file_name != nullptr) &&
13559 (m_create_info->data_file_name[0] != '\0');
13560 ut_ad(!(m_use_shared_space && m_use_data_dir));
13561 }
13562
13563 /** Initialize the create_table_info_t object.
13564 @return error number */
13565 int create_table_info_t::initialize() {
13566 DBUG_TRACE;
13567
13568 ut_ad(m_thd != nullptr);
13569 ut_ad(m_create_info != nullptr);
13570
13571 if (m_form->s->fields > REC_MAX_N_USER_FIELDS) {
13572 return HA_ERR_TOO_MANY_FIELDS;
13573 }
13574
13575 ut_ad(m_form->s->row_type == m_create_info->row_type);
13576
13577 /* Check for name conflicts (with reserved name) for
13578 any user indices to be created. */
13579 if (innobase_index_name_is_reserved(m_thd, m_form->key_info,
13580 m_form->s->keys)) {
13581 return HA_ERR_WRONG_INDEX;
13582 }
13583
13584 m_trx->will_lock++;
13585
13586 m_table = nullptr;
13587
13588 return 0;
13589 }
13590
13591 /** Initialize the autoinc of this table if necessary, which should
13592 be called before we flush logs, so autoinc counter can be persisted. */
13593 void create_table_info_t::initialize_autoinc() {
13594 dict_table_t *innobase_table;
13595
13596 const bool persist = !(m_create_info->options & HA_LEX_CREATE_TMP_TABLE) &&
13597 m_form->found_next_number_field;
13598
13599 if (!persist && m_create_info->auto_increment_value == 0) {
13600 return;
13601 }
13602
13603 innobase_table =
13604 thd_to_innodb_session(m_thd)->lookup_table_handler(m_table_name);
13605
13606 if (innobase_table == nullptr) {
13607 innobase_table = dd_table_open_on_name_in_mem(m_table_name, false);
13608 } else {
13609 innobase_table->acquire();
13610 ut_ad(innobase_table->is_intrinsic());
13611 }
13612
13613 assert(innobase_table != nullptr);
13614
13615 if (persist) {
13616 dict_table_autoinc_set_col_pos(
13617 innobase_table, m_form->found_next_number_field->field_index());
13618 ut_ad(dict_table_has_autoinc_col(innobase_table));
13619 }
13620
13621 /* We need to copy the AUTOINC value from the old table if
13622 this is an ALTER|OPTIMIZE TABLE or CREATE INDEX because CREATE INDEX
13623 does a table copy too. If query was one of :
13624
13625 CREATE TABLE ...AUTO_INCREMENT = x; or
13626 ALTER TABLE...AUTO_INCREMENT = x; or
13627 OPTIMIZE TABLE t; or
13628 CREATE INDEX x on t(...);
13629
13630 Find out a table definition from the dictionary and get
13631 the current value of the auto increment field. Set a new
13632 value to the auto increment field if the value is greater
13633 than the maximum value in the column. */
13634
13635 enum_sql_command cmd = static_cast<enum_sql_command>(thd_sql_command(m_thd));
13636
13637 if (m_create_info->auto_increment_value > 0 &&
13638 ((m_create_info->used_fields & HA_CREATE_USED_AUTO) ||
13639 cmd == SQLCOM_ALTER_TABLE || cmd == SQLCOM_OPTIMIZE ||
13640 cmd == SQLCOM_CREATE_INDEX)) {
13641 uint64_t auto_inc_value;
13642
13643 auto_inc_value = m_create_info->auto_increment_value;
13644
13645 dict_table_autoinc_lock(innobase_table);
13646 dict_table_autoinc_initialize(innobase_table, auto_inc_value);
13647 dict_table_autoinc_unlock(innobase_table);
13648 }
13649
13650 dd_table_close(innobase_table, nullptr, nullptr, false);
13651 }
13652
13653 /** Prepare to create a new table to an InnoDB database.
13654 @param[in] name Table name
13655 @return error number */
13656 int create_table_info_t::prepare_create_table(const char *name) {
13657 DBUG_TRACE;
13658
13659 ut_ad(m_thd != nullptr);
13660 ut_ad(m_form->s->row_type == m_create_info->row_type);
13661
13662 if (!normalize_table_name(m_table_name, name)) {
13663 /* purecov: begin inspected */
13664 ut_d(ut_error);
13665 ut_o(return (HA_ERR_TOO_LONG_PATH));
13666 /* purecov: end */
13667 }
13668
13669 set_tablespace_type(false);
13670
13671 /* Validate the create options if innodb_strict_mode is set.
13672 Do not use the regular message for ER_ILLEGAL_HA_CREATE_OPTION
13673 because InnoDB might actually support the option, but not under
13674 the current conditions. The messages revealing the specific
13675 problems are reported inside this function. */
13676 if (create_options_are_invalid()) {
13677 return HA_WRONG_CREATE_OPTION;
13678 }
13679
13680 /* Create the table flags and flags2 */
13681 if (flags() == 0 && flags2() == 0) {
13682 if (!innobase_table_flags()) {
13683 return HA_WRONG_CREATE_OPTION;
13684 }
13685 }
13686
13687 ut_ad(!high_level_read_only || is_intrinsic_temp_table());
13688
13689 return parse_table_name(name);
13690 }
13691
13692 /** Check a column (name) is a base column for any stored column in the table
13693 @param[in] table TABLE* for the table
13694 @param[in] name column name to check
13695 @return true if this is a base column */
13696 static bool innobase_is_base_s_col(const TABLE *table, const char *name) {
13697 for (uint i = 0; i < table->s->fields; ++i) {
13698 const Field *field = table->field[i];
13699
13700 if (!innobase_is_s_fld(field)) {
13701 continue;
13702 }
13703
13704 for (uint j = 0; j < table->s->fields; ++j) {
13705 if (bitmap_is_set(&field->gcol_info->base_columns_map, j)) {
13706 const Field *base_field = table->field[j];
13707 if (innobase_strcasecmp(base_field->field_name, name) == 0) {
13708 return (true);
13709 }
13710 }
13711 }
13712 }
13713
13714 return (false);
13715 }
13716
13717 /** Check any cascading foreign key columns are base columns
13718 for any stored columns in the table
13719 @param[in] dd_table dd::Table for the table
13720 @param[in] table TABLE* for the table
13721 @return DB_NO_FK_ON_S_BASE_COL if found or DB_SUCCESS */
13722 static dberr_t innobase_check_fk_base_col(const dd::Table *dd_table,
13723 const TABLE *table) {
13724 for (const dd::Foreign_key *key : dd_table->foreign_keys()) {
13725 bool upd_cascade = false;
13726 bool del_cascade = false;
13727
13728 switch (key->update_rule()) {
13729 case dd::Foreign_key::RULE_CASCADE:
13730 case dd::Foreign_key::RULE_SET_NULL:
13731 upd_cascade = true;
13732 break;
13733 case dd::Foreign_key::RULE_NO_ACTION:
13734 case dd::Foreign_key::RULE_RESTRICT:
13735 case dd::Foreign_key::RULE_SET_DEFAULT:
13736 break;
13737 }
13738
13739 switch (key->delete_rule()) {
13740 case dd::Foreign_key::RULE_CASCADE:
13741 case dd::Foreign_key::RULE_SET_NULL:
13742 del_cascade = true;
13743 break;
13744 case dd::Foreign_key::RULE_NO_ACTION:
13745 case dd::Foreign_key::RULE_RESTRICT:
13746 case dd::Foreign_key::RULE_SET_DEFAULT:
13747 break;
13748 }
13749
13750 if (!upd_cascade && !del_cascade) {
13751 continue;
13752 }
13753
13754 for (const dd::Foreign_key_element *key_e : key->elements()) {
13755 dd::String_type col_name = key_e->column().name();
13756
13757 if (innobase_is_base_s_col(table, col_name.c_str())) {
13758 return (DB_NO_FK_ON_S_BASE_COL);
13759 }
13760 }
13761 }
13762 return (DB_SUCCESS);
13763 }
13764
13765 /** Create the internal innodb table.
13766 @param[in] dd_table dd::Table or nullptr for intrinsic table
13767 @param[in] old_part_table dd::Table from an old partition for partitioned
13768 table, NULL otherwise.
13769 @return 0 or error number */
13770 int create_table_info_t::create_table(const dd::Table *dd_table,
13771 const dd::Table *old_part_table) {
13772 int error;
13773 uint primary_key_no;
13774 uint i;
13775 const char *stmt;
13776 size_t stmt_len;
13777
13778 DBUG_TRACE;
13779 assert(m_form->s->keys <= MAX_KEY);
13780
13781 /* Check if dd table has hidden fts doc id index.
13782 Note: in case of TRUNCATE a fulltext table with
13783 hidden doc id index. */
13784 if (dd_table != nullptr) {
13785 dberr_t err = innobase_check_fk_base_col(dd_table, m_form);
13786
13787 if (err != DB_SUCCESS) {
13788 error = convert_error_code_to_mysql(err, m_flags, nullptr);
13789
13790 return error;
13791 }
13792
13793 for (auto index : dd_table->indexes()) {
13794 if (my_strcasecmp(system_charset_info, index->name().c_str(),
13795 FTS_DOC_ID_INDEX_NAME) == 0 &&
13796 index->is_hidden()) {
13797 m_flags2 |= DICT_TF2_FTS_ADD_DOC_ID;
13798 }
13799 }
13800 }
13801
13802 /* Look for a primary key */
13803 primary_key_no = m_form->s->primary_key;
13804
13805 /* Our function innobase_get_mysql_key_number_for_index assumes
13806 the primary key is always number 0, if it exists */
13807 ut_a(primary_key_no == MAX_KEY || primary_key_no == 0);
13808
13809 error = create_table_def(dd_table, old_part_table);
13810 if (error) {
13811 return error;
13812 }
13813
13814 ut_ad(m_table != nullptr);
13815
13816 /* Create the keys */
13817
13818 if (m_form->s->keys == 0 || primary_key_no == MAX_KEY) {
13819 /* Create an index which is used as the clustered index;
13820 order the rows by their row id which is internally generated
13821 by InnoDB */
13822
13823 error =
13824 create_clustered_index_when_no_primary(m_trx, m_flags, m_table_name);
13825 if (error) {
13826 return error;
13827 }
13828 }
13829
13830 if (primary_key_no != MAX_KEY) {
13831 /* In InnoDB the clustered index must always be created
13832 first */
13833 error = create_index(m_trx, m_form, m_flags, m_table_name, primary_key_no,
13834 dd_table);
13835 if (error) {
13836 return error;
13837 }
13838 }
13839
13840 /* Create the ancillary tables that are common to all FTS indexes on
13841 this table. */
13842 if (m_flags2 & (DICT_TF2_FTS | DICT_TF2_FTS_ADD_DOC_ID)) {
13843 fts_doc_id_index_enum ret;
13844
13845 /* Check whether there already exists FTS_DOC_ID_INDEX */
13846 ret = innobase_fts_check_doc_id_index_in_def(m_form->s->keys,
13847 m_form->key_info);
13848
13849 switch (ret) {
13850 case FTS_INCORRECT_DOC_ID_INDEX:
13851 push_warning_printf(m_thd, Sql_condition::SL_WARNING,
13852 ER_WRONG_NAME_FOR_INDEX,
13853 " InnoDB: Index name %s is reserved"
13854 " for the unique index on"
13855 " FTS_DOC_ID column for FTS"
13856 " Document ID indexing"
13857 " on table %s. Please check"
13858 " the index definition to"
13859 " make sure it is of correct"
13860 " type\n",
13861 FTS_DOC_ID_INDEX_NAME, m_table->name.m_name);
13862
13863 if (m_table->fts) {
13864 fts_free(m_table);
13865 }
13866
13867 my_error(ER_WRONG_NAME_FOR_INDEX, MYF(0), FTS_DOC_ID_INDEX_NAME);
13868 error = -1;
13869 return error;
13870 case FTS_EXIST_DOC_ID_INDEX:
13871 case FTS_NOT_EXIST_DOC_ID_INDEX:
13872 break;
13873 }
13874
13875 dberr_t err = fts_create_common_tables(m_trx, m_table, m_table_name,
13876 (ret == FTS_EXIST_DOC_ID_INDEX));
13877
13878 error = convert_error_code_to_mysql(err, 0, nullptr);
13879
13880 DICT_TF2_FLAG_UNSET(m_table, DICT_TF2_FTS_ADD_DOC_ID);
13881
13882 if (error) {
13883 return error;
13884 }
13885 }
13886
13887 for (i = 0; i < m_form->s->keys; i++) {
13888 if (i != primary_key_no) {
13889 error = create_index(m_trx, m_form, m_flags, m_table_name, i, dd_table);
13890 if (error) {
13891 return error;
13892 }
13893 }
13894 }
13895
13896 initialize_autoinc();
13897
13898 /* Cache all the FTS indexes on this table in the FTS specific
13899 structure. They are used for FTS indexed column update handling. */
13900 if (m_flags2 & DICT_TF2_FTS) {
13901 fts_t *fts = m_table->fts;
13902
13903 ut_a(fts != nullptr);
13904
13905 dict_table_get_all_fts_indexes(m_table, fts->indexes);
13906 }
13907
13908 stmt = innobase_get_stmt_unsafe(m_thd, &stmt_len);
13909
13910 innodb_session_t *&priv = thd_to_innodb_session(m_trx->mysql_thd);
13911 dict_table_t *handler = priv->lookup_table_handler(m_table_name);
13912
13913 ut_ad(handler == nullptr || handler->is_intrinsic());
13914 ut_ad(handler == nullptr || is_intrinsic_temp_table());
13915
13916 /* There is no concept of foreign key for intrinsic tables. */
13917 if (handler == nullptr && stmt != nullptr && dd_table != nullptr
13918 /* FIXME: NewDD: WL#6049 should add a new call to check if a table
13919 is a parent table of any FK. If the table is not child table, nor
13920 parent table, then it can skip the check:
13921 dd_table->foreign_keys().empty() &&
13922 dd_table->referenced_keys().empty() */
13923 ) {
13924 dberr_t err = DB_SUCCESS;
13925
13926 dict_sys_mutex_enter();
13927 err = row_table_load_foreign_constraints(m_trx, m_table_name, dd_table);
13928 dict_sys_mutex_exit();
13929
13930 switch (err) {
13931 case DB_PARENT_NO_INDEX:
13932 push_warning_printf(m_thd, Sql_condition::SL_WARNING,
13933 HA_ERR_CANNOT_ADD_FOREIGN,
13934 "Create table '%s' with foreign key constraint"
13935 " failed. There is no index in the referenced"
13936 " table where the referenced columns appear"
13937 " as the first columns.\n",
13938 m_table_name);
13939 break;
13940
13941 case DB_CHILD_NO_INDEX:
13942 push_warning_printf(m_thd, Sql_condition::SL_WARNING,
13943 HA_ERR_CANNOT_ADD_FOREIGN,
13944 "Create table '%s' with foreign key constraint"
13945 " failed. There is no index in the referencing"
13946 " table where referencing columns appear"
13947 " as the first columns.\n",
13948 m_table_name);
13949 break;
13950 case DB_NO_FK_ON_S_BASE_COL:
13951 push_warning_printf(m_thd, Sql_condition::SL_WARNING,
13952 HA_ERR_CANNOT_ADD_FOREIGN,
13953 "Create table '%s' with foreign key constraint"
13954 " failed. Cannot add foreign key constraint"
13955 " placed on the base column of stored"
13956 " column.\n",
13957 m_table_name);
13958 break;
13959 default:
13960 break;
13961 }
13962
13963 error = convert_error_code_to_mysql(err, m_flags, nullptr);
13964
13965 if (error) {
13966 if (handler != nullptr) {
13967 priv->unregister_table_handler(m_table_name);
13968 }
13969 return error;
13970 }
13971 }
13972
13973 return 0;
13974 }
13975
13976 /** Update a new table in an InnoDB database.
13977 @return error number */
13978 int create_table_info_t::create_table_update_dict() {
13979 DBUG_TRACE;
13980
13981 assert(m_table != nullptr);
13982
13983 #ifdef UNIV_DEBUG
13984 if (m_table->is_intrinsic()) {
13985 dict_table_t *innobase_table =
13986 thd_to_innodb_session(m_thd)->lookup_table_handler(m_table_name);
13987 ut_ad(m_table == innobase_table);
13988 }
13989 #endif /* UNIV_DEBUG */
13990
13991 /* Temp table must be uncompressed and reside in tmp tablespace. */
13992 ut_ad(!dict_table_is_compressed_temporary(m_table));
13993 if (m_table->fts != nullptr) {
13994 if (m_table->fts_doc_id_index == nullptr) {
13995 m_table->fts_doc_id_index =
13996 dict_table_get_index_on_name(m_table, FTS_DOC_ID_INDEX_NAME);
13997 assert(m_table->fts_doc_id_index != nullptr);
13998 } else {
13999 assert(m_table->fts_doc_id_index ==
14000 dict_table_get_index_on_name(m_table, FTS_DOC_ID_INDEX_NAME));
14001 }
14002 }
14003
14004 assert((m_table->fts == nullptr) == (m_table->fts_doc_id_index == nullptr));
14005
14006 innobase_copy_frm_flags_from_create_info(m_table, m_create_info);
14007
14008 dict_stats_update(m_table, DICT_STATS_EMPTY_TABLE);
14009
14010 /* Since no dict_table_close(), deinitialize it explicitly. */
14011 dict_stats_deinit(m_table);
14012
14013 /* Load server stopword into FTS cache */
14014 if (m_flags2 & DICT_TF2_FTS) {
14015 if (!innobase_fts_load_stopword(m_table, nullptr, m_thd)) {
14016 return -1;
14017 }
14018 }
14019
14020 innobase_parse_hint_from_comment(m_thd, m_table, m_form->s);
14021 return 0;
14022 }
14023
14024 /** Update the global data dictionary.
14025 @param[in] dd_table dd::Table or dd::Partition
14026 @retval 0 On success
14027 @retval error number On failure */
14028 template <typename Table>
14029 int create_table_info_t::create_table_update_global_dd(Table *dd_table) {
14030 DBUG_TRACE;
14031
14032 if (dd_table == nullptr || (m_flags2 & DICT_TF2_TEMPORARY)) {
14033 /* No need to fill in metadata for all temporary tables.
14034 The Table object for temporary table is either NULL or
14035 a fake one, whose metadata would not be written back later */
14036 return 0;
14037 }
14038
14039 if (m_form->found_next_number_field != nullptr) {
14040 dd_set_autoinc(dd_table->se_private_data(),
14041 m_create_info->auto_increment_value);
14042 }
14043
14044 dd::cache::Dictionary_client *client = dd::get_dd_client(m_thd);
14045 dd::cache::Dictionary_client::Auto_releaser releaser(client);
14046
14047 ut_ad(m_table != nullptr);
14048 ut_ad(!m_table->is_temporary());
14049
14050 bool file_per_table = dict_table_is_file_per_table(m_table);
14051 dd::Object_id dd_space_id = dd::INVALID_OBJECT_ID;
14052 bool is_dd_table = m_table->space == dict_sys_t::s_dict_space_id;
14053
14054 if (is_dd_table) {
14055 dd_space_id = dict_sys_t::s_dd_dict_space_id;
14056 } else if (m_table->space == TRX_SYS_SPACE) {
14057 dd_space_id = dict_sys_t::s_dd_sys_space_id;
14058 } else if (file_per_table) {
14059 char *filename = fil_space_get_first_path(m_table->space);
14060
14061 if (dd_create_implicit_tablespace(client, m_table->space,
14062 m_table->name.m_name, filename, false,
14063 dd_space_id)) {
14064 ut::free(filename);
14065 return HA_ERR_GENERIC;
14066 }
14067
14068 ut_ad(dd_space_id != dd::INVALID_OBJECT_ID);
14069 ut::free(filename);
14070 } else {
14071 ut_ad(DICT_TF_HAS_SHARED_SPACE(m_table->flags));
14072
14073 dd_space_id = dd_get_space_id(*dd_table);
14074
14075 const dd::Tablespace *index_space = nullptr;
14076 if (client->acquire<dd::Tablespace>(dd_space_id, &index_space)) {
14077 return HA_ERR_GENERIC;
14078 }
14079
14080 DBUG_EXECUTE_IF("create_table_update_dd_fail", index_space = nullptr;);
14081
14082 uint32_t id;
14083 if (index_space == nullptr) {
14084 my_error(ER_TABLESPACE_MISSING, MYF(0), m_table->name.m_name);
14085 return HA_ERR_TABLESPACE_MISSING;
14086 } else if (index_space->se_private_data().get(
14087 dd_space_key_strings[DD_SPACE_ID], &id) ||
14088 id != m_table->space) {
14089 ut_ad(!"missing or incorrect tablespace id");
14090 return HA_ERR_GENERIC;
14091 }
14092 }
14093
14094 m_table->dd_space_id = dd_space_id;
14095
14096 dd_set_table_options(dd_table, m_table);
14097
14098 dd_write_table(dd_space_id, dd_table, m_table);
14099
14100 if (m_flags2 & (DICT_TF2_FTS | DICT_TF2_FTS_ADD_DOC_ID)) {
14101 ut_d(bool ret =) fts_create_common_dd_tables(m_table);
14102 ut_ad(ret);
14103 fts_create_index_dd_tables(m_table);
14104 }
14105
14106 ut_ad(dd_table_match(m_table, dd_table));
14107
14108 return 0;
14109 }
14110
14111 template int create_table_info_t::create_table_update_global_dd<dd::Table>(
14112 dd::Table *);
14113
14114 template int create_table_info_t::create_table_update_global_dd<dd::Partition>(
14115 dd::Partition *);
14116
14117 template <typename Table>
14118 int innobase_basic_ddl::create_impl(THD *thd, const char *name, TABLE *form,
14119 HA_CREATE_INFO *create_info, Table *dd_tab,
14120 bool file_per_table, bool evictable,
14121 bool skip_strict, uint32_t old_flags,
14122 uint32_t old_flags2,
14123 const dd::Table *old_part_table) {
14124 char norm_name[FN_REFLEN] = {'\0'}; /* {database}/{tablename} */
14125 char remote_path[FN_REFLEN] = {'\0'}; /* Absolute path of table */
14126 char tablespace[NAME_LEN] = {'\0'}; /* Tablespace name identifier */
14127 trx_t *trx;
14128
14129 if (high_level_read_only &&
14130 !(create_info->options & HA_LEX_CREATE_INTERNAL_TMP_TABLE)) {
14131 return HA_ERR_INNODB_READ_ONLY;
14132 }
14133
14134 /* Get the transaction associated with the current thd, or create one
14135 if not yet created */
14136 trx = check_trx_exists(thd);
14137
14138 if (!(create_info->options & HA_LEX_CREATE_TMP_TABLE)) {
14139 trx_start_if_not_started(trx, true, UT_LOCATION_HERE);
14140 }
14141
14142 create_table_info_t info(thd, form, create_info, norm_name, remote_path,
14143 tablespace, file_per_table, skip_strict, old_flags,
14144 old_flags2, false);
14145
14146 /* Initialize the object. */
14147 int error = info.initialize();
14148
14149 if (error != 0) {
14150 return (error);
14151 }
14152
14153 /* Prepare for create and validate options. */
14154 error = info.prepare_create_table(name);
14155
14156 if (error != 0) {
14157 return (error);
14158 }
14159
14160 error = info.create_table(dd_tab != nullptr ? &dd_tab->table() : nullptr,
14161 old_part_table);
14162 if (error) {
14163 goto cleanup;
14164 }
14165
14166 error = info.create_table_update_global_dd(dd_tab);
14167 if (error) {
14168 goto cleanup;
14169 }
14170
14171 error = info.create_table_update_dict();
14172
14173 if (evictable && !(info.is_temp_table() || info.is_intrinsic_temp_table())) {
14174 info.detach();
14175 }
14176
14177 return (error);
14178
14179 cleanup:
14180 if (!info.is_intrinsic_temp_table() && info.is_temp_table()) {
14181 dict_sys_mutex_enter();
14182
14183 dict_table_t *table = dict_table_check_if_in_cache_low(norm_name);
14184
14185 if (table != nullptr) {
14186 for (dict_index_t *index = table->first_index(); index != nullptr;
14187 index = index->next()) {
14188 ut_ad(index->space == table->space);
14189 page_no_t root = index->page;
14190 index->page = FIL_NULL;
14191 dict_drop_temporary_table_index(index, root);
14192 }
14193 dict_table_remove_from_cache(table);
14194 }
14195
14196 dict_sys_mutex_exit();
14197 } else {
14198 dict_table_t *intrinsic_table =
14199 thd_to_innodb_session(thd)->lookup_table_handler(info.table_name());
14200
14201 if (intrinsic_table != nullptr) {
14202 thd_to_innodb_session(thd)->unregister_table_handler(info.table_name());
14203
14204 for (;;) {
14205 dict_index_t *index;
14206 index = UT_LIST_GET_FIRST(intrinsic_table->indexes);
14207 if (index == nullptr) {
14208 break;
14209 }
14210 rw_lock_free(&index->lock);
14211 UT_LIST_REMOVE(intrinsic_table->indexes, index);
14212 dict_mem_index_free(index);
14213 index = nullptr;
14214 }
14215
14216 dict_mem_table_free(intrinsic_table);
14217 intrinsic_table = nullptr;
14218 }
14219 }
14220
14221 return (error);
14222 }
14223
14224 template int innobase_basic_ddl::create_impl<dd::Table>(
14225 THD *, const char *, TABLE *, HA_CREATE_INFO *, dd::Table *, bool, bool,
14226 bool, uint32_t, uint32_t, const dd::Table *);
14227
14228 template int innobase_basic_ddl::create_impl<dd::Partition>(
14229 THD *, const char *, TABLE *, HA_CREATE_INFO *, dd::Partition *, bool, bool,
14230 bool, uint32_t, uint32_t, const dd::Table *);
14231
14232 template <typename Table>
14233 int innobase_basic_ddl::delete_impl(THD *thd, const char *name,
14234 const Table *dd_tab, const TABLE *td) {
14235 dberr_t error = DB_SUCCESS;
14236 char norm_name[FN_REFLEN];
14237
14238 DBUG_EXECUTE_IF("test_normalize_table_name", test_normalize_table_name(););
14239 DBUG_EXECUTE_IF("test_ut_format_name", test_ut_format_name(););
14240
14241 /* Strangely, MySQL passes the table name without the '.frm'
14242 extension, in contrast to ::create */
14243 if (!normalize_table_name(norm_name, name)) {
14244 /* purecov: begin inspected */
14245 ut_d(ut_error);
14246 ut_o(return (HA_ERR_TOO_LONG_PATH));
14247 /* purecov: end */
14248 }
14249
14250 innodb_session_t *&priv = thd_to_innodb_session(thd);
14251 dict_table_t *handler = priv->lookup_table_handler(norm_name);
14252
14253 if (handler != nullptr) {
14254 for (auto index : handler->indexes) {
14255 if (index->last_ins_cur) {
14256 /* last_ins_cur and last_sel_cur are allocated together, therefore only
14257 checking last_ins_cur before releasing mtr */
14258 index->last_ins_cur->release();
14259 index->last_sel_cur->release();
14260 }
14261 }
14262 } else if (srv_read_only_mode ||
14263 srv_force_recovery >= SRV_FORCE_NO_UNDO_LOG_SCAN) {
14264 return (HA_ERR_TABLE_READONLY);
14265 }
14266
14267 trx_t *trx = check_trx_exists(thd);
14268
14269 TrxInInnoDB trx_in_innodb(trx);
14270
14271 ulint name_len = strlen(name);
14272
14273 ut_a(name_len < 1000);
14274
14275 /* Either the transaction is already flagged as a locking transaction
14276 or it hasn't been started yet. */
14277
14278 ut_a(!trx_is_started(trx) || trx->will_lock > 0);
14279
14280 /* We are doing a DDL operation. */
14281 ++trx->will_lock;
14282
14283 bool file_per_table = false;
14284 if (dd_tab != nullptr && dd_tab->is_persistent()) {
14285 dict_table_t *tab;
14286
14287 dd::cache::Dictionary_client *client = dd::get_dd_client(thd);
14288 dd::cache::Dictionary_client::Auto_releaser releaser(client);
14289
14290 int err = dd_table_open_on_dd_obj(
14291 thd, client, dd_tab->table(),
14292 (!dd_table_is_partitioned(dd_tab->table())
14293 ? nullptr
14294 : reinterpret_cast<const dd::Partition *>(dd_tab)),
14295 norm_name, tab, td);
14296
14297 if (err == 0 && tab != nullptr) {
14298 if (tab->can_be_evicted && dd_table_is_partitioned(dd_tab->table())) {
14299 dict_sys_mutex_enter();
14300 dict_table_ddl_acquire(tab);
14301 dict_sys_mutex_exit();
14302 }
14303
14304 file_per_table = dict_table_is_file_per_table(tab);
14305 dd_table_close(tab, thd, nullptr, false);
14306 } else if (err == 4) {
14307 /* Could not open existing table. Definition may contain bad SQL. */
14308 error = DB_ERROR;
14309 }
14310 }
14311
14312 /* Don't drop what we can't open; otherwise, we'll hit asserts later. */
14313 if ((error == DB_SUCCESS) &&
14314 ((error = row_drop_table_for_mysql(norm_name, trx, true, handler)) ==
14315 DB_SUCCESS)) {
14316 if (handler != nullptr) {
14317 priv->unregister_table_handler(norm_name);
14318 }
14319
14320 if (file_per_table) {
14321 dd::Object_id dd_space_id = dd_first_index(dd_tab)->tablespace_id();
14322 dd::cache::Dictionary_client *client = dd::get_dd_client(thd);
14323 dd::cache::Dictionary_client::Auto_releaser releaser(client);
14324
14325 if (dd_drop_tablespace(client, dd_space_id)) {
14326 error = DB_ERROR;
14327 }
14328 }
14329 }
14330
14331 return (convert_error_code_to_mysql(error, 0, nullptr));
14332 }
14333
14334 template int innobase_basic_ddl::delete_impl<dd::Table>(THD *, const char *,
14335 const dd::Table *,
14336 const TABLE *);
14337
14338 template int innobase_basic_ddl::delete_impl<dd::Partition>(
14339 THD *, const char *, const dd::Partition *, const TABLE *);
14340
14341 template <typename Table>
14342 int innobase_basic_ddl::rename_impl(THD *thd, const char *from, const char *to,
14343 const Table *from_table,
14344 const Table *to_table, const TABLE *td) {
14345 dberr_t error;
14346 char norm_to[FN_REFLEN];
14347 char norm_from[FN_REFLEN];
14348 bool rename_file = false;
14349 space_id_t space = SPACE_UNKNOWN;
14350 dict_table_t *table = nullptr;
14351
14352 ut_ad(!srv_read_only_mode);
14353
14354 if (!normalize_table_name(norm_to, to) ||
14355 !normalize_table_name(norm_from, from)) {
14356 /* purecov: begin inspected */
14357 ut_d(ut_error);
14358 ut_o(return (HA_ERR_TOO_LONG_PATH));
14359 /* purecov: end */
14360 }
14361
14362 ut_ad(strcmp(norm_from, norm_to) != 0);
14363
14364 DEBUG_SYNC_C("innodb_rename_table_ready");
14365
14366 trx_t *trx = check_trx_exists(thd);
14367
14368 trx_start_if_not_started(trx, true, UT_LOCATION_HERE);
14369
14370 TrxInInnoDB trx_in_innodb(trx);
14371
14372 ++trx->will_lock;
14373
14374 dd::cache::Dictionary_client *client = dd::get_dd_client(thd);
14375 dd::cache::Dictionary_client::Auto_releaser releaser(client);
14376
14377 int err = dd_table_open_on_dd_obj(
14378 thd, client, from_table->table(),
14379 (!dd_table_is_partitioned(from_table->table())
14380 ? nullptr
14381 : reinterpret_cast<const dd::Partition *>(from_table)),
14382 norm_from, table, td);
14383 if (err != 0 || table == nullptr) {
14384 error = DB_TABLE_NOT_FOUND;
14385 return (convert_error_code_to_mysql(error, 0, nullptr));
14386 }
14387
14388 rename_file = dict_table_is_file_per_table(table);
14389 space = table->space;
14390
14391 if (row_is_mysql_tmp_table_name(norm_from) &&
14392 !row_is_mysql_tmp_table_name(norm_to) &&
14393 !dd_table_is_partitioned(from_table->table())) {
14394 table->refresh_fk = true;
14395 }
14396
14397 if (dd_table_is_partitioned(from_table->table())) {
14398 dict_sys_mutex_enter();
14399 dict_table_ddl_acquire(table);
14400 dict_sys_mutex_exit();
14401 }
14402
14403 dd_table_close(table, thd, nullptr, false);
14404
14405 /* Serialize data dictionary operations with dictionary mutex:
14406 no deadlocks can occur then in these operations. */
14407
14408 row_mysql_lock_data_dictionary(trx, UT_LOCATION_HERE);
14409
14410 error = row_rename_table_for_mysql(norm_from, norm_to, &to_table->table(),
14411 trx, false);
14412
14413 row_mysql_unlock_data_dictionary(trx);
14414
14415 if (error == DB_SUCCESS && rename_file) {
14416 char *new_path = fil_space_get_first_path(space);
14417
14418 auto dd_space_id = dd_first_index(to_table)->tablespace_id();
14419
14420 error = dd_tablespace_rename(dd_space_id, false, norm_to, new_path);
14421
14422 if (new_path != nullptr) {
14423 ut::free(new_path);
14424 }
14425 }
14426
14427 DEBUG_SYNC(thd, "after_innobase_rename_table");
14428
14429 if (error == DB_SUCCESS) {
14430 char errstr[512];
14431 dberr_t ret;
14432
14433 ret = dict_stats_rename_table(norm_from, norm_to, errstr, sizeof(errstr));
14434
14435 if (ret != DB_SUCCESS) {
14436 ib::error(ER_IB_MSG_566) << errstr;
14437
14438 push_warning(thd, Sql_condition::SL_WARNING, ER_LOCK_WAIT_TIMEOUT,
14439 errstr);
14440 }
14441 }
14442
14443 /* The duplicate key scenario was possible only for old DD since InnoDB
14444 would update it internally. With new DD, the rename conflict should be
14445 checked by server before diving into SE */
14446 ut_ad(error != DB_DUPLICATE_KEY);
14447
14448 return (convert_error_code_to_mysql(error, 0, nullptr));
14449 }
14450
14451 template int innobase_basic_ddl::rename_impl<dd::Table>(THD *, const char *,
14452 const char *,
14453 const dd::Table *,
14454 const dd::Table *,
14455 const TABLE *);
14456
14457 template int innobase_basic_ddl::rename_impl<dd::Partition>(
14458 THD *, const char *, const char *, const dd::Partition *,
14459 const dd::Partition *, const TABLE *);
14460
14461 template <typename Table>
14462 innobase_truncate<Table>::~innobase_truncate() {
14463 if (m_table != nullptr) {
14464 dd_table_close(m_table, m_thd, nullptr, false);
14465 m_table = nullptr;
14466 }
14467 }
14468
14469 template innobase_truncate<dd::Table>::~innobase_truncate();
14470 template innobase_truncate<dd::Partition>::~innobase_truncate();
14471
14472 template <typename Table>
14473 int innobase_truncate<Table>::open_table(dict_table_t *&innodb_table) {
14474 if (m_dd_table->table().is_persistent()) {
14475 dd::cache::Dictionary_client *client = dd::get_dd_client(m_thd);
14476 dd::cache::Dictionary_client::Auto_releaser releaser(client);
14477
14478 int error = dd_table_open_on_dd_obj(
14479 m_thd, client, m_dd_table->table(),
14480 (dd_table_is_partitioned(m_dd_table->table())
14481 ? reinterpret_cast<const dd::Partition *>(m_dd_table)
14482 : nullptr),
14483 m_name, innodb_table, m_form);
14484
14485 if (error != 0) {
14486 return (error);
14487 }
14488 } else {
14489 innodb_table = dd_table_open_on_name_in_mem(m_name, false);
14490 ut_ad(innodb_table->is_temporary());
14491 }
14492
14493 m_table = innodb_table;
14494
14495 return (0);
14496 }
14497
14498 template int innobase_truncate<dd::Table>::open_table(
14499 dict_table_t *&innodb_table);
14500 template int innobase_truncate<dd::Partition>::open_table(
14501 dict_table_t *&innodb_table);
14502
14503 template <typename Table>
14504 int innobase_truncate<Table>::prepare() {
14505 int error = 0;
14506
14507 if (m_table == nullptr) {
14508 error = open_table(m_table);
14509
14510 if (error != 0) {
14511 return (error);
14512 }
14513 }
14514
14515 ut_ad(m_table != nullptr);
14516
14517 m_trx = check_trx_exists(m_thd);
14518 m_file_per_table = dict_table_is_file_per_table(m_table);
14519 m_flags = m_table->flags;
14520 m_flags2 = m_table->flags2;
14521
14522 update_create_info_from_table(&m_create_info, m_form);
14523
14524 dd::cache::Dictionary_client *client = dd::get_dd_client(m_thd);
14525 dd::cache::Dictionary_client::Auto_releaser releaser(client);
14526
14527 /* Get the autoextend_size attribute value for the table being
14528 truncated. This values will be used to create the new table as
14529 part of truncate. */
14530 uint64_t autoextend_size{};
14531
14532 dd::Object_id space_id = dd_first_index(m_dd_table)->tablespace_id();
14533
14534 if (m_file_per_table) {
14535 dd_get_tablespace_size_option(client, space_id, &autoextend_size);
14536 }
14537
14538 m_create_info.m_implicit_tablespace_autoextend_size = autoextend_size;
14539
14540 m_create_info.tablespace = nullptr;
14541 if (m_table->is_temporary()) {
14542 m_create_info.options |= HA_LEX_CREATE_TMP_TABLE;
14543 } else {
14544 if (m_table->tablespace != nullptr) {
14545 m_create_info.tablespace = mem_strdup(m_table->tablespace);
14546 }
14547 }
14548
14549 m_create_info.key_block_size = m_form->s->key_block_size;
14550
14551 if (m_table->data_dir_path != nullptr) {
14552 m_create_info.data_file_name = mem_strdup(m_table->data_dir_path);
14553 } else {
14554 m_create_info.data_file_name = nullptr;
14555 }
14556
14557 if (m_table->can_be_evicted) {
14558 dict_sys_mutex_enter();
14559 dict_table_ddl_acquire(m_table);
14560 dict_sys_mutex_exit();
14561 }
14562
14563 if (!dict_table_has_autoinc_col(m_table)) {
14564 m_keep_autoinc = false;
14565 }
14566
14567 return (error);
14568 }
14569
14570 template <typename Table>
14571 int innobase_truncate<Table>::truncate() {
14572 int error = 0;
14573 bool reset = false;
14574 uint64_t autoinc = 0;
14575 uint64_t autoinc_persisted = 0;
14576
14577 /* Rename tablespace file to avoid existing file in create. */
14578 if (m_file_per_table) {
14579 error = rename_tablespace();
14580 }
14581
14582 DBUG_EXECUTE_IF("ib_truncate_fail_after_rename", error = HA_ERR_GENERIC;);
14583
14584 if (error != 0) {
14585 return (error);
14586 }
14587
14588 if (m_keep_autoinc) {
14589 autoinc_persisted = m_table->autoinc_persisted;
14590 autoinc = m_table->autoinc;
14591 }
14592
14593 dd_table_close(m_table, m_thd, nullptr, false);
14594 m_table = nullptr;
14595
14596 DBUG_EXECUTE_IF("ib_truncate_crash_after_rename", DBUG_SUICIDE(););
14597
14598 error = innobase_basic_ddl::delete_impl(m_thd, m_name, m_dd_table, nullptr);
14599
14600 DBUG_EXECUTE_IF("ib_truncate_fail_after_delete", error = HA_ERR_GENERIC;);
14601
14602 if (error != 0) {
14603 return (error);
14604 }
14605
14606 DBUG_EXECUTE_IF("ib_truncate_crash_after_drop_old_table", DBUG_SUICIDE(););
14607
14608 if (m_dd_table->is_persistent()) {
14609 m_dd_table->set_se_private_id(dd::INVALID_OBJECT_ID);
14610 for (auto dd_index : *m_dd_table->indexes()) {
14611 dd_index->se_private_data().clear();
14612 }
14613 }
14614
14615 if (dd_table_is_partitioned(m_dd_table->table()) &&
14616 m_create_info.tablespace != nullptr &&
14617 m_dd_table->tablespace_id() == dd::INVALID_OBJECT_ID) {
14618 /* Don't change the tablespace if it's a partitioned table,
14619 so temporarily set the tablespace_id as an explicit one
14620 to make it consistent with info->tablespace */
14621 m_dd_table->set_tablespace_id(dd_first_index(m_dd_table)->tablespace_id());
14622 reset = true;
14623 }
14624
14625 m_trx->in_truncate = true;
14626 bool inherit_metadata = false;
14627 if (dd_table_has_instant_cols(m_dd_table->table()) &&
14628 dd_table_is_partitioned(m_dd_table->table()) && !m_table_truncate) {
14629 /* For a partition table, if this is not a full table truncate, and first
14630 partition is getting truncated, make sure INSTANT metadata is inherited. */
14631 inherit_metadata = true;
14632 }
14633 error = innobase_basic_ddl::create_impl(
14634 m_thd, m_name, m_form, &m_create_info, m_dd_table, m_file_per_table,
14635 false, true, m_flags, m_flags2,
14636 inherit_metadata ? &m_dd_table->table() : nullptr);
14637 m_trx->in_truncate = false;
14638
14639 if (reset) {
14640 m_dd_table->set_tablespace_id(dd::INVALID_OBJECT_ID);
14641 }
14642
14643 if (error == 0) {
14644 dict_sys_mutex_enter();
14645 m_table = dict_table_check_if_in_cache_low(m_name);
14646 ut_ad(m_table != nullptr);
14647 m_table->acquire();
14648
14649 if (m_keep_autoinc) {
14650 m_table->autoinc_persisted = autoinc_persisted;
14651 m_table->autoinc = autoinc;
14652 }
14653
14654 dict_sys_mutex_exit();
14655 }
14656
14657 DBUG_EXECUTE_IF("ib_truncate_fail_after_create_new_table",
14658 error = HA_ERR_GENERIC;);
14659
14660 DBUG_EXECUTE_IF("ib_truncate_crash_after_create_new_table", DBUG_SUICIDE(););
14661
14662 return (error);
14663 }
14664
14665 template <typename Table>
14666 int innobase_truncate<Table>::rename_tablespace() {
14667 ut_ad(m_table != nullptr);
14668 ut_ad(dict_table_is_file_per_table(m_table));
14669 ut_ad(!m_table->is_temporary());
14670 ut_ad(m_table->trunc_name.m_name == nullptr);
14671
14672 uint64_t old_size = mem_heap_get_size(m_table->heap);
14673 char *temp_name = dict_mem_create_temporary_tablename(
14674 m_table->heap, m_table->name.m_name, m_table->id);
14675 uint64_t new_size = mem_heap_get_size(m_table->heap);
14676
14677 dict_sys_mutex_enter();
14678 dict_sys->size += new_size - old_size;
14679 dict_sys_mutex_exit();
14680
14681 std::string new_path;
14682 char *old_path = fil_space_get_first_path(m_table->space);
14683
14684 if (DICT_TF_HAS_DATA_DIR(m_table->flags)) {
14685 new_path = Fil_path::make_new_path(old_path, temp_name, IBD);
14686 } else {
14687 char *ptr = Fil_path::make_ibd_from_table_name(temp_name);
14688 new_path.assign(ptr);
14689 ut::free(ptr);
14690 }
14691
14692 /* New filepath must not exist. */
14693 dberr_t err = fil_rename_tablespace_check(m_table->space, old_path,
14694 new_path.c_str(), false);
14695
14696 if (err == DB_SUCCESS) {
14697 dict_sys_mutex_enter();
14698 err = fil_rename_tablespace(m_table->space, old_path, temp_name,
14699 new_path.c_str());
14700 dict_sys_mutex_exit();
14701
14702 if (err == DB_SUCCESS) {
14703 m_table->trunc_name.m_name = temp_name;
14704 }
14705 }
14706
14707 ut::free(old_path);
14708
14709 return (convert_error_code_to_mysql(err, m_table->flags, nullptr));
14710 }
14711
14712 template <typename Table>
14713 void innobase_truncate<Table>::cleanup() {
14714 if (m_table == nullptr) {
14715 m_table = dd_table_open_on_name_in_mem(m_name, false);
14716 }
14717
14718 if (m_table != nullptr) {
14719 m_table->trunc_name.m_name = nullptr;
14720 }
14721
14722 char *tablespace = const_cast<char *>(m_create_info.tablespace);
14723 char *data_file_name = const_cast<char *>(m_create_info.data_file_name);
14724
14725 ut::free(tablespace);
14726 ut::free(data_file_name);
14727 }
14728
14729 template <typename Table>
14730 int innobase_truncate<Table>::load_fk() {
14731 if (dd_table_is_partitioned(m_dd_table->table())) {
14732 return (0);
14733 }
14734
14735 int error = 0;
14736 dict_names_t fk_tables;
14737 dd::cache::Dictionary_client *client = dd::get_dd_client(m_thd);
14738 dd::cache::Dictionary_client::Auto_releaser releaser(client);
14739
14740 ut_ad(m_table != nullptr);
14741 error =
14742 dd_table_check_for_child(client, m_table->name.m_name, nullptr, m_table,
14743 true, DICT_ERR_IGNORE_NONE, &fk_tables);
14744
14745 ut_ad(fk_tables.empty());
14746
14747 if (error != DB_SUCCESS) {
14748 push_warning_printf(m_thd, Sql_condition::SL_WARNING,
14749 HA_ERR_CANNOT_ADD_FOREIGN,
14750 "Truncate table '%s' failed to load some"
14751 " foreign key constraints.",
14752 m_name);
14753 } else {
14754 error = 0;
14755 }
14756
14757 return (error);
14758 }
14759
14760 template <typename Table>
14761 int innobase_truncate<Table>::exec() {
14762 int error = 0;
14763
14764 error = prepare();
14765
14766 if (error == 0) {
14767 error = truncate();
14768 }
14769
14770 cleanup();
14771
14772 if (error == 0) {
14773 error = load_fk();
14774 }
14775
14776 DBUG_EXECUTE_IF("ib_truncate_crash_after_innodb_complete", DBUG_SUICIDE(););
14777
14778 DBUG_EXECUTE_IF("ib_truncate_rollback_test", error = HA_ERR_GENERIC;);
14779
14780 return (error);
14781 }
14782
14783 template int innobase_truncate<dd::Table>::exec();
14784 template int innobase_truncate<dd::Partition>::exec();
14785
14786 /** Check if a column is the only column in an index.
14787 @param[in] index data dictionary index
14788 @param[in] column the column to look for
14789 @return whether the column is the only column in the index */
14790 static bool dd_is_only_column(const dd::Index *index,
14791 const dd::Column *column) {
14792 return (index->elements().size() == 1 &&
14793 &(*index->elements().begin())->column() == column);
14794 }
14795
14796 /** Add hidden columns and indexes to an InnoDB table definition.
14797 @param[in,out] dd_table data dictionary cache object
14798 @return error number
14799 @retval 0 on success */
14800 int ha_innobase::get_extra_columns_and_keys(const HA_CREATE_INFO *,
14801 const List<Create_field> *,
14802 const KEY *, uint,
14803 dd::Table *dd_table) {
14804 DBUG_TRACE;
14805 THD *thd = ha_thd();
14806 dd::Index *primary = nullptr;
14807 bool has_fulltext = false;
14808 const dd::Index *fts_doc_id_index = nullptr;
14809
14810 for (dd::Index *i : *dd_table->indexes()) {
14811 /* The name "PRIMARY" is reserved for the PRIMARY KEY */
14812 ut_ad((i->type() == dd::Index::IT_PRIMARY) ==
14813 !my_strcasecmp(system_charset_info, i->name().c_str(),
14814 primary_key_name));
14815
14816 if (!my_strcasecmp(system_charset_info, i->name().c_str(),
14817 FTS_DOC_ID_INDEX_NAME)) {
14818 ut_ad(!fts_doc_id_index);
14819 ut_ad(i->type() != dd::Index::IT_PRIMARY);
14820 fts_doc_id_index = i;
14821 }
14822
14823 switch (i->algorithm()) {
14824 case dd::Index::IA_SE_SPECIFIC:
14825 ut_d(ut_error);
14826 ut_o(break);
14827 case dd::Index::IA_HASH:
14828 /* This is currently blocked
14829 by ha_innobase::is_index_algorithm_supported(). */
14830 ut_d(ut_error);
14831 ut_o(break);
14832 case dd::Index::IA_RTREE:
14833 if (i->type() == dd::Index::IT_SPATIAL) {
14834 continue;
14835 }
14836 ut_d(ut_error);
14837 ut_o(break);
14838 case dd::Index::IA_BTREE:
14839 switch (i->type()) {
14840 case dd::Index::IT_PRIMARY:
14841 ut_ad(!primary);
14842 ut_ad(i == *dd_table->indexes()->begin());
14843 primary = i;
14844 continue;
14845 case dd::Index::IT_UNIQUE:
14846 if (primary == nullptr && i->is_candidate_key()) {
14847 primary = i;
14848 ut_ad(*dd_table->indexes()->begin() == i);
14849 }
14850 continue;
14851 case dd::Index::IT_MULTIPLE:
14852 continue;
14853 case dd::Index::IT_FULLTEXT:
14854 case dd::Index::IT_SPATIAL:
14855 ut_d(ut_error);
14856 }
14857 break;
14858 case dd::Index::IA_FULLTEXT:
14859 if (i->type() == dd::Index::IT_FULLTEXT) {
14860 has_fulltext = true;
14861 continue;
14862 }
14863 ut_d(ut_error);
14864 ut_o(break);
14865 }
14866
14867 my_error(ER_UNSUPPORTED_INDEX_ALGORITHM, MYF(0), i->name().c_str());
14868 return ER_UNSUPPORTED_INDEX_ALGORITHM;
14869 }
14870
14871 if (has_fulltext) {
14872 /* Add FTS_DOC_ID_INDEX(FTS_DOC_ID) if needed */
14873 const dd::Column *fts_doc_id =
14874 dd_find_column(dd_table, FTS_DOC_ID_COL_NAME);
14875
14876 if (fts_doc_id_index) {
14877 switch (fts_doc_id_index->type()) {
14878 case dd::Index::IT_PRIMARY:
14879 /* PRIMARY!=FTS_DOC_ID_INDEX */
14880 ut_ad(!"wrong fts_doc_id_index");
14881 [[fallthrough]];
14882 case dd::Index::IT_UNIQUE:
14883 /* We already checked for this. */
14884 ut_ad(fts_doc_id_index->algorithm() == dd::Index::IA_BTREE);
14885 if (dd_is_only_column(fts_doc_id_index, fts_doc_id)) {
14886 break;
14887 }
14888 [[fallthrough]];
14889 case dd::Index::IT_MULTIPLE:
14890 case dd::Index::IT_FULLTEXT:
14891 case dd::Index::IT_SPATIAL:
14892 my_error(ER_INNODB_FT_WRONG_DOCID_INDEX, MYF(0),
14893 fts_doc_id_index->name().c_str());
14894 push_warning(thd, Sql_condition::SL_WARNING, ER_WRONG_NAME_FOR_INDEX,
14895 " InnoDB: Index name " FTS_DOC_ID_INDEX_NAME
14896 " is reserved"
14897 " for UNIQUE INDEX(" FTS_DOC_ID_COL_NAME
14898 ") for "
14899 " FULLTEXT Document ID indexing.");
14900 return ER_INNODB_FT_WRONG_DOCID_INDEX;
14901 }
14902 ut_ad(fts_doc_id);
14903 }
14904
14905 if (fts_doc_id) {
14906 if (fts_doc_id->type() != dd::enum_column_types::LONGLONG ||
14907 fts_doc_id->is_nullable() ||
14908 fts_doc_id->name() != FTS_DOC_ID_COL_NAME) {
14909 my_error(ER_INNODB_FT_WRONG_DOCID_COLUMN, MYF(0),
14910 fts_doc_id->name().c_str());
14911 push_warning(thd, Sql_condition::SL_WARNING, ER_WRONG_COLUMN_NAME,
14912 " InnoDB: Column name " FTS_DOC_ID_COL_NAME
14913 " is reserved for"
14914 " FULLTEXT Document ID indexing.");
14915 return ER_INNODB_FT_WRONG_DOCID_COLUMN;
14916 }
14917 } else {
14918 /* Add hidden FTS_DOC_ID column */
14919 dd::Column *col = dd_table->add_column();
14920 col->set_hidden(dd::Column::enum_hidden_type::HT_HIDDEN_SE);
14921 col->set_name(FTS_DOC_ID_COL_NAME);
14922 col->set_type(dd::enum_column_types::LONGLONG);
14923 col->set_nullable(false);
14924 col->set_unsigned(true);
14925 col->set_collation_id(1);
14926 fts_doc_id = col;
14927 }
14928
14929 ut_ad(fts_doc_id);
14930
14931 if (fts_doc_id_index == nullptr) {
14932 dd_set_hidden_unique_index(dd_table->add_index(), FTS_DOC_ID_INDEX_NAME,
14933 fts_doc_id);
14934 }
14935 }
14936
14937 if (primary == nullptr) {
14938 dd::Column *db_row_id = dd_add_hidden_column(
14939 dd_table, "DB_ROW_ID", DATA_ROW_ID_LEN, dd::enum_column_types::INT24);
14940
14941 if (db_row_id == nullptr) {
14942 return ER_WRONG_COLUMN_NAME;
14943 }
14944
14945 primary = dd_set_hidden_unique_index(dd_table->add_first_index(),
14946 primary_key_name, db_row_id);
14947 }
14948
14949 /* Add PRIMARY KEY columns to each secondary index, including:
14950 1. all PRIMARY KEY column prefixes
14951 2. full PRIMARY KEY columns which don't exist in the secondary index */
14952
14953 std::vector<const dd::Index_element *,
14954 ut::allocator<const dd::Index_element *>>
14955 pk_elements;
14956
14957 for (dd::Index *index : *dd_table->indexes()) {
14958 if (index == primary) {
14959 continue;
14960 }
14961
14962 pk_elements.clear();
14963 for (const dd::Index_element *e : primary->elements()) {
14964 if (e->is_prefix() ||
14965 std::search_n(
14966 index->elements().begin(), index->elements().end(), 1, e,
14967 [](const dd::Index_element *ie, const dd::Index_element *e) {
14968 return (&ie->column() == &e->column());
14969 }) == index->elements().end()) {
14970 pk_elements.push_back(e);
14971 }
14972 }
14973
14974 for (const dd::Index_element *e : pk_elements) {
14975 auto ie = index->add_element(const_cast<dd::Column *>(&e->column()));
14976 ie->set_hidden(true);
14977 ie->set_order(e->order());
14978 }
14979 }
14980
14981 /* Add the InnoDB system columns DB_TRX_ID, DB_ROLL_PTR. */
14982 dd::Column *db_trx_id = dd_add_hidden_column(
14983 dd_table, "DB_TRX_ID", DATA_TRX_ID_LEN, dd::enum_column_types::INT24);
14984 if (db_trx_id == nullptr) {
14985 return ER_WRONG_COLUMN_NAME;
14986 }
14987
14988 dd::Column *db_roll_ptr =
14989 dd_add_hidden_column(dd_table, "DB_ROLL_PTR", DATA_ROLL_PTR_LEN,
14990 dd::enum_column_types::LONGLONG);
14991 if (db_roll_ptr == nullptr) {
14992 return ER_WRONG_COLUMN_NAME;
14993 }
14994
14995 dd_add_hidden_element(primary, db_trx_id);
14996 dd_add_hidden_element(primary, db_roll_ptr);
14997
14998 /* Add all non-virtual columns to the clustered index,
14999 unless they already part of the PRIMARY KEY. */
15000
15001 for (const dd::Column *c :
15002 const_cast<const dd::Table *>(dd_table)->columns()) {
15003 if (c->is_se_hidden() || c->is_virtual()) {
15004 continue;
15005 }
15006
15007 if (std::search_n(primary->elements().begin(), primary->elements().end(), 1,
15008 c, [](const dd::Index_element *e, const dd::Column *c) {
15009 return (!e->is_prefix() && &e->column() == c);
15010 }) == primary->elements().end()) {
15011 dd_add_hidden_element(primary, c);
15012 }
15013 }
15014
15015 return 0;
15016 }
15017
15018 /** Set Engine specific data to dd::Table object for upgrade.
15019 @param[in,out] thd thread handle
15020 @param[in] db_name database name
15021 @param[in] table_name table name
15022 @param[in,out] dd_table data dictionary cache object
15023 @return 0 on success, non-zero on failure */
15024 bool ha_innobase::upgrade_table(THD *thd, const char *db_name,
15025 const char *table_name, dd::Table *dd_table) {
15026 return (dd_upgrade_table(thd, db_name, table_name, dd_table, table));
15027 }
15028
15029 /** Get storage-engine private data for a data dictionary table.
15030 @param[in,out] dd_table data dictionary table definition
15031 @param reset reset counters
15032 @retval true an error occurred
15033 @retval false success */
15034 bool ha_innobase::get_se_private_data(dd::Table *dd_table, bool reset) {
15035 static uint n_tables = 0;
15036 static uint n_indexes = 0;
15037 static uint n_pages = 4;
15038
15039 /* Reset counters on second create during upgrade. */
15040 if (reset) {
15041 n_tables = 0;
15042 n_indexes = 0;
15043 n_pages = 4;
15044 // Also need to reset the set of DD table ids.
15045 dict_sys_t::s_dd_table_ids.clear();
15046 }
15047 #ifdef UNIV_DEBUG
15048 const uint n_indexes_old = n_indexes;
15049 #endif
15050
15051 DBUG_TRACE;
15052 assert(dd_table != nullptr);
15053 assert(n_tables < innodb_dd_table_size);
15054
15055 if ((*(const_cast<const dd::Table *>(dd_table))->columns().begin())
15056 ->is_auto_increment()) {
15057 dd_set_autoinc(dd_table->se_private_data(), 0);
15058 }
15059
15060 #ifdef UNIV_DEBUG
15061 {
15062 /* These tables must not be partitioned. */
15063 assert(dd_table->partitions()->empty());
15064 }
15065
15066 const innodb_dd_table_t &data = innodb_dd_table[n_tables];
15067 #endif
15068
15069 assert(dd_table->name() == data.name);
15070
15071 dd_table->set_se_private_id(++n_tables);
15072 dd_table->set_tablespace_id(dict_sys_t::s_dd_dict_space_id);
15073
15074 /* Set the table id for each column to be conform with the
15075 implementation in dd_write_table(). */
15076 for (auto dd_column : *dd_table->table().columns()) {
15077 dd_column->se_private_data().set(dd_index_key_strings[DD_TABLE_ID],
15078 n_tables);
15079 }
15080
15081 for (dd::Index *i : *dd_table->indexes()) {
15082 i->set_tablespace_id(dict_sys_t::s_dd_dict_space_id);
15083
15084 if (fsp_is_inode_page(n_pages)) {
15085 ++n_pages;
15086 ut_ad(!fsp_is_inode_page(n_pages));
15087 }
15088
15089 dd::Properties &p = i->se_private_data();
15090
15091 p.set(dd_index_key_strings[DD_INDEX_ROOT], n_pages++);
15092 p.set(dd_index_key_strings[DD_INDEX_ID], ++n_indexes);
15093 p.set(dd_index_key_strings[DD_INDEX_TRX_ID], 0);
15094 p.set(dd_index_key_strings[DD_INDEX_SPACE_ID], dict_sys_t::s_dict_space_id);
15095 p.set(dd_index_key_strings[DD_TABLE_ID], n_tables);
15096 }
15097
15098 assert(n_indexes - n_indexes_old == data.n_indexes);
15099
15100 return false;
15101 }
15102
15103 /** Create an InnoDB table.
15104 @param[in] name table name in filename-safe encoding
15105 @param[in] form table structure
15106 @param[in] create_info more information on the table
15107 @param[in,out] table_def dd::Table describing table to be
15108 created. Can be adjusted by SE, the changes will be saved into data-dictionary
15109 at statement commit time.
15110 @return error number
15111 @retval 0 on success */
15112 int ha_innobase::create(const char *name, TABLE *form,
15113 HA_CREATE_INFO *create_info, dd::Table *table_def) {
15114 THD *thd = ha_thd();
15115
15116 if (thd_sql_command(thd) == SQLCOM_TRUNCATE) {
15117 return (truncate_impl(name, form, table_def));
15118 }
15119
15120 trx_t *trx = check_trx_exists(thd);
15121
15122 if (!(create_info->options & HA_LEX_CREATE_TMP_TABLE)) {
15123 innobase_register_trx(ht, thd, trx);
15124 }
15125
15126 /* Determine if this CREATE TABLE will be making a file-per-table
15127 tablespace. Note that "srv_file_per_table" is not under
15128 dict_sys mutex protection, and could be changed while creating the
15129 table. So we read the current value here and make all further
15130 decisions based on this. */
15131 return (innobase_basic_ddl::create_impl(ha_thd(), name, form, create_info,
15132 table_def, srv_file_per_table, true,
15133 false, 0, 0, nullptr));
15134 }
15135
15136 /** Discards or imports an InnoDB tablespace.
15137 @param[in] discard true if discard, else import
15138 @param[in,out] table_def dd::Table describing table which
15139 tablespace is to be imported or discarded. Can be adjusted by SE,
15140 the changes will be saved into the data-dictionary at statement
15141 commit time.
15142 @return 0 == success, -1 == error */
15143
15144 int ha_innobase::discard_or_import_tablespace(bool discard,
15145 dd::Table *table_def) {
15146 DBUG_TRACE;
15147
15148 ut_a(m_prebuilt->trx != nullptr);
15149 ut_a(m_prebuilt->trx->magic_n == TRX_MAGIC_N);
15150 ut_a(m_prebuilt->trx == thd_to_trx(ha_thd()));
15151
15152 if (high_level_read_only) {
15153 return HA_ERR_TABLE_READONLY;
15154 }
15155
15156 dict_table_t *dict_table = m_prebuilt->table;
15157
15158 if (dict_table->is_temporary()) {
15159 ib_senderrf(m_prebuilt->trx->mysql_thd, IB_LOG_LEVEL_ERROR,
15160 ER_CANNOT_DISCARD_TEMPORARY_TABLE);
15161
15162 return HA_ERR_TABLE_NEEDS_UPGRADE;
15163 }
15164
15165 if (dict_table->space == TRX_SYS_SPACE) {
15166 ib_senderrf(m_prebuilt->trx->mysql_thd, IB_LOG_LEVEL_ERROR,
15167 ER_TABLE_IN_SYSTEM_TABLESPACE, dict_table->name.m_name);
15168
15169 return HA_ERR_TABLE_NEEDS_UPGRADE;
15170 }
15171
15172 if (DICT_TF_HAS_SHARED_SPACE(dict_table->flags)) {
15173 my_printf_error(ER_NOT_ALLOWED_COMMAND,
15174 "InnoDB: Cannot %s table `%s` because it is in"
15175 " a general tablespace. It must be file-per-table.",
15176 MYF(0), discard ? "discard" : "import",
15177 dict_table->name.m_name);
15178
15179 return HA_ERR_NOT_ALLOWED_COMMAND;
15180 }
15181
15182 TrxInInnoDB trx_in_innodb(m_prebuilt->trx);
15183
15184 if (trx_in_innodb.is_aborted()) {
15185 innobase_rollback(ht, m_user_thd, false);
15186
15187 return convert_error_code_to_mysql(DB_FORCED_ABORT, 0, m_user_thd);
15188 }
15189
15190 trx_start_if_not_started(m_prebuilt->trx, true, UT_LOCATION_HERE);
15191
15192 /* Obtain an exclusive lock on the table. */
15193 dberr_t err = row_mysql_lock_table(
15194 m_prebuilt->trx, dict_table, LOCK_X,
15195 discard ? "setting table lock for DISCARD TABLESPACE"
15196 : "setting table lock for IMPORT TABLESPACE");
15197
15198 if (err != DB_SUCCESS) {
15199 /* unable to lock the table: do nothing */
15200 /* purecov: begin inspected */
15201 return convert_error_code_to_mysql(err, dict_table->flags, nullptr);
15202 /* purecov: end */
15203 }
15204
15205 /* Concurrent clone operation is not supported. */
15206 Clone_notify notifier(Clone_notify::Type::SPACE_IMPORT,
15207 dict_sys_t::s_invalid_space_id, false);
15208 if (notifier.failed()) {
15209 return notifier.get_error();
15210 }
15211
15212 if (discard) {
15213 /* Discarding an already discarded tablespace should be an
15214 idempotent operation. Also, if the .ibd file is missing the
15215 user may want to set the DISCARD flag in order to IMPORT
15216 a new tablespace. */
15217
15218 if (dict_table->ibd_file_missing) {
15219 ib_senderrf(m_prebuilt->trx->mysql_thd, IB_LOG_LEVEL_WARN,
15220 ER_TABLESPACE_MISSING, dict_table->name.m_name);
15221 }
15222
15223 err = row_discard_tablespace_for_mysql(dict_table->name.m_name,
15224 m_prebuilt->trx);
15225
15226 } else if (!dict_table->ibd_file_missing) {
15227 ib::error(ER_IB_MSG_567)
15228 << "Unable to import tablespace " << dict_table->name
15229 << " because it already"
15230 " exists. Please DISCARD the tablespace"
15231 " before IMPORT.";
15232 ib_senderrf(m_prebuilt->trx->mysql_thd, IB_LOG_LEVEL_ERROR,
15233 ER_TABLESPACE_EXISTS, dict_table->name.m_name);
15234
15235 return HA_ERR_TABLE_EXIST;
15236 } else {
15237 err = row_import_for_mysql(dict_table, table_def, m_prebuilt);
15238
15239 if (err == DB_SUCCESS) {
15240 info(HA_STATUS_TIME | HA_STATUS_CONST | HA_STATUS_VARIABLE |
15241 HA_STATUS_AUTO);
15242 }
15243 }
15244
15245 /* Set the TABLESPACE DISCARD flag in the table definition
15246 on disk. */
15247 if (err == DB_SUCCESS) {
15248 dd_table_discard_tablespace(m_prebuilt->trx->mysql_thd, dict_table,
15249 table_def, discard);
15250 }
15251
15252 if (err == DB_SUCCESS && !discard &&
15253 dict_stats_is_persistent_enabled(dict_table)) {
15254 dberr_t ret;
15255
15256 /* Adjust the persistent statistics. */
15257 ret = dict_stats_update(dict_table, DICT_STATS_RECALC_PERSISTENT);
15258
15259 if (ret != DB_SUCCESS) {
15260 push_warning_printf(ha_thd(), Sql_condition::SL_WARNING, ER_ALTER_INFO,
15261 "Error updating stats for table '%s'"
15262 " after table rebuild: %s",
15263 dict_table->name.m_name, ut_strerr(ret));
15264 }
15265 }
15266
15267 return convert_error_code_to_mysql(err, dict_table->flags, nullptr);
15268 }
15269
15270 int ha_innobase::truncate_impl(const char *name, TABLE *form,
15271 dd::Table *table_def) {
15272 DBUG_TRACE;
15273
15274 /* Truncate of intrinsic table or hard-coded DD tables is not allowed
15275 for now. */
15276 if (table_def == nullptr ||
15277 dict_sys_t::is_dd_table_id(table_def->se_private_id())) {
15278 my_error(ER_NOT_ALLOWED_COMMAND, MYF(0));
15279 return HA_ERR_UNSUPPORTED;
15280 }
15281
15282 if (high_level_read_only) {
15283 return HA_ERR_TABLE_READONLY;
15284 }
15285
15286 char norm_name[FN_REFLEN];
15287 THD *thd = ha_thd();
15288 dict_table_t *innodb_table = nullptr;
15289 bool has_autoinc = false;
15290 int error = 0;
15291 const bool is_instant = dd_table_has_instant_cols(*table_def);
15292
15293 if (!normalize_table_name(norm_name, name)) {
15294 /* purecov: begin inspected */
15295 ut_d(ut_error);
15296 ut_o(return (HA_ERR_TOO_LONG_PATH));
15297 /* purecov: end */
15298 }
15299
15300 innobase_truncate<dd::Table> truncator(thd, norm_name, form, table_def, false,
15301 true);
15302
15303 error = truncator.open_table(innodb_table);
15304
15305 if (error != 0) {
15306 return error;
15307 }
15308
15309 has_autoinc = dict_table_has_autoinc_col(innodb_table);
15310
15311 if (dict_table_is_discarded(innodb_table)) {
15312 ib_senderrf(thd, IB_LOG_LEVEL_ERROR, ER_TABLESPACE_DISCARDED, norm_name);
15313 return HA_ERR_NO_SUCH_TABLE;
15314 } else if (innodb_table->ibd_file_missing) {
15315 return HA_ERR_TABLESPACE_MISSING;
15316 }
15317
15318 trx_t *trx = check_trx_exists(thd);
15319 innobase_register_trx(ht, thd, trx);
15320
15321 error = truncator.exec();
15322
15323 if (error == 0) {
15324 if (has_autoinc) {
15325 dd_set_autoinc(table_def->se_private_data(), 0);
15326 }
15327
15328 if (is_instant) {
15329 if (dd_clear_instant_table(*table_def, true) != DB_SUCCESS) {
15330 error = HA_ERR_GENERIC;
15331 }
15332 }
15333 }
15334
15335 return error;
15336 }
15337
15338 /** Drop a table.
15339 @param[in] name table name
15340 @param[in] table_def dd::Table describing table to
15341 be dropped
15342 @return error number
15343 @retval 0 on success */
15344 int ha_innobase::delete_table(const char *name, const dd::Table *table_def) {
15345 if (table_def != nullptr &&
15346 dict_sys_t::is_dd_table_id(table_def->se_private_id())) {
15347 my_error(ER_NOT_ALLOWED_COMMAND, MYF(0));
15348 return (HA_ERR_UNSUPPORTED);
15349 }
15350
15351 THD *thd = ha_thd();
15352 trx_t *trx = check_trx_exists(thd);
15353
15354 if (table_def != nullptr && table_def->is_persistent()) {
15355 innobase_register_trx(ht, thd, trx);
15356 }
15357
15358 return (innobase_basic_ddl::delete_impl(thd, name, table_def, nullptr));
15359 }
15360
15361 /** Validate the parameters in st_alter_tablespace
15362 before using them in InnoDB tablespace functions.
15363 @param[in] type Type os tablespace being validated
15364 @param[in] alter_info How to do the command.
15365 @return MySQL handler error code like HA_... */
15366 static int validate_create_tablespace_info(ib_file_suffix type,
15367 st_alter_tablespace *alter_info) {
15368 /* The parser ensures that these fields are provided. */
15369 ut_a(alter_info->data_file_name != nullptr);
15370 ut_a(alter_info->tablespace_name != nullptr);
15371
15372 if (high_level_read_only) {
15373 return (HA_ERR_INNODB_READ_ONLY);
15374 }
15375
15376 /* Name validation should be ensured from the SQL layer. */
15377 ut_ad(0 == validate_tablespace_name(alter_info->ts_cmd_type,
15378 alter_info->tablespace_name));
15379
15380 int error = 0;
15381
15382 /* Make sure the tablespace is not already open. */
15383
15384 space_id_t space_id;
15385
15386 space_id = fil_space_get_id_by_name(alter_info->tablespace_name);
15387
15388 if (space_id != SPACE_UNKNOWN) {
15389 my_printf_error(ER_TABLESPACE_EXISTS,
15390 "InnoDB: A tablespace named `%s`"
15391 " already exists.",
15392 MYF(0), alter_info->tablespace_name);
15393 error = HA_ERR_TABLESPACE_EXISTS;
15394 }
15395
15396 if (type == IBD && alter_info->file_block_size) {
15397 /* Check for a bad file block size. */
15398 if (!ut_is_2pow(alter_info->file_block_size) ||
15399 alter_info->file_block_size < UNIV_ZIP_SIZE_MIN ||
15400 alter_info->file_block_size > UNIV_PAGE_SIZE_MAX) {
15401 my_printf_error(ER_ILLEGAL_HA_CREATE_OPTION,
15402 "InnoDB does not support"
15403 " FILE_BLOCK_SIZE=%llu",
15404 MYF(0), alter_info->file_block_size);
15405 error = HA_WRONG_CREATE_OPTION;
15406
15407 /* Don't allow a file block size larger than UNIV_PAGE_SIZE. */
15408 } else if (alter_info->file_block_size > UNIV_PAGE_SIZE) {
15409 my_printf_error(ER_ILLEGAL_HA_CREATE_OPTION,
15410 "InnoDB: Cannot create a tablespace"
15411 " with FILE_BLOCK_SIZE=%llu because"
15412 " INNODB_PAGE_SIZE=" ULINTPF ".",
15413 MYF(0), alter_info->file_block_size, UNIV_PAGE_SIZE);
15414 error = HA_WRONG_CREATE_OPTION;
15415
15416 /* Don't allow a compressed tablespace when page size > 16k. */
15417 } else if (UNIV_PAGE_SIZE > UNIV_PAGE_SIZE_DEF &&
15418 alter_info->file_block_size != UNIV_PAGE_SIZE) {
15419 my_printf_error(ER_ILLEGAL_HA_CREATE_OPTION,
15420 "InnoDB: Cannot create a COMPRESSED"
15421 " tablespace when innodb_page_size >"
15422 " 16k.",
15423 MYF(0));
15424 error = HA_WRONG_CREATE_OPTION;
15425 }
15426 }
15427
15428 /* Validate AUTOEXTEND_SIZE clause. */
15429 if (alter_info->autoextend_size.has_value() &&
15430 alter_info->autoextend_size.value() > 0 &&
15431 validate_autoextend_size_value(alter_info->autoextend_size.value()) !=
15432 DB_SUCCESS) {
15433 error = HA_WRONG_CREATE_OPTION;
15434 }
15435
15436 /* Validate the ADD DATAFILE name. */
15437 std::string datafile_name(alter_info->data_file_name);
15438
15439 /* Undo Tablespace ADD DATAFILE filenames cannot be relative paths
15440 because it would be unclear what they are relative to. However,
15441 srv_undo_dir can be a relative directory. So evaluate this
15442 ADD DATAFILE value before it is appended to the undo dir. */
15443 if (type == IBU && Fil_path::is_relative_path(datafile_name)) {
15444 my_printf_error(ER_WRONG_FILE_NAME,
15445 "The ADD DATAFILE filepath for an UNDO TABLESPACE"
15446 " cannot be a relative path.",
15447 MYF(0));
15448
15449 error = HA_ERR_WRONG_FILE_NAME;
15450 }
15451
15452 /* If this is an undo tablespace basename and the innodb-undo-directory
15453 is not the datadir, then use an undo::Tablespace object to get the name
15454 since it will to attach a basename to the undo directory instead of the
15455 datadir. */
15456 if (alter_info->ts_cmd_type == CREATE_UNDO_TABLESPACE &&
15457 std::string::npos == datafile_name.find_first_of(Fil_path::SEPARATOR) &&
15458 !MySQL_undo_path.is_same_as(MySQL_datadir_path)) {
15459 undo::Tablespace undo_space(0);
15460 undo_space.set_file_name(datafile_name.c_str());
15461 datafile_name = undo_space.file_name();
15462 }
15463
15464 Fil_path filepath(datafile_name, true);
15465
15466 /* If this path contains a circular section such as "/anydir/../" then
15467 reject it since if that unnecessary directory reference is deleted
15468 the path will not be useaable on Linux. */
15469 if (filepath.is_circular()) {
15470 my_printf_error(ER_WRONG_FILE_NAME,
15471 "The ADD DATAFILE filepath cannot contain circular "
15472 "directory references.",
15473 MYF(0));
15474 error = HA_ERR_WRONG_FILE_NAME;
15475 }
15476
15477 #ifndef _WIN32
15478 /* On Non-Windows platforms, '\\' is a valid file name character.
15479 But for InnoDB datafiles, we always assume it is a directory
15480 separator and convert these to '/' */
15481 if (strchr(filepath, '\\') != nullptr) {
15482 ib::warn(ER_IB_MSG_568) << "Converting backslash to forward slash in"
15483 " ADD DATAFILE "
15484 << filepath.path();
15485 }
15486 #endif /* _WIN32 */
15487
15488 /* The filepath must end with a valid suffix and contain a basename of at
15489 least 1 character before the suffix. */
15490 size_t dirname_len = dirname_length(filepath);
15491 const char *basename = filepath + dirname_len;
15492 auto basename_len = strlen(basename);
15493
15494 if (basename_len <= 4) {
15495 my_printf_error(
15496 ER_WRONG_FILE_NAME,
15497 "The ADD DATAFILE filepath does not have a proper filename.", MYF(0));
15498 error = HA_ERR_WRONG_FILE_NAME;
15499 }
15500
15501 if (!Fil_path::has_suffix(type, basename)) {
15502 my_printf_error(ER_WRONG_FILE_NAME,
15503 "The ADD DATAFILE filepath must end with '%s'.", MYF(0),
15504 dot_ext[type]);
15505 error = HA_ERR_WRONG_FILE_NAME;
15506 }
15507
15508 if (!filepath.is_valid()) {
15509 my_error(ER_WRONG_FILE_NAME, MYF(0), filepath.path().c_str());
15510
15511 my_printf_error(ER_WRONG_FILE_NAME, "Invalid use of ':'.", MYF(0));
15512
15513 return (HA_ERR_WRONG_FILE_NAME);
15514 }
15515
15516 /* If this file already exists, we cannot use this filename. */
15517 if (os_file_exists(filepath.path().c_str())) {
15518 my_printf_error(ER_WRONG_FILE_NAME,
15519 "The ADD DATAFILE filepath already exists.", MYF(0));
15520 error = HA_ERR_WRONG_FILE_NAME;
15521 }
15522
15523 Fil_path dirpath((dirname_len == 0 ? "." : datafile_name.c_str()),
15524 (dirname_len == 0 ? 1 : dirname_len), true);
15525
15526 if (!dirpath.is_directory_and_exists()) {
15527 ib::error(ER_IB_MSG_WRONG_TABLESPACE_DIR, alter_info->tablespace_name);
15528 my_printf_error(ER_WRONG_FILE_NAME,
15529 "The directory does not exist or is incorrect.", MYF(0));
15530
15531 error = HA_ERR_WRONG_FILE_NAME;
15532 }
15533
15534 /* Do not allow the file to be created in a unique undo directory. */
15535 if (type == IBD && MySQL_undo_path_is_unique &&
15536 (MySQL_undo_path.is_same_as(dirpath) ||
15537 MySQL_undo_path.is_ancestor(dirpath))) {
15538 std::string msg("The DATAFILE location cannot be the undo directory.");
15539
15540 my_printf_error(ER_WRONG_FILE_NAME, "%s", MYF(0), msg.c_str());
15541
15542 ib::error(ER_IB_MSG_INVALID_LOCATION_FOR_TABLESPACE,
15543 alter_info->tablespace_name, msg.c_str());
15544
15545 error = HA_ERR_WRONG_FILE_NAME;
15546 }
15547
15548 /* General tablespaces can be inside but not under the datadir
15549 since those directories contain datafiles for specific schemas.*/
15550 if (type == IBD && MySQL_datadir_path.is_ancestor(dirpath)) {
15551 std::string msg("The DATAFILE location cannot be under the datadir.");
15552
15553 my_printf_error(ER_WRONG_FILE_NAME, "%s", MYF(0), msg.c_str());
15554
15555 ib::error(ER_IB_MSG_INVALID_LOCATION_FOR_TABLESPACE,
15556 alter_info->tablespace_name, msg.c_str());
15557
15558 error = HA_ERR_WRONG_FILE_NAME;
15559 }
15560
15561 /* Validate the tablespace location. */
15562 bool in_datadir = MySQL_datadir_path.is_ancestor(dirpath) ||
15563 MySQL_datadir_path.is_same_as(dirpath);
15564 bool in_known_location =
15565 in_datadir ? true : fil_path_is_known(dirpath.path());
15566
15567 /* All undo and general tablespaces must be in known directories */
15568 if (!in_known_location) {
15569 std::string msg("The ");
15570 msg += (type == IBU ? "UNDO " : "");
15571 msg += "DATAFILE location must be in a known directory.";
15572
15573 my_printf_error(ER_WRONG_FILE_NAME, "%s", MYF(0), msg.c_str());
15574
15575 ib::error(ER_IB_MSG_INVALID_LOCATION_FOR_TABLESPACE,
15576 alter_info->tablespace_name, msg.c_str());
15577
15578 error = HA_ERR_WRONG_FILE_NAME;
15579 }
15580
15581 return (error);
15582 }
15583
15584 /** CREATE a tablespace.
15585 @param[in] hton Handlerton of InnoDB
15586 @param[in] thd Connection
15587 @param[in] alter_info How to do the command
15588 @param[in,out] dd_space Tablespace metadata
15589 @return MySQL error code*/
15590 static int innodb_create_tablespace(handlerton *hton, THD *thd,
15591 st_alter_tablespace *alter_info,
15592 dd::Tablespace *dd_space) {
15593 int error;
15594 Tablespace tablespace;
15595 uint32_t fsp_flags = 0;
15596
15597 DBUG_TRACE;
15598 assert(hton == innodb_hton_ptr);
15599
15600 ut_ad(alter_info->tablespace_name == dd_space->name());
15601 ut_ad(strcmp(alter_info->data_file_name,
15602 dd_tablespace_get_filename(dd_space)) == 0);
15603
15604 /* Be sure the input parameters are valid before continuing. */
15605 error = validate_create_tablespace_info(IBD, alter_info);
15606 if (error) {
15607 return error;
15608 }
15609
15610 /* Create the tablespace object. */
15611 tablespace.set_name(alter_info->tablespace_name);
15612
15613 dberr_t err = tablespace.add_datafile(alter_info->data_file_name);
15614 if (err != DB_SUCCESS) {
15615 return convert_error_code_to_mysql(err, 0, nullptr);
15616 }
15617
15618 tablespace.set_autoextend_size(alter_info->autoextend_size.has_value()
15619 ? alter_info->autoextend_size.value()
15620 : 0);
15621
15622 /* Get the transaction associated with the current thd. */
15623 trx_t *trx = check_trx_exists(thd);
15624 TrxInInnoDB trx_in_innodb(trx);
15625 trx_start_if_not_started(trx, true, UT_LOCATION_HERE);
15626 ++trx->will_lock;
15627
15628 row_mysql_lock_data_dictionary(trx, UT_LOCATION_HERE);
15629
15630 /* In FSP_FLAGS, a zip_ssize of zero means that the tablespace
15631 holds non-compresssed tables. A non-zero zip_ssize means that
15632 the general tablespace can ONLY contain compressed tables. */
15633 uint32_t zip_size = static_cast<uint32_t>(alter_info->file_block_size);
15634 ut_ad(zip_size <= UNIV_PAGE_SIZE_MAX);
15635 if (zip_size == 0) {
15636 zip_size = UNIV_PAGE_SIZE;
15637 }
15638 bool zipped = (zip_size != UNIV_PAGE_SIZE);
15639 page_size_t page_size(zip_size, UNIV_PAGE_SIZE, zipped);
15640 bool atomic_blobs = page_size.is_compressed();
15641
15642 bool encrypted = false;
15643 if (dd_space->options().exists("encryption")) {
15644 dd::String_type encrypt;
15645 (void)dd_space->options().get("encryption", &encrypt);
15646
15647 /* Validate Encryption option provided */
15648 if (Encryption::validate(encrypt.c_str()) != DB_SUCCESS) {
15649 /* Incorrect encryption option */
15650 my_error(ER_INVALID_ENCRYPTION_OPTION, MYF(0));
15651 err = DB_UNSUPPORTED;
15652 goto error_exit;
15653 }
15654
15655 /* If encryption is to be done */
15656 if (!Encryption::is_none(encrypt.c_str())) {
15657 /* Check if keyring is ready. */
15658 if (!Encryption::check_keyring()) {
15659 my_error(ER_CANNOT_FIND_KEY_IN_KEYRING, MYF(0));
15660 err = DB_UNSUPPORTED;
15661 goto error_exit;
15662 }
15663 encrypted = true;
15664 }
15665
15666 DBUG_EXECUTE_IF("ib_crash_during_create_tablespace_for_encryption",
15667 DBUG_SUICIDE(););
15668 }
15669
15670 /* Create the filespace flags */
15671 fsp_flags =
15672 fsp_flags_init(page_size, /* page sizes and a flag if compressed */
15673 atomic_blobs, /* needed only for compressed tables */
15674 false, /* This is not a file-per-table tablespace */
15675 true, /* This is a general shared tablespace */
15676 false, /* Temporary General Tablespaces not allowed */
15677 encrypted); /* If tablespace is to be Encrypted */
15678 tablespace.set_flags(fsp_flags);
15679
15680 err = dict_build_tablespace(trx, &tablespace);
15681
15682 if (err == DB_SUCCESS) {
15683 /* Update the fil_space_t with autoextend_size value. */
15684 fil_set_autoextend_size(tablespace.space_id(),
15685 tablespace.get_autoextend_size());
15686
15687 err = btr_sdi_create_index(tablespace.space_id(), true);
15688 if (err == DB_SUCCESS) {
15689 fsp_flags_set_sdi(fsp_flags);
15690 tablespace.set_flags(fsp_flags);
15691
15692 /* Make sure the DD has the space_id and the flags. */
15693 dd_write_tablespace(dd_space, tablespace.space_id(), tablespace.flags(),
15694 DD_SPACE_STATE_NORMAL);
15695 }
15696 }
15697
15698 error_exit:
15699 if (err != DB_SUCCESS) {
15700 error = convert_error_code_to_mysql(err, 0, nullptr);
15701 }
15702
15703 row_mysql_unlock_data_dictionary(trx);
15704
15705 return error;
15706 }
15707
15708 /** Alter AUTOEXTEND_SIZE a tablespace.
15709 @param[in] hton Handlerton of InnoDB
15710 @param[in] alter_info How to do the command
15711 @param[in] old_dd_space Tablespace metadata
15712 @return MySQL error code */
15713 static int innobase_alter_autoextend_size_tablespace(
15714 handlerton *hton, st_alter_tablespace *alter_info,
15715 const dd::Tablespace *old_dd_space) {
15716 space_id_t space_id = SPACE_UNKNOWN;
15717
15718 DBUG_TRACE;
15719 assert(hton == innodb_hton_ptr);
15720
15721 DEBUG_SYNC(current_thd, "innodb_alter_autoextend_size_tablespace");
15722
15723 ut_ad(alter_info->tablespace_name == old_dd_space->name());
15724
15725 if (srv_read_only_mode) {
15726 return HA_ERR_INNODB_READ_ONLY;
15727 }
15728
15729 /* Validate the name */
15730 ut_ad(0 == validate_tablespace_name(alter_info->ts_cmd_type,
15731 alter_info->tablespace_name));
15732
15733 /* Be sure that this tablespace is known and valid. */
15734 if (old_dd_space->se_private_data().get(dd_space_key_strings[DD_SPACE_ID],
15735 &space_id) ||
15736 space_id == SPACE_UNKNOWN) {
15737 return HA_ERR_TABLESPACE_MISSING;
15738 }
15739
15740 /* Make sure tablespace is loaded. */
15741 fil_space_t *space = fil_space_acquire(space_id);
15742 if (space == nullptr) {
15743 return HA_ERR_TABLESPACE_MISSING;
15744 }
15745 ut_ad(fsp_flags_is_valid(space->flags));
15746
15747 /* Validate the autoextend_size value. */
15748 ut_ad(alter_info->autoextend_size.has_value());
15749
15750 uint64_t autoextend_size = alter_info->autoextend_size.value();
15751
15752 if (autoextend_size > 0) {
15753 int ret = validate_autoextend_size_value(autoextend_size);
15754
15755 if (ret != DB_SUCCESS) {
15756 fil_space_release(space);
15757 return ret;
15758 }
15759 }
15760
15761 fil_set_autoextend_size(space_id, alter_info->autoextend_size.value());
15762
15763 fil_space_release(space);
15764
15765 return 0;
15766 }
15767
15768 /**
15769 Return data filename extension for a InnoDB tablespace.
15770 */
15771
15772 static const char *innobase_get_tablespace_filename_ext() { return ".ibd"; }
15773
15774 /** Alter Encrypt/Unencrypt a tablespace.
15775 @param[in] hton Handlerton of InnoDB
15776 @param[in] thd Connection
15777 @param[in] alter_info How to do the command
15778 @param[in] old_dd_space Tablespace metadata
15779 @param[in,out] new_dd_space Tablespace metadata
15780 @return MySQL error code*/
15781 static int innobase_alter_encrypt_tablespace(handlerton *hton, THD *thd,
15782 st_alter_tablespace *alter_info,
15783 const dd::Tablespace *old_dd_space,
15784 dd::Tablespace *new_dd_space) {
15785 trx_t *trx = nullptr;
15786 dberr_t err = DB_SUCCESS;
15787 int error = 0;
15788 space_id_t space_id = SPACE_UNKNOWN;
15789
15790 DBUG_TRACE;
15791 assert(hton == innodb_hton_ptr);
15792
15793 DEBUG_SYNC(current_thd, "innodb_alter_encrypt_tablespace");
15794
15795 ut_ad(alter_info->tablespace_name == old_dd_space->name());
15796
15797 if (srv_read_only_mode) {
15798 return HA_ERR_INNODB_READ_ONLY;
15799 }
15800
15801 /* Name validation should be ensured from the SQL layer. */
15802 ut_ad(0 == validate_tablespace_name(alter_info->ts_cmd_type,
15803 alter_info->tablespace_name));
15804
15805 /* Be sure that this tablespace is known and valid. */
15806 if (old_dd_space->se_private_data().get(dd_space_key_strings[DD_SPACE_ID],
15807 &space_id) ||
15808 space_id == SPACE_UNKNOWN) {
15809 return HA_ERR_TABLESPACE_MISSING;
15810 }
15811
15812 /* Make sure keyring plugin is loaded. */
15813 if (!Encryption::check_keyring()) {
15814 my_error(ER_CANNOT_FIND_KEY_IN_KEYRING, MYF(0));
15815 error = convert_error_code_to_mysql(DB_ERROR, 0, nullptr);
15816 return error;
15817 }
15818
15819 /* Make sure tablespace is loaded. */
15820 fil_space_t *space = fil_space_get(space_id);
15821 if (space == nullptr) {
15822 return HA_ERR_TABLESPACE_MISSING;
15823 }
15824 ut_ad(fsp_flags_is_valid(space->flags));
15825
15826 const dd::Properties &oldopts = old_dd_space->options();
15827 const dd::Properties &newopts = new_dd_space->options();
15828
15829 /* Get value of old encryption option. */
15830 dd::String_type oldenc;
15831 if (oldopts.exists("encryption")) {
15832 (void)oldopts.get("encryption", &oldenc);
15833 }
15834
15835 /* Get value of new encryption option. */
15836 ut_ad(newopts.exists("encryption"));
15837 dd::String_type newenc;
15838 (void)newopts.get("encryption", &newenc);
15839
15840 /* Validate new encryption option provided */
15841 const char *encrypt = newenc.data();
15842 if (Encryption::validate(encrypt) != DB_SUCCESS) {
15843 /* Incorrect encryption option */
15844 my_error(ER_INVALID_ENCRYPTION_OPTION, MYF(0));
15845 error = convert_error_code_to_mysql(DB_ERROR, 0, nullptr);
15846 return error;
15847 }
15848
15849 /* If old tablespace definition says it's encrypted */
15850 bool is_old_encrypted =
15851 !(oldenc.empty() || Encryption::is_none(oldenc.data()));
15852 /* If new tablespace definition says it's encrypted */
15853 bool is_new_encrypted = !Encryption::is_none(newenc.data());
15854
15855 bool to_encrypt = false;
15856 if (!is_old_encrypted && is_new_encrypted) {
15857 /* Encrypt tablespace */
15858 to_encrypt = true;
15859 } else if (is_old_encrypted && !is_new_encrypted) {
15860 /* Unencrypt tablespace */
15861 to_encrypt = false;
15862 } else {
15863 /* Nothing to do */
15864 return error;
15865 }
15866
15867 /* Get the transaction associated with the current thd */
15868 trx = check_trx_exists(thd);
15869 innobase_register_trx(hton, thd, trx);
15870
15871 trx_start_if_not_started(trx, true, UT_LOCATION_HERE);
15872
15873 DBUG_EXECUTE_IF("alter_encrypt_tablespace_crash_before_processing",
15874 DBUG_SUICIDE(););
15875
15876 /* do encryption/unencryption processing now. */
15877 err = fsp_alter_encrypt_tablespace(thd, space_id, to_encrypt, new_dd_space);
15878
15879 DBUG_EXECUTE_IF("alter_encrypt_tablespace_crash_after_processing",
15880 DBUG_SUICIDE(););
15881
15882 error = convert_error_code_to_mysql(err, 0, nullptr);
15883 return error;
15884 }
15885
15886 /** ALTER an undo tablespace.
15887 @param[in] hton Handlerton of InnoDB
15888 @param[in] thd Connection
15889 @param[in] alter_info How to do the command
15890 @param[in] old_dd_space Tablespace metadata
15891 @param[in] new_dd_space Tablespace metadata
15892 @return MySQL error code*/
15893 static int innodb_alter_tablespace(handlerton *hton, THD *thd,
15894 st_alter_tablespace *alter_info,
15895 const dd::Tablespace *old_dd_space,
15896 dd::Tablespace *new_dd_space) {
15897 space_id_t space_id = SPACE_UNKNOWN;
15898 ulint old_size, new_size;
15899
15900 DBUG_TRACE;
15901 assert(hton == innodb_hton_ptr);
15902
15903 if (alter_info->ts_alter_tablespace_type != ALTER_TABLESPACE_RENAME &&
15904 alter_info->ts_alter_tablespace_type != ALTER_TABLESPACE_OPTIONS) {
15905 return HA_ADMIN_NOT_IMPLEMENTED;
15906 }
15907
15908 /* Name validation should be ensured from the SQL layer. */
15909 ut_ad(0 == validate_tablespace_name(ALTER_TABLESPACE,
15910 alter_info->tablespace_name));
15911
15912 /* Be sure that this tablespace is known and valid. */
15913 if (old_dd_space->se_private_data().get(dd_space_key_strings[DD_SPACE_ID],
15914 &space_id) ||
15915 space_id == SPACE_UNKNOWN || fil_space_get_size(space_id) == 0) {
15916 return HA_ERR_TABLESPACE_MISSING;
15917 }
15918
15919 if (fsp_is_undo_tablespace(space_id)) {
15920 my_printf_error(ER_WRONG_TABLESPACE_NAME,
15921 "Cannot ALTER TABLESPACE `%s` because it is an undo "
15922 "tablespace. Please use ALTER UNDO TABLESPACE.",
15923 MYF(0), alter_info->tablespace_name);
15924
15925 return HA_ERR_NOT_ALLOWED_COMMAND;
15926 }
15927
15928 /* ALTER_TABLESPACE_OPTIONS */
15929 if (alter_info->ts_alter_tablespace_type == ALTER_TABLESPACE_OPTIONS) {
15930 int err = 0;
15931 /* Process the encryption option if specified with the
15932 ALTER TABLESPACE statement. */
15933 if (alter_info->encryption != nullptr &&
15934 new_dd_space->options().exists("encryption")) {
15935 err = innobase_alter_encrypt_tablespace(hton, thd, alter_info,
15936 old_dd_space, new_dd_space);
15937 }
15938
15939 /* Process the AUTOEXTEND_SIZE clause if mentioned with
15940 the ALTER TABLESPACE statement. */
15941 if (!err && alter_info->autoextend_size.has_value() &&
15942 new_dd_space->options().exists(autoextend_size_str)) {
15943 err = innobase_alter_autoextend_size_tablespace(hton, alter_info,
15944 old_dd_space);
15945 }
15946
15947 /* Ignore any other ALTER TABLESPACE options. */
15948 return err;
15949 }
15950
15951 /* ALTER_TABLESPACE_RENAME */
15952 const char *from = old_dd_space->name().c_str();
15953 const char *to = new_dd_space->name().c_str();
15954
15955 /* mysql tablespace can't be renamed */
15956 if (innobase_strcasecmp(from, dict_sys_t::s_dd_space_name) == 0) {
15957 my_printf_error(ER_WRONG_TABLESPACE_NAME,
15958 "InnoDB: `mysql` is a reserved"
15959 " tablespace name.",
15960 MYF(0));
15961 return HA_WRONG_CREATE_OPTION;
15962 }
15963
15964 ut_ad(ut_strcmp(from, to) != 0);
15965
15966 dberr_t err = fil_rename_tablespace_by_id(space_id, from, to);
15967 if (err != DB_SUCCESS) {
15968 return convert_error_code_to_mysql(err, 0, nullptr);
15969 }
15970
15971 /* Rename any in-memory cached table->tablespace */
15972 dict_sys_mutex_enter();
15973 for (auto table : dict_sys->table_LRU) {
15974 if (table->tablespace && strcmp(from, table->tablespace) == 0) {
15975 old_size = mem_heap_get_size(table->heap);
15976
15977 table->tablespace = mem_heap_strdupl(table->heap, to, strlen(to));
15978
15979 new_size = mem_heap_get_size(table->heap);
15980 dict_sys->size += new_size - old_size;
15981 }
15982 }
15983
15984 for (auto table : dict_sys->table_non_LRU) {
15985 if (table->tablespace && strcmp(from, table->tablespace) == 0) {
15986 old_size = mem_heap_get_size(table->heap);
15987
15988 table->tablespace = mem_heap_strdupl(table->heap, to, strlen(to));
15989
15990 new_size = mem_heap_get_size(table->heap);
15991 dict_sys->size += new_size - old_size;
15992 }
15993 }
15994
15995 dict_sys_mutex_exit();
15996
15997 return 0;
15998 }
15999
16000 /** DROP a tablespace.
16001 @param[in] hton Handlerton of InnoDB
16002 @param[in] thd Connection
16003 @param[in] alter_info How to do the command
16004 @param[in] dd_space Tablespace metadata
16005 @return MySQL error code*/
16006 static int innodb_drop_tablespace(handlerton *hton, THD *thd,
16007 st_alter_tablespace *alter_info,
16008 const dd::Tablespace *dd_space) {
16009 int error = 0;
16010 space_id_t space_id = SPACE_UNKNOWN;
16011
16012 DBUG_TRACE;
16013 assert(hton == innodb_hton_ptr);
16014
16015 auto dd_space_name = dd_space->name();
16016
16017 ut_ad(alter_info->tablespace_name == dd_space->name());
16018
16019 /* Name validation should be ensured from the SQL layer. */
16020 ut_ad(0 ==
16021 validate_tablespace_name(DROP_TABLESPACE, alter_info->tablespace_name));
16022
16023 /* Be sure that this tablespace is known and valid. */
16024 if (dd_space->se_private_data().get(dd_space_key_strings[DD_SPACE_ID],
16025 &space_id) ||
16026 space_id == SPACE_UNKNOWN) {
16027 return HA_ERR_TABLESPACE_MISSING;
16028 }
16029
16030 if (fsp_is_undo_tablespace(space_id)) {
16031 my_printf_error(ER_WRONG_TABLESPACE_NAME,
16032 "Cannot DROP TABLESPACE `%s` because it is an undo "
16033 "tablespace. Please use DROP UNDO TABLESPACE.",
16034 MYF(0), alter_info->tablespace_name);
16035
16036 return HA_ERR_NOT_ALLOWED_COMMAND;
16037 }
16038
16039 if (fil_space_get_flags(space_id) == UINT32_UNDEFINED) {
16040 /* The DD knows about it but the actual tablespace is missing.
16041 Allow it to be dropped from the DD. */
16042 return 0;
16043 }
16044
16045 /* Get the transaction associated with the current thd. */
16046 trx_t *trx = check_trx_exists(thd);
16047 TrxInInnoDB trx_in_innodb(trx);
16048 trx_start_if_not_started(trx, true, UT_LOCATION_HERE);
16049 ++trx->will_lock;
16050
16051 /* Acquire Exclusive MDL on SDI table of tablespace.
16052 This is to prevent concurrent purge on SDI table */
16053 MDL_ticket *sdi_mdl = nullptr;
16054 dberr_t err = dd_sdi_acquire_exclusive_mdl(thd, space_id, &sdi_mdl);
16055 if (err != DB_SUCCESS) {
16056 error = convert_error_code_to_mysql(err, 0, nullptr);
16057 return error;
16058 }
16059
16060 err = log_ddl->write_delete_space_log(trx, nullptr, space_id,
16061 dd_tablespace_get_filename(dd_space),
16062 true, false);
16063 if (err != DB_SUCCESS) {
16064 error = convert_error_code_to_mysql(err, 0, nullptr);
16065 }
16066
16067 return error;
16068 }
16069
16070 /** CREATE an undo tablespace.
16071 @param[in] hton Handlerton of InnoDB
16072 @param[in] thd Connection
16073 @param[in] alter_info How to do the command
16074 @param[in,out] dd_space Tablespace metadata
16075 @return MySQL error code*/
16076 static int innodb_create_undo_tablespace(handlerton *hton, THD *thd,
16077 st_alter_tablespace *alter_info,
16078 dd::Tablespace *dd_space) {
16079 int error = 0;
16080 dberr_t err;
16081 uint32_t flags;
16082
16083 DBUG_TRACE;
16084 assert(hton == innodb_hton_ptr);
16085
16086 ut_ad(alter_info->tablespace_name == dd_space->name());
16087 ut_ad(strcmp(alter_info->data_file_name,
16088 dd_tablespace_get_filename(dd_space)) == 0);
16089
16090 /* Be sure the input parameters are valid before continuing. */
16091 error = validate_create_tablespace_info(IBU, alter_info);
16092 if (error) {
16093 return error;
16094 }
16095
16096 /* Notify clone about the UNDO DDL and possibly wait. We don't
16097 need similar notification for drop which is recoverable with DDL
16098 log. */
16099 Clone_notify notifier(Clone_notify::Type::SPACE_UNDO_DDL,
16100 dict_sys_t::s_invalid_space_id, false);
16101 if (notifier.failed()) {
16102 return notifier.get_error();
16103 }
16104
16105 /* Create the tablespace object. */
16106
16107 /* Serialize all undo tablespace DDLs */
16108 mutex_enter(&undo::ddl_mutex);
16109
16110 /* Get the transaction associated with the current thd and make
16111 sure it will not block this DDL. */
16112 check_trx_exists(thd);
16113
16114 /* Allocate a new transaction for this DDL */
16115 trx_t *trx = innobase_trx_allocate(thd);
16116 trx_start_if_not_started(trx, true, UT_LOCATION_HERE);
16117 ++trx->will_lock;
16118
16119 /* Find the next available undo space number and mark it in-use. */
16120 space_id_t space_id = undo::get_next_available_space_num();
16121 if (space_id == SPACE_UNKNOWN ||
16122 undo::spaces->size() == FSP_MAX_UNDO_TABLESPACES) {
16123 /* All available explicit undo tablespaces have been used. */
16124 ib::error(ER_IB_MSG_MAX_UNDO_SPACES_REACHED, alter_info->tablespace_name,
16125 alter_info->data_file_name, int{FSP_MAX_UNDO_TABLESPACES});
16126 error = HA_ERR_TABLESPACE_EXISTS;
16127 trx_rollback_for_mysql(trx);
16128 goto cleanup;
16129 }
16130
16131 err = srv_undo_tablespace_create(alter_info->tablespace_name,
16132 alter_info->data_file_name, space_id);
16133
16134 if (err != DB_SUCCESS) {
16135 error = convert_error_code_to_mysql(err, 0, nullptr);
16136 trx_rollback_for_mysql(trx);
16137 goto cleanup;
16138 }
16139
16140 innobase_commit_low(trx);
16141
16142 /* Make sure the DD has the space_id and the flags. */
16143 flags = fsp_flags_init(univ_page_size, false, false, false, false);
16144 dd_write_tablespace(dd_space, space_id, flags, DD_SPACE_STATE_ACTIVE);
16145
16146 /* Mark the undo tablespace 'active' in undo::spaces. */
16147 undo::set_active(space_id);
16148 ut_d(ib::info(ER_IB_MSG_UNDO_MARKED_ACTIVE, alter_info->tablespace_name));
16149
16150 cleanup:
16151 trx_free_for_mysql(trx);
16152
16153 mutex_exit(&undo::ddl_mutex);
16154
16155 ib::info(ER_IB_MSG_CREATED_UNDO_SPACE, alter_info->tablespace_name);
16156
16157 return error;
16158 }
16159
16160 /** ALTER an undo tablespace to ACTIVE.
16161 @param[in] undo_space Undo Tablespace object
16162 @param[in] dd_state Current state in the DD.
16163 @param[in] dd_space Tablespace metadata
16164 @return MySQL error code*/
16165 static int innodb_alter_undo_tablespace_active(undo::Tablespace *undo_space,
16166 dd::String_type dd_state,
16167 dd::Tablespace *dd_space) {
16168 /* Change the state of the undo tablespace.
16169 ALTER UNDO TABLESPACE is idempotent. */
16170 if (dd_state != dd_space_state_values[DD_SPACE_STATE_ACTIVE]) {
16171 dd_tablespace_set_state(dd_space, DD_SPACE_STATE_ACTIVE);
16172 }
16173
16174 /* Start using this undo tablespace. */
16175 undo_space->alter_active();
16176
16177 return (0);
16178 }
16179
16180 /** ALTER an undo tablespace to INACTIVE.
16181 @param[in] undo_space Undo Tablespace object
16182 @param[in] dd_state Current state in the DD.
16183 @param[in] dd_space Tablespace metadata
16184 @return MySQL error code*/
16185 static int innodb_alter_undo_tablespace_inactive(undo::Tablespace *undo_space,
16186 dd::String_type dd_state,
16187 dd::Tablespace *dd_space) {
16188 /* If it is already empty, just return. */
16189 if (undo_space->is_empty() &&
16190 dd_state == dd_space_state_values[DD_SPACE_STATE_EMPTY]) {
16191 return (0);
16192 }
16193
16194 if (undo_space->is_active()) {
16195 /* There must be at least 2 active undo tablespaces besides the one we
16196 are trying to make inactive explicitly. One of those two could be in
16197 the process of being implicitly truncated. So if one other space is
16198 inactive_implicit, then it is being truncated and will be put back
16199 to active before this undo_space is truncated. */
16200 ulint other_active_spaces = 0;
16201 for (auto undo_ts : undo::spaces->m_spaces) {
16202 if (undo_ts != undo_space) {
16203 if (undo_ts->is_active()) {
16204 other_active_spaces++;
16205 } else if (undo_ts->is_inactive_implicit() &&
16206 purge_sys->undo_trunc.get_marked_space_num() ==
16207 undo_ts->num()) {
16208 other_active_spaces++;
16209 }
16210 }
16211 }
16212
16213 if (other_active_spaces < 2) {
16214 my_printf_error(ER_DISALLOWED_OPERATION,
16215 "Cannot set %s inactive since there would be"
16216 " less than 2 undo tablespaces left active.",
16217 MYF(0), undo_space->space_name());
16218
16219 return (HA_ERR_NOT_ALLOWED_COMMAND);
16220 }
16221 }
16222
16223 /* If truncation is happening too often on this undo tablespace there
16224 may be too many old files still in the fil_system with their pages
16225 still in the buffer pool. If this is the case, return an error. */
16226 auto count = fil_count_undo_deleted(undo_space->num());
16227 if (count > CONCURRENT_UNDO_TRUNCATE_LIMIT) {
16228 my_printf_error(ER_DISALLOWED_OPERATION,
16229 "Cannot set %s inactive since there would be more"
16230 " than %zu old versions of this undo tablespace"
16231 " in cache. Please wait for the next checkpoint.",
16232 MYF(0), undo_space->space_name(),
16233 CONCURRENT_UNDO_TRUNCATE_LIMIT);
16234
16235 return (HA_ERR_NOT_ALLOWED_COMMAND);
16236 }
16237
16238 /* Make sure the DD shows inactive if it is active. */
16239 dd_tablespace_set_state(dd_space, DD_SPACE_STATE_INACTIVE);
16240
16241 /* Apply this to new transactions. */
16242 undo_space->set_inactive_explicit();
16243 ut_d(ib::info(ER_IB_MSG_UNDO_ALTERED_INACTIVE, undo_space->file_name()));
16244
16245 srv_wake_purge_thread_if_not_active();
16246
16247 return (0);
16248 }
16249
16250 /** ALTER an undo tablespace. Either make it ACTIVE or INACTIVE.
16251 @param[in] hton Handlerton of InnoDB
16252 @param[in] alter_info How to do the command
16253 @param[in] dd_space Tablespace metadata
16254 @return MySQL error code*/
16255 static int innodb_alter_undo_tablespace(handlerton *hton,
16256 st_alter_tablespace *alter_info,
16257 dd::Tablespace *dd_space) {
16258 space_id_t space_id = SPACE_UNKNOWN;
16259
16260 DBUG_TRACE;
16261 assert(hton == innodb_hton_ptr);
16262
16263 ut_ad(alter_info->tablespace_name == dd_space->name());
16264
16265 /* Name validation should be ensured from the SQL layer. */
16266 ut_ad(0 == validate_tablespace_name(ALTER_UNDO_TABLESPACE,
16267 alter_info->tablespace_name));
16268
16269 /* Be sure that this tablespace is known and valid. */
16270 if (dd_space->se_private_data().get(dd_space_key_strings[DD_SPACE_ID],
16271 &space_id) ||
16272 space_id == SPACE_UNKNOWN || fil_space_get_size(space_id) == 0) {
16273 return HA_ERR_TABLESPACE_MISSING;
16274 }
16275
16276 if (!fsp_is_undo_tablespace(space_id)) {
16277 my_printf_error(ER_WRONG_TABLESPACE_NAME,
16278 "Cannot ALTER UNDO TABLESPACE `%s` because it is a "
16279 "general tablespace. Please use ALTER TABLESPACE.",
16280 MYF(0), alter_info->tablespace_name);
16281
16282 return HA_ERR_NOT_ALLOWED_COMMAND;
16283 }
16284
16285 /* Get the current state of the undo tablespace from the DD. */
16286 dd::String_type dd_state;
16287 dd_tablespace_get_state(dd_space, &dd_state, space_id);
16288
16289 /* Serialize all undo tablespace DDLs */
16290 mutex_enter(&undo::ddl_mutex);
16291
16292 /* Get the current undo_space object. */
16293 undo::spaces->s_lock();
16294 space_id_t space_num = undo::id2num(space_id);
16295 undo::Tablespace *undo_space = undo::spaces->find(space_num);
16296
16297 /* ALTER UNDO TABLESPACE is idempotent. */
16298 int err = 0;
16299 switch (alter_info->ts_alter_tablespace_type) {
16300 case ALTER_UNDO_TABLESPACE_SET_ACTIVE:
16301 err = innodb_alter_undo_tablespace_active(undo_space, dd_state, dd_space);
16302 break;
16303
16304 case ALTER_UNDO_TABLESPACE_SET_INACTIVE:
16305 err =
16306 innodb_alter_undo_tablespace_inactive(undo_space, dd_state, dd_space);
16307 break;
16308
16309 default:
16310 err = HA_ADMIN_NOT_IMPLEMENTED;
16311 }
16312
16313 undo::spaces->s_unlock();
16314
16315 mutex_exit(&undo::ddl_mutex);
16316
16317 return err;
16318 }
16319
16320 /** DROP an undo tablespace.
16321 @param[in] hton Handlerton of InnoDB
16322 @param[in] thd Connection
16323 @param[in] alter_info How to do the command
16324 @param[in] dd_space Tablespace metadata
16325 @return MySQL error code*/
16326 static int innodb_drop_undo_tablespace(handlerton *hton, THD *thd,
16327 st_alter_tablespace *alter_info,
16328 const dd::Tablespace *dd_space) {
16329 space_id_t space_id = SPACE_UNKNOWN;
16330
16331 DBUG_TRACE;
16332 assert(hton == innodb_hton_ptr);
16333
16334 ut_ad(alter_info->tablespace_name == dd_space->name());
16335
16336 /* Name validation should be ensured from the SQL layer. */
16337 ut_ad(0 == validate_tablespace_name(DROP_UNDO_TABLESPACE,
16338 alter_info->tablespace_name));
16339
16340 /* Be sure that this tablespace is known and valid. */
16341 if (dd_space->se_private_data().get(dd_space_key_strings[DD_SPACE_ID],
16342 &space_id) ||
16343 space_id == SPACE_UNKNOWN) {
16344 return HA_ERR_TABLESPACE_MISSING;
16345 }
16346
16347 if (!fsp_is_undo_tablespace(space_id)) {
16348 my_printf_error(ER_WRONG_TABLESPACE_NAME,
16349 "Cannot DROP UNDO TABLESPACE `%s` because it is a "
16350 "general tablespace. Please use DROP TABLESPACE.",
16351 MYF(0), alter_info->tablespace_name);
16352
16353 return HA_ERR_NOT_ALLOWED_COMMAND;
16354 }
16355
16356 /* Serialize all undo tablespace DDLs */
16357 mutex_enter(&undo::ddl_mutex);
16358
16359 undo::spaces->x_lock();
16360 space_id_t space_num = undo::id2num(space_id);
16361 undo::Tablespace *undo_space = undo::spaces->find(space_num);
16362
16363 /* If the undo space is missing, allow the DROP UNDO TABLESPACE to
16364 continue to completion. */
16365 if (undo_space == nullptr) {
16366 undo::spaces->x_unlock();
16367 mutex_exit(&undo::ddl_mutex);
16368
16369 /* Start the transaction associated with the current thd so that MySQL
16370 can continue. */
16371 trx_t *trx = check_trx_exists(thd);
16372 trx_start_if_not_started(trx, true, UT_LOCATION_HERE);
16373 ++trx->will_lock;
16374
16375 return (0);
16376 }
16377
16378 /* Verify that the undo tablespace is not one of the first two undo spaces,
16379 has been altered inactive and is now empty. */
16380 if (undo_space->num() <= FSP_IMPLICIT_UNDO_TABLESPACES ||
16381 !undo_space->is_empty()) {
16382 ib::error err_msg;
16383 err_msg << "Cannot drop undo tablespace '" << undo_space->space_name();
16384 if (undo_space->num() <= FSP_IMPLICIT_UNDO_TABLESPACES) {
16385 err_msg << "' because it was not created explicitly.";
16386 } else if (undo_space->is_active() || undo_space->is_inactive_implicit()) {
16387 err_msg << "' because it is active. "
16388 << "Please do: ALTER UNDO TABLESPACE " << undo_space->space_name()
16389 << " SET INACTIVE;";
16390 } else {
16391 err_msg << "' because it is still being truncated."
16392 " Please try again later.";
16393 }
16394
16395 undo::spaces->x_unlock();
16396 mutex_exit(&undo::ddl_mutex);
16397
16398 return HA_ERR_TABLESPACE_IS_NOT_EMPTY;
16399 }
16400
16401 /* We don't need to invalidate buffer pool pages belonging to this undo
16402 tablespace before dropping it, as they will be set as stale and to be
16403 lazily freed. */
16404
16405 /* Save the file name before undo_space is dropped. */
16406 std::string file_name{undo_space->file_name()};
16407
16408 /* Empty and inactive, take it out of view. */
16409 undo::spaces->drop(undo_space);
16410 undo::spaces->x_unlock();
16411
16412 /* Get the transaction associated with the current thd and write a
16413 delete_space record to the DDL_LOG. */
16414 trx_t *trx = check_trx_exists(thd);
16415 TrxInInnoDB trx_in_innodb(trx);
16416 trx_start_if_not_started(trx, true, UT_LOCATION_HERE);
16417 ++trx->will_lock;
16418
16419 auto err = log_ddl->write_delete_space_log(trx, nullptr, space_id,
16420 file_name.c_str(), true, false);
16421 int error = 0;
16422 if (err != DB_SUCCESS) {
16423 error = convert_error_code_to_mysql(err, 0, nullptr);
16424 }
16425
16426 mutex_exit(&undo::ddl_mutex);
16427
16428 ib::info(ER_IB_MSG_DROPPED_UNDO_SPACE, alter_info->tablespace_name);
16429
16430 return error;
16431 }
16432
16433 /** This API handles CREATE, ALTER & DROP commands for InnoDB tablespaces.
16434 @param[in] hton Handlerton of InnoDB
16435 @param[in] thd Connection
16436 @param[in] alter_info Describes the command and how to do it.
16437 @param[in] old_ts_def Old version of dd::Tablespace object for the
16438 tablespace.
16439 @param[in,out] new_ts_def New version of dd::Tablespace object for the
16440 tablespace. Can be adjusted by SE. Changes will be persisted in the
16441 data-dictionary at statement commit.
16442 @return MySQL error code*/
16443 static int innobase_alter_tablespace(handlerton *hton, THD *thd,
16444 st_alter_tablespace *alter_info,
16445 const dd::Tablespace *old_ts_def,
16446 dd::Tablespace *new_ts_def) {
16447 int error = 0; /* return zero for success */
16448 DBUG_TRACE;
16449
16450 if (srv_read_only_mode || srv_force_recovery > 0) {
16451 my_printf_error(ER_INNODB_READ_ONLY,
16452 "Changes to undo tablespaces are not allowed in"
16453 " %s mode",
16454 MYF(0),
16455 (srv_read_only_mode ? "read_only" : "force_recovery"));
16456 error = HA_ERR_INNODB_READ_ONLY;
16457 goto handle_error;
16458 }
16459
16460 switch (alter_info->ts_cmd_type) {
16461 case CREATE_TABLESPACE:
16462 ut_ad(new_ts_def != nullptr);
16463 error = innodb_create_tablespace(hton, thd, alter_info, new_ts_def);
16464 break;
16465
16466 case ALTER_TABLESPACE:
16467 ut_ad(old_ts_def != nullptr);
16468 ut_ad(new_ts_def != nullptr);
16469 error = innodb_alter_tablespace(hton, thd, alter_info, old_ts_def,
16470 new_ts_def);
16471 break;
16472
16473 case DROP_TABLESPACE:
16474 ut_ad(old_ts_def != nullptr);
16475 error = innodb_drop_tablespace(hton, thd, alter_info, old_ts_def);
16476 break;
16477
16478 case CREATE_UNDO_TABLESPACE:
16479 error = innodb_create_undo_tablespace(hton, thd, alter_info, new_ts_def);
16480 break;
16481
16482 case ALTER_UNDO_TABLESPACE:
16483 ut_ad(new_ts_def != nullptr);
16484 error = innodb_alter_undo_tablespace(hton, alter_info, new_ts_def);
16485 break;
16486
16487 case DROP_UNDO_TABLESPACE:
16488 ut_ad(old_ts_def != nullptr);
16489 error = innodb_drop_undo_tablespace(hton, thd, alter_info, old_ts_def);
16490 break;
16491
16492 default:
16493 error = HA_ADMIN_NOT_IMPLEMENTED;
16494 }
16495
16496 handle_error:
16497 if (error) {
16498 /* These are the most common message params */
16499 const char *ibd_type = "TABLESPACE";
16500 const char *undo_type = "UNDO TABLESPACE";
16501 uint32_t code = ER_CREATE_FILEGROUP_FAILED;
16502 const char *subject = ibd_type;
16503
16504 /* Modify those params as needed. */
16505 switch (alter_info->ts_cmd_type) {
16506 case CREATE_TABLESPACE:
16507 break;
16508 case ALTER_TABLESPACE:
16509 code = ER_ALTER_FILEGROUP_FAILED;
16510 break;
16511 case DROP_TABLESPACE:
16512 code = ER_DROP_FILEGROUP_FAILED;
16513 break;
16514 case CREATE_UNDO_TABLESPACE:
16515 subject = undo_type;
16516 break;
16517 case ALTER_UNDO_TABLESPACE:
16518 code = ER_ALTER_FILEGROUP_FAILED;
16519 subject = undo_type;
16520 break;
16521 case DROP_UNDO_TABLESPACE:
16522 code = ER_DROP_FILEGROUP_FAILED;
16523 subject = undo_type;
16524 break;
16525 case CREATE_LOGFILE_GROUP:
16526 case DROP_LOGFILE_GROUP:
16527 case ALTER_LOGFILE_GROUP:
16528 subject = "LOGFILE GROUP";
16529 break;
16530 case ALTER_ACCESS_MODE_TABLESPACE:
16531 subject = "ACCESS MODE";
16532 break;
16533 case CHANGE_FILE_TABLESPACE:
16534 subject = "CHANGE FILE";
16535 break;
16536 case TS_CMD_NOT_DEFINED:
16537 subject = "UNKNOWN";
16538 break;
16539 }
16540
16541 switch (alter_info->ts_cmd_type) {
16542 case CREATE_TABLESPACE:
16543 case ALTER_TABLESPACE:
16544 case DROP_TABLESPACE:
16545 case CREATE_UNDO_TABLESPACE:
16546 case ALTER_UNDO_TABLESPACE:
16547 case DROP_UNDO_TABLESPACE:
16548 ib_errf(thd, IB_LOG_LEVEL_ERROR, code, "%s %s", subject,
16549 alter_info->tablespace_name);
16550 break;
16551
16552 case CREATE_LOGFILE_GROUP:
16553 case ALTER_ACCESS_MODE_TABLESPACE:
16554 case DROP_LOGFILE_GROUP:
16555 case ALTER_LOGFILE_GROUP:
16556 case CHANGE_FILE_TABLESPACE:
16557 case TS_CMD_NOT_DEFINED:
16558 my_error(ER_FEATURE_UNSUPPORTED, MYF(0), subject, "by InnoDB");
16559 break;
16560 }
16561 }
16562
16563 return error;
16564 }
16565
16566 /** Renames an InnoDB table.
16567 @param[in] from Old name of the table.
16568 @param[in] to New name of the table.
16569 @param[in] from_table_def dd::Table object describing old version
16570 of table.
16571 @param[in,out] to_table_def dd::Table object describing version of
16572 table with new name. Can be updated by SE. Changes are persisted to the
16573 dictionary at statement commit time.
16574 @return 0 or error code */
16575 int ha_innobase::rename_table(const char *from, const char *to,
16576 const dd::Table *from_table_def,
16577 dd::Table *to_table_def) {
16578 THD *thd = ha_thd();
16579 trx_t *trx = check_trx_exists(thd);
16580 TrxInInnoDB trx_in_innodb(trx);
16581
16582 DBUG_TRACE;
16583 ut_ad(from_table_def->se_private_id() == to_table_def->se_private_id());
16584 ut_ad(from_table_def->se_private_data().raw_string() ==
16585 to_table_def->se_private_data().raw_string());
16586
16587 if (high_level_read_only) {
16588 ib_senderrf(thd, IB_LOG_LEVEL_WARN, ER_READ_ONLY_MODE);
16589 return HA_ERR_TABLE_READONLY;
16590 }
16591
16592 if (dict_sys_t::is_dd_table_id(to_table_def->se_private_id())) {
16593 my_error(ER_NOT_ALLOWED_COMMAND, MYF(0));
16594 return HA_ERR_UNSUPPORTED;
16595 }
16596
16597 innobase_register_trx(ht, thd, trx);
16598
16599 return innobase_basic_ddl::rename_impl<dd::Table>(
16600 thd, from, to, from_table_def, to_table_def, nullptr);
16601 }
16602
16603 /** Returns the exact number of records that this client can see using this
16604 handler object.
16605 @return Error code in case something goes wrong.
16606 These errors will abort the current query:
16607 case HA_ERR_LOCK_DEADLOCK:
16608 case HA_ERR_LOCK_TABLE_FULL:
16609 case HA_ERR_LOCK_WAIT_TIMEOUT:
16610 case HA_ERR_QUERY_INTERRUPTED:
16611 For other error codes, the server will fall back to counting records. */
16612
16613 int ha_innobase::records(ha_rows *num_rows) /*!< out: number of rows */
16614 {
16615 DBUG_TRACE;
16616
16617 dberr_t ret;
16618 ulint n_rows = 0; /* Record count in this view */
16619
16620 update_thd();
16621
16622 if (dict_table_is_discarded(m_prebuilt->table)) {
16623 ib_senderrf(m_user_thd, IB_LOG_LEVEL_ERROR, ER_TABLESPACE_DISCARDED,
16624 table->s->table_name.str);
16625
16626 *num_rows = HA_POS_ERROR;
16627 return HA_ERR_NO_SUCH_TABLE;
16628
16629 } else if (m_prebuilt->table->ibd_file_missing) {
16630 ib_senderrf(m_user_thd, IB_LOG_LEVEL_ERROR, ER_TABLESPACE_MISSING,
16631 table->s->table_name.str);
16632
16633 *num_rows = HA_POS_ERROR;
16634 return HA_ERR_TABLESPACE_MISSING;
16635
16636 } else if (m_prebuilt->table->is_corrupted()) {
16637 ib_errf(m_user_thd, IB_LOG_LEVEL_WARN, ER_INNODB_INDEX_CORRUPT,
16638 "Table '%s' is corrupt.", table->s->table_name.str);
16639
16640 *num_rows = HA_POS_ERROR;
16641 return HA_ERR_INDEX_CORRUPT;
16642 }
16643
16644 TrxInInnoDB trx_in_innodb(m_prebuilt->trx);
16645
16646 m_prebuilt->trx->op_info = "counting records";
16647
16648 dict_index_t *index = m_prebuilt->table->first_index();
16649
16650 ut_ad(index->is_clustered());
16651
16652 m_prebuilt->index_usable = index->is_usable(m_prebuilt->trx);
16653
16654 if (!m_prebuilt->index_usable) {
16655 *num_rows = HA_POS_ERROR;
16656 return HA_ERR_TABLE_DEF_CHANGED;
16657 }
16658
16659 /* (Re)Build the m_prebuilt->mysql_template if it is null to use
16660 the clustered index and just the key, no off-record data. */
16661 m_prebuilt->index = index;
16662 m_prebuilt->clear_search_tuples();
16663 m_prebuilt->read_just_key = 1;
16664 build_template(false);
16665
16666 size_t max_threads = thd_parallel_read_threads(m_prebuilt->trx->mysql_thd);
16667
16668 /* Count the records in the clustered index */
16669 ret =
16670 row_scan_index_for_mysql(m_prebuilt, index, max_threads, false, &n_rows);
16671 reset_template();
16672 switch (ret) {
16673 case DB_SUCCESS:
16674 break;
16675 case DB_DEADLOCK:
16676 case DB_LOCK_TABLE_FULL:
16677 case DB_LOCK_WAIT_TIMEOUT:
16678 *num_rows = HA_POS_ERROR;
16679 return convert_error_code_to_mysql(ret, 0, m_user_thd);
16680 case DB_INTERRUPTED:
16681 *num_rows = HA_POS_ERROR;
16682 return HA_ERR_QUERY_INTERRUPTED;
16683 default:
16684 /* No other error besides the three below is returned from
16685 row_scan_index_for_mysql(). Make a debug catch. */
16686 *num_rows = HA_POS_ERROR;
16687 return -1;
16688 }
16689
16690 m_prebuilt->trx->op_info = "";
16691
16692 if (thd_killed(m_user_thd)) {
16693 *num_rows = HA_POS_ERROR;
16694 return HA_ERR_QUERY_INTERRUPTED;
16695 }
16696
16697 *num_rows = n_rows;
16698 return 0;
16699 }
16700
16701 /** Estimates the number of index records in a range.
16702 @return estimated number of rows */
16703
16704 ha_rows ha_innobase::records_in_range(
16705 uint keynr, /*!< in: index number */
16706 key_range *min_key, /*!< in: start key value of the
16707 range, may also be 0 */
16708 key_range *max_key) /*!< in: range end key val, may
16709 also be 0 */
16710 {
16711 KEY *key;
16712 dict_index_t *index;
16713 dtuple_t *range_start;
16714 dtuple_t *range_end;
16715 int64_t n_rows;
16716 page_cur_mode_t mode1;
16717 page_cur_mode_t mode2;
16718 mem_heap_t *heap;
16719
16720 DBUG_TRACE;
16721
16722 ut_a(m_prebuilt->trx == thd_to_trx(ha_thd()));
16723
16724 m_prebuilt->trx->op_info = "estimating records in index range";
16725
16726 TrxInInnoDB trx_in_innodb(m_prebuilt->trx);
16727
16728 active_index = keynr;
16729
16730 key = table->key_info + active_index;
16731
16732 index = innobase_get_index(keynr);
16733
16734 /* There exists possibility of not being able to find requested
16735 index due to inconsistency between MySQL and InoDB dictionary info.
16736 Necessary message should have been printed in innobase_get_index() */
16737 if (dict_table_is_discarded(m_prebuilt->table)) {
16738 n_rows = HA_POS_ERROR;
16739 goto func_exit;
16740 }
16741 if (!index) {
16742 n_rows = HA_POS_ERROR;
16743 goto func_exit;
16744 }
16745 if (index->is_corrupted()) {
16746 n_rows = HA_ERR_INDEX_CORRUPT;
16747 goto func_exit;
16748 }
16749 if (!index->is_usable(m_prebuilt->trx)) {
16750 n_rows = HA_ERR_TABLE_DEF_CHANGED;
16751 goto func_exit;
16752 }
16753
16754 heap = mem_heap_create(
16755 2 * (key->actual_key_parts * sizeof(dfield_t) + sizeof(dtuple_t)),
16756 UT_LOCATION_HERE);
16757
16758 range_start = dtuple_create(heap, key->actual_key_parts);
16759 dict_index_copy_types(range_start, index, key->actual_key_parts);
16760
16761 range_end = dtuple_create(heap, key->actual_key_parts);
16762 dict_index_copy_types(range_end, index, key->actual_key_parts);
16763
16764 row_sel_convert_mysql_key_to_innobase(
16765 range_start, m_prebuilt->srch_key_val1, m_prebuilt->srch_key_val_len,
16766 index, (byte *)(min_key ? min_key->key : (const uchar *)nullptr),
16767 (ulint)(min_key ? min_key->length : 0));
16768
16769 assert(min_key ? range_start->n_fields > 0 : range_start->n_fields == 0);
16770
16771 row_sel_convert_mysql_key_to_innobase(
16772 range_end, m_prebuilt->srch_key_val2, m_prebuilt->srch_key_val_len, index,
16773 (byte *)(max_key ? max_key->key : (const uchar *)nullptr),
16774 (ulint)(max_key ? max_key->length : 0));
16775
16776 assert(max_key ? range_end->n_fields > 0 : range_end->n_fields == 0);
16777
16778 mode1 = convert_search_mode_to_innobase(min_key ? min_key->flag
16779 : HA_READ_KEY_EXACT);
16780
16781 mode2 = convert_search_mode_to_innobase(max_key ? max_key->flag
16782 : HA_READ_KEY_EXACT);
16783
16784 if (mode1 != PAGE_CUR_UNSUPP && mode2 != PAGE_CUR_UNSUPP) {
16785 if (dict_index_is_spatial(index)) {
16786 /*Only min_key used in spatial index. */
16787 n_rows = rtr_estimate_n_rows_in_range(index, range_start, mode1);
16788 } else {
16789 n_rows = btr_estimate_n_rows_in_range(index, range_start, mode1,
16790 range_end, mode2);
16791 }
16792 } else {
16793 n_rows = HA_POS_ERROR;
16794 }
16795
16796 mem_heap_free(heap);
16797
16798 DBUG_EXECUTE_IF(
16799 "print_btr_estimate_n_rows_in_range_return_value",
16800 push_warning_printf(ha_thd(), Sql_condition::SL_WARNING, ER_NO_DEFAULT,
16801 "btr_estimate_n_rows_in_range(): %" PRId64, n_rows););
16802
16803 func_exit:
16804
16805 m_prebuilt->trx->op_info = (char *)"";
16806
16807 /* The MySQL optimizer seems to believe an estimate of 0 rows is
16808 always accurate and may return the result 'Empty set' based on that.
16809 The accuracy is not guaranteed, and even if it were, for a locking
16810 read we should anyway perform the search to set the next-key lock.
16811 Add 1 to the value to make sure MySQL does not make the assumption! */
16812
16813 if (n_rows == 0) {
16814 n_rows = 1;
16815 }
16816
16817 return (ha_rows)n_rows;
16818 }
16819
16820 /** Gives an UPPER BOUND to the number of rows in a table. This is used in
16821 filesort.cc.
16822 @return upper bound of rows */
16823
16824 ha_rows ha_innobase::estimate_rows_upper_bound() {
16825 const dict_index_t *index;
16826 ulonglong estimate;
16827 ulonglong local_data_file_length;
16828
16829 DBUG_TRACE;
16830
16831 /* We do not know if MySQL can call this function before calling
16832 external_lock(). To be safe, update the thd of the current table
16833 handle. */
16834
16835 update_thd(ha_thd());
16836
16837 TrxInInnoDB trx_in_innodb(m_prebuilt->trx);
16838
16839 m_prebuilt->trx->op_info = "calculating upper bound for table rows";
16840
16841 index = m_prebuilt->table->first_index();
16842
16843 ulint stat_n_leaf_pages = index->stat_n_leaf_pages;
16844
16845 ut_a(stat_n_leaf_pages > 0);
16846
16847 local_data_file_length = ((ulonglong)stat_n_leaf_pages) * UNIV_PAGE_SIZE;
16848
16849 /* Calculate a minimum length for a clustered index record and from
16850 that an upper bound for the number of rows. Since we only calculate
16851 new statistics in row0mysql.cc when a table has grown by a threshold
16852 factor, we must add a safety factor 2 in front of the formula below. */
16853
16854 estimate = 2 * local_data_file_length / dict_index_calc_min_rec_len(index);
16855
16856 m_prebuilt->trx->op_info = "";
16857
16858 /* Set num_rows less than MERGEBUFF to simulate the case where we do
16859 not have enough space to merge the externally sorted file blocks. */
16860 DBUG_EXECUTE_IF("set_num_rows_lt_MERGEBUFF", estimate = 2;
16861 DBUG_SET("-d,set_num_rows_lt_MERGEBUFF"););
16862
16863 return (ha_rows)estimate;
16864 }
16865
16866 /** How many seeks it will take to read through the table. This is to be
16867 comparable to the number returned by records_in_range so that we can
16868 decide if we should scan the table or use keys.
16869 @return estimated time measured in disk seeks */
16870
16871 double ha_innobase::scan_time() {
16872 /* Since MySQL seems to favor table scans too much over index
16873 searches, we pretend that a sequential read takes the same time
16874 as a random disk read, that is, we do not divide the following
16875 by 10, which would be physically realistic. */
16876
16877 /* The locking below is disabled for performance reasons. Without
16878 it we could end up returning uninitialized value to the caller,
16879 which in the worst case could make some query plan go bogus or
16880 issue a Valgrind warning. */
16881
16882 if (m_prebuilt == nullptr) {
16883 /* In case of derived table, Optimizer will try to fetch stat
16884 for table even before table is create or open. In such
16885 cases return default value of 1.
16886 TODO: This will be further improved to return some approximate
16887 estimate but that would also needs pre-population of stats
16888 structure. As of now approach is in sync with MyISAM. */
16889 return (ulonglong2double(stats.data_file_length) / IO_SIZE + 2);
16890 }
16891
16892 ulint stat_clustered_index_size;
16893
16894 ut_a(m_prebuilt->table->stat_initialized);
16895
16896 stat_clustered_index_size = m_prebuilt->table->stat_clustered_index_size;
16897
16898 return ((double)stat_clustered_index_size);
16899 }
16900
16901 /** Calculate the time it takes to read a set of ranges through an index
16902 This enables us to optimise reads for clustered indexes.
16903 @return estimated time measured in disk seeks */
16904
16905 double ha_innobase::read_time(
16906 uint index, /*!< in: key number */
16907 uint ranges, /*!< in: how many ranges */
16908 ha_rows rows) /*!< in: estimated number of rows in the ranges */
16909 {
16910 ha_rows total_rows;
16911
16912 if (index != table->s->primary_key) {
16913 /* Not clustered */
16914 return (handler::read_time(index, ranges, rows));
16915 }
16916
16917 if (rows <= 2) {
16918 return ((double)rows);
16919 }
16920
16921 /* Assume that the read time is proportional to the scan time for all
16922 rows + at most one seek per range. */
16923
16924 double time_for_scan = scan_time();
16925
16926 if ((total_rows = estimate_rows_upper_bound()) < rows) {
16927 return (time_for_scan);
16928 }
16929
16930 return (ranges + (double)rows / (double)total_rows * time_for_scan);
16931 }
16932
16933 /** Return the size of the InnoDB memory buffer. */
16934
16935 longlong ha_innobase::get_memory_buffer_size() const {
16936 return (srv_buf_pool_curr_size);
16937 }
16938
16939 /** Update the system variable with the given value of the InnoDB
16940 buffer pool size.
16941 @param[in] buf_pool_size given value of buffer pool size.*/
16942 void innodb_set_buf_pool_size(long long buf_pool_size) {
16943 srv_buf_pool_curr_size = buf_pool_size;
16944 }
16945
16946 /** Calculates the key number used inside MySQL for an Innobase index. We
16947 will first check the "index translation table" for a match of the index to
16948 get the index number. If there does not exist an "index translation table",
16949 or not able to find the index in the translation table, then we will fall
16950 back to the traditional way of looping through dict_index_t list to find a
16951 match. In this case, we have to take into account if we generated a
16952 default clustered index for the table
16953 @return the key number used inside MySQL */
16954 static int innobase_get_mysql_key_number_for_index(
16955 INNOBASE_SHARE *share, /*!< in: share structure for index
16956 translation table. */
16957 const TABLE *table, /*!< in: table in MySQL data
16958 dictionary */
16959 dict_table_t *ib_table, /*!< in: table in InnoDB data
16960 dictionary */
16961 const dict_index_t *index) /*!< in: index */
16962 {
16963 const dict_index_t *ind;
16964 unsigned int i;
16965
16966 /* If index does not belong to the table object of share structure
16967 (ib_table comes from the share structure) search the index->table
16968 object instead */
16969 if (index->table != ib_table) {
16970 i = 0;
16971 ind = index->table->first_index();
16972
16973 while (index != ind) {
16974 ind = ind->next();
16975 i++;
16976 }
16977
16978 if (row_table_got_default_clust_index(index->table)) {
16979 ut_a(i > 0);
16980 i--;
16981 }
16982
16983 return (i);
16984 }
16985
16986 /* If index translation table exists, we will first check
16987 the index through index translation table for a match. */
16988 if (share->idx_trans_tbl.index_mapping != nullptr) {
16989 for (i = 0; i < share->idx_trans_tbl.index_count; i++) {
16990 if (share->idx_trans_tbl.index_mapping[i] == index) {
16991 return (i);
16992 }
16993 }
16994
16995 /* Print an error message if we cannot find the index
16996 in the "index translation table". */
16997 if (index->is_committed()) {
16998 log_errlog(ERROR_LEVEL, ER_INNODB_FAILED_TO_FIND_IDX, index->name());
16999 }
17000 }
17001
17002 /* If we do not have an "index translation table", or not able
17003 to find the index in the translation table, we'll directly find
17004 matching index with information from mysql TABLE structure and
17005 InnoDB dict_index_t list */
17006 for (i = 0; i < table->s->keys; i++) {
17007 ind = dict_table_get_index_on_name(ib_table, table->key_info[i].name);
17008
17009 if (index == ind) {
17010 return (i);
17011 }
17012 }
17013
17014 /* Loop through each index of the table and lock them */
17015 for (ind = ib_table->first_index(); ind != nullptr; ind = ind->next()) {
17016 if (index == ind) {
17017 /* Temp index is internal to InnoDB, that is
17018 not present in the MySQL index list, so no
17019 need to print such mismatch warning. */
17020 if (index->is_committed()) {
17021 log_errlog(WARNING_LEVEL, ER_INNODB_INTERNAL_INDEX, index->name());
17022 }
17023 return (-1);
17024 }
17025 }
17026
17027 ut_error;
17028 }
17029
17030 /** Calculate Record Per Key value.
17031 Need to exclude the NULL value if innodb_stats_method is set to "nulls_ignored"
17032 @param[in] index InnoDB index.
17033 @param[in] i The column we are calculating rec per key.
17034 @param[in] records Estimated total records.
17035 @return estimated record per key value */
17036 rec_per_key_t innodb_rec_per_key(const dict_index_t *index, ulint i,
17037 ha_rows records) {
17038 rec_per_key_t rec_per_key;
17039 uint64_t n_diff;
17040
17041 ut_a(index->table->stat_initialized);
17042
17043 ut_ad(i < dict_index_get_n_unique(index));
17044 ut_ad(!dict_index_is_spatial(index));
17045
17046 if (records == 0) {
17047 /* "Records per key" is meaningless for empty tables.
17048 Return 1.0 because that is most convenient to the Optimizer. */
17049 return (1.0);
17050 }
17051
17052 n_diff = index->stat_n_diff_key_vals[i];
17053
17054 if (n_diff == 0) {
17055 rec_per_key = static_cast<rec_per_key_t>(records);
17056 } else if (srv_innodb_stats_method == SRV_STATS_NULLS_IGNORED) {
17057 uint64_t n_null;
17058 uint64_t n_non_null;
17059
17060 n_non_null = index->stat_n_non_null_key_vals[i];
17061
17062 /* In theory, index->stat_n_non_null_key_vals[i]
17063 should always be less than the number of records.
17064 Since this is statistics value, the value could
17065 have slight discrepancy. But we will make sure
17066 the number of null values is not a negative number. */
17067 if (records < n_non_null) {
17068 n_null = 0;
17069 } else {
17070 n_null = records - n_non_null;
17071 }
17072
17073 /* If the number of NULL values is the same as or
17074 large than that of the distinct values, we could
17075 consider that the table consists mostly of NULL value.
17076 Set rec_per_key to 1. */
17077 if (n_diff <= n_null) {
17078 rec_per_key = 1.0;
17079 } else {
17080 /* Need to exclude rows with NULL values from
17081 rec_per_key calculation */
17082 rec_per_key =
17083 static_cast<rec_per_key_t>(records - n_null) / (n_diff - n_null);
17084 }
17085 } else {
17086 #ifdef UNIV_DEBUG
17087 if (!index->table->is_dd_table) {
17088 DEBUG_SYNC_C("after_checking_for_0");
17089 }
17090 #endif /* UNIV_DEBUG */
17091 rec_per_key = static_cast<rec_per_key_t>(records) / n_diff;
17092 }
17093
17094 if (rec_per_key < 1.0) {
17095 /* Values below 1.0 are meaningless and must be due to the
17096 stats being imprecise. */
17097 rec_per_key = 1.0;
17098 }
17099
17100 return (rec_per_key);
17101 }
17102
17103 /** Read the auto_increment counter of a table, using the AUTOINC lock
17104 irrespective of innodb_autoinc_lock_mode.
17105 @param[in,out] innodb_table InnoDB table object
17106 @param[in] print_note Print note if not an I_S query.
17107 @return the autoinc value */
17108 static ulonglong innobase_peek_autoinc(dict_table_t *innodb_table,
17109 bool print_note) {
17110 ulonglong auto_inc;
17111
17112 ut_a(innodb_table != nullptr);
17113
17114 dict_table_autoinc_lock(innodb_table);
17115
17116 auto_inc = dict_table_autoinc_read(innodb_table);
17117
17118 if (auto_inc == 0 && print_note) {
17119 ib::info(ER_IB_MSG_569) << "AUTOINC next value generation is disabled for "
17120 << innodb_table->name;
17121 }
17122
17123 dict_table_autoinc_unlock(innodb_table);
17124
17125 return (auto_inc);
17126 }
17127
17128 /** Calculate delete length statistic.
17129 @param[in] ib_table table object
17130 @param[in,out] stats stats structure to hold calculated values
17131 @param[in,out] thd user thread handle (for issuing warnings) */
17132 static void calculate_delete_length_stat(const dict_table_t *ib_table,
17133 ha_statistics *stats, THD *thd) {
17134 uintmax_t avail_space;
17135
17136 avail_space = fsp_get_available_space_in_free_extents(ib_table->space);
17137
17138 if (avail_space == UINTMAX_MAX) {
17139 char errbuf[MYSYS_STRERROR_SIZE];
17140 std::ostringstream err_msg;
17141 err_msg << "InnoDB: Trying to get the free space for table "
17142 << ib_table->name
17143 << " but its tablespace has been"
17144 " discarded or the .ibd file is missing. Setting"
17145 " the free space to zero. (errno: "
17146 << errno << " - " << my_strerror(errbuf, sizeof(errbuf), errno)
17147 << ")";
17148
17149 push_warning(thd, Sql_condition::SL_WARNING, ER_CANT_GET_STAT,
17150 err_msg.str().c_str());
17151
17152 stats->delete_length = 0;
17153 } else {
17154 stats->delete_length = avail_space * 1024;
17155 }
17156 }
17157
17158 /** Calculate stats based on index size.
17159 @param[in] ib_table table object
17160 @param[in] n_rows number of rows
17161 @param[in] stat_clustered_index_size clustered index size
17162 @param[in] stat_sum_of_other_index_sizes sum of non-clustered index sizes
17163 @param[in,out] stats the stats structure to hold
17164 calculated values */
17165 static void calculate_index_size_stats(const dict_table_t *ib_table,
17166 uint64_t n_rows,
17167 ulint stat_clustered_index_size,
17168 ulint stat_sum_of_other_index_sizes,
17169 ha_statistics *stats) {
17170 const page_size_t &page_size = dict_table_page_size(ib_table);
17171
17172 stats->records = static_cast<ha_rows>(n_rows);
17173 stats->data_file_length =
17174 static_cast<ulonglong>(stat_clustered_index_size) * page_size.physical();
17175 stats->index_file_length =
17176 static_cast<ulonglong>(stat_sum_of_other_index_sizes) *
17177 page_size.physical();
17178 if (stats->records == 0) {
17179 stats->mean_rec_length = 0;
17180 } else {
17181 stats->mean_rec_length =
17182 static_cast<ulong>(stats->data_file_length / stats->records);
17183 }
17184 }
17185
17186 /** Estimate what percentage of an index's pages are cached in the buffer pool
17187 @param[in] index index whose pages to look up
17188 @return a real number in [0.0, 1.0] designating the percentage of cached pages
17189 */
17190 inline double index_pct_cached(const dict_index_t *index) {
17191 const ulint n_leaf = index->stat_n_leaf_pages;
17192
17193 if (n_leaf == 0) {
17194 return (0.0);
17195 }
17196
17197 const uint64_t n_in_mem =
17198 buf_stat_per_index->get(index_id_t(index->space, index->id));
17199
17200 const double ratio = static_cast<double>(n_in_mem) / n_leaf;
17201
17202 return (std::max(std::min(ratio, 1.0), 0.0));
17203 }
17204
17205 /** Returns statistics information of the table to the MySQL interpreter, in
17206 various fields of the handle object.
17207 @param[in] flag what information is requested
17208 @param[in] is_analyze True if called from "::analyze()".
17209 @return HA_ERR_* error code or 0 */
17210 int ha_innobase::info_low(uint flag, bool is_analyze) {
17211 dict_table_t *ib_table;
17212 uint64_t n_rows;
17213
17214 DBUG_TRACE;
17215
17216 DEBUG_SYNC_C("ha_innobase_info_low");
17217
17218 /* If we are forcing recovery at a high level, we will suppress
17219 statistics calculation on tables, because that may crash the
17220 server if an index is badly corrupted. */
17221
17222 /* We do not know if MySQL can call this function before calling
17223 external_lock(). To be safe, update the thd of the current table
17224 handle. */
17225
17226 update_thd(ha_thd());
17227
17228 m_prebuilt->trx->op_info = (char *)"returning various info to MySQL";
17229
17230 ib_table = m_prebuilt->table;
17231 assert(ib_table->n_ref_count > 0);
17232
17233 if (flag & HA_STATUS_TIME) {
17234 if (is_analyze || innobase_stats_on_metadata) {
17235 dict_stats_upd_option_t opt;
17236 dberr_t ret;
17237
17238 m_prebuilt->trx->op_info = "updating table statistics";
17239
17240 if (dict_stats_is_persistent_enabled(ib_table)) {
17241 if (is_analyze) {
17242 opt = DICT_STATS_RECALC_PERSISTENT;
17243 } else {
17244 /* This is e.g. 'SHOW INDEXES', fetch
17245 the persistent stats from disk. */
17246 opt = DICT_STATS_FETCH_ONLY_IF_NOT_IN_MEMORY;
17247 }
17248 } else {
17249 opt = DICT_STATS_RECALC_TRANSIENT;
17250 }
17251
17252 ut_ad(!dict_sys_mutex_own());
17253 ret = dict_stats_update(ib_table, opt);
17254
17255 if (ret != DB_SUCCESS) {
17256 m_prebuilt->trx->op_info = "";
17257 return HA_ERR_GENERIC;
17258 }
17259
17260 m_prebuilt->trx->op_info = "returning various info to MySQL";
17261 }
17262
17263 stats.update_time = (ulong)std::chrono::system_clock::to_time_t(
17264 ib_table->update_time.load());
17265 }
17266
17267 if (flag & HA_STATUS_VARIABLE) {
17268 ulint stat_clustered_index_size;
17269 ulint stat_sum_of_other_index_sizes;
17270
17271 if (!(flag & HA_STATUS_NO_LOCK)) {
17272 dict_table_stats_lock(ib_table, RW_S_LATCH);
17273 }
17274
17275 ut_a(ib_table->stat_initialized);
17276
17277 n_rows = ib_table->stat_n_rows;
17278
17279 stat_clustered_index_size = ib_table->stat_clustered_index_size;
17280
17281 stat_sum_of_other_index_sizes = ib_table->stat_sum_of_other_index_sizes;
17282
17283 if (!(flag & HA_STATUS_NO_LOCK)) {
17284 dict_table_stats_unlock(ib_table, RW_S_LATCH);
17285 }
17286
17287 /*
17288 The MySQL optimizer seems to assume in a left join that n_rows
17289 is an accurate estimate if it is zero. Of course, it is not,
17290 since we do not have any locks on the rows yet at this phase.
17291 Since SHOW TABLE STATUS seems to call this function with the
17292 HA_STATUS_TIME flag set, while the left join optimizer does not
17293 set that flag, we add one to a zero value if the flag is not
17294 set. That way SHOW TABLE STATUS will show the best estimate,
17295 while the optimizer never sees the table empty.
17296 However, if it is internal temporary table used by optimizer,
17297 the count should be accurate */
17298
17299 if (n_rows == 0 && !(flag & HA_STATUS_TIME) &&
17300 table_share->table_category != TABLE_CATEGORY_TEMPORARY) {
17301 n_rows++;
17302 }
17303
17304 stats.records = (ha_rows)n_rows;
17305 stats.deleted = 0;
17306
17307 calculate_index_size_stats(ib_table, n_rows, stat_clustered_index_size,
17308 stat_sum_of_other_index_sizes, &stats);
17309
17310 /* Since fsp_get_available_space_in_free_extents() is
17311 acquiring latches inside InnoDB, we do not call it if we
17312 are asked by MySQL to avoid locking. Another reason to
17313 avoid the call is that it uses quite a lot of CPU.
17314 See Bug#38185. */
17315 if (flag & HA_STATUS_NO_LOCK || !(flag & HA_STATUS_VARIABLE_EXTRA)) {
17316 /* We do not update delete_length if no
17317 locking is requested so the "old" value can
17318 remain. delete_length is initialized to 0 in
17319 the ha_statistics' constructor. Also we only
17320 need delete_length to be set when
17321 HA_STATUS_VARIABLE_EXTRA is set */
17322 } else if (srv_force_recovery >= SRV_FORCE_NO_IBUF_MERGE) {
17323 /* Avoid accessing the tablespace if
17324 innodb_crash_recovery is set to a high value. */
17325 stats.delete_length = 0;
17326 } else {
17327 calculate_delete_length_stat(ib_table, &stats, ha_thd());
17328 }
17329
17330 stats.check_time = 0;
17331 stats.mrr_length_per_rec = ref_length + sizeof(void *);
17332 }
17333
17334 /* Verify the number of indexes in InnoDB and MySQL
17335 matches up. If m_prebuilt->clust_index_was_generated
17336 holds, InnoDB defines GEN_CLUST_INDEX internally. */
17337 ulint num_innodb_index = UT_LIST_GET_LEN(ib_table->indexes) -
17338 m_prebuilt->clust_index_was_generated;
17339 if (table->s->keys < num_innodb_index) {
17340 /* If there are too many indexes defined
17341 inside InnoDB, ignore those that are being
17342 created, because MySQL will only consider
17343 the fully built indexes here. */
17344
17345 for (const dict_index_t *index : ib_table->indexes) {
17346 /* First, online index creation is
17347 completed inside InnoDB, and then
17348 MySQL attempts to upgrade the
17349 meta-data lock so that it can rebuild
17350 the .frm file. If we get here in that
17351 time frame, dict_index_is_online_ddl()
17352 would not hold and the index would
17353 still not be included in TABLE_SHARE. */
17354 if (!index->is_committed()) {
17355 num_innodb_index--;
17356 }
17357 }
17358
17359 if (table->s->keys < num_innodb_index &&
17360 innobase_fts_check_doc_id_index(ib_table, nullptr, nullptr) ==
17361 FTS_EXIST_DOC_ID_INDEX) {
17362 num_innodb_index--;
17363 }
17364 }
17365
17366 if (table->s->keys != num_innodb_index) {
17367 log_errlog(ERROR_LEVEL, ER_INNODB_IDX_CNT_MORE_THAN_DEFINED_IN_MYSQL,
17368 ib_table->name.m_name, num_innodb_index, table->s->keys);
17369 }
17370
17371 if (!(flag & HA_STATUS_NO_LOCK)) {
17372 dict_table_stats_lock(ib_table, RW_S_LATCH);
17373 }
17374
17375 ut_a(ib_table->stat_initialized);
17376
17377 const dict_index_t *pk = UT_LIST_GET_FIRST(ib_table->indexes);
17378
17379 for (uint i = 0; i < table->s->keys; i++) {
17380 ulong j;
17381 /* We could get index quickly through internal
17382 index mapping with the index translation table.
17383 The identity of index (match up index name with
17384 that of table->key_info[i]) is already verified in
17385 innobase_get_index(). */
17386 dict_index_t *index = innobase_get_index(i);
17387
17388 if (index == nullptr) {
17389 log_errlog(ERROR_LEVEL, ER_INNODB_IDX_CNT_FEWER_THAN_DEFINED_IN_MYSQL,
17390 ib_table->name.m_name, TROUBLESHOOTING_MSG);
17391 break;
17392 }
17393
17394 KEY *key = &table->key_info[i];
17395
17396 double pct_cached;
17397
17398 /* We do not maintain stats for fulltext or spatial indexes.
17399 Thus, we can't calculate pct_cached below because we need
17400 dict_index_t::stat_n_leaf_pages for that. See
17401 dict_stats_should_ignore_index(). */
17402 if ((key->flags & HA_FULLTEXT) || (key->flags & HA_SPATIAL)) {
17403 pct_cached = IN_MEMORY_ESTIMATE_UNKNOWN;
17404 } else {
17405 pct_cached = index_pct_cached(index);
17406 }
17407
17408 key->set_in_memory_estimate(pct_cached);
17409
17410 if (index == pk) {
17411 stats.table_in_mem_estimate = pct_cached;
17412 }
17413
17414 if (flag & HA_STATUS_CONST) {
17415 if (!key->supports_records_per_key()) {
17416 continue;
17417 }
17418
17419 for (j = 0; j < key->actual_key_parts; j++) {
17420 if ((key->flags & HA_FULLTEXT) || (key->flags & HA_SPATIAL)) {
17421 /* The record per key does not apply to
17422 FTS or Spatial indexes. */
17423 key->set_records_per_key(j, 1.0f);
17424 continue;
17425 }
17426
17427 if (j + 1 > index->n_uniq) {
17428 log_errlog(ERROR_LEVEL, ER_INNODB_IDX_COLUMN_CNT_DIFF, index->name(),
17429 ib_table->name.m_name, (unsigned long)index->n_uniq, j + 1,
17430 TROUBLESHOOTING_MSG);
17431 break;
17432 }
17433
17434 /* innodb_rec_per_key() will use
17435 index->stat_n_diff_key_vals[] and the value we
17436 pass index->table->stat_n_rows. Both are
17437 calculated by ANALYZE and by the background
17438 stats gathering thread (which kicks in when too
17439 much of the table has been changed). In
17440 addition table->stat_n_rows is adjusted with
17441 each DML (e.g. ++ on row insert). Those
17442 adjustments are not MVCC'ed and not even
17443 reversed on rollback. So,
17444 index->stat_n_diff_key_vals[] and
17445 index->table->stat_n_rows could have been
17446 calculated at different time. This is
17447 acceptable. */
17448 const rec_per_key_t rec_per_key =
17449 innodb_rec_per_key(index, (ulint)j, index->table->stat_n_rows);
17450
17451 key->set_records_per_key(j, rec_per_key);
17452
17453 /* The code below is legacy and should be
17454 removed together with this comment once we
17455 are sure the new floating point rec_per_key,
17456 set via set_records_per_key(), works fine. */
17457
17458 ulong rec_per_key_int = static_cast<ulong>(
17459 innodb_rec_per_key(index, (ulint)j, stats.records));
17460
17461 /* Since MySQL seems to favor table scans
17462 too much over index searches, we pretend
17463 index selectivity is 2 times better than
17464 our estimate: */
17465
17466 rec_per_key_int = rec_per_key_int / 2;
17467
17468 if (rec_per_key_int == 0) {
17469 rec_per_key_int = 1;
17470 }
17471
17472 key->rec_per_key[j] = rec_per_key_int;
17473 }
17474 }
17475 }
17476
17477 if (!(flag & HA_STATUS_NO_LOCK)) {
17478 dict_table_stats_unlock(ib_table, RW_S_LATCH);
17479 }
17480
17481 if (srv_force_recovery >= SRV_FORCE_NO_IBUF_MERGE) {
17482 goto func_exit;
17483
17484 } else if (flag & HA_STATUS_ERRKEY) {
17485 const dict_index_t *err_index;
17486
17487 ut_a(m_prebuilt->trx);
17488 ut_a(m_prebuilt->trx->magic_n == TRX_MAGIC_N);
17489
17490 err_index = trx_get_error_index(m_prebuilt->trx);
17491
17492 if (err_index) {
17493 errkey = innobase_get_mysql_key_number_for_index(m_share, table, ib_table,
17494 err_index);
17495 } else {
17496 errkey =
17497 (unsigned int)((m_prebuilt->trx->error_key_num == ULINT_UNDEFINED)
17498 ? ~0
17499 : m_prebuilt->trx->error_key_num);
17500 }
17501 }
17502
17503 if ((flag & HA_STATUS_AUTO) && table->found_next_number_field) {
17504 ulonglong auto_inc_val = innobase_peek_autoinc(ib_table, true);
17505 /* Initialize autoinc value if not set. */
17506 if (auto_inc_val == 0) {
17507 dict_table_autoinc_lock(m_prebuilt->table);
17508 innobase_initialize_autoinc();
17509 dict_table_autoinc_unlock(m_prebuilt->table);
17510
17511 auto_inc_val = innobase_peek_autoinc(ib_table, true);
17512 }
17513 stats.auto_increment_value = auto_inc_val;
17514 }
17515
17516 func_exit:
17517 m_prebuilt->trx->op_info = (char *)"";
17518
17519 return 0;
17520 }
17521
17522 /** Returns statistics information of the table to the MySQL interpreter,
17523 in various fields of the handle object.
17524 @return HA_ERR_* error code or 0 */
17525
17526 int ha_innobase::info(uint flag) /*!< in: what information is requested */
17527 {
17528 return (info_low(flag, false /* not ANALYZE */));
17529 }
17530
17531 /** Get the autoincrement for the given table id which is
17532 not in the cache.
17533 @param[in] se_private_id InnoDB table id
17534 @param[in] tbl_se_private_data table SE private data
17535 @return autoincrement value for the given table_id. */
17536 static uint64_t innodb_get_auto_increment_for_uncached(
17537 dd::Object_id se_private_id, const dd::Properties &tbl_se_private_data) {
17538 uint64_t autoinc = 0;
17539 uint64_t meta_autoinc = 0;
17540
17541 bool exists =
17542 tbl_se_private_data.exists(dd_table_key_strings[DD_TABLE_AUTOINC]);
17543
17544 /** Get the auto_increment from the table SE private data. */
17545 if (exists) {
17546 tbl_se_private_data.get(dd_table_key_strings[DD_TABLE_AUTOINC], &autoinc);
17547 }
17548
17549 /** Get the auto_increment value from innodb_dynamic_metadata
17550 table. */
17551 mutex_enter(&dict_persist->mutex);
17552
17553 DDTableBuffer *table_buffer = dict_persist->table_buffer;
17554
17555 uint64_t version;
17556 const auto readmeta = table_buffer->get(se_private_id, &version);
17557
17558 if (!readmeta.empty()) {
17559 PersistentTableMetadata metadata(se_private_id, version);
17560
17561 dict_table_read_dynamic_metadata(readmeta.data(), readmeta.size(),
17562 &metadata);
17563
17564 meta_autoinc = metadata.get_autoinc();
17565 }
17566
17567 mutex_exit(&dict_persist->mutex);
17568
17569 return (std::max(meta_autoinc, autoinc));
17570 }
17571
17572 /** Retrieves table statistics only for uncache table only.
17573 @param[in] db_name database name
17574 @param[in] tbl_name table name
17575 @param[in] norm_name tablespace name
17576 @param[in] se_private_id InnoDB table id
17577 @param[in] ts_se_private_data tablespace se private data
17578 @param[in] tbl_se_private_data table se private data
17579 @param[in] stat_flags flags used to retrieve specific stats
17580 @param[in,out] stats structure to save the retrieved statistics
17581 @return true if the stats information filled successfully
17582 @return false if tablespace is missing or table doesn't have persistent
17583 stats. */
17584 static bool innodb_get_table_statistics_for_uncached(
17585 const char *db_name, const char *tbl_name, const char *norm_name,
17586 dd::Object_id se_private_id, const dd::Properties &ts_se_private_data,
17587 const dd::Properties &tbl_se_private_data, ulint stat_flags,
17588 ha_statistics *stats) {
17589 TableStatsRecord stat_info;
17590 space_id_t space_id;
17591
17592 if (!row_search_table_stats(db_name, tbl_name, stat_info)) {
17593 return (false);
17594 }
17595
17596 /** Server passes dummy ts_se_private_data for file_per_table
17597 tablespace. In that case, InnoDB should find the space_id using
17598 the tablespace name. */
17599 bool exists = ts_se_private_data.exists(dd_space_key_strings[DD_SPACE_ID]);
17600
17601 if (exists) {
17602 ts_se_private_data.get(dd_space_key_strings[DD_SPACE_ID], &space_id);
17603 } else {
17604 space_id = fil_space_get_id_by_name(norm_name);
17605
17606 if (space_id == SPACE_UNKNOWN) {
17607 return (false);
17608 }
17609 }
17610
17611 fil_space_t *space;
17612 uint32_t fsp_flags;
17613
17614 space = fil_space_acquire(space_id);
17615
17616 /** Tablespace is missing in this case. */
17617 if (space == nullptr) {
17618 return (false);
17619 }
17620
17621 fsp_flags = space->flags;
17622 page_size_t page_size(fsp_flags);
17623
17624 if (stat_flags & HA_STATUS_VARIABLE_EXTRA) {
17625 ulint avail_space = fsp_get_available_space_in_free_extents(space);
17626 stats->delete_length = avail_space * 1024;
17627 }
17628
17629 fil_space_release(space);
17630
17631 if (stat_flags & HA_STATUS_AUTO) {
17632 stats->auto_increment_value = innodb_get_auto_increment_for_uncached(
17633 se_private_id, tbl_se_private_data);
17634 }
17635
17636 if (stat_flags & HA_STATUS_TIME) {
17637 stats->update_time = (time_t)NULL;
17638 }
17639
17640 if (stat_flags & HA_STATUS_VARIABLE) {
17641 stats->records = static_cast<ha_rows>(stat_info.get_n_rows());
17642 stats->data_file_length =
17643 static_cast<ulonglong>(stat_info.get_clustered_index_size()) *
17644 page_size.physical();
17645 stats->index_file_length =
17646 static_cast<ulonglong>(stat_info.get_sum_of_other_index_size()) *
17647 page_size.physical();
17648
17649 if (stats->records == 0) {
17650 stats->mean_rec_length = 0;
17651 } else {
17652 stats->mean_rec_length =
17653 static_cast<ulong>(stats->data_file_length / stats->records);
17654 }
17655 }
17656
17657 return (true);
17658 }
17659
17660 static bool innobase_get_table_statistics(
17661 const char *db_name, const char *table_name, dd::Object_id se_private_id,
17662 const dd::Properties &ts_se_private_data,
17663 const dd::Properties &tbl_se_private_data, uint stat_flags,
17664 ha_statistics *stats) {
17665 char norm_name[FN_REFLEN];
17666 dict_table_t *ib_table;
17667
17668 char buf[2 * NAME_CHAR_LEN * 5 + 2 + 1];
17669 bool truncated;
17670 build_table_filename(buf, sizeof(buf), db_name, table_name, nullptr, 0,
17671 &truncated);
17672
17673 if (truncated || !normalize_table_name(norm_name, buf)) {
17674 ut_d(ut_error);
17675 ut_o(return true); // (HA_ERR_TOO_LONG_PATH);
17676 }
17677
17678 MDL_ticket *mdl = nullptr;
17679 THD *thd = current_thd;
17680
17681 ib_table = dd_table_open_on_name_in_mem(norm_name, false);
17682 if (ib_table == nullptr) {
17683 if (innodb_get_table_statistics_for_uncached(
17684 db_name, table_name, norm_name, se_private_id, ts_se_private_data,
17685 tbl_se_private_data, stat_flags, stats)) {
17686 return (false);
17687 }
17688
17689 /** If the table doesn't have persistent stats then
17690 load the table from disk. */
17691 ib_table = dd_table_open_on_name(thd, &mdl, norm_name, false,
17692 DICT_ERR_IGNORE_NONE);
17693
17694 if (ib_table == nullptr) {
17695 return (true);
17696 }
17697 }
17698
17699 if (stat_flags & HA_STATUS_AUTO) {
17700 stats->auto_increment_value = innobase_peek_autoinc(ib_table, false);
17701 }
17702
17703 if (stat_flags & HA_STATUS_TIME) {
17704 stats->update_time = static_cast<ulong>(
17705 std::chrono::system_clock::to_time_t(ib_table->update_time.load()));
17706 }
17707
17708 if (stat_flags & HA_STATUS_VARIABLE_EXTRA) {
17709 calculate_delete_length_stat(ib_table, stats, current_thd);
17710 }
17711
17712 if (stat_flags & HA_STATUS_VARIABLE) {
17713 dict_stats_init(ib_table);
17714
17715 ut_a(ib_table->stat_initialized);
17716
17717 /* Note it may look like ib_table->* arguments are
17718 redundant. If you see the usage of this call in info_low(),
17719 the stats can be retrieved while holding a latch if
17720 !HA_STATUS_NO_LOCK is passed. */
17721 calculate_index_size_stats(ib_table, ib_table->stat_n_rows,
17722 ib_table->stat_clustered_index_size,
17723 ib_table->stat_sum_of_other_index_sizes, stats);
17724 }
17725
17726 dd_table_close(ib_table, thd, &mdl, false);
17727
17728 return (false);
17729 }
17730
17731 static bool innobase_get_index_column_cardinality(
17732 const char *db_name, const char *table_name, const char *index_name, uint,
17733 uint column_ordinal_position, dd::Object_id, ulonglong *cardinality) {
17734 char norm_name[FN_REFLEN];
17735 dict_table_t *ib_table;
17736 bool failure = true;
17737
17738 char buf[2 * NAME_CHAR_LEN * 5 + 2 + 1];
17739 bool truncated;
17740 build_table_filename(buf, sizeof(buf), db_name, table_name, nullptr, 0,
17741 &truncated);
17742
17743 if (truncated || !normalize_table_name(norm_name, buf)) {
17744 /* purecov: begin inspected */
17745 ut_d(ut_error);
17746 ut_o(return (true));
17747 /* purecov: end */
17748 }
17749
17750 MDL_ticket *mdl = nullptr;
17751 THD *thd = current_thd;
17752
17753 ib_table = dd_table_open_on_name_in_mem(norm_name, false);
17754 if (ib_table == nullptr) {
17755 if (row_search_index_stats(db_name, table_name, index_name,
17756 column_ordinal_position, cardinality)) {
17757 return (false);
17758 }
17759
17760 /** If the table doesn't have persistent stats then
17761 load the table from disk. */
17762 ib_table = dd_table_open_on_name(thd, &mdl, norm_name, false,
17763 DICT_ERR_IGNORE_NONE);
17764
17765 if (ib_table == nullptr) {
17766 return (true);
17767 }
17768 }
17769
17770 if (ib_table->is_fts_aux()) {
17771 /* Server should not ask for Stats for Internal Tables */
17772 dd_table_close(ib_table, thd, &mdl, false);
17773 ut_d(ut_error);
17774 ut_o(return (true));
17775 }
17776
17777 for (const dict_index_t *index : ib_table->indexes) {
17778 if (index->is_committed() && ut_strcmp(index_name, index->name) == 0) {
17779 if (ib_table->stat_initialized == 0) {
17780 dict_stats_init(ib_table);
17781 ut_a(ib_table->stat_initialized != 0);
17782 }
17783
17784 DEBUG_SYNC(thd, "innodb.after_init_check");
17785 if (index->type & (DICT_FTS | DICT_SPATIAL)) {
17786 /* For these indexes innodb_rec_per_key is
17787 fixed as 1.0 */
17788 *cardinality = ib_table->stat_n_rows;
17789 } else {
17790 uint64_t n_rows = ib_table->stat_n_rows;
17791 double records =
17792 (n_rows /
17793 innodb_rec_per_key(index, (ulint)column_ordinal_position, n_rows));
17794 *cardinality = static_cast<ulonglong>(round(records));
17795 }
17796
17797 failure = false;
17798 break;
17799 }
17800 }
17801
17802 dd_table_close(ib_table, thd, &mdl, false);
17803 return (failure);
17804 }
17805
17806 static bool innobase_get_tablespace_type(const dd::Tablespace &space,
17807 Tablespace_type *space_type) {
17808 space_id_t id = 0;
17809 uint32_t flags = 0;
17810
17811 ut_ad(innobase_strcasecmp(space.engine().c_str(), "InnoDB") == 0);
17812
17813 if (space.se_private_data().get(dd_space_key_strings[DD_SPACE_ID], &id) ||
17814 space.se_private_data().get(dd_space_key_strings[DD_SPACE_FLAGS],
17815 &flags)) {
17816 return true;
17817 }
17818
17819 if (space.id() == MYSQL_TABLESPACE_DD_ID &&
17820 id == dict_sys_t::s_dict_space_id) {
17821 *space_type = Tablespace_type::SPACE_TYPE_DICTIONARY;
17822 } else if (id == TRX_SYS_SPACE) {
17823 *space_type = Tablespace_type::SPACE_TYPE_SYSTEM;
17824 } else if (fsp_is_undo_tablespace(id)) {
17825 *space_type = Tablespace_type::SPACE_TYPE_UNDO;
17826 } else if (fsp_is_system_temporary(id)) {
17827 *space_type = Tablespace_type::SPACE_TYPE_TEMPORARY;
17828 } else if (fsp_is_shared_tablespace(flags) && fsp_is_ibd_tablespace(id)) {
17829 *space_type = Tablespace_type::SPACE_TYPE_SHARED;
17830 } else if (fsp_is_file_per_table(id, flags)) {
17831 *space_type = Tablespace_type::SPACE_TYPE_IMPLICIT;
17832 } else {
17833 ut_d(ut_error);
17834 ut_o(return true);
17835 }
17836
17837 return false;
17838 }
17839
17840 /** Get the tablespace type given the name.
17841
17842 @param[in] tablespace_name tablespace name
17843 @param[out] space_type type of space
17844
17845 @return Operation status.
17846 @retval false on success and true for failure.
17847 */
17848 static bool innobase_get_tablespace_type_by_name(const char *tablespace_name,
17849 Tablespace_type *space_type) {
17850 if ((tablespace_name == nullptr && srv_file_per_table) ||
17851 (tablespace_name &&
17852 0 == strcmp(tablespace_name, dict_sys_t::s_file_per_table_name))) {
17853 *space_type = Tablespace_type::SPACE_TYPE_IMPLICIT;
17854 } else if ((tablespace_name == nullptr && !srv_file_per_table) ||
17855 (tablespace_name &&
17856 0 == strcmp(tablespace_name, dict_sys_t::s_sys_space_name))) {
17857 *space_type = Tablespace_type::SPACE_TYPE_SYSTEM;
17858 } else if (0 == strcmp(tablespace_name, dict_sys_t::s_dd_space_name)) {
17859 *space_type = Tablespace_type::SPACE_TYPE_DICTIONARY;
17860 } else if (0 == strcmp(tablespace_name, dict_sys_t::s_temp_space_name)) {
17861 *space_type = Tablespace_type::SPACE_TYPE_TEMPORARY;
17862 } else if (0 == strcmp(tablespace_name,
17863 dict_sys_t::s_default_undo_space_name_1) ||
17864 0 == strcmp(tablespace_name,
17865 dict_sys_t::s_default_undo_space_name_2)) {
17866 /*
17867 TODO: This function doesn't consider user created UNDO
17868 tablespaces because, as of now this function is not being
17869 called for UNDO tablesapces. But should consider this in
17870 future for completeness.
17871 */
17872 *space_type = Tablespace_type::SPACE_TYPE_UNDO;
17873 } else {
17874 *space_type = Tablespace_type::SPACE_TYPE_SHARED;
17875 }
17876
17877 return false;
17878 }
17879
17880 static bool innobase_get_tablespace_statistics(
17881 const char *tablespace_name, const char *file_name,
17882 const dd::Properties &ts_se_private_data, ha_tablespace_statistics *stats) {
17883 /* Tablespace does not have space id stored. */
17884 if (!ts_se_private_data.exists(dd_space_key_strings[DD_SPACE_ID])) {
17885 my_error(ER_TABLESPACE_MISSING, MYF(0), tablespace_name);
17886 return (DD_FAILURE);
17887 }
17888
17889 space_id_t space_id;
17890
17891 ts_se_private_data.get(dd_space_key_strings[DD_SPACE_ID], &space_id);
17892
17893 if (fsp_is_undo_tablespace(space_id)) {
17894 /* Get the ddl_mutex so that if an undo truncation is happening by
17895 the purge thread, it will complete before we continue. */
17896 mutex_enter(&undo::ddl_mutex);
17897
17898 /* When selecting information_schema.files, no MVCC is used. So it is
17899 possible to read an uncommitted DD record that indicates the undo
17900 space is empty and shows the new space_id after a truncation.
17901 Adjust for that possibility by always using the current space_id. */
17902 undo::spaces->s_lock();
17903 space_id_t undo_num = undo::id2num(space_id);
17904 undo::Tablespace *undo_space = undo::spaces->find(undo_num);
17905 if (undo_space != nullptr) {
17906 space_id = undo_space->id();
17907 }
17908 undo::spaces->s_unlock();
17909 }
17910
17911 auto space = fil_space_acquire(space_id);
17912
17913 /* Tablespace is missing in this case. */
17914 if (space == nullptr) {
17915 my_error(ER_TABLESPACE_MISSING, MYF(0), tablespace_name);
17916 if (fsp_is_undo_tablespace(space_id)) {
17917 mutex_exit(&undo::ddl_mutex);
17918 }
17919 return (DD_FAILURE);
17920 }
17921
17922 stats->m_id = space->id;
17923
17924 const char *type = "TABLESPACE";
17925
17926 fil_type_t purpose = space->purpose;
17927
17928 switch (purpose) {
17929 case FIL_TYPE_TABLESPACE:
17930 if (fsp_is_undo_tablespace(space_id)) {
17931 type = "UNDO LOG";
17932 break;
17933 } /* else fall through for TABLESPACE */
17934 case FIL_TYPE_IMPORT:
17935 /* 'IMPORTING'is a status. The type is TABLESPACE. */
17936 break;
17937 case FIL_TYPE_TEMPORARY:
17938 type = "TEMPORARY";
17939 break;
17940 }
17941
17942 stats->m_type = type;
17943
17944 stats->m_free_extents = space->free_len;
17945
17946 page_size_t page_size{space->flags};
17947
17948 page_no_t extent_pages = fsp_get_extent_size_in_pages(page_size);
17949
17950 stats->m_total_extents = space->size_in_header / extent_pages;
17951
17952 stats->m_extent_size = extent_pages * page_size.physical();
17953
17954 const fil_node_t *file = nullptr;
17955
17956 /* Use only the basename when searching for system tablespaces since
17957 InnoDB places them in innodb_data_home_dir and the DD may only know
17958 the basename. Since they are open, they are in the right place. */
17959 std::string search_name =
17960 (space->id == TRX_SYS_SPACE || space->id == dict_sys_t::s_temp_space_id)
17961 ? Fil_path::get_basename(file_name)
17962 : file_name;
17963
17964 /* Normalize the file name to search for. */
17965 Fil_path::normalize(search_name);
17966
17967 /* Find the fil_node_t that matches the filename. */
17968 for (const auto &f : space->files) {
17969 if (Fil_path::is_same_as(search_name, f.name)) {
17970 file = &f;
17971 break;
17972 }
17973
17974 /* Try to compare only the basename. */
17975 if (space->id == TRX_SYS_SPACE ||
17976 space->id == dict_sys_t::s_temp_space_id) {
17977 if (Fil_path::is_same_as(search_name, Fil_path::get_basename(f.name))) {
17978 file = &f;
17979 break;
17980 }
17981 }
17982
17983 if (space->files.size() == 1) {
17984 file = &f;
17985
17986 ib::info(ER_IB_MSG_570)
17987 << "Tablespace '" << tablespace_name << "'with DD filename '"
17988 << file_name << "' doesn't match the InnoDB filename '" << f.name
17989 << "'";
17990 }
17991 }
17992
17993 if (file == nullptr) {
17994 ib::warn(ER_IB_MSG_571) << "Tablespace '" << tablespace_name << "'"
17995 << " filename is unknown. Use --innodb-directories"
17996 << " to tell InnoDB the location of the file.";
17997
17998 my_error(ER_TABLESPACE_MISSING, MYF(0), tablespace_name);
17999
18000 if (fsp_is_undo_tablespace(space_id)) {
18001 mutex_exit(&undo::ddl_mutex);
18002 }
18003
18004 return (DD_FAILURE);
18005 }
18006
18007 stats->m_initial_size = file->init_size * page_size.physical();
18008
18009 /** Store maximum size */
18010 if (file->max_size >= PAGE_NO_MAX) {
18011 stats->m_maximum_size = ~0ULL;
18012 } else {
18013 stats->m_maximum_size = file->max_size * page_size.physical();
18014 }
18015
18016 /** Store autoextend size */
18017 page_no_t extend_pages;
18018
18019 if (space->id == TRX_SYS_SPACE) {
18020 extend_pages = srv_sys_space.get_increment();
18021
18022 } else if (fsp_is_system_temporary(space->id)) {
18023 extend_pages = srv_tmp_space.get_increment();
18024
18025 } else if (fsp_is_undo_tablespace(space->id)) {
18026 extend_pages = space->m_undo_extend;
18027
18028 } else if (space->autoextend_size_in_bytes > 0) {
18029 extend_pages = space->autoextend_size_in_bytes / page_size.physical();
18030 } else {
18031 extend_pages = fsp_get_pages_to_extend_ibd(page_size, file->size);
18032 }
18033
18034 stats->m_autoextend_size = extend_pages * page_size.physical();
18035
18036 auto avail_space = fsp_get_available_space_in_free_extents(space);
18037
18038 stats->m_data_free = avail_space * 1024;
18039
18040 stats->m_status = (purpose == FIL_TYPE_IMPORT ? "IMPORTING" : "NORMAL");
18041
18042 fil_space_release(space);
18043
18044 if (fsp_is_undo_tablespace(space_id)) {
18045 mutex_exit(&undo::ddl_mutex);
18046 }
18047
18048 return (DD_SUCCESS);
18049 }
18050
18051 /** Enable indexes.
18052 @param[in] mode enable index mode.
18053 @return HA_ERR_* error code or 0 */
18054 int ha_innobase::enable_indexes(uint mode) {
18055 int error = HA_ERR_WRONG_COMMAND;
18056
18057 /* Enable index only for intrinsic table. Behavior for all other
18058 table continue to remain same. */
18059
18060 if (m_prebuilt->table->is_intrinsic()) {
18061 ut_ad(mode == HA_KEY_SWITCH_ALL);
18062 for (auto index : m_prebuilt->table->indexes) {
18063 /* InnoDB being clustered index we can't disable/enable
18064 clustered index itself. */
18065 if (index->is_clustered()) {
18066 continue;
18067 }
18068
18069 index->allow_duplicates = false;
18070 }
18071 error = 0;
18072 }
18073
18074 return (error);
18075 }
18076
18077 /** Disable indexes.
18078 @param[in] mode disable index mode.
18079 @return HA_ERR_* error code or 0 */
18080 int ha_innobase::disable_indexes(uint mode) {
18081 int error = HA_ERR_WRONG_COMMAND;
18082
18083 /* Disable index only for intrinsic table. Behavior for all other
18084 table continue to remain same. */
18085
18086 if (m_prebuilt->table->is_intrinsic()) {
18087 ut_ad(mode == HA_KEY_SWITCH_ALL);
18088 for (auto index : m_prebuilt->table->indexes) {
18089 /* InnoDB being clustered index we can't disable/enable
18090 clustered index itself. */
18091 if (index->is_clustered()) {
18092 continue;
18093 }
18094
18095 index->allow_duplicates = true;
18096 }
18097 error = 0;
18098 }
18099
18100 return (error);
18101 }
18102
18103 /**
18104 Updates index cardinalities of the table, based on random dives into
18105 each index tree. This does NOT calculate exact statistics on the table.
18106 @return HA_ADMIN_* error code or HA_ADMIN_OK */
18107
18108 int ha_innobase::analyze(THD *, /*!< in: connection thread handle */
18109 HA_CHECK_OPT *) /*!< in: currently ignored */
18110 {
18111 /* Simply call info_low() with all the flags
18112 and request recalculation of the statistics */
18113 int ret = info_low(HA_STATUS_TIME | HA_STATUS_CONST | HA_STATUS_VARIABLE,
18114 true /* this is ANALYZE */);
18115
18116 if (ret != 0) {
18117 return (HA_ADMIN_FAILED);
18118 }
18119
18120 return (HA_ADMIN_OK);
18121 }
18122
18123 /** This is mapped to "ALTER TABLE tablename ENGINE=InnoDB", which rebuilds
18124 the table in MySQL. */
18125
18126 int ha_innobase::optimize(THD *, /*!< in: connection thread handle */
18127 HA_CHECK_OPT *) /*!< in: currently ignored */
18128 {
18129 TrxInInnoDB trx_in_innodb(m_prebuilt->trx);
18130
18131 /* FTS-FIXME: Since MySQL doesn't support engine-specific commands,
18132 we have to hijack some existing command in order to be able to test
18133 the new admin commands added in InnoDB's FTS support. For now, we
18134 use MySQL's OPTIMIZE command, normally mapped to ALTER TABLE in
18135 InnoDB (so it recreates the table anew), and map it to OPTIMIZE.
18136
18137 This works OK otherwise, but MySQL locks the entire table during
18138 calls to OPTIMIZE, which is undesirable. */
18139
18140 if (innodb_optimize_fulltext_only) {
18141 if (m_prebuilt->table->fts && m_prebuilt->table->fts->cache &&
18142 !dict_table_is_discarded(m_prebuilt->table)) {
18143 fts_sync_table(m_prebuilt->table, false, true, false);
18144 fts_optimize_table(m_prebuilt->table);
18145 }
18146 return (HA_ADMIN_OK);
18147 } else {
18148 return (HA_ADMIN_TRY_ALTER);
18149 }
18150 }
18151
18152 /** Tries to check that an InnoDB table is not corrupted. If corruption is
18153 noticed, prints to stderr information about it. In case of corruption
18154 may also assert a failure and crash the server.
18155 @return HA_ADMIN_CORRUPT or HA_ADMIN_OK */
18156
18157 int ha_innobase::check(THD *thd, /*!< in: user thread handle */
18158 HA_CHECK_OPT *check_opt) /*!< in: check options */
18159 {
18160 dict_index_t *index;
18161 ulint n_rows;
18162 ulint n_rows_in_table = ULINT_UNDEFINED;
18163 ulint n_dups = 0;
18164 bool is_ok = true;
18165 ulint old_isolation_level;
18166 dberr_t ret;
18167
18168 DBUG_TRACE;
18169 assert(thd == ha_thd());
18170 ut_a(m_prebuilt->trx->magic_n == TRX_MAGIC_N);
18171 ut_a(m_prebuilt->trx == thd_to_trx(thd));
18172
18173 TrxInInnoDB trx_in_innodb(m_prebuilt->trx);
18174
18175 if (m_prebuilt->mysql_template == nullptr) {
18176 /* Build the template; we will use a dummy template
18177 in index scans done in checking */
18178
18179 build_template(true);
18180 }
18181
18182 if (dict_table_is_discarded(m_prebuilt->table)) {
18183 ib_senderrf(thd, IB_LOG_LEVEL_ERROR, ER_TABLESPACE_DISCARDED,
18184 table->s->table_name.str);
18185
18186 return HA_ADMIN_CORRUPT;
18187
18188 } else if (m_prebuilt->table->ibd_file_missing) {
18189 ib_senderrf(thd, IB_LOG_LEVEL_ERROR, ER_TABLESPACE_MISSING,
18190 table->s->table_name.str);
18191
18192 return HA_ADMIN_CORRUPT;
18193 }
18194
18195 m_prebuilt->trx->op_info = "checking table";
18196
18197 if (m_prebuilt->table->is_corrupted()) {
18198 /* Now that the table is already marked as corrupted,
18199 there is no need to check any index of this table */
18200 m_prebuilt->trx->op_info = "";
18201 if (thd_killed(m_user_thd)) {
18202 thd_set_kill_status(m_user_thd);
18203 }
18204
18205 return HA_ADMIN_CORRUPT;
18206 }
18207
18208 old_isolation_level = m_prebuilt->trx->isolation_level;
18209
18210 /* We must run the index record counts at an isolation level
18211 >= READ COMMITTED, because a dirty read can see a wrong number
18212 of records in some index; to play safe, we use always
18213 REPEATABLE READ here */
18214 m_prebuilt->trx->isolation_level = TRX_ISO_REPEATABLE_READ;
18215
18216 ut_ad(!m_prebuilt->table->is_corrupted());
18217
18218 for (index = m_prebuilt->table->first_index(); index != nullptr;
18219 index = index->next()) {
18220 /* If this is an index being created or dropped, skip */
18221 if (!index->is_committed()) {
18222 continue;
18223 }
18224
18225 if (!(check_opt->flags & T_QUICK) && !index->is_corrupted()) {
18226 /* Enlarge the fatal lock wait timeout during
18227 CHECK TABLE. */
18228 srv_fatal_semaphore_wait_extend.fetch_add(1);
18229
18230 bool valid = btr_validate_index(index, m_prebuilt->trx, false);
18231
18232 /* Restore the fatal lock wait timeout after
18233 CHECK TABLE. */
18234 srv_fatal_semaphore_wait_extend.fetch_sub(1);
18235
18236 if (!valid) {
18237 is_ok = false;
18238
18239 push_warning_printf(thd, Sql_condition::SL_WARNING, ER_NOT_KEYFILE,
18240 "InnoDB: The B-tree of"
18241 " index %s is corrupted.",
18242 index->name());
18243 continue;
18244 }
18245 }
18246
18247 /* Instead of invoking change_active_index(), set up
18248 a dummy template for non-locking reads, disabling
18249 access to the clustered index. */
18250 m_prebuilt->index = index;
18251
18252 m_prebuilt->index_usable = m_prebuilt->index->is_usable(m_prebuilt->trx);
18253
18254 if (!m_prebuilt->index_usable) {
18255 if (m_prebuilt->index->is_corrupted()) {
18256 push_warning_printf(m_user_thd, Sql_condition::SL_WARNING,
18257 HA_ERR_INDEX_CORRUPT,
18258 "InnoDB: Index %s is marked as"
18259 " corrupted",
18260 index->name());
18261 is_ok = false;
18262 } else {
18263 push_warning_printf(thd, Sql_condition::SL_WARNING,
18264 HA_ERR_TABLE_DEF_CHANGED,
18265 "InnoDB: Insufficient history for"
18266 " index %s",
18267 index->name());
18268 }
18269 continue;
18270 }
18271
18272 m_prebuilt->sql_stat_start = true;
18273 m_prebuilt->template_type = ROW_MYSQL_DUMMY_TEMPLATE;
18274 m_prebuilt->n_template = 0;
18275 m_prebuilt->need_to_access_clustered = false;
18276
18277 m_prebuilt->clear_search_tuples();
18278
18279 m_prebuilt->select_lock_type = LOCK_NONE;
18280
18281 size_t max_threads = thd_parallel_read_threads(m_prebuilt->trx->mysql_thd);
18282
18283 /* Scan this index. */
18284 if (dict_index_is_spatial(index)) {
18285 ret = row_count_rtree_recs(m_prebuilt, &n_rows, &n_dups);
18286 if ((check_opt->flags & T_EXTEND) && (ret == DB_SUCCESS) &&
18287 !(n_rows < n_rows_in_table || n_dups < n_rows - n_rows_in_table)) {
18288 /* For CHECK TABLE EXTENDED; we also want to make sure that MBR stored
18289 in SPATIAL Index is matching the MBR of geometry stored in Clustered
18290 record. */
18291 m_prebuilt->need_to_access_clustered = true;
18292 n_rows = 0;
18293 n_dups = 0;
18294 ret = row_count_rtree_recs(m_prebuilt, &n_rows, &n_dups);
18295 }
18296 } else {
18297 ret = row_scan_index_for_mysql(m_prebuilt, index, max_threads, true,
18298 &n_rows);
18299 }
18300
18301 DBUG_EXECUTE_IF(
18302 "dict_set_clust_index_corrupted",
18303 if (index->is_clustered()) { ret = DB_CORRUPTION; });
18304
18305 DBUG_EXECUTE_IF(
18306 "dict_set_index_corrupted",
18307 if (!index->is_clustered()) { ret = DB_CORRUPTION; });
18308
18309 if (ret == DB_INTERRUPTED || thd_killed(m_user_thd)) {
18310 /* Do not report error since this could happen
18311 during shutdown */
18312 break;
18313 }
18314 if (ret != DB_SUCCESS) {
18315 /* Assume some kind of corruption. */
18316 push_warning_printf(thd, Sql_condition::SL_WARNING, ER_NOT_KEYFILE,
18317 "InnoDB: The B-tree of"
18318 " index %s is corrupted.",
18319 index->name());
18320 is_ok = false;
18321 dict_set_corrupted(index);
18322 }
18323
18324 if (index == m_prebuilt->table->first_index()) {
18325 n_rows_in_table = n_rows;
18326 } else if (!(index->type & DICT_FTS) && (n_rows != n_rows_in_table) &&
18327 (!index->is_multi_value()) &&
18328 (!dict_index_is_spatial(index) || (n_rows < n_rows_in_table) ||
18329 (n_dups < n_rows - n_rows_in_table))) {
18330 push_warning_printf(thd, Sql_condition::SL_WARNING, ER_NOT_KEYFILE,
18331 "InnoDB: Index '%-.200s' contains %lu"
18332 " entries, should be %lu.",
18333 index->name(), (ulong)n_rows, (ulong)n_rows_in_table);
18334 is_ok = false;
18335 dict_set_corrupted(index);
18336 }
18337 }
18338
18339 /* Restore the original isolation level */
18340 m_prebuilt->trx->isolation_level =
18341 static_cast<trx_t::isolation_level_t>(old_isolation_level);
18342
18343 #if defined UNIV_AHI_DEBUG || defined UNIV_DEBUG
18344 /* We validate the whole adaptive hash index for all tables
18345 at every CHECK TABLE only when QUICK flag is not present. */
18346
18347 if (!(check_opt->flags & T_QUICK) && !btr_search_validate()) {
18348 push_warning(thd, Sql_condition::SL_WARNING, ER_NOT_KEYFILE,
18349 "InnoDB: The adaptive hash index is corrupted.");
18350 is_ok = false;
18351 }
18352 #endif /* defined UNIV_AHI_DEBUG || defined UNIV_DEBUG */
18353 m_prebuilt->trx->op_info = "";
18354 if (thd_killed(m_user_thd)) {
18355 thd_set_kill_status(m_user_thd);
18356 }
18357
18358 return is_ok ? HA_ADMIN_OK : HA_ADMIN_CORRUPT;
18359 }
18360
18361 /** Tells something additional to the handler about how to do things.
18362 @return 0 or error number */
18363
18364 int ha_innobase::extra(enum ha_extra_function operation)
18365 /*!< in: HA_EXTRA_FLUSH or some other flag */
18366 {
18367 if (m_prebuilt->table) {
18368 #ifdef UNIV_DEBUG
18369 if (m_prebuilt->table->n_ref_count > 0)
18370 #endif /* UNIV_DEBUG */
18371 update_thd();
18372 }
18373
18374 /* Warning: since it is not sure that MySQL calls external_lock
18375 before calling this function, the trx field in m_prebuilt can be
18376 obsolete! */
18377
18378 switch (operation) {
18379 case HA_EXTRA_FLUSH:
18380 if (m_prebuilt->blob_heap) {
18381 row_mysql_prebuilt_free_blob_heap(m_prebuilt);
18382 }
18383 break;
18384 case HA_EXTRA_RESET_STATE:
18385 reset_template();
18386 m_prebuilt->replace = 0;
18387 m_prebuilt->on_duplicate_key_update = 0;
18388 break;
18389 case HA_EXTRA_NO_KEYREAD:
18390 m_prebuilt->read_just_key = 0;
18391 break;
18392 case HA_EXTRA_KEYREAD:
18393 m_prebuilt->read_just_key = 1;
18394 break;
18395 case HA_EXTRA_KEYREAD_PRESERVE_FIELDS:
18396 m_prebuilt->keep_other_fields_on_keyread = 1;
18397 break;
18398
18399 /* IMPORTANT: m_prebuilt->trx can be obsolete in
18400 this method, because it is not sure that MySQL
18401 calls external_lock before this method with the
18402 parameters below. We must not invoke update_thd()
18403 either, because the calling threads may change.
18404 CAREFUL HERE, OR MEMORY CORRUPTION MAY OCCUR! */
18405 case HA_EXTRA_INSERT_WITH_UPDATE:
18406 m_prebuilt->on_duplicate_key_update = 1;
18407 break;
18408 case HA_EXTRA_NO_IGNORE_DUP_KEY:
18409 m_prebuilt->on_duplicate_key_update = 0;
18410 break;
18411 case HA_EXTRA_WRITE_CAN_REPLACE:
18412 m_prebuilt->replace = 1;
18413 break;
18414 case HA_EXTRA_WRITE_CANNOT_REPLACE:
18415 m_prebuilt->replace = 0;
18416 break;
18417 case HA_EXTRA_NO_READ_LOCKING:
18418 m_prebuilt->no_read_locking = true;
18419 break;
18420 case HA_EXTRA_BEGIN_ALTER_COPY:
18421 m_prebuilt->table->skip_alter_undo = 1;
18422 break;
18423 case HA_EXTRA_END_ALTER_COPY:
18424 alter_stats_rebuild(m_prebuilt->table, m_prebuilt->table->name.m_name,
18425 m_user_thd);
18426 m_prebuilt->table->skip_alter_undo = 0;
18427 break;
18428 case HA_EXTRA_NO_AUTOINC_LOCKING:
18429 m_prebuilt->no_autoinc_locking = true;
18430 break;
18431 default: /* Do nothing */
18432 ;
18433 }
18434
18435 return (0);
18436 }
18437
18438 /**
18439 MySQL calls this method at the end of each statement. This method
18440 exists for readability only. ha_innobase::reset() doesn't give any
18441 clue about the method. */
18442
18443 int ha_innobase::end_stmt() {
18444 if (m_prebuilt->blob_heap) {
18445 row_mysql_prebuilt_free_blob_heap(m_prebuilt);
18446 }
18447
18448 m_prebuilt->end_stmt();
18449
18450 reset_template();
18451
18452 m_ds_mrr.reset();
18453
18454 /* TODO: This should really be reset in reset_template() but for now
18455 it's safer to do it explicitly here. */
18456
18457 /* This is a statement level counter. */
18458 m_prebuilt->autoinc_last_value = 0;
18459
18460 m_prebuilt->no_read_locking = false;
18461 m_prebuilt->no_autoinc_locking = false;
18462
18463 /* This transaction had called ha_innobase::start_stmt() */
18464 trx_t *trx = m_prebuilt->trx;
18465
18466 if (!m_prebuilt->table->is_temporary() && trx != thd_to_trx(ha_thd())) {
18467 ut_d(ut_error);
18468 ut_o(return (0));
18469 }
18470
18471 ut_ad(!m_prebuilt->replace);
18472 ut_ad(!m_prebuilt->on_duplicate_key_update);
18473
18474 if (trx->lock.start_stmt) {
18475 trx->lock.start_stmt = false;
18476 TrxInInnoDB::end_stmt(trx);
18477 }
18478
18479 return (0);
18480 }
18481
18482 /**
18483 MySQL calls this method at the end of each statement */
18484
18485 int ha_innobase::reset() { return (end_stmt()); }
18486
18487 /** MySQL calls this function at the start of each SQL statement inside LOCK
18488 TABLES. Inside LOCK TABLES the "::external_lock" method does not work to mark
18489 SQL statement borders. Note also a special case: if a temporary table is
18490 created inside LOCK TABLES, MySQL has not called external_lock() at all on
18491 that table.
18492 MySQL-5.0 also calls this before each statement in an execution of a stored
18493 procedure. To make the execution more deterministic for binlogging, MySQL-5.0
18494 locks all tables involved in a stored procedure with full explicit table locks
18495 (thd_in_lock_tables(thd) holds in store_lock()) before executing the procedure.
18496 @param[in] thd handle to the user thread
18497 @param[in] lock_type lock type
18498 @return 0 or error code */
18499 int ha_innobase::start_stmt(THD *thd, thr_lock_type lock_type) {
18500 trx_t *trx = m_prebuilt->trx;
18501
18502 DBUG_TRACE;
18503
18504 update_thd(thd);
18505
18506 ut_ad(m_prebuilt->table != nullptr);
18507
18508 TrxInInnoDB trx_in_innodb(trx);
18509
18510 if (m_prebuilt->table->is_intrinsic()) {
18511 if (thd_sql_command(thd) == SQLCOM_ALTER_TABLE) {
18512 return HA_ERR_WRONG_COMMAND;
18513 }
18514
18515 return 0;
18516 }
18517
18518 trx = m_prebuilt->trx;
18519
18520 innobase_srv_conc_force_exit_innodb(trx);
18521
18522 /* Reset the AUTOINC statement level counter for multi-row INSERTs. */
18523 trx->n_autoinc_rows = 0;
18524
18525 m_prebuilt->sql_stat_start = true;
18526 m_prebuilt->hint_need_to_fetch_extra_cols = 0;
18527 reset_template();
18528
18529 if (m_prebuilt->table->is_temporary() && m_mysql_has_locked &&
18530 m_prebuilt->select_lock_type == LOCK_NONE) {
18531 dberr_t error;
18532
18533 switch (thd_sql_command(thd)) {
18534 case SQLCOM_INSERT:
18535 case SQLCOM_UPDATE:
18536 case SQLCOM_DELETE:
18537 case SQLCOM_REPLACE:
18538 init_table_handle_for_HANDLER();
18539 m_prebuilt->select_lock_type = LOCK_X;
18540 m_stored_select_lock_type = LOCK_X;
18541 error = row_lock_table(m_prebuilt);
18542
18543 if (error != DB_SUCCESS) {
18544 int st = convert_error_code_to_mysql(error, 0, thd);
18545 return st;
18546 }
18547 break;
18548 }
18549 }
18550
18551 if (!m_mysql_has_locked) {
18552 /* This handle is for a temporary table created inside
18553 this same LOCK TABLES; since MySQL does NOT call external_lock
18554 in this case, we must use x-row locks inside InnoDB to be
18555 prepared for an update of a row */
18556
18557 m_prebuilt->select_lock_type = LOCK_X;
18558
18559 } else if ((trx->isolation_level != TRX_ISO_SERIALIZABLE &&
18560 lock_type == TL_READ && thd_sql_command(thd) == SQLCOM_SELECT) ||
18561 (trx->skip_gap_locks() &&
18562 (lock_type == TL_READ || lock_type == TL_READ_NO_INSERT) &&
18563 (thd_sql_command(thd) == SQLCOM_INSERT_SELECT ||
18564 thd_sql_command(thd) == SQLCOM_REPLACE_SELECT ||
18565 thd_sql_command(thd) == SQLCOM_UPDATE ||
18566 thd_sql_command(thd) == SQLCOM_CREATE_TABLE))) {
18567 /* For other than temporary tables, we obtain
18568 no lock for consistent read (plain SELECT).
18569
18570 If this session is using READ COMMITTED or READ
18571 UNCOMMITTED isolation level and MySQL is doing INSERT
18572 INTO... SELECT or REPLACE INTO...SELECT or UPDATE ...
18573 = (SELECT ...) or CREATE ... SELECT... without FOR
18574 UPDATE or IN SHARE MODE in select, then we use
18575 consistent read for select.
18576
18577 See also similar code in ha_innobase::store_lock(). */
18578
18579 m_prebuilt->select_lock_type = LOCK_NONE;
18580 } else {
18581 /* Not a consistent read: restore the
18582 select_lock_type value. The value of
18583 stored_select_lock_type was decided in:
18584 1) ::store_lock(),
18585 2) ::external_lock(),
18586 3) ::init_table_handle_for_HANDLER(). */
18587
18588 ut_a(m_stored_select_lock_type != LOCK_NONE_UNSET);
18589
18590 m_prebuilt->select_lock_type = m_stored_select_lock_type;
18591 }
18592
18593 *trx->detailed_error = 0;
18594
18595 innobase_register_trx(ht, thd, trx);
18596
18597 if (!trx_is_started(trx)) {
18598 ++trx->will_lock;
18599 }
18600
18601 /* Only do it once per transaction. */
18602 if (!trx->lock.start_stmt && lock_type != TL_UNLOCK) {
18603 trx->lock.start_stmt = true;
18604 TrxInInnoDB::begin_stmt(trx);
18605 }
18606
18607 return 0;
18608 }
18609
18610 trx_t::isolation_level_t innobase_trx_map_isolation_level(
18611 enum_tx_isolation iso) {
18612 trx_t::isolation_level_t trx_isolation_level;
18613
18614 switch (iso) {
18615 case ISO_REPEATABLE_READ:
18616 trx_isolation_level = TRX_ISO_REPEATABLE_READ;
18617 break;
18618 case ISO_READ_COMMITTED:
18619 trx_isolation_level = TRX_ISO_READ_COMMITTED;
18620 break;
18621 case ISO_SERIALIZABLE:
18622 trx_isolation_level = TRX_ISO_SERIALIZABLE;
18623 break;
18624 case ISO_READ_UNCOMMITTED:
18625 trx_isolation_level = TRX_ISO_READ_UNCOMMITTED;
18626 break;
18627 default:
18628 ut_error;
18629 }
18630
18631 return trx_isolation_level;
18632 }
18633
18634 /** As MySQL will execute an external lock for every new table it uses when it
18635 starts to process an SQL statement (an exception is when MySQL calls
18636 start_stmt for the handle) we can use this function to store the pointer to
18637 the THD in the handle. We will also use this function to communicate
18638 to InnoDB that a new SQL statement has started and that we must store a
18639 savepoint to our transaction handle, so that we are able to roll back
18640 the SQL statement in case of an error.
18641 @return 0 */
18642
18643 int ha_innobase::external_lock(THD *thd, /*!< in: handle to the user thread */
18644 int lock_type) /*!< in: lock type */
18645 {
18646 DBUG_TRACE;
18647 DBUG_PRINT("enter", ("lock_type: %d", lock_type));
18648
18649 update_thd(thd);
18650
18651 trx_t *trx = m_prebuilt->trx;
18652
18653 enum_sql_command sql_command = (enum_sql_command)thd_sql_command(thd);
18654
18655 ut_ad(m_prebuilt->table);
18656
18657 if (m_prebuilt->table->is_intrinsic()) {
18658 if (sql_command == SQLCOM_ALTER_TABLE) {
18659 return HA_ERR_WRONG_COMMAND;
18660 }
18661
18662 TrxInInnoDB::begin_stmt(trx);
18663
18664 return 0;
18665 }
18666
18667 /* Statement based binlogging does not work in isolation level
18668 READ UNCOMMITTED and READ COMMITTED since the necessary
18669 locks cannot be taken. In this case, we print an
18670 informative error message and return with an error.
18671 Note: decide_logging_format would give the same error message,
18672 except it cannot give the extra details. */
18673
18674 if (lock_type == F_WRLCK && !(table_flags() & HA_BINLOG_STMT_CAPABLE) &&
18675 thd_binlog_format(thd) == BINLOG_FORMAT_STMT &&
18676 thd_binlog_filter_ok(thd) && thd_sqlcom_can_generate_row_events(thd)) {
18677 bool skip = false;
18678
18679 /* used by test case */
18680 DBUG_EXECUTE_IF("no_innodb_binlog_errors", skip = true;);
18681
18682 if (!skip) {
18683 my_error(ER_BINLOG_STMT_MODE_AND_ROW_ENGINE, MYF(0),
18684 " InnoDB is limited to row-logging when"
18685 " transaction isolation level is"
18686 " READ COMMITTED or READ UNCOMMITTED.");
18687
18688 return HA_ERR_LOGGING_IMPOSSIBLE;
18689 }
18690 }
18691
18692 /* Check for UPDATEs in read-only mode. */
18693 if (srv_read_only_mode &&
18694 (sql_command == SQLCOM_UPDATE || sql_command == SQLCOM_INSERT ||
18695 sql_command == SQLCOM_REPLACE || sql_command == SQLCOM_DROP_TABLE ||
18696 sql_command == SQLCOM_ALTER_TABLE || sql_command == SQLCOM_OPTIMIZE ||
18697 (sql_command == SQLCOM_CREATE_TABLE && lock_type == F_WRLCK) ||
18698 sql_command == SQLCOM_CREATE_INDEX || sql_command == SQLCOM_DROP_INDEX ||
18699 sql_command == SQLCOM_DELETE)) {
18700 if (sql_command == SQLCOM_CREATE_TABLE) {
18701 ib_senderrf(thd, IB_LOG_LEVEL_WARN, ER_INNODB_READ_ONLY);
18702 return HA_ERR_INNODB_READ_ONLY;
18703 } else {
18704 ib_senderrf(thd, IB_LOG_LEVEL_WARN, ER_READ_ONLY_MODE);
18705 return HA_ERR_TABLE_READONLY;
18706 }
18707 }
18708
18709 m_prebuilt->sql_stat_start = true;
18710 m_prebuilt->hint_need_to_fetch_extra_cols = 0;
18711
18712 reset_template();
18713
18714 switch (m_prebuilt->table->quiesce) {
18715 case QUIESCE_START:
18716 /* Check for FLUSH TABLE t WITH READ LOCK; */
18717 if (!srv_read_only_mode && sql_command == SQLCOM_FLUSH &&
18718 lock_type == F_RDLCK) {
18719 if (dict_table_is_discarded(m_prebuilt->table)) {
18720 ib_senderrf(trx->mysql_thd, IB_LOG_LEVEL_ERROR,
18721 ER_TABLESPACE_DISCARDED, table->s->table_name.str);
18722
18723 return HA_ERR_NO_SUCH_TABLE;
18724 }
18725
18726 row_quiesce_table_start(m_prebuilt->table, trx);
18727
18728 /* Use the transaction instance to track UNLOCK
18729 TABLES. It can be done via START TRANSACTION; too
18730 implicitly. */
18731
18732 ++trx->flush_tables;
18733 }
18734 break;
18735
18736 case QUIESCE_COMPLETE:
18737 /* Check for UNLOCK TABLES; implicit or explicit
18738 or trx interruption. */
18739 if (trx->flush_tables > 0 &&
18740 (lock_type == F_UNLCK || trx_is_interrupted(trx))) {
18741 row_quiesce_table_complete(m_prebuilt->table, trx);
18742
18743 ut_a(trx->flush_tables > 0);
18744 --trx->flush_tables;
18745 }
18746
18747 break;
18748
18749 case QUIESCE_NONE:
18750 break;
18751 }
18752
18753 if (lock_type == F_WRLCK) {
18754 /* If this is a SELECT, then it is in UPDATE TABLE ...
18755 or SELECT ... FOR UPDATE */
18756 m_prebuilt->select_lock_type = LOCK_X;
18757 m_stored_select_lock_type = LOCK_X;
18758 }
18759
18760 ut_ad(!(lock_type == F_RDLCK && m_prebuilt->select_lock_type == LOCK_X));
18761
18762 if (lock_type != F_UNLCK) {
18763 /* MySQL is setting a new table lock */
18764
18765 *trx->detailed_error = 0;
18766
18767 innobase_register_trx(ht, thd, trx);
18768
18769 /*
18770 For reads we will use LOCK_NONE, LOCK_S or LOCK_X according to this chart:
18771 +-----------------------------------------+
18772 | is_dd_table or skip_locking |
18773 +----------------------------------+------+
18774 | false | true |
18775 +----------------------------------| |
18776 | TRANSACTION ISOLATION LEVEL | |
18777 +----------------+-----------------+ |
18778 | < SERIALIZABLE | = SERIALIZABLE | |
18779 +--------------------+----------------+-----------------+------+
18780 | non-locking SELECT | NONE [1] | S [3] | NONE |
18781 | SELECT FOR SHARE | S [2] | S | NONE |
18782 | SELECT FOR UPDATE | X | X | X |
18783 +--------------------+----------------+-----------------+------+
18784 Where LOCK_NONE means a non-locking consistent reads via read-view, and
18785 `no_read_locking` is set to `true` by Server calling
18786 ha_extra().
18787 Notes:
18788 [1,2] The server layer calls external_lock(..,F_RDLCK) which retains the old
18789 value of select_lock_type before the call. In most cases it is the value
18790 set by a previous call to store_lock(..):
18791 [1] For a non-locking SELECT the Server layer calls store_lock(..,TL_READ)
18792 which sets select_lock_type = LOCK_NONE, except for ACL tables which
18793 treat it as in [1].
18794 [2] In case of SELECT FOR SHARE the Server layer calls
18795 store_lock(..,TL_READ_WITH_SHARED_LOCKS) which sets
18796 select_lock_type = LOCK_S
18797 [3] An exception is consistent reads in the AUTOCOMMIT=1 mode:
18798 we know that they are read-only transactions, and they can be serialized
18799 also if performed as consistent reads. Thus we use LOCK_NONE for them.
18800
18801 For non-SELECT commands, there may be still possibility of setting
18802 skip_locking=1. E.g.,
18803 - UPDATE ... WHERE ... (SELECT... acl_table);
18804 - DELETE ... WHERE ... (SELECT... acl_table);
18805 The first entry 'non-locking SELECT' in above table applies in these case.
18806 */
18807 if (lock_type == F_RDLCK) {
18808 /**
18809 To limit range of circumstances under which transaction's isolation
18810 level can be compromised, we allow disabling readlocks only for DD
18811 and ACL tables.
18812 */
18813 ut_ad(!m_prebuilt->no_read_locking || m_prebuilt->table->is_dd_table ||
18814 is_acl_table(table));
18815
18816 if (m_prebuilt->table->is_dd_table || m_prebuilt->no_read_locking) {
18817 m_prebuilt->select_lock_type = LOCK_NONE;
18818 m_stored_select_lock_type = LOCK_NONE;
18819 } else if (trx->isolation_level == TRX_ISO_SERIALIZABLE &&
18820 m_prebuilt->select_lock_type == LOCK_NONE &&
18821 thd_test_options(thd, OPTION_NOT_AUTOCOMMIT | OPTION_BEGIN)) {
18822 m_prebuilt->select_lock_type = LOCK_S;
18823 m_stored_select_lock_type = LOCK_S;
18824 } else {
18825 // Retain value set earlier for example via store_lock()
18826 // which is LOCK_S or LOCK_NONE
18827 ut_ad(m_prebuilt->select_lock_type == LOCK_S ||
18828 m_prebuilt->select_lock_type == LOCK_NONE);
18829 }
18830 }
18831
18832 /* Starting from 4.1.9, no InnoDB table lock is taken in LOCK
18833 TABLES if AUTOCOMMIT=1. It does not make much sense to acquire
18834 an InnoDB table lock if it is released immediately at the end
18835 of LOCK TABLES, and InnoDB's table locks in that case cause
18836 VERY easily deadlocks.
18837
18838 We do not set InnoDB table locks if user has not explicitly
18839 requested a table lock. Note that thd_in_lock_tables(thd)
18840 can hold in some cases, e.g., at the start of a stored
18841 procedure call (SQLCOM_CALL). */
18842
18843 if (m_prebuilt->select_lock_type != LOCK_NONE) {
18844 if (sql_command == SQLCOM_LOCK_TABLES && THDVAR(thd, table_locks) &&
18845 thd_test_options(thd, OPTION_NOT_AUTOCOMMIT) &&
18846 thd_in_lock_tables(thd)) {
18847 dberr_t error = row_lock_table(m_prebuilt);
18848
18849 if (error != DB_SUCCESS) {
18850 return convert_error_code_to_mysql(error, 0, thd);
18851 }
18852 }
18853
18854 trx->mysql_n_tables_locked++;
18855 }
18856
18857 trx->n_mysql_tables_in_use++;
18858 m_mysql_has_locked = true;
18859
18860 if (!trx_is_started(trx) && (m_prebuilt->select_lock_type != LOCK_NONE ||
18861 m_stored_select_lock_type != LOCK_NONE)) {
18862 ++trx->will_lock;
18863 }
18864
18865 TrxInInnoDB::begin_stmt(trx);
18866
18867 #ifdef UNIV_DEBUG
18868 if (thd != nullptr && thd_tx_is_dd_trx(thd)) {
18869 trx->is_dd_trx = true;
18870 }
18871 #endif /* UNIV_DEBUG */
18872 return 0;
18873 } else {
18874 TrxInInnoDB::end_stmt(trx);
18875
18876 DEBUG_SYNC_C("ha_innobase_end_statement");
18877 }
18878
18879 /* MySQL is releasing a table lock */
18880
18881 trx->n_mysql_tables_in_use--;
18882 m_mysql_has_locked = false;
18883
18884 innobase_srv_conc_force_exit_innodb(trx);
18885
18886 /* If the MySQL lock count drops to zero we know that the current SQL
18887 statement has ended */
18888
18889 if (trx->n_mysql_tables_in_use == 0) {
18890 trx->mysql_n_tables_locked = 0;
18891 m_prebuilt->used_in_HANDLER = false;
18892
18893 if (!thd_test_options(thd, OPTION_NOT_AUTOCOMMIT | OPTION_BEGIN)) {
18894 if (trx_is_started(trx)) {
18895 innobase_commit(ht, thd, true);
18896 } else {
18897 /* Since the trx state is TRX_NOT_STARTED,
18898 trx_commit() will not be called. Reset
18899 trx->is_dd_trx here */
18900 ut_d(trx->is_dd_trx = false);
18901 }
18902
18903 } else if (trx->isolation_level <= TRX_ISO_READ_COMMITTED &&
18904 MVCC::is_view_active(trx->read_view)) {
18905 mutex_enter(&trx_sys->mutex);
18906
18907 trx_sys->mvcc->view_close(trx->read_view, true);
18908
18909 mutex_exit(&trx_sys->mutex);
18910 }
18911 }
18912
18913 if (!trx_is_started(trx) && lock_type != F_UNLCK &&
18914 (m_prebuilt->select_lock_type != LOCK_NONE ||
18915 m_stored_select_lock_type != LOCK_NONE)) {
18916 ++trx->will_lock;
18917 }
18918
18919 return 0;
18920 }
18921
18922 /** Here we export InnoDB status variables to MySQL. */
18923 static void innodb_export_status() {
18924 if (innodb_inited) {
18925 srv_export_innodb_status();
18926 }
18927 }
18928
18929 /** Implements the SHOW ENGINE INNODB STATUS command. Sends the output of the
18930 InnoDB Monitor to the client.
18931 @param[in] hton the innodb handlerton
18932 @param[in] thd the MySQL query thread of the caller
18933 @param[in] stat_print print function
18934 @return 0 on success */
18935 static int innodb_show_status(handlerton *hton, THD *thd,
18936 stat_print_fn *stat_print) {
18937 static const char truncated_msg[] = "... truncated...\n";
18938 const long MAX_STATUS_SIZE = 1048576;
18939 ulint trx_list_start = ULINT_UNDEFINED;
18940 ulint trx_list_end = ULINT_UNDEFINED;
18941 bool ret_val;
18942
18943 DBUG_TRACE;
18944 assert(hton == innodb_hton_ptr);
18945
18946 /* We don't create the temp files or associated
18947 mutexes in read-only-mode */
18948
18949 if (srv_read_only_mode) {
18950 return 0;
18951 }
18952
18953 trx_t *trx = check_trx_exists(thd);
18954
18955 innobase_srv_conc_force_exit_innodb(trx);
18956
18957 TrxInInnoDB trx_in_innodb(trx);
18958
18959 /* We let the InnoDB Monitor to output at most MAX_STATUS_SIZE
18960 bytes of text. */
18961
18962 char *str;
18963 ssize_t flen;
18964
18965 mutex_enter(&srv_monitor_file_mutex);
18966 rewind(srv_monitor_file);
18967
18968 srv_printf_innodb_monitor(srv_monitor_file, false, &trx_list_start,
18969 &trx_list_end);
18970
18971 os_file_set_eof(srv_monitor_file);
18972
18973 if ((flen = ftell(srv_monitor_file)) < 0) {
18974 flen = 0;
18975 }
18976
18977 ssize_t usable_len;
18978
18979 if (flen > MAX_STATUS_SIZE) {
18980 usable_len = MAX_STATUS_SIZE;
18981 srv_truncated_status_writes++;
18982 } else {
18983 usable_len = flen;
18984 }
18985
18986 /* allocate buffer for the string, and
18987 read the contents of the temporary file */
18988
18989 str = (char *)my_malloc(PSI_INSTRUMENT_ME, usable_len + 1, MYF(0));
18990 if (!str) {
18991 mutex_exit(&srv_monitor_file_mutex);
18992 return 1;
18993 }
18994
18995 rewind(srv_monitor_file);
18996
18997 if (flen < MAX_STATUS_SIZE) {
18998 /* Display the entire output. */
18999 flen = fread(str, 1, flen, srv_monitor_file);
19000 } else if (trx_list_end < (ulint)flen && trx_list_start < trx_list_end &&
19001 trx_list_start + (flen - trx_list_end) <
19002 MAX_STATUS_SIZE - sizeof truncated_msg - 1) {
19003 /* Omit the beginning of the list of active transactions. */
19004 ssize_t len = fread(str, 1, trx_list_start, srv_monitor_file);
19005
19006 memcpy(str + len, truncated_msg, sizeof truncated_msg - 1);
19007 len += sizeof truncated_msg - 1;
19008 usable_len = (MAX_STATUS_SIZE - 1) - len;
19009 fseek(srv_monitor_file, static_cast<long>(flen - usable_len), SEEK_SET);
19010 len += fread(str + len, 1, usable_len, srv_monitor_file);
19011 flen = len;
19012 } else {
19013 /* Omit the end of the output. */
19014 flen = fread(str, 1, MAX_STATUS_SIZE - 1, srv_monitor_file);
19015 }
19016
19017 mutex_exit(&srv_monitor_file_mutex);
19018
19019 ret_val = stat_print(thd, innobase_hton_name,
19020 static_cast<uint>(strlen(innobase_hton_name)),
19021 STRING_WITH_LEN(""), str, static_cast<uint>(flen));
19022
19023 my_free(str);
19024
19025 return ret_val;
19026 }
19027
19028 /** Implements Log_resource lock.
19029 @param[in] hton the innodb handlerton
19030 @return false on success */
19031 static bool innobase_lock_hton_log(handlerton *hton) {
19032 bool ret_val = false;
19033
19034 DBUG_TRACE;
19035 assert(hton == innodb_hton_ptr);
19036
19037 log_position_lock(*log_sys);
19038
19039 return ret_val;
19040 }
19041
19042 /** Implements Log_resource unlock.
19043 @param[in] hton the innodb handlerton
19044 @return false on success */
19045 static bool innobase_unlock_hton_log(handlerton *hton) {
19046 bool ret_val = false;
19047
19048 DBUG_TRACE;
19049 assert(hton == innodb_hton_ptr);
19050
19051 log_position_unlock(*log_sys);
19052
19053 return ret_val;
19054 }
19055
19056 /** Implements Log_resource collect_info.
19057 @param[in] hton the innodb handlerton
19058 @param[in] json the JSON dom to receive the log info
19059 @return false on success */
19060 static bool innobase_collect_hton_log_info(handlerton *hton, Json_dom *json) {
19061 bool ret_val = false;
19062 lsn_t lsn;
19063 lsn_t lsn_checkpoint;
19064
19065 DBUG_TRACE;
19066 assert(hton == innodb_hton_ptr);
19067
19068 log_position_collect_lsn_info(*log_sys, &lsn, &lsn_checkpoint);
19069
19070 Json_object *json_engines = static_cast<Json_object *>(json);
19071 Json_object json_innodb;
19072 Json_int json_lsn(lsn);
19073 Json_int json_lsn_checkpoint(lsn_checkpoint);
19074
19075 ret_val = json_innodb.add_clone("LSN", &json_lsn);
19076 if (!ret_val)
19077 ret_val = json_innodb.add_clone("LSN_checkpoint", &json_lsn_checkpoint);
19078 if (!ret_val) ret_val = json_engines->add_clone("InnoDB", &json_innodb);
19079
19080 return ret_val;
19081 }
19082
19083 /** Callback for collecting mutex statistics */
19084 struct ShowStatus {
19085 /** For tracking the mutex metrics */
19086 struct Value {
19087 /** Constructor
19088 @param[in] name Name of the mutex
19089 @param[in] spins Number of spins
19090 @param[in] waits OS waits so far
19091 @param[in] calls Number of calls to enter() */
19092 Value(const char *name, ulint spins, uint64_t waits, uint64_t calls)
19093 : m_name(name), m_spins(spins), m_waits(waits), m_calls(calls) {
19094 /* No op */
19095 }
19096
19097 /** Mutex name */
19098 std::string m_name;
19099
19100 /** Spins so far */
19101 ulint m_spins;
19102
19103 /** Waits so far */
19104 uint64_t m_waits;
19105
19106 /** Number of calls so far */
19107 uint64_t m_calls;
19108 };
19109
19110 /** Order by m_waits, in descending order. */
19111 struct OrderByWaits {
19112 /** @return true if rhs < lhs */
19113 bool operator()(const Value &lhs, const Value &rhs) const UNIV_NOTHROW {
19114 return (rhs.m_waits < lhs.m_waits);
19115 }
19116 };
19117
19118 typedef std::vector<Value, ut::allocator<Value>> Values;
19119
19120 /** Collect the individual latch counts */
19121 struct GetCount {
19122 typedef latch_meta_t::CounterType::Count Count;
19123
19124 /** Constructor
19125 @param[in] name Latch name
19126 @param[in,out] values Put the values here */
19127 GetCount(const char *name, Values *values) UNIV_NOTHROW : m_name(name),
19128 m_values(values) {
19129 /* No op */
19130 }
19131
19132 /** Collect the latch metrics. Ignore entries where the
19133 spins and waits are zero.
19134 @param[in] count The latch metrics */
19135 void operator()(const Count *count) UNIV_NOTHROW {
19136 if (count->m_spins > 0 || count->m_waits > 0) {
19137 m_values->push_back(
19138 Value(m_name, count->m_spins, count->m_waits, count->m_calls));
19139 }
19140 }
19141
19142 /** The latch name */
19143 const char *m_name;
19144
19145 /** For collecting the active mutex stats. */
19146 Values *m_values;
19147 };
19148
19149 /** Constructor */
19150 ShowStatus() = default;
19151
19152 /** Callback for collecting the stats
19153 @param[in] latch_meta Latch meta data
19154 @return always returns true */
19155 bool operator()(latch_meta_t &latch_meta) UNIV_NOTHROW {
19156 latch_meta.get_counter()->iterate(
19157 GetCount{latch_meta.get_name(), &m_values});
19158
19159 return (true);
19160 }
19161
19162 /** Implements the SHOW MUTEX STATUS command, for mutexes.
19163 The table structure is like so: Engine | Mutex Name | Status
19164 We store the metrics in the "Status" column as:
19165
19166 spins=N,waits=N,calls=N"
19167
19168 The user has to parse the data unfortunately
19169 @param[in,out] thd the MySQL query thread of the caller
19170 @param[in,out] stat_print function for printing statistics
19171 @return true on success. */
19172 bool to_string(THD *thd, stat_print_fn *stat_print) UNIV_NOTHROW;
19173
19174 /** For collecting the active mutex stats. */
19175 Values m_values;
19176 };
19177
19178 /** Implements the SHOW MUTEX STATUS command, for mutexes.
19179 The table structure is like so: Engine | Mutex Name | Status
19180 We store the metrics in the "Status" column as:
19181
19182 spins=N,waits=N,calls=N"
19183
19184 The user has to parse the data unfortunately
19185 @param[in,out] thd the MySQL query thread of the caller
19186 @param[in,out] stat_print function for printing statistics
19187 @return true on success. */
19188 bool ShowStatus::to_string(THD *thd, stat_print_fn *stat_print) UNIV_NOTHROW {
19189 uint hton_name_len = (uint)strlen(innobase_hton_name);
19190
19191 std::sort(m_values.begin(), m_values.end(), OrderByWaits());
19192
19193 Values::iterator end = m_values.end();
19194
19195 for (Values::iterator it = m_values.begin(); it != end; ++it) {
19196 int name_len;
19197 char name_buf[IO_SIZE];
19198
19199 name_len = snprintf(name_buf, sizeof(name_buf), "%s", it->m_name.c_str());
19200
19201 int status_len;
19202 char status_buf[IO_SIZE];
19203
19204 status_len = snprintf(status_buf, sizeof(status_buf),
19205 "spins=%lu,waits=%lu,calls=" TRX_ID_FMT,
19206 static_cast<ulong>(it->m_spins),
19207 static_cast<long>(it->m_waits), it->m_calls);
19208
19209 if (stat_print(thd, innobase_hton_name, hton_name_len, name_buf,
19210 static_cast<uint>(name_len), status_buf,
19211 static_cast<uint>(status_len))) {
19212 return (false);
19213 }
19214 }
19215
19216 return (true);
19217 }
19218
19219 /** Implements the SHOW MUTEX STATUS command, for mutexes.
19220 @param[in,out] hton the innodb handlerton
19221 @param[in,out] thd the MySQL query thread of the caller
19222 @param[in,out] stat_print function for printing statistics
19223 @return 0 on success. */
19224 static int innodb_show_mutex_status(handlerton *hton, THD *thd,
19225 stat_print_fn *stat_print) {
19226 DBUG_TRACE;
19227
19228 ShowStatus collector;
19229
19230 assert(hton == innodb_hton_ptr);
19231
19232 mutex_monitor->iterate(collector);
19233
19234 if (!collector.to_string(thd, stat_print)) {
19235 return 1;
19236 }
19237
19238 return 0;
19239 }
19240
19241 /** Implements the SHOW MUTEX STATUS command.
19242 @param[in,out] hton the innodb handlerton
19243 @param[in,out] thd the MySQL query thread of the caller
19244 @param[in,out] stat_print function for printing statistics
19245 @return 0 on success. */
19246 static int innodb_show_rwlock_status(handlerton *hton, THD *thd,
19247 stat_print_fn *stat_print) {
19248 DBUG_TRACE;
19249
19250 rw_lock_t *block_rwlock = nullptr;
19251 ulint block_rwlock_oswait_count = 0;
19252 uint hton_name_len = (uint)strlen(innobase_hton_name);
19253
19254 assert(hton == innodb_hton_ptr);
19255
19256 mutex_enter(&rw_lock_list_mutex);
19257
19258 for (auto rw_lock : rw_lock_list) {
19259 if (rw_lock->count_os_wait == 0) {
19260 continue;
19261 }
19262
19263 int buf1len;
19264 char buf1[IO_SIZE];
19265
19266 if (rw_lock->is_block_lock) {
19267 block_rwlock = rw_lock;
19268 block_rwlock_oswait_count += rw_lock->count_os_wait;
19269
19270 continue;
19271 }
19272
19273 buf1len = snprintf(buf1, sizeof buf1, "rwlock: %s:%lu",
19274 innobase_basename(rw_lock->clocation.filename),
19275 static_cast<ulong>(rw_lock->clocation.line));
19276
19277 int buf2len;
19278 char buf2[IO_SIZE];
19279
19280 buf2len = snprintf(buf2, sizeof buf2, "waits=%lu",
19281 static_cast<ulong>(rw_lock->count_os_wait));
19282
19283 if (stat_print(thd, innobase_hton_name, hton_name_len, buf1,
19284 static_cast<uint>(buf1len), buf2,
19285 static_cast<uint>(buf2len))) {
19286 mutex_exit(&rw_lock_list_mutex);
19287
19288 return 1;
19289 }
19290 }
19291
19292 if (block_rwlock != nullptr) {
19293 int buf1len;
19294 char buf1[IO_SIZE];
19295
19296 buf1len = snprintf(buf1, sizeof buf1, "sum rwlock: %s:%lu",
19297 innobase_basename(block_rwlock->clocation.filename),
19298 static_cast<ulong>(block_rwlock->clocation.line));
19299
19300 int buf2len;
19301 char buf2[IO_SIZE];
19302
19303 buf2len = snprintf(buf2, sizeof buf2, "waits=%lu",
19304 static_cast<ulong>(block_rwlock_oswait_count));
19305
19306 if (stat_print(thd, innobase_hton_name, hton_name_len, buf1,
19307 static_cast<uint>(buf1len), buf2,
19308 static_cast<uint>(buf2len))) {
19309 mutex_exit(&rw_lock_list_mutex);
19310
19311 return 1;
19312 }
19313 }
19314
19315 mutex_exit(&rw_lock_list_mutex);
19316
19317 return 0;
19318 }
19319
19320 /** Implements the SHOW MUTEX STATUS command.
19321 @param[in,out] hton the innodb handlerton
19322 @param[in,out] thd the MySQL query thread of the caller
19323 @param[in,out] stat_print function for printing statistics
19324 @return 0 on success. */
19325 static int innodb_show_latch_status(handlerton *hton, THD *thd,
19326 stat_print_fn *stat_print) {
19327 int ret = innodb_show_mutex_status(hton, thd, stat_print);
19328
19329 if (ret != 0) {
19330 return (ret);
19331 }
19332
19333 return (innodb_show_rwlock_status(hton, thd, stat_print));
19334 }
19335
19336 /** Return 0 on success and non-zero on failure. Note: the bool return type
19337 seems to be abused here, should be an int.
19338 @param[in] hton the innodb handlerton
19339 @param[in] thd the MySQL query thread of the caller
19340 @param[in] stat_print print function
19341 @param[in] stat_type status to show */
19342 static bool innobase_show_status(handlerton *hton, THD *thd,
19343 stat_print_fn *stat_print,
19344 enum ha_stat_type stat_type) {
19345 assert(hton == innodb_hton_ptr);
19346
19347 switch (stat_type) {
19348 case HA_ENGINE_STATUS:
19349 /* Non-zero return value means there was an error. */
19350 return (innodb_show_status(hton, thd, stat_print) != 0);
19351
19352 case HA_ENGINE_MUTEX:
19353 return (innodb_show_latch_status(hton, thd, stat_print) != 0);
19354
19355 case HA_ENGINE_LOGS:
19356 /* Not handled */
19357 break;
19358 }
19359
19360 /* Success */
19361 return (false);
19362 }
19363
19364 /** Handling the shared INNOBASE_SHARE structure that is needed to provide table
19365 locking. Register the table name if it doesn't exist in the hash table. */
19366 static INNOBASE_SHARE *get_share(const char *table_name) {
19367 INNOBASE_SHARE *share;
19368
19369 mysql_mutex_lock(&innobase_share_mutex);
19370
19371 const auto hash_value = ut::hash_string(table_name);
19372
19373 HASH_SEARCH(table_name_hash, innobase_open_tables, hash_value,
19374 INNOBASE_SHARE *, share, ut_ad(share->use_count > 0),
19375 !strcmp(share->table_name, table_name));
19376
19377 if (share == nullptr) {
19378 uint length = (uint)strlen(table_name);
19379
19380 /* TODO: invoke HASH_MIGRATE if innobase_open_tables
19381 grows too big */
19382
19383 share = reinterpret_cast<INNOBASE_SHARE *>(
19384 my_malloc(PSI_INSTRUMENT_ME, sizeof(*share) + length + 1,
19385 MYF(MY_FAE | MY_ZEROFILL)));
19386
19387 share->table_name =
19388 reinterpret_cast<char *>(memcpy(share + 1, table_name, length + 1));
19389
19390 HASH_INSERT(INNOBASE_SHARE, table_name_hash, innobase_open_tables,
19391 hash_value, share);
19392
19393 /* Index translation table initialization */
19394 share->idx_trans_tbl.index_mapping = nullptr;
19395 share->idx_trans_tbl.index_count = 0;
19396 share->idx_trans_tbl.array_size = 0;
19397 }
19398
19399 ++share->use_count;
19400
19401 mysql_mutex_unlock(&innobase_share_mutex);
19402
19403 return (share);
19404 }
19405
19406 /** Free the shared object that was registered with get_share(). */
19407 static void free_share(
19408 INNOBASE_SHARE *share) /*!< in/own: table share to free */
19409 {
19410 mysql_mutex_lock(&innobase_share_mutex);
19411
19412 #ifdef UNIV_DEBUG
19413 INNOBASE_SHARE *share2;
19414 const auto hash_value = ut::hash_string(share->table_name);
19415
19416 HASH_SEARCH(table_name_hash, innobase_open_tables, hash_value,
19417 INNOBASE_SHARE *, share2, ut_ad(share->use_count > 0),
19418 !strcmp(share->table_name, share2->table_name));
19419
19420 ut_a(share2 == share);
19421 #endif /* UNIV_DEBUG */
19422
19423 --share->use_count;
19424
19425 if (share->use_count == 0) {
19426 const auto hash_value = ut::hash_string(share->table_name);
19427
19428 HASH_DELETE(INNOBASE_SHARE, table_name_hash, innobase_open_tables,
19429 hash_value, share);
19430
19431 /* Free any memory from index translation table */
19432 ut::free(share->idx_trans_tbl.index_mapping);
19433
19434 my_free(share);
19435
19436 /* TODO: invoke HASH_MIGRATE if innobase_open_tables
19437 shrinks too much */
19438 }
19439
19440 mysql_mutex_unlock(&innobase_share_mutex);
19441 }
19442
19443 /** Returns number of THR_LOCK locks used for one instance of InnoDB table.
19444 InnoDB no longer relies on THR_LOCK locks so 0 value is returned.
19445 Instead of THR_LOCK locks InnoDB relies on combination of metadata locks
19446 (e.g. for LOCK TABLES and DDL) and its own locking subsystem.
19447 Note that even though this method returns 0, SQL-layer still calls
19448 "::store_lock()", "::start_stmt()" and "::external_lock()" methods for InnoDB
19449 tables. */
19450
19451 uint ha_innobase::lock_count(void) const { return 0; }
19452
19453 /** Supposed to convert a MySQL table lock stored in the 'lock' field of the
19454 handle to a proper type before storing pointer to the lock into an array
19455 of pointers.
19456 In practice, since InnoDB no longer relies on THR_LOCK locks and its
19457 lock_count() method returns 0 it just informs storage engine about type
19458 of THR_LOCK which SQL-layer would have acquired for this specific statement
19459 on this specific table.
19460 MySQL also calls this if it wants to reset some table locks to a not-locked
19461 state during the processing of an SQL query. An example is that during a
19462 SELECT the read lock is released early on the 'const' tables where we only
19463 fetch one row. MySQL does not call this when it releases all locks at the
19464 end of an SQL statement.
19465 @return pointer to the current element in the 'to' array. */
19466
19467 THR_LOCK_DATA **ha_innobase::store_lock(
19468 THD *thd, /*!< in: user thread handle */
19469 THR_LOCK_DATA **to, /*!< in: pointer to the current
19470 element in an array of pointers
19471 to lock structs;
19472 only used as return value */
19473 thr_lock_type lock_type) /*!< in: lock type to store in
19474 'lock'; this may also be
19475 TL_IGNORE */
19476 {
19477 /* Note that trx in this function is NOT necessarily m_prebuilt->trx
19478 because we call update_thd() later, in ::external_lock()! Failure to
19479 understand this caused a serious memory corruption bug in 5.1.11. */
19480
19481 trx_t *trx = check_trx_exists(thd);
19482
19483 TrxInInnoDB trx_in_innodb(trx);
19484
19485 /* NOTE: MySQL can call this function with lock 'type' TL_IGNORE!
19486 Be careful to ignore TL_IGNORE if we are going to do something with
19487 only 'real' locks! */
19488
19489 /* If no MySQL table is in use, we need to set the isolation level
19490 of the transaction. */
19491
19492 if (lock_type != TL_IGNORE && trx->n_mysql_tables_in_use == 0) {
19493 trx->isolation_level =
19494 innobase_trx_map_isolation_level(thd_get_trx_isolation(thd));
19495
19496 if (trx->isolation_level <= TRX_ISO_READ_COMMITTED &&
19497 MVCC::is_view_active(trx->read_view)) {
19498 /* At low transaction isolation levels we let
19499 each consistent read set its own snapshot */
19500
19501 mutex_enter(&trx_sys->mutex);
19502
19503 trx_sys->mvcc->view_close(trx->read_view, true);
19504
19505 mutex_exit(&trx_sys->mutex);
19506 }
19507 }
19508
19509 assert(EQ_CURRENT_THD(thd));
19510 const bool in_lock_tables = thd_in_lock_tables(thd);
19511 const uint sql_command = thd_sql_command(thd);
19512
19513 if (srv_read_only_mode && !m_prebuilt->table->is_intrinsic() &&
19514 (sql_command == SQLCOM_UPDATE || sql_command == SQLCOM_INSERT ||
19515 sql_command == SQLCOM_REPLACE || sql_command == SQLCOM_DROP_TABLE ||
19516 sql_command == SQLCOM_ALTER_TABLE || sql_command == SQLCOM_OPTIMIZE ||
19517 (sql_command == SQLCOM_CREATE_TABLE &&
19518 (lock_type >= TL_WRITE_CONCURRENT_INSERT && lock_type <= TL_WRITE)) ||
19519 sql_command == SQLCOM_CREATE_INDEX || sql_command == SQLCOM_DROP_INDEX ||
19520 sql_command == SQLCOM_DELETE)) {
19521 ib_senderrf(trx->mysql_thd, IB_LOG_LEVEL_WARN, ER_READ_ONLY_MODE);
19522
19523 } else if (sql_command == SQLCOM_FLUSH && lock_type == TL_READ_NO_INSERT) {
19524 /* Check for FLUSH TABLES ... WITH READ LOCK */
19525
19526 /* Note: This call can fail, but there is no way to return
19527 the error to the caller. We simply ignore it for now here
19528 and push the error code to the caller where the error is
19529 detected in the function. */
19530
19531 dberr_t err = row_quiesce_set_state(m_prebuilt->table, QUIESCE_START, trx);
19532
19533 ut_a(err == DB_SUCCESS || err == DB_UNSUPPORTED);
19534
19535 if (trx->isolation_level == TRX_ISO_SERIALIZABLE) {
19536 m_prebuilt->select_lock_type = LOCK_S;
19537 m_stored_select_lock_type = LOCK_S;
19538 } else {
19539 m_prebuilt->select_lock_type = LOCK_NONE;
19540 m_stored_select_lock_type = LOCK_NONE;
19541 }
19542
19543 /* Check for DROP TABLE */
19544 } else if (sql_command == SQLCOM_DROP_TABLE) {
19545 /* MySQL calls this function in DROP TABLE though this table
19546 handle may belong to another thd that is running a query. Let
19547 us in that case skip any changes to the m_prebuilt struct. */
19548
19549 /* Check for LOCK TABLE t1,...,tn WITH SHARED LOCKS */
19550 } else if ((lock_type == TL_READ && in_lock_tables) ||
19551 (lock_type == TL_READ_HIGH_PRIORITY && in_lock_tables) ||
19552 lock_type == TL_READ_WITH_SHARED_LOCKS ||
19553 lock_type == TL_READ_NO_INSERT ||
19554 (lock_type != TL_IGNORE && sql_command != SQLCOM_SELECT)) {
19555 /* The OR cases above are in this order:
19556 1) MySQL is doing LOCK TABLES ... READ LOCAL, or we
19557 are processing a stored procedure or function, or
19558 2) (we do not know when TL_READ_HIGH_PRIORITY is used), or
19559 3) this is a SELECT ... IN SHARE MODE/FOR SHARE, or
19560 4) we are doing a complex SQL statement like
19561 INSERT INTO ... SELECT ... and the logical logging (MySQL
19562 binlog) requires the use of a locking read, or
19563 MySQL is doing LOCK TABLES ... READ.
19564 5) we let InnoDB do locking reads for all SQL statements that
19565 are not simple SELECTs; note that select_lock_type in this
19566 case may get strengthened in ::external_lock() to LOCK_X.
19567 Note that we MUST use a locking read in all data modifying
19568 SQL statements, because otherwise the execution would not be
19569 serializable, and also the results from the update could be
19570 unexpected if an obsolete consistent read view would be
19571 used. */
19572
19573 /* Use consistent read for checksum table */
19574
19575 if (sql_command == SQLCOM_CHECKSUM ||
19576 (trx->skip_gap_locks() &&
19577 (lock_type == TL_READ || lock_type == TL_READ_NO_INSERT) &&
19578 (sql_command == SQLCOM_INSERT_SELECT ||
19579 sql_command == SQLCOM_REPLACE_SELECT ||
19580 sql_command == SQLCOM_UPDATE ||
19581 sql_command == SQLCOM_CREATE_TABLE))) {
19582 /* If this session is using READ COMMITTED or READ
19583 UNCOMMITTED isolation level and MySQL is doing INSERT
19584 INTO... SELECT or REPLACE INTO...SELECT or UPDATE ...
19585 = (SELECT ...) or CREATE ... SELECT... without FOR
19586 UPDATE or IN SHARE MODE in select, then we use
19587 consistent read for select.
19588
19589 See also similar code in ha_innobase::start_stmt(). */
19590
19591 m_prebuilt->select_lock_type = LOCK_NONE;
19592 m_stored_select_lock_type = LOCK_NONE;
19593 } else {
19594 m_prebuilt->select_lock_type = LOCK_S;
19595 m_stored_select_lock_type = LOCK_S;
19596 }
19597
19598 } else if (lock_type != TL_IGNORE) {
19599 /* We set possible LOCK_X value in external_lock, not yet
19600 here even if this would be SELECT ... FOR UPDATE */
19601
19602 m_prebuilt->select_lock_type = LOCK_NONE;
19603 m_stored_select_lock_type = LOCK_NONE;
19604 }
19605
19606 /* Set select mode for SKIP LOCKED / NOWAIT */
19607 if (lock_type != TL_IGNORE) {
19608 switch (table->pos_in_table_list->lock_descriptor().action) {
19609 case THR_SKIP:
19610 m_prebuilt->select_mode = SELECT_SKIP_LOCKED;
19611 break;
19612 case THR_NOWAIT:
19613 m_prebuilt->select_mode = SELECT_NOWAIT;
19614 break;
19615 default:
19616 m_prebuilt->select_mode = SELECT_ORDINARY;
19617 break;
19618 }
19619 }
19620
19621 /* Ignore SKIP LOCKED / NO_WAIT for high priority transaction */
19622 if (trx_is_high_priority(trx)) {
19623 m_prebuilt->select_mode = SELECT_ORDINARY;
19624 }
19625
19626 if (!trx_is_started(trx) && (m_prebuilt->select_lock_type != LOCK_NONE ||
19627 m_stored_select_lock_type != LOCK_NONE)) {
19628 ++trx->will_lock;
19629 }
19630
19631 #ifdef UNIV_DEBUG
19632 if (trx->is_dd_trx) {
19633 ut_ad(trx->will_lock == 0 && m_prebuilt->select_lock_type == LOCK_NONE);
19634 }
19635 #endif /* UNIV_DEBUG */
19636
19637 return (to);
19638 }
19639
19640 /** Read the next autoinc value. Acquire the relevant locks before reading
19641 the AUTOINC value. If SUCCESS then the table AUTOINC mutex will be locked
19642 on return and all relevant locks acquired.
19643 @return DB_SUCCESS or error code */
19644
19645 dberr_t ha_innobase::innobase_get_autoinc(
19646 ulonglong *value) /*!< out: autoinc value */
19647 {
19648 *value = 0;
19649
19650 m_prebuilt->autoinc_error = innobase_lock_autoinc();
19651
19652 if (m_prebuilt->autoinc_error == DB_SUCCESS) {
19653 /* Determine the first value of the interval */
19654 *value = dict_table_autoinc_read(m_prebuilt->table);
19655
19656 /* It should have been initialized during open. */
19657 if (*value == 0) {
19658 m_prebuilt->autoinc_error = DB_UNSUPPORTED;
19659 dict_table_autoinc_unlock(m_prebuilt->table);
19660 }
19661 }
19662
19663 return (m_prebuilt->autoinc_error);
19664 }
19665
19666 void ha_innobase::release_auto_increment() {
19667 trx_t *trx = m_prebuilt->trx;
19668 TrxInInnoDB trx_in_innodb(trx);
19669
19670 /* Clear the trx's autoinc_rows as the operation requiring auto increment
19671 values has been completed.
19672
19673 We usually end up in this scenario when we do not know the correct estimation
19674 of rows in the table in the case of bulk inserts. */
19675 if (trx->n_autoinc_rows > 0) {
19676 trx->n_autoinc_rows = 0;
19677 }
19678 }
19679
19680 /** Returns the value of the auto-inc counter in *first_value and ~0 on failure.
19681 */
19682
19683 void ha_innobase::get_auto_increment(
19684 ulonglong offset, /*!< in: table autoinc offset */
19685 ulonglong increment, /*!< in: table autoinc
19686 increment */
19687 ulonglong nb_desired_values, /*!< in: number of values
19688 reqd */
19689 ulonglong *first_value, /*!< out: the autoinc value */
19690 ulonglong *nb_reserved_values) /*!< out: count of reserved
19691 values */
19692 {
19693 trx_t *trx;
19694 dberr_t error;
19695 ulonglong autoinc = 0;
19696
19697 /* Prepare m_prebuilt->trx in the table handle */
19698 update_thd(ha_thd());
19699
19700 error = innobase_get_autoinc(&autoinc);
19701
19702 if (error != DB_SUCCESS) {
19703 *first_value = (~(ulonglong)0);
19704 return;
19705 }
19706
19707 /* This is a hack, since nb_desired_values seems to be accurate only
19708 for the first call to get_auto_increment() for multi-row INSERT and
19709 meaningless for other statements e.g, LOAD etc. Subsequent calls to
19710 this method for the same statement results in different values which
19711 don't make sense. Therefore we store the value the first time we are
19712 called and count down from that as rows are written (see write_row()).
19713 */
19714
19715 trx = m_prebuilt->trx;
19716
19717 TrxInInnoDB trx_in_innodb(trx);
19718
19719 /* Note: We can't rely on *first_value since some MySQL engines,
19720 in particular the partition engine, don't initialize it to 0 when
19721 invoking this method. So we are not sure if it's guaranteed to
19722 be 0 or not. */
19723
19724 /* We need the upper limit of the col type to check for
19725 whether we update the table autoinc counter or not. */
19726 ulonglong col_max_value = table->next_number_field->get_max_int_value();
19727
19728 /** The following logic is needed to avoid duplicate key error
19729 for autoincrement column.
19730
19731 (1) InnoDB gives the current autoincrement value with respect
19732 to increment and offset value.
19733
19734 (2) Basically it does compute_next_insert_id() logic inside InnoDB
19735 to avoid the current auto increment value changed by handler layer.
19736
19737 (3) It is restricted only for insert operations. */
19738
19739 if (increment > 1 && m_prebuilt->table->skip_alter_undo == false &&
19740 autoinc < col_max_value) {
19741 ulonglong diff = ULLONG_MAX - autoinc;
19742 /* Check for overflow */
19743 if (increment <= diff) {
19744 ulonglong prev_auto_inc = autoinc;
19745 autoinc = ((autoinc - 1) + increment - offset) / increment;
19746 autoinc = autoinc * increment + offset;
19747
19748 /* If autoinc exceeds the col_max_value then reset
19749 to old autoinc value. Because in case of non-strict
19750 sql mode, boundary value is not considered as error. */
19751 if (autoinc >= col_max_value) {
19752 autoinc = prev_auto_inc;
19753 }
19754
19755 ut_ad(autoinc > 0);
19756 }
19757 }
19758
19759 /* Called for the first time ? */
19760 if (trx->n_autoinc_rows == 0) {
19761 trx->n_autoinc_rows = (ulint)nb_desired_values;
19762
19763 /* It's possible for nb_desired_values to be 0:
19764 e.g., INSERT INTO T1(C) SELECT C FROM T2; */
19765 if (nb_desired_values == 0) {
19766 trx->n_autoinc_rows = 1;
19767 }
19768
19769 *first_value = std::max(*first_value, autoinc);
19770 /* Not in the middle of a mult-row INSERT. */
19771 } else if (m_prebuilt->autoinc_last_value == 0) {
19772 *first_value = std::max(*first_value, autoinc);
19773 /* Check for -ve values. */
19774 } else if (*first_value > col_max_value && trx->n_autoinc_rows > 0) {
19775 /* Set to next logical value. */
19776 ut_a(autoinc > trx->n_autoinc_rows);
19777 *first_value = (autoinc - trx->n_autoinc_rows) - 1;
19778 }
19779
19780 *nb_reserved_values = trx->n_autoinc_rows;
19781
19782 /* With old style AUTOINC locking we only update the table's
19783 AUTOINC counter after attempting to insert the row. */
19784 if (innobase_autoinc_lock_mode != AUTOINC_OLD_STYLE_LOCKING ||
19785 m_prebuilt->no_autoinc_locking) {
19786 ulonglong current;
19787 ulonglong next_value;
19788
19789 current = *first_value > col_max_value ? autoinc : *first_value;
19790
19791 /* Compute the last value in the interval */
19792 next_value = innobase_next_autoinc(current, *nb_reserved_values, increment,
19793 offset, col_max_value);
19794
19795 m_prebuilt->autoinc_last_value = next_value;
19796
19797 if (m_prebuilt->autoinc_last_value < *first_value) {
19798 *first_value = (~(ulonglong)0);
19799 } else {
19800 /* Update the table autoinc variable */
19801 dict_table_autoinc_update_if_greater(m_prebuilt->table,
19802 m_prebuilt->autoinc_last_value);
19803 }
19804 } else {
19805 /* This will force write_row() into attempting an update
19806 of the table's AUTOINC counter. */
19807 m_prebuilt->autoinc_last_value = 0;
19808 }
19809
19810 /* The increment to be used to increase the AUTOINC value, we use
19811 this in write_row() and update_row() to increase the autoinc counter
19812 for columns that are filled by the user. We need the offset and
19813 the increment. */
19814 m_prebuilt->autoinc_offset = offset;
19815 m_prebuilt->autoinc_increment = increment;
19816
19817 dict_table_autoinc_unlock(m_prebuilt->table);
19818 }
19819
19820 /** See comment in handler.cc */
19821
19822 bool ha_innobase::get_error_message(int, String *buf) {
19823 trx_t *trx = check_trx_exists(ha_thd());
19824
19825 buf->copy(trx->detailed_error, (uint)strlen(trx->detailed_error),
19826 system_charset_info);
19827
19828 return false;
19829 }
19830
19831 /** Retrieves the names of the table and the key for which there was a
19832 duplicate entry in the case of HA_ERR_FOREIGN_DUPLICATE_KEY.
19833
19834 If any of the names is not available, then this method will return
19835 false and will not change any of child_table_name or child_key_name.
19836
19837 @param[out] child_table_name Table name
19838 @param[in] child_table_name_len Table name buffer size
19839 @param[out] child_key_name Key name
19840 @param[in] child_key_name_len Key name buffer size
19841
19842 @retval true table and key names were available and were written into the
19843 corresponding out parameters.
19844 @retval false table and key names were not available, the out parameters
19845 were not touched. */
19846 bool ha_innobase::get_foreign_dup_key(char *child_table_name,
19847 uint child_table_name_len,
19848 char *child_key_name,
19849 uint child_key_name_len) {
19850 const dict_index_t *err_index;
19851
19852 ut_a(m_prebuilt->trx != nullptr);
19853 ut_a(m_prebuilt->trx->magic_n == TRX_MAGIC_N);
19854
19855 err_index = trx_get_error_index(m_prebuilt->trx);
19856
19857 if (err_index == nullptr) {
19858 return (false);
19859 }
19860 /* else */
19861
19862 /* copy table name (and convert from filename-safe encoding to
19863 system_charset_info) */
19864 char *p = strchr(err_index->table->name.m_name, '/');
19865
19866 /* strip ".../" prefix if any */
19867 if (p != nullptr) {
19868 p++;
19869 } else {
19870 p = err_index->table->name.m_name;
19871 }
19872
19873 size_t len;
19874
19875 len = filename_to_tablename(p, child_table_name, child_table_name_len);
19876
19877 child_table_name[len] = '\0';
19878
19879 /* copy index name */
19880 snprintf(child_key_name, child_key_name_len, "%s", err_index->name());
19881
19882 return (true);
19883 }
19884
19885 /** Compares two 'refs'. A 'ref' is the (internal) primary key value of the row.
19886 If there is no explicitly declared non-null unique key or a primary key, then
19887 InnoDB internally uses the row id as the primary key.
19888 @return < 0 if ref1 < ref2, 0 if equal, else > 0 */
19889
19890 int ha_innobase::cmp_ref(
19891 const uchar *ref1, /*!< in: an (internal) primary key value in the
19892 MySQL key value format */
19893 const uchar *ref2) /*!< in: an (internal) primary key value in the
19894 MySQL key value format */
19895 const {
19896 enum_field_types mysql_type;
19897 Field *field;
19898 KEY_PART_INFO *key_part;
19899 KEY_PART_INFO *key_part_end;
19900 uint len1;
19901 uint len2;
19902 int result;
19903
19904 if (m_prebuilt->clust_index_was_generated) {
19905 /* The 'ref' is an InnoDB row id */
19906
19907 return (memcmp(ref1, ref2, DATA_ROW_ID_LEN));
19908 }
19909
19910 /* Do a type-aware comparison of primary key fields. PK fields
19911 are always NOT NULL, so no checks for NULL are performed. */
19912
19913 key_part = table->key_info[table->s->primary_key].key_part;
19914
19915 key_part_end =
19916 key_part + table->key_info[table->s->primary_key].user_defined_key_parts;
19917
19918 for (; key_part != key_part_end; ++key_part) {
19919 field = key_part->field;
19920 mysql_type = field->type();
19921
19922 if (mysql_type == MYSQL_TYPE_TINY_BLOB ||
19923 mysql_type == MYSQL_TYPE_MEDIUM_BLOB || mysql_type == MYSQL_TYPE_BLOB ||
19924 mysql_type == MYSQL_TYPE_LONG_BLOB) {
19925 /* In the MySQL key value format, a column prefix of
19926 a BLOB is preceded by a 2-byte length field */
19927
19928 len1 = innobase_read_from_2_little_endian(ref1);
19929 len2 = innobase_read_from_2_little_endian(ref2);
19930
19931 result =
19932 down_cast<Field_blob *>(field)->cmp(ref1 + 2, len1, ref2 + 2, len2);
19933 } else {
19934 result = field->key_cmp(ref1, ref2);
19935 }
19936
19937 if (result) {
19938 if (key_part->key_part_flag & HA_REVERSE_SORT) {
19939 result = -result;
19940 }
19941 return result;
19942 }
19943
19944 ref1 += key_part->store_length;
19945 ref2 += key_part->store_length;
19946 }
19947
19948 return (0);
19949 }
19950
19951 /** This function is used to find the storage length in bytes of the first n
19952 characters for prefix indexes using a multibyte character set. The function
19953 finds charset information and returns length of prefix_len characters in the
19954 index field in bytes.
19955 @return number of bytes occupied by the first n characters */
19956 ulint innobase_get_at_most_n_mbchars(
19957 ulint charset_id, /*!< in: character set id */
19958 ulint prefix_len, /*!< in: prefix length in bytes of the index
19959 (this has to be divided by mbmaxlen to get the
19960 number of CHARACTERS n in the prefix) */
19961 ulint data_len, /*!< in: length of the string in bytes */
19962 const char *str) /*!< in: character string */
19963 {
19964 ulint char_length; /*!< character length in bytes */
19965 ulint n_chars; /*!< number of characters in prefix */
19966 CHARSET_INFO *charset; /*!< charset used in the field */
19967
19968 charset = get_charset((uint)charset_id, MYF(MY_WME));
19969
19970 ut_ad(charset);
19971 ut_ad(charset->mbmaxlen);
19972
19973 /* Calculate how many characters at most the prefix index contains */
19974
19975 n_chars = prefix_len / charset->mbmaxlen;
19976
19977 /* If the charset is multi-byte, then we must find the length of the
19978 first at most n chars in the string. If the string contains less
19979 characters than n, then we return the length to the end of the last
19980 character. */
19981
19982 if (charset->mbmaxlen > 1) {
19983 /* my_charpos() returns the byte length of the first n_chars
19984 characters, or a value bigger than the length of str, if
19985 there were not enough full characters in str.
19986
19987 Why does the code below work:
19988 Suppose that we are looking for n UTF-8 characters.
19989
19990 1) If the string is long enough, then the prefix contains at
19991 least n complete UTF-8 characters + maybe some extra
19992 characters + an incomplete UTF-8 character. No problem in
19993 this case. The function returns the pointer to the
19994 end of the nth character.
19995
19996 2) If the string is not long enough, then the string contains
19997 the complete value of a column, that is, only complete UTF-8
19998 characters, and we can store in the column prefix index the
19999 whole string. */
20000
20001 char_length = my_charpos(charset, str, str + data_len, (int)n_chars);
20002 if (char_length > data_len) {
20003 char_length = data_len;
20004 }
20005 } else if (data_len < prefix_len) {
20006 char_length = data_len;
20007
20008 } else {
20009 char_length = prefix_len;
20010 }
20011
20012 return (char_length);
20013 }
20014
20015 /** This function is used to prepare an X/Open XA distributed transaction.
20016 @return 0 or error number */
20017 static int innobase_xa_prepare(handlerton *hton, /*!< in: InnoDB handlerton */
20018 THD *thd, /*!< in: handle to the MySQL thread of
20019 the user whose XA transaction should
20020 be prepared */
20021 bool prepare_trx) /*!< in: true - prepare
20022 transaction false - the current
20023 SQL statement ended */
20024 {
20025 trx_t *trx = check_trx_exists(thd);
20026
20027 assert(hton == innodb_hton_ptr);
20028
20029 thd_get_xid(thd, (MYSQL_XID *)trx->xid);
20030
20031 innobase_srv_conc_force_exit_innodb(trx);
20032
20033 TrxInInnoDB trx_in_innodb(trx);
20034
20035 if (trx_in_innodb.is_aborted() ||
20036 DBUG_EVALUATE_IF("simulate_xa_failure_prepare_in_engine", 1, 0)) {
20037 innobase_rollback(hton, thd, prepare_trx);
20038
20039 return (convert_error_code_to_mysql(DB_FORCED_ABORT, 0, thd));
20040 }
20041
20042 if (!trx_is_registered_for_2pc(trx) && trx_is_started(trx)) {
20043 log_errlog(ERROR_LEVEL, ER_INNODB_UNREGISTERED_TRX_ACTIVE);
20044 }
20045
20046 if (prepare_trx ||
20047 (!thd_test_options(thd, OPTION_NOT_AUTOCOMMIT | OPTION_BEGIN))) {
20048 /* We were instructed to prepare the whole transaction, or
20049 this is an SQL statement end and autocommit is on */
20050
20051 ut_ad(trx_is_registered_for_2pc(trx));
20052
20053 dberr_t err = trx_prepare_for_mysql(trx);
20054
20055 ut_ad(err == DB_SUCCESS || err == DB_FORCED_ABORT);
20056
20057 if (err == DB_FORCED_ABORT) {
20058 innobase_rollback(hton, thd, prepare_trx);
20059
20060 return (convert_error_code_to_mysql(DB_FORCED_ABORT, 0, thd));
20061 }
20062
20063 } else {
20064 /* We just mark the SQL statement ended and do not do a
20065 transaction prepare */
20066
20067 /* If we had reserved the auto-inc lock for some
20068 table in this SQL statement we release it now */
20069
20070 lock_unlock_table_autoinc(trx);
20071
20072 /* Store the current undo_no of the transaction so that we
20073 know where to roll back if we have to roll back the next
20074 SQL statement */
20075
20076 trx_mark_sql_stat_end(trx);
20077 }
20078
20079 if (thd_sql_command(thd) != SQLCOM_XA_PREPARE &&
20080 (prepare_trx ||
20081 !thd_test_options(thd, OPTION_NOT_AUTOCOMMIT | OPTION_BEGIN))) {
20082 /* For mysqlbackup to work the order of transactions in binlog
20083 and InnoDB must be the same. Consider the situation
20084
20085 thread1> prepare; write to binlog; ...
20086 <context switch>
20087 thread2> prepare; write to binlog; commit
20088 thread1> ... commit
20089
20090 The server guarantees that writes to the binary log
20091 and commits are in the same order, so we do not have
20092 to handle this case. */
20093 }
20094
20095 return (0);
20096 }
20097
20098 /** This function is used to recover X/Open XA distributed transactions.
20099 @return number of prepared transactions stored in xid_list */
20100 static int innobase_xa_recover(
20101 handlerton *hton, /*!< in: InnoDB handlerton */
20102 XA_recover_txn *txn_list, /*!< in/out: prepared transactions */
20103 uint len, /*!< in: number of slots in xid_list */
20104 MEM_ROOT *mem_root) /*!< in: memory for table names */
20105 {
20106 assert(hton == innodb_hton_ptr);
20107
20108 if (len == 0 || txn_list == nullptr) {
20109 return (0);
20110 }
20111
20112 return (trx_recover_for_mysql(txn_list, len, mem_root));
20113 }
20114
20115 static int innobase_xa_recover_prepared_in_tc(handlerton *hton,
20116 Xa_state_list &xa_list) {
20117 assert(hton == innodb_hton_ptr);
20118
20119 return (trx_recover_tc_for_mysql(xa_list));
20120 }
20121
20122 /** This function is used to commit one X/Open XA distributed transaction
20123 which is in the prepared state
20124 @return 0 or error number */
20125 static xa_status_code innobase_commit_by_xid(
20126 handlerton *hton, XID *xid) /*!< in: X/Open XA transaction identification */
20127 {
20128 assert(hton == innodb_hton_ptr);
20129
20130 trx_t *trx = trx_get_trx_by_xid(xid);
20131
20132 if (trx != nullptr) {
20133 {
20134 TrxInInnoDB trx_in_innodb(trx);
20135
20136 innobase_commit_low(trx);
20137 }
20138 ut_ad(trx->mysql_thd == nullptr);
20139 /* use cases are: disconnected xa, slave xa, recovery */
20140 trx_deregister_from_2pc(trx);
20141 ut_ad(!trx->will_lock); /* trx cache requirement */
20142 trx_free_for_background(trx);
20143
20144 return (XA_OK);
20145 } else {
20146 return (XAER_NOTA);
20147 }
20148 }
20149
20150 /** This function is used to rollback one X/Open XA distributed transaction
20151 which is in the prepared state
20152 @return 0 or error number */
20153 static xa_status_code innobase_rollback_by_xid(
20154 handlerton *hton, /*!< in: InnoDB handlerton */
20155 XID *xid) /*!< in: X/Open XA transaction
20156 identification */
20157 {
20158 assert(hton == innodb_hton_ptr);
20159
20160 trx_t *trx = trx_get_trx_by_xid(xid);
20161
20162 if (trx != nullptr) {
20163 int ret;
20164 {
20165 TrxInInnoDB trx_in_innodb(trx);
20166
20167 ret = innobase_rollback_trx(trx);
20168 }
20169
20170 trx_deregister_from_2pc(trx);
20171 ut_ad(!trx->will_lock);
20172 trx_free_for_background(trx);
20173
20174 return (ret != 0 ? XAER_RMERR : XA_OK);
20175 } else {
20176 return (XAER_NOTA);
20177 }
20178 }
20179
20180 static int innobase_set_prepared_in_tc(handlerton *hton, THD *thd) {
20181 assert(hton == innodb_hton_ptr);
20182 assert(thd != nullptr);
20183
20184 trx_t *trx = check_trx_exists(thd);
20185 assert(trx != nullptr);
20186
20187 thd_get_xid(thd, (MYSQL_XID *)trx->xid);
20188
20189 innobase_srv_conc_force_exit_innodb(trx);
20190
20191 ut_ad(trx_is_registered_for_2pc(trx) || thd == nullptr);
20192
20193 dberr_t err = trx_set_prepared_in_tc_for_mysql(trx);
20194 ut_ad(err != DB_FORCED_ABORT);
20195
20196 return convert_error_code_to_mysql(err, 0, thd);
20197 }
20198
20199 static xa_status_code innobase_set_prepared_in_tc_by_xid(handlerton *hton,
20200 XID *xid) {
20201 assert(hton == innodb_hton_ptr);
20202 assert(xid != nullptr);
20203
20204 trx_t *trx = trx_get_trx_by_xid(xid);
20205
20206 if (trx != nullptr) {
20207 /* Side effect of retrieving the transaction is XID being set to null */
20208 *trx->xid = *xid;
20209
20210 if (trx_is_prepared_in_tc(trx)) {
20211 return XA_OK;
20212 }
20213
20214 innobase_srv_conc_force_exit_innodb(trx);
20215
20216 dberr_t err = trx_set_prepared_in_tc_for_mysql(trx);
20217
20218 ut_ad(err != DB_FORCED_ABORT);
20219
20220 return (err != DB_SUCCESS ? XAER_RMERR : XA_OK);
20221 } else {
20222 return (XAER_NOTA);
20223 }
20224 }
20225
20226 /** */
20227
20228 bool ha_innobase::check_if_incompatible_data(HA_CREATE_INFO *info,
20229 uint table_changes) {
20230 innobase_copy_frm_flags_from_create_info(m_prebuilt->table, info);
20231
20232 if (table_changes != IS_EQUAL_YES) {
20233 return (COMPATIBLE_DATA_NO);
20234 }
20235
20236 /* Check that auto_increment value was not changed */
20237 if ((info->used_fields & HA_CREATE_USED_AUTO) &&
20238 info->auto_increment_value != 0) {
20239 return (COMPATIBLE_DATA_NO);
20240 }
20241
20242 /* Check that row format didn't change */
20243 if ((info->used_fields & HA_CREATE_USED_ROW_FORMAT) &&
20244 info->row_type != table->s->real_row_type) {
20245 return (COMPATIBLE_DATA_NO);
20246 }
20247
20248 /* Specifying KEY_BLOCK_SIZE requests a rebuild of the table. */
20249 if (info->used_fields & HA_CREATE_USED_KEY_BLOCK_SIZE) {
20250 return (COMPATIBLE_DATA_NO);
20251 }
20252
20253 return (COMPATIBLE_DATA_YES);
20254 }
20255
20256 /** Update the system variable innodb_io_capacity_max using the "saved"
20257 value. This function is registered as a callback with MySQL. */
20258 static void innodb_io_capacity_max_update(
20259 THD *thd, /*!< in: thread handle */
20260 SYS_VAR *, /*!< in: pointer to
20261 system variable */
20262 void *, /*!< out: where the
20263 formal string goes */
20264 const void *save) /*!< in: immediate result
20265 from check function */
20266 {
20267 ulong in_val = *static_cast<const ulong *>(save);
20268
20269 if (in_val < srv_io_capacity) {
20270 in_val = srv_io_capacity;
20271 push_warning_printf(thd, Sql_condition::SL_WARNING, ER_WRONG_ARGUMENTS,
20272 "innodb_io_capacity_max cannot be"
20273 " set lower than innodb_io_capacity.");
20274 push_warning_printf(thd, Sql_condition::SL_WARNING, ER_WRONG_ARGUMENTS,
20275 "Setting innodb_io_capacity_max to %lu",
20276 srv_io_capacity);
20277 }
20278
20279 srv_max_io_capacity = in_val;
20280 }
20281
20282 /** Update the system variable innodb_io_capacity using the "saved"
20283 value. This function is registered as a callback with MySQL. */
20284 static void innodb_io_capacity_update(
20285 THD *thd, /*!< in: thread handle */
20286 SYS_VAR *, /*!< in: pointer to system variable */
20287 void *, /*!< out: where the formal string goes */
20288 const void *save) /*!< in: immediate result from check function */
20289 {
20290 ulong in_val = *static_cast<const ulong *>(save);
20291 if (in_val > srv_max_io_capacity) {
20292 in_val = srv_max_io_capacity;
20293 push_warning_printf(thd, Sql_condition::SL_WARNING, ER_WRONG_ARGUMENTS,
20294 "innodb_io_capacity cannot be set"
20295 " higher than innodb_io_capacity_max.");
20296 push_warning_printf(thd, Sql_condition::SL_WARNING, ER_WRONG_ARGUMENTS,
20297 "Setting innodb_io_capacity to %lu",
20298 srv_max_io_capacity);
20299 }
20300
20301 srv_io_capacity = in_val;
20302 }
20303
20304 /** Update the system variable innodb_max_dirty_pages_pct using the "saved"
20305 value. This function is registered as a callback with MySQL. */
20306 static void innodb_max_dirty_pages_pct_update(
20307 THD *thd, /*!< in: thread handle */
20308 SYS_VAR *, /*!< in: pointer to
20309 system variable */
20310 void *, /*!< out: where the
20311 formal string goes */
20312 const void *save) /*!< in: immediate result
20313 from check function */
20314 {
20315 double in_val = *static_cast<const double *>(save);
20316 if (in_val < srv_max_dirty_pages_pct_lwm) {
20317 push_warning_printf(thd, Sql_condition::SL_WARNING, ER_WRONG_ARGUMENTS,
20318 "innodb_max_dirty_pages_pct cannot be"
20319 " set lower than"
20320 " innodb_max_dirty_pages_pct_lwm.");
20321 push_warning_printf(thd, Sql_condition::SL_WARNING, ER_WRONG_ARGUMENTS,
20322 "Lowering"
20323 " innodb_max_dirty_page_pct_lwm to %lf",
20324 in_val);
20325
20326 srv_max_dirty_pages_pct_lwm = in_val;
20327 }
20328
20329 srv_max_buf_pool_modified_pct = in_val;
20330 }
20331
20332 /** Update the system variable innodb_max_dirty_pages_pct_lwm using the
20333 "saved" value. This function is registered as a callback with MySQL. */
20334 static void innodb_max_dirty_pages_pct_lwm_update(
20335 THD *thd, /*!< in: thread handle */
20336 SYS_VAR *, /*!< in: pointer to
20337 system variable */
20338 void *, /*!< out: where the
20339 formal string goes */
20340 const void *save) /*!< in: immediate result
20341 from check function */
20342 {
20343 double in_val = *static_cast<const double *>(save);
20344 if (in_val > srv_max_buf_pool_modified_pct) {
20345 in_val = srv_max_buf_pool_modified_pct;
20346 push_warning_printf(thd, Sql_condition::SL_WARNING, ER_WRONG_ARGUMENTS,
20347 "innodb_max_dirty_pages_pct_lwm"
20348 " cannot be set higher than"
20349 " innodb_max_dirty_pages_pct.");
20350 push_warning_printf(thd, Sql_condition::SL_WARNING, ER_WRONG_ARGUMENTS,
20351 "Setting innodb_max_dirty_page_pct_lwm"
20352 " to %lf",
20353 in_val);
20354 }
20355
20356 srv_max_dirty_pages_pct_lwm = in_val;
20357 }
20358
20359 static int innodb_stopword_table_validate(THD *thd, SYS_VAR *, void *save,
20360 struct st_mysql_value *value) {
20361 const char *stopword_table_name;
20362 char buff[STRING_BUFFER_USUAL_SIZE];
20363 int len = sizeof(buff);
20364 int ret = 1;
20365
20366 ut_a(save != nullptr);
20367 ut_a(value != nullptr);
20368
20369 stopword_table_name = value->val_str(value, buff, &len);
20370
20371 if (stopword_table_name != nullptr) {
20372 if (stopword_table_name == buff) {
20373 /* Allocate from thd's memroot */
20374 stopword_table_name = thd_strmake(thd, stopword_table_name, len);
20375 }
20376 }
20377
20378 /* Validate the stopword table's (if supplied) existence and
20379 of the right format */
20380 if (!stopword_table_name || fts_valid_stopword_table(stopword_table_name)) {
20381 *static_cast<const char **>(save) = stopword_table_name;
20382 ret = 0;
20383 }
20384
20385 return (ret);
20386 }
20387
20388 /**
20389 Utility method that checks if user provided valid value.
20390 If yes, then store that in the save variable.
20391 @return 0 on success, 1 on failure.
20392 */
20393 static int check_func_bool(THD *, SYS_VAR *, void *save,
20394 st_mysql_value *value) {
20395 int result;
20396 if (value->value_type(value) == MYSQL_VALUE_TYPE_STRING) {
20397 char buff[STRING_BUFFER_USUAL_SIZE];
20398 int length = sizeof(buff);
20399
20400 const char *str = value->val_str(value, buff, &length);
20401
20402 if (str == nullptr) return 1;
20403
20404 result = find_type(&bool_typelib, str, length, true) - 1;
20405
20406 if (result < 0) return 1;
20407 } else {
20408 long long tmp;
20409 if (value->val_int(value, &tmp) < 0) return 1;
20410 if (tmp > 1 || tmp < 0) return 1;
20411 result = static_cast<int>(tmp);
20412 }
20413 *(bool *)save = result ? true : false;
20414 return 0;
20415 }
20416
20417 /**
20418 Utility method that checks if user has correct session administrative
20419 dynamic privileges.
20420 @return 0 on success, 1 on failure.
20421 */
20422 static int check_session_admin(THD *thd) {
20423 Security_context *sctx = thd->security_context();
20424 if (!sctx->has_global_grant(STRING_WITH_LEN("SESSION_VARIABLES_ADMIN"))
20425 .first &&
20426 !sctx->has_global_grant(STRING_WITH_LEN("SYSTEM_VARIABLES_ADMIN"))
20427 .first) {
20428 return 1;
20429 }
20430 return 0;
20431 }
20432
20433 /**
20434 Check if SESSION_VARIABLES_ADMIN granted. Throw SQL error if not.
20435 We also accept SYSTEM_VARIABLES_ADMIN since it doesn't make a lot of
20436 sense to be allowed to set the global variable and not the session ones.
20437
20438 @param thd the session context
20439 @param var the system variable to set value for
20440 @param save set the updated value
20441 @param value A struct that reads us the values from mysqld
20442
20443 @retval 1 failure
20444 @retval 0 success
20445 */
20446 static int innodb_check_session_admin(THD *thd, SYS_VAR *var, void *save,
20447 struct st_mysql_value *value) {
20448 if (check_session_admin(thd)) {
20449 my_error(ER_SPECIFIC_ACCESS_DENIED_ERROR, MYF(0),
20450 "SYSTEM_VARIABLES_ADMIN or SESSION_VARIABLES_ADMIN");
20451 return 1;
20452 }
20453 return check_func_bool(thd, var, save, value);
20454 }
20455
20456 static void innodb_srv_buffer_pool_in_core_file_update(THD *, SYS_VAR *, void *,
20457 const void *save) {
20458 srv_buffer_pool_in_core_file = *(bool *)save;
20459 buf_pool_update_madvise();
20460 }
20461
20462 /** Validate the requested buffer pool size. Also, reserve the necessary
20463 memory needed for buffer pool resize.
20464 @param[in] thd thread handle
20465 @param[in] buffer_pool_size buffer pool size value to be validated
20466 @param[out] aligned_buffer_pool_size aligned version of buffer_pool_size
20467 if validation succeeds, else original value passed in
20468 @return true on success, false on failure.
20469 */
20470 static bool innodb_buffer_pool_size_validate(THD *thd,
20471 longlong buffer_pool_size,
20472 ulint &aligned_buffer_pool_size) {
20473 os_rmb;
20474 ut_ad(srv_buf_pool_old_size == srv_buf_pool_size);
20475
20476 if (srv_buf_pool_instances > 1 &&
20477 buffer_pool_size < BUF_POOL_SIZE_THRESHOLD) {
20478 #ifdef UNIV_DEBUG
20479 /* Ignore 1G constraint to enable multiple instances
20480 for debug and test. */
20481 if (srv_buf_pool_debug) {
20482 goto debug_set;
20483 }
20484 #endif /* UNIV_DEBUG */
20485
20486 push_warning_printf(thd, Sql_condition::SL_WARNING, ER_WRONG_ARGUMENTS,
20487 "Cannot update innodb_buffer_pool_size"
20488 " to less than 1GB if"
20489 " innodb_buffer_pool_instances > 1.");
20490 return false;
20491 }
20492
20493 #ifdef UNIV_DEBUG
20494 debug_set:
20495 #endif /* UNIV_DEBUG */
20496
20497 if constexpr (sizeof(ulint) == 4) {
20498 if (buffer_pool_size > UINT_MAX32) {
20499 push_warning_printf(
20500 thd, Sql_condition::SL_WARNING, ER_WRONG_VALUE_FOR_VAR,
20501 ER_THD(thd, ER_WRONG_VALUE_FOR_VAR), "innodb_buffer_pool_size",
20502 std::to_string(buffer_pool_size).c_str());
20503 return false;
20504 }
20505 }
20506
20507 aligned_buffer_pool_size =
20508 buf_pool_size_align(static_cast<ulint>(buffer_pool_size));
20509
20510 if (srv_buf_pool_size == static_cast<ulint>(buffer_pool_size)) {
20511 /* nothing to do */
20512 } else if (srv_buf_pool_size == aligned_buffer_pool_size) {
20513 push_warning_printf(thd, Sql_condition::SL_WARNING, ER_WRONG_ARGUMENTS,
20514 "InnoDB: Cannot resize buffer pool to lesser than"
20515 " chunk size of %llu bytes.",
20516 srv_buf_pool_chunk_unit);
20517 } else {
20518 srv_buf_pool_size = aligned_buffer_pool_size;
20519 os_wmb;
20520
20521 if (buffer_pool_size != static_cast<longlong>(aligned_buffer_pool_size)) {
20522 push_warning_printf(
20523 thd, Sql_condition::SL_WARNING, ER_TRUNCATED_WRONG_VALUE,
20524 ER_THD(thd, ER_TRUNCATED_WRONG_VALUE), "innodb_buffer_pool_size",
20525 std::to_string(buffer_pool_size).c_str());
20526 }
20527 }
20528
20529 return true;
20530 }
20531
20532 /** Set the variable tbsp_extend_and_initialize. This function is registered
20533 as a callback to MySQL.
20534 On Linux, the variable tbsp_extend_and_initialize will be set to the value
20535 passed by the user. A warning will be printed that the user is not
20536 allowed to change the value if the server is running on Windows
20537 or other posix implementations.
20538 @param[in] thd thread handle
20539 @param[out] var_ptr value to be set after the validation
20540 @param[in] save value set by the user */
20541 static void innodb_extend_and_initialize_update(THD *thd, SYS_VAR *,
20542 void *var_ptr,
20543 const void *save) {
20544 bool extend_and_initialize [[maybe_unused]] =
20545 *static_cast<const bool *>(save);
20546 #if !defined(NO_FALLOCATE) && defined(UNIV_LINUX)
20547 *static_cast<bool *>(var_ptr) = extend_and_initialize;
20548 #else /* !NO_FALLOCATE && UNIV_LINUX */
20549 push_warning_printf(thd, Sql_condition::SL_WARNING,
20550 ER_WARN_VAR_VALUE_CHANGE_NOT_SUPPORTED,
20551 ER_THD(thd, ER_WARN_VAR_VALUE_CHANGE_NOT_SUPPORTED),
20552 "innodb_extend_and_initialize");
20553 *static_cast<bool *>(var_ptr) = true;
20554 #endif /* !NO_FALLOCATE && UNIV_LINUX */
20555 }
20556
20557 /** Update the system variable innodb_buffer_pool_size using the "saved"
20558 value. This function is registered as a callback with MySQL.
20559 @param[in] thd thread handle
20560 @param[out] var_ptr where the formal string goes
20561 @param[in] save immediate result from check function */
20562 static void innodb_buffer_pool_size_update(THD *thd, SYS_VAR *, void *var_ptr,
20563 const void *save) {
20564 longlong requested_buffer_pool_size = *static_cast<const longlong *>(save);
20565 ulint aligned_buffer_pool_size = 0u;
20566
20567 /* Since this function can be called at any time, we must allow change
20568 in status code only if no other resize is in progress */
20569 if (buf_pool_resize_status_code.load() == BUF_POOL_RESIZE_COMPLETE ||
20570 buf_pool_resize_status_code.load() == BUF_POOL_RESIZE_FAILED) {
20571 /* No other resize is in progress */
20572 snprintf(export_vars.innodb_buffer_pool_resize_status,
20573 sizeof(export_vars.innodb_buffer_pool_resize_status),
20574 "Requested to resize buffer pool.");
20575 buf_pool_resize_status_code.store(BUF_POOL_RESIZE_START);
20576 buf_pool_resize_status_progress.store(0);
20577
20578 if (innodb_buffer_pool_size_validate(thd, requested_buffer_pool_size,
20579 aligned_buffer_pool_size)) {
20580 ib::info(ER_IB_MSG_573)
20581 << export_vars.innodb_buffer_pool_resize_status
20582 << " (new size: " << aligned_buffer_pool_size << " bytes)";
20583 os_event_set(srv_buf_resize_event);
20584
20585 *static_cast<longlong *>(var_ptr) = aligned_buffer_pool_size;
20586 } else {
20587 snprintf(export_vars.innodb_buffer_pool_resize_status,
20588 sizeof(export_vars.innodb_buffer_pool_resize_status),
20589 "Failed to validate requested buffer pool size.");
20590 buf_pool_resize_status_code.store(BUF_POOL_RESIZE_FAILED);
20591 buf_pool_resize_status_progress.store(100);
20592 }
20593 } else {
20594 /* Resize operation is in progress */
20595 push_warning(thd, ER_BUFPOOL_RESIZE_INPROGRESS);
20596 }
20597 }
20598
20599 /** Update the system variable innobase_deadlock_detect using the "saved" value.
20600 Makes sure to "wake up" the dedicated deadlock detector thread if needed.
20601 This function is registered as a callback with MySQL.
20602 @param[in] save immediate result from check function */
20603 static void innobase_deadlock_detect_update(THD *, SYS_VAR *, void *,
20604 const void *save) {
20605 innobase_deadlock_detect = *(bool *)save;
20606 /* In case deadlock detection was disabled for a long time it could happen
20607 that all clients have deadlocked with each other and thus they stopped
20608 changing the wait-for graph, which in turn causes deadlock detection to not
20609 observe any action and thus it will not search for deadlocks. So if we now
20610 change from OFF to ON we need to "kick-start" the process. It never hurts to
20611 do so, so we do it even if we check from ON to OFF */
20612 lock_wait_request_check_for_cycles();
20613 }
20614
20615 /** Check whether valid argument given to "innodb_fts_internal_tbl_name"
20616 This function is registered as a callback with MySQL.
20617 @param[in] thd thread handle
20618 @param[out] save immediate result for update function
20619 @param[in] value incoming string
20620 @return 0 for valid stopword table */
20621 static int innodb_internal_table_validate(THD *thd, SYS_VAR *, void *save,
20622 struct st_mysql_value *value) {
20623 const char *table_name;
20624 char buff[STRING_BUFFER_USUAL_SIZE];
20625 int len = sizeof(buff);
20626 int ret = 1;
20627 dict_table_t *user_table;
20628 MDL_ticket *mdl = nullptr;
20629
20630 ut_a(save != nullptr);
20631 ut_a(value != nullptr);
20632
20633 table_name = value->val_str(value, buff, &len);
20634
20635 if (!table_name) {
20636 *static_cast<const char **>(save) = nullptr;
20637 return (0);
20638 } else if (table_name == buff) {
20639 /* Allocate memory from thd's mem_root */
20640 table_name = thd_strmake(thd, table_name, len);
20641 }
20642
20643 /* If name is longer than NAME_LEN, no need to try to open it */
20644 if (len >= NAME_LEN) {
20645 return (1);
20646 }
20647
20648 user_table =
20649 dd_table_open_on_name(thd, &mdl, table_name, false, DICT_ERR_IGNORE_NONE);
20650
20651 if (user_table) {
20652 if (dict_table_has_fts_index(user_table)) {
20653 *static_cast<const char **>(save) = table_name;
20654 ret = 0;
20655 }
20656
20657 dd_table_close(user_table, thd, &mdl, false);
20658
20659 DBUG_EXECUTE_IF("innodb_evict_autoinc_table", dict_sys_mutex_enter();
20660 dict_table_remove_from_cache_debug(user_table, true);
20661 dict_sys_mutex_exit(););
20662 }
20663
20664 return (ret);
20665 }
20666
20667 /** Update the system variable innodb_adaptive_hash_index using the "saved"
20668 value. This function is registered as a callback with MySQL. */
20669 static void innodb_adaptive_hash_index_update(
20670 THD *, /*!< in: thread handle */
20671 SYS_VAR *, /*!< in: pointer to
20672 system variable */
20673 void *, /*!< out: where the
20674 formal string goes */
20675 const void *save) /*!< in: immediate result
20676 from check function */
20677 {
20678 if (*(bool *)save) {
20679 btr_search_enable();
20680 } else {
20681 btr_search_disable();
20682 }
20683 }
20684
20685 /** Update the system variable innodb_cmp_per_index using the "saved"
20686 value. This function is registered as a callback with MySQL. */
20687 static void innodb_cmp_per_index_update(
20688 THD *, /*!< in: thread handle */
20689 SYS_VAR *, /*!< in: pointer to
20690 system variable */
20691 void *, /*!< out: where the
20692 formal string goes */
20693 const void *save) /*!< in: immediate result
20694 from check function */
20695 {
20696 /* Reset the stats whenever we enable the table
20697 INFORMATION_SCHEMA.innodb_cmp_per_index. */
20698 if (!srv_cmp_per_index_enabled && *(bool *)save) {
20699 page_zip_reset_stat_per_index();
20700 }
20701
20702 srv_cmp_per_index_enabled = *(bool *)save;
20703 }
20704
20705 /** Update the system variable innodb_old_blocks_pct using the "saved"
20706 value. This function is registered as a callback with MySQL. */
20707 static void innodb_old_blocks_pct_update(
20708 THD *, /*!< in: thread handle */
20709 SYS_VAR *, /*!< in: pointer to
20710 system variable */
20711 void *, /*!< out: where the
20712 formal string goes */
20713 const void *save) /*!< in: immediate result
20714 from check function */
20715 {
20716 innobase_old_blocks_pct = static_cast<uint>(
20717 buf_LRU_old_ratio_update(*static_cast<const uint *>(save), true));
20718 }
20719
20720 /** Update the system variable innodb_old_blocks_pct using the "saved"
20721 value. This function is registered as a callback with MySQL. */
20722 static void innodb_change_buffer_max_size_update(
20723 THD *, /*!< in: thread handle */
20724 SYS_VAR *, /*!< in: pointer to
20725 system variable */
20726 void *, /*!< out: where the
20727 formal string goes */
20728 const void *save) /*!< in: immediate result
20729 from check function */
20730 {
20731 srv_change_buffer_max_size = (*static_cast<const uint *>(save));
20732 ibuf_max_size_update(srv_change_buffer_max_size);
20733 }
20734
20735 #ifdef UNIV_DEBUG
20736 static ulong srv_fil_make_page_dirty_debug = 0;
20737 static ulong srv_saved_page_number_debug = 0;
20738
20739 /** Save an InnoDB page number. */
20740 static void innodb_save_page_no(THD *, /*!< in: thread handle */
20741 SYS_VAR *, /*!< in: pointer to
20742 system variable */
20743 void *, /*!< out: where the
20744 formal string goes */
20745 const void *save) /*!< in: immediate result
20746 from check function */
20747 {
20748 srv_saved_page_number_debug = *static_cast<const ulong *>(save);
20749
20750 ib::info(ER_IB_MSG_1257) << "Saving InnoDB page number: "
20751 << srv_saved_page_number_debug;
20752 }
20753
20754 /** Make the first page of given user tablespace dirty. */
20755 static void innodb_make_page_dirty(THD *, /*!< in: thread handle */
20756 SYS_VAR *, /*!< in: pointer to
20757 system variable */
20758 void *, /*!< out: where the
20759 formal string goes */
20760 const void *save) /*!< in: immediate result
20761 from check function */
20762 {
20763 mtr_t mtr;
20764 ulong space_id = *static_cast<const ulong *>(save);
20765 page_no_t page_no = srv_saved_page_number_debug;
20766
20767 fil_space_t *space = fil_space_acquire_silent(space_id);
20768
20769 if (space == nullptr) {
20770 return;
20771 }
20772
20773 if (page_no > space->size) {
20774 fil_space_release(space);
20775 return;
20776 }
20777
20778 auto page_id = page_id_t{space->id, page_no};
20779
20780 mtr.start();
20781
20782 buf_block_t *block = buf_page_get(page_id, page_size_t(space->flags),
20783 RW_X_LATCH, UT_LOCATION_HERE, &mtr);
20784
20785 if (block != nullptr) {
20786 byte *page = block->frame;
20787 page_type_t page_type = fil_page_get_type(page);
20788
20789 /* Don't dirty a page that is not yet used. */
20790 if (page_type != FIL_PAGE_TYPE_ALLOCATED) {
20791 ib::info(ER_IB_MSG_574)
20792 << "Dirtying page: " << page_id
20793 << ", page_type=" << fil_get_page_type_str(page_type);
20794
20795 dblwr::Force_crash = page_id;
20796
20797 mlog_write_ulint(page + FIL_PAGE_TYPE, page_type, MLOG_2BYTES, &mtr);
20798 }
20799 }
20800
20801 mtr.commit();
20802
20803 fil_space_release(space);
20804
20805 if (block != nullptr) {
20806 buf_flush_sync_all_buf_pools();
20807 }
20808 }
20809 #endif // UNIV_DEBUG
20810
20811 /** Update the monitor counter according to the "set_option", turn
20812 on/off or reset specified monitor counter. */
20813 static void innodb_monitor_set_option(
20814 const monitor_info_t *monitor_info, /*!< in: monitor info for the monitor
20815 to set */
20816 mon_option_t set_option) /*!< in: Turn on/off reset the
20817 counter */
20818 {
20819 monitor_id_t monitor_id = monitor_info->monitor_id;
20820
20821 /* If module type is MONITOR_GROUP_MODULE, it cannot be
20822 turned on/off individually. It should never use this
20823 function to set options */
20824 ut_a(!(monitor_info->monitor_type & MONITOR_GROUP_MODULE));
20825
20826 switch (set_option) {
20827 case MONITOR_TURN_ON:
20828 MONITOR_ON(monitor_id);
20829 MONITOR_INIT(monitor_id);
20830 MONITOR_SET_START(monitor_id);
20831
20832 /* If the monitor to be turned on uses
20833 existing monitor counter (status variable),
20834 make special processing to remember existing
20835 counter value. */
20836 if (monitor_info->monitor_type & MONITOR_EXISTING) {
20837 srv_mon_process_existing_counter(monitor_id, MONITOR_TURN_ON);
20838 }
20839
20840 if (MONITOR_IS_ON(MONITOR_LATCHES)) {
20841 mutex_monitor->enable();
20842 }
20843 break;
20844
20845 case MONITOR_TURN_OFF:
20846 if (monitor_info->monitor_type & MONITOR_EXISTING) {
20847 srv_mon_process_existing_counter(monitor_id, MONITOR_TURN_OFF);
20848 }
20849
20850 MONITOR_OFF(monitor_id);
20851 MONITOR_SET_OFF(monitor_id);
20852
20853 if (!MONITOR_IS_ON(MONITOR_LATCHES)) {
20854 mutex_monitor->disable();
20855 }
20856 break;
20857
20858 case MONITOR_RESET_VALUE:
20859 srv_mon_reset(monitor_id);
20860
20861 if (monitor_id == (MONITOR_LATCHES)) {
20862 mutex_monitor->reset();
20863 }
20864 break;
20865
20866 case MONITOR_RESET_ALL_VALUE:
20867 srv_mon_reset_all(monitor_id);
20868 mutex_monitor->reset();
20869 break;
20870
20871 default:
20872 ut_error;
20873 }
20874 }
20875
20876 /** Find matching InnoDB monitor counters and update their status
20877 according to the "set_option", turn on/off or reset specified
20878 monitor counter. */
20879 static void innodb_monitor_update_wildcard(
20880 const char *name, /*!< in: monitor name to match */
20881 mon_option_t set_option) /*!< in: the set option, whether
20882 to turn on/off or reset the counter */
20883 {
20884 ut_a(name);
20885
20886 for (ulint use = 0; use < NUM_MONITOR; use++) {
20887 ulint type;
20888 monitor_id_t monitor_id = static_cast<monitor_id_t>(use);
20889 monitor_info_t *monitor_info;
20890
20891 if (!innobase_wildcasecmp(srv_mon_get_name(monitor_id), name)) {
20892 monitor_info = srv_mon_get_info(monitor_id);
20893
20894 type = monitor_info->monitor_type;
20895
20896 /* If the monitor counter is of MONITOR_MODULE
20897 type, skip it. Except for those also marked with
20898 MONITOR_GROUP_MODULE flag, which can be turned
20899 on only as a module. */
20900 if (!(type & MONITOR_MODULE) && !(type & MONITOR_GROUP_MODULE)) {
20901 innodb_monitor_set_option(monitor_info, set_option);
20902 }
20903
20904 /* Need to special handle counters marked with
20905 MONITOR_GROUP_MODULE, turn on the whole module if
20906 any one of it comes here. Currently, only
20907 "module_buf_page" is marked with MONITOR_GROUP_MODULE */
20908 if (type & MONITOR_GROUP_MODULE) {
20909 if ((monitor_id >= MONITOR_MODULE_BUF_PAGE) &&
20910 (monitor_id < MONITOR_MODULE_OS)) {
20911 if (set_option == MONITOR_TURN_ON &&
20912 MONITOR_IS_ON(MONITOR_MODULE_BUF_PAGE)) {
20913 continue;
20914 }
20915
20916 srv_mon_set_module_control(MONITOR_MODULE_BUF_PAGE, set_option);
20917 } else {
20918 /* If new monitor is added with
20919 MONITOR_GROUP_MODULE, it needs
20920 to be added here. */
20921 ut_d(ut_error);
20922 }
20923 }
20924 }
20925 }
20926 }
20927
20928 /** Given a configuration variable name, find corresponding monitor counter
20929 and return its monitor ID if found.
20930 @return monitor ID if found, MONITOR_NO_MATCH if there is no match */
20931 static ulint innodb_monitor_id_by_name_get(
20932 const char *name) /*!< in: monitor counter namer */
20933 {
20934 ut_a(name);
20935
20936 /* Search for wild character '%' in the name, if
20937 found, we treat it as a wildcard match. We do not search for
20938 single character wildcard '_' since our monitor names already contain
20939 such character. To avoid confusion, we request user must include
20940 at least one '%' character to activate the wildcard search. */
20941 if (strchr(name, '%')) {
20942 return (MONITOR_WILDCARD_MATCH);
20943 }
20944
20945 /* Not wildcard match, check for an exact match */
20946 for (ulint i = 0; i < NUM_MONITOR; i++) {
20947 if (!innobase_strcasecmp(name,
20948 srv_mon_get_name(static_cast<monitor_id_t>(i)))) {
20949 return (i);
20950 }
20951 }
20952
20953 return (MONITOR_NO_MATCH);
20954 }
20955 /** Validate that the passed in monitor name matches at least one
20956 monitor counter name with wildcard compare.
20957 @return true if at least one monitor name matches */
20958 static bool innodb_monitor_validate_wildcard_name(
20959 const char *name) /*!< in: monitor counter namer */
20960 {
20961 for (ulint i = 0; i < NUM_MONITOR; i++) {
20962 if (!innobase_wildcasecmp(srv_mon_get_name(static_cast<monitor_id_t>(i)),
20963 name)) {
20964 return true;
20965 }
20966 }
20967
20968 return false;
20969 }
20970 /** Validate the passed in monitor name, find and save the
20971 corresponding monitor name in the function parameter "save".
20972 @return 0 if monitor name is valid */
20973 static int innodb_monitor_valid_byname(
20974 void *save, /*!< out: immediate result
20975 for update function */
20976 const char *name) /*!< in: incoming monitor name */
20977 {
20978 ulint use;
20979 monitor_info_t *monitor_info;
20980
20981 if (!name) {
20982 return (1);
20983 }
20984
20985 use = innodb_monitor_id_by_name_get(name);
20986
20987 /* No monitor name matches, nor it is wildcard match */
20988 if (use == MONITOR_NO_MATCH) {
20989 return (1);
20990 }
20991
20992 if (use < NUM_MONITOR) {
20993 monitor_info = srv_mon_get_info((monitor_id_t)use);
20994
20995 /* If the monitor counter is marked with
20996 MONITOR_GROUP_MODULE flag, then this counter
20997 cannot be turned on/off individually, instead
20998 it shall be turned on/off as a group using
20999 its module name */
21000 if ((monitor_info->monitor_type & MONITOR_GROUP_MODULE) &&
21001 (!(monitor_info->monitor_type & MONITOR_MODULE))) {
21002 log_errlog(WARNING_LEVEL, ER_INNODB_USE_MONITOR_GROUP_NAME, name);
21003 return (1);
21004 }
21005
21006 } else {
21007 ut_a(use == MONITOR_WILDCARD_MATCH);
21008
21009 /* For wildcard match, if there is not a single monitor
21010 counter name that matches, treat it as an invalid
21011 value for the system configuration variables */
21012 if (!innodb_monitor_validate_wildcard_name(name)) {
21013 return (1);
21014 }
21015 }
21016
21017 /* Save the configure name for innodb_monitor_update() */
21018 *static_cast<const char **>(save) = name;
21019
21020 return (0);
21021 }
21022 /** Validate passed-in "value" is a valid monitor counter name.
21023 This function is registered as a callback with MySQL.
21024 @return 0 for valid name */
21025 static int innodb_monitor_validate(
21026 THD *, /*!< in: thread handle */
21027 SYS_VAR *, /*!< in: pointer to system
21028 variable */
21029 void *save, /*!< out: immediate result
21030 for update function */
21031 struct st_mysql_value *value) /*!< in: incoming string */
21032 {
21033 const char *name;
21034 char *monitor_name;
21035 char buff[STRING_BUFFER_USUAL_SIZE];
21036 int len = sizeof(buff);
21037 int ret;
21038
21039 ut_a(save != nullptr);
21040 ut_a(value != nullptr);
21041
21042 name = value->val_str(value, buff, &len);
21043
21044 if (name == nullptr) {
21045 return (1);
21046 }
21047
21048 /* Check if the value is a valid string. */
21049 size_t valid_len;
21050 bool len_error;
21051 if (validate_string(system_charset_info, name, len, &valid_len, &len_error)) {
21052 return (1);
21053 }
21054
21055 /* monitor_name could point to memory from MySQL
21056 or buff[]. Always dup the name to memory allocated
21057 by InnoDB, so we can access it in another callback
21058 function innodb_monitor_update() and free it appropriately */
21059 if (name) {
21060 monitor_name = my_strdup(PSI_INSTRUMENT_ME, name, MYF(0));
21061 } else {
21062 return (1);
21063 }
21064
21065 ret = innodb_monitor_valid_byname(save, monitor_name);
21066
21067 if (ret) {
21068 /* Validation failed */
21069 my_free(monitor_name);
21070 } else {
21071 /* monitor_name will be freed in separate callback function
21072 innodb_monitor_update(). Assert "save" point to
21073 the "monitor_name" variable */
21074 ut_ad(*static_cast<char **>(save) == monitor_name);
21075 }
21076
21077 return (ret);
21078 }
21079
21080 /** Update the system variable innodb_enable(disable/reset/reset_all)_monitor
21081 according to the "set_option" and turn on/off or reset specified monitor
21082 counter. */
21083 static void innodb_monitor_update(
21084 THD *thd, /*!< in: thread handle */
21085 void *var_ptr, /*!< out: where the
21086 formal string goes */
21087 const void *save, /*!< in: immediate result
21088 from check function */
21089 mon_option_t set_option, /*!< in: the set option,
21090 whether to turn on/off or
21091 reset the counter */
21092 bool free_mem) /*!< in: whether we will
21093 need to free the memory */
21094 {
21095 monitor_info_t *monitor_info;
21096 ulint monitor_id;
21097 ulint err_monitor = 0;
21098 const char *name;
21099
21100 ut_a(save != nullptr);
21101
21102 name = *static_cast<const char *const *>(save);
21103
21104 if (!name) {
21105 monitor_id = MONITOR_DEFAULT_START;
21106 } else {
21107 monitor_id = innodb_monitor_id_by_name_get(name);
21108
21109 /* Double check we have a valid monitor ID */
21110 if (monitor_id == MONITOR_NO_MATCH) {
21111 return;
21112 }
21113 }
21114
21115 if (monitor_id == MONITOR_DEFAULT_START) {
21116 /* If user set the variable to "default", we will
21117 print a message and make this set operation a "noop".
21118 The check is being made here is because "set default"
21119 does not go through validation function */
21120 if (thd) {
21121 push_warning_printf(thd, Sql_condition::SL_WARNING, ER_NO_DEFAULT,
21122 "Default value is not defined for"
21123 " this set option. Please specify"
21124 " correct counter or module name.");
21125 } else {
21126 log_errlog(ERROR_LEVEL, ER_INNODB_MONITOR_DEFAULT_VALUE_NOT_DEFINED);
21127 }
21128
21129 if (var_ptr) {
21130 *(const char **)var_ptr = nullptr;
21131 }
21132 } else if (monitor_id == MONITOR_WILDCARD_MATCH) {
21133 innodb_monitor_update_wildcard(name, set_option);
21134 } else {
21135 monitor_info = srv_mon_get_info(static_cast<monitor_id_t>(monitor_id));
21136
21137 ut_a(monitor_info);
21138
21139 /* If monitor is already turned on, someone could already
21140 collect monitor data, exit and ask user to turn off the
21141 monitor before turn it on again. */
21142 if (set_option == MONITOR_TURN_ON && MONITOR_IS_ON(monitor_id)) {
21143 err_monitor = monitor_id;
21144 goto exit;
21145 }
21146
21147 if (var_ptr) {
21148 *(const char **)var_ptr = monitor_info->monitor_name;
21149 }
21150
21151 /* Depending on the monitor name is for a module or
21152 a counter, process counters in the whole module or
21153 individual counter. */
21154 if (monitor_info->monitor_type & MONITOR_MODULE) {
21155 srv_mon_set_module_control(static_cast<monitor_id_t>(monitor_id),
21156 set_option);
21157 } else {
21158 innodb_monitor_set_option(monitor_info, set_option);
21159 }
21160 }
21161 exit:
21162 /* Only if we are trying to turn on a monitor that already
21163 been turned on, we will set err_monitor. Print related
21164 information */
21165 if (err_monitor) {
21166 log_errlog(WARNING_LEVEL, ER_INNODB_MONITOR_IS_ENABLED,
21167 srv_mon_get_name((monitor_id_t)err_monitor));
21168 }
21169
21170 if (free_mem && name) {
21171 my_free((void *)name);
21172 }
21173
21174 return;
21175 }
21176
21177 /** Validate if passed-in "value" is a valid value for
21178 innodb_buffer_pool_filename. On Windows, file names with colon (:)
21179 are not allowed.
21180 @param[in] thd thread handle
21181 @param[in] save immediate result from update function
21182 @param[in] value incoming string
21183 @return 0 for valid name */
21184 static int innodb_srv_buf_dump_filename_validate(THD *thd, SYS_VAR *,
21185 void *save,
21186 struct st_mysql_value *value) {
21187 char buff[OS_FILE_MAX_PATH];
21188 int len = sizeof(buff);
21189
21190 ut_a(save != nullptr);
21191 ut_a(value != nullptr);
21192
21193 const char *buf_name = value->val_str(value, buff, &len);
21194
21195 if (buf_name == nullptr) {
21196 return (1);
21197 }
21198
21199 if (buf_name == buff) {
21200 /* Allocate from thd's memroot */
21201 buf_name = thd_strmake(thd, buf_name, len);
21202 }
21203
21204 #ifdef _WIN32
21205 if (is_filename_allowed(buf_name, len, false)) {
21206 *static_cast<const char **>(save) = buf_name;
21207 return (0);
21208 } else {
21209 push_warning_printf(thd, Sql_condition::SL_WARNING, ER_WRONG_ARGUMENTS,
21210 "InnoDB: innodb_buffer_pool_filename"
21211 " cannot have colon (:) in the file name.");
21212 return (1);
21213 }
21214 #else /* _WIN32 */
21215 *static_cast<const char **>(save) = buf_name;
21216 return (0);
21217 #endif
21218 }
21219
21220 #ifdef UNIV_DEBUG
21221 static char *srv_buffer_pool_evict;
21222
21223 /** Evict all uncompressed pages of compressed tables from the buffer pool.
21224 Keep the compressed pages in the buffer pool.
21225 @return whether all uncompressed pages were evicted */
21226 [[nodiscard]] static bool innodb_buffer_pool_evict_uncompressed(void) {
21227 bool all_evicted = true;
21228
21229 for (ulint i = 0; i < srv_buf_pool_instances; i++) {
21230 buf_pool_t *buf_pool = &buf_pool_ptr[i];
21231
21232 mutex_enter(&buf_pool->LRU_list_mutex);
21233
21234 for (buf_block_t *block = UT_LIST_GET_LAST(buf_pool->unzip_LRU);
21235 block != nullptr;) {
21236 buf_block_t *prev_block = UT_LIST_GET_PREV(unzip_LRU, block);
21237 ut_ad(buf_block_get_state(block) == BUF_BLOCK_FILE_PAGE);
21238 ut_ad(block->in_unzip_LRU_list);
21239 ut_ad(block->page.in_LRU_list);
21240
21241 mutex_enter(&block->mutex);
21242
21243 if (!buf_LRU_free_page(&block->page, false)) {
21244 mutex_exit(&block->mutex);
21245 all_evicted = false;
21246 } else {
21247 /* buf_LRU_free_page() released LRU_list_mutex.
21248 have to restart the unzip_LRU scan. */
21249 mutex_enter(&buf_pool->LRU_list_mutex);
21250 block = UT_LIST_GET_LAST(buf_pool->unzip_LRU);
21251 continue;
21252 }
21253 block = prev_block;
21254 }
21255
21256 mutex_exit(&buf_pool->LRU_list_mutex);
21257 }
21258
21259 return (all_evicted);
21260 }
21261
21262 /** Called on SET GLOBAL innodb_buffer_pool_evict=...
21263 Handles some values specially, to evict pages from the buffer pool.
21264 SET GLOBAL innodb_buffer_pool_evict='uncompressed'
21265 evicts all uncompressed page frames of compressed tablespaces.
21266 @param[in] save immediate result from check function */
21267 static void innodb_buffer_pool_evict_update(THD *, SYS_VAR *, void *,
21268 const void *save) {
21269 if (const char *op = *static_cast<const char *const *>(save)) {
21270 if (!strcmp(op, "uncompressed")) {
21271 for (uint tries = 0; tries < 10000; tries++) {
21272 if (innodb_buffer_pool_evict_uncompressed()) {
21273 return;
21274 }
21275
21276 std::this_thread::sleep_for(std::chrono::milliseconds(10));
21277 }
21278
21279 /* We failed to evict all uncompressed pages. */
21280 ut_d(ut_error);
21281 }
21282 }
21283 }
21284 #endif /* UNIV_DEBUG */
21285
21286 /** Update the system variable innodb_monitor_enable and enable
21287 specified monitor counter.
21288 This function is registered as a callback with MySQL.
21289 @param[in] thd thread handle
21290 @param[out] var_ptr where the formal string goes
21291 @param[in] save immediate result from check function */
21292 static void innodb_enable_monitor_update(THD *thd, SYS_VAR *, void *var_ptr,
21293 const void *save) {
21294 innodb_monitor_update(thd, var_ptr, save, MONITOR_TURN_ON, true);
21295 }
21296
21297 /** Update the system variable innodb_monitor_disable and turn
21298 off specified monitor counter.
21299 @param[in] thd thread handle
21300 @param[out] var_ptr where the formal string goes
21301 @param[in] save immediate result from check function */
21302 static void innodb_disable_monitor_update(THD *thd, SYS_VAR *, void *var_ptr,
21303 const void *save) {
21304 innodb_monitor_update(thd, var_ptr, save, MONITOR_TURN_OFF, true);
21305 }
21306
21307 /** Update the system variable innodb_monitor_reset and reset
21308 specified monitor counter(s).
21309 This function is registered as a callback with MySQL.
21310 @param[in] thd thread handle
21311 @param[out] var_ptr where the formal string goes
21312 @param[in] save immediate result from check function */
21313 static void innodb_reset_monitor_update(THD *thd, SYS_VAR *, void *var_ptr,
21314 const void *save) {
21315 innodb_monitor_update(thd, var_ptr, save, MONITOR_RESET_VALUE, true);
21316 }
21317
21318 /** Update the system variable innodb_monitor_reset_all and reset
21319 all value related monitor counter.
21320 This function is registered as a callback with MySQL.
21321 @param[in] thd thread handle
21322 @param[out] var_ptr where the formal string goes
21323 @param[in] save immediate result from check function */
21324 static void innodb_reset_all_monitor_update(THD *thd, SYS_VAR *, void *var_ptr,
21325 const void *save) {
21326 innodb_monitor_update(thd, var_ptr, save, MONITOR_RESET_ALL_VALUE, true);
21327 }
21328
21329 /** Validate the value of innodb_undo_tablespaces global variable. This function
21330 is registered as a callback with MySQL.
21331 @param[in] thd thread handle
21332 @param[in] var pointer to system variable
21333 @param[in] var_ptr where the formal string goes
21334 @param[in] save immediate result from check function */
21335 static void innodb_undo_tablespaces_update(THD *thd [[maybe_unused]],
21336 SYS_VAR *var [[maybe_unused]],
21337 void *var_ptr [[maybe_unused]],
21338 const void *save [[maybe_unused]]) {
21339 innodb_undo_tablespaces_deprecate();
21340 }
21341
21342 /* Declare default check function for boolean system variable. Cannot include
21343 sql_plugin_var.h header in this file due to conflicting macro definitions. */
21344 int check_func_bool(THD *, SYS_VAR *, void *save, st_mysql_value *value);
21345
21346 /** Validate the value of innodb_undo_log_encrypt global variable. This function
21347 is registered as a callback with MySQL.
21348 @param[in] thd thread handle
21349 @param[in] var pointer to system variable
21350 @param[in] save possibly updated variable value
21351 @param[in] value current variable value
21352 @return error code */
21353 static int validate_innodb_undo_log_encrypt(THD *thd, SYS_VAR *var, void *save,
21354 struct st_mysql_value *value) {
21355 /* Call the default check function first. */
21356 auto error = check_func_bool(thd, var, save, value);
21357 if (error != 0) {
21358 return (error);
21359 }
21360 bool target = *static_cast<bool *>(save);
21361
21362 /* Set the default output to current value for all error cases. */
21363 *static_cast<bool *>(save) = srv_undo_log_encrypt;
21364
21365 if (srv_undo_log_encrypt == target) {
21366 /* No change */
21367 return (0);
21368 }
21369
21370 /* If encryption is to be disabled. This will just make sure I/O doesn't
21371 write UNDO pages encrypted from now on. */
21372 if (target == false) {
21373 *static_cast<bool *>(save) = false;
21374 return (0);
21375 }
21376
21377 /* There would be at least 2 UNDO tablespaces */
21378 ut_ad(undo::spaces->size() >= FSP_IMPLICIT_UNDO_TABLESPACES);
21379
21380 if (srv_read_only_mode) {
21381 ib::error(ER_IB_MSG_1051);
21382 return (0);
21383 }
21384
21385 /* UNDO tablespace encryption to be mutually exclusive with any UNDO DDL */
21386 mutex_enter(&undo::ddl_mutex);
21387
21388 /* Enable encryption for UNDO tablespaces */
21389 bool ret = srv_enable_undo_encryption();
21390
21391 if (!ret) {
21392 /* At this point, all UNDO tablespaces have been encrypted. */
21393 *static_cast<bool *>(save) = true;
21394 }
21395
21396 mutex_exit(&undo::ddl_mutex);
21397 return (0);
21398 }
21399
21400 /** Validate the value of innodb_redo_log_encrypt global variable. This function
21401 is registered as a callback with MySQL.
21402 @param[in] thd thread handle
21403 @param[in] var pointer to system variable
21404 @param[in] save possibly updated variable value
21405 @param[in] value current variable value
21406 @return error code */
21407 static int validate_innodb_redo_log_encrypt(THD *thd, SYS_VAR *var, void *save,
21408 struct st_mysql_value *value) {
21409 /* Call the default check function first. */
21410 auto error = check_func_bool(thd, var, save, value);
21411 if (error != 0) {
21412 return (error);
21413 }
21414 bool target = *static_cast<bool *>(save);
21415
21416 /* Set the default output to current value for all error cases. */
21417 *static_cast<bool *>(save) = srv_redo_log_encrypt;
21418
21419 if (srv_redo_log_encrypt == target) {
21420 /* No change */
21421 return (0);
21422 }
21423
21424 /* If encryption is to be disabled. This will just make sure I/O doesn't
21425 write REDO encrypted from now on. */
21426 if (target == false) {
21427 *static_cast<bool *>(save) = false;
21428 return (0);
21429 }
21430
21431 if (srv_read_only_mode) {
21432 ib::error(ER_IB_MSG_LOG_FILES_CANNOT_ENCRYPT_IN_READ_ONLY);
21433 return (0);
21434 }
21435
21436 /* Enable encryption for REDO tablespaces */
21437 bool ret = srv_enable_redo_encryption();
21438
21439 if (!ret) {
21440 /* At this point, REDO log is set to be encrypted. */
21441 *static_cast<bool *>(save) = true;
21442 }
21443 return (0);
21444 }
21445
21446 /** Update the number of rollback segments per tablespace when the
21447 system variable innodb_rollback_segments is changed.
21448 This function is registered as a callback with MySQL.
21449 @param[in] save immediate result from check function */
21450 static void innodb_rollback_segments_update(THD *, SYS_VAR *, void *,
21451 const void *save) {
21452 ulong target = *static_cast<const ulong *>(save);
21453
21454 if (srv_rollback_segments == target) {
21455 return;
21456 }
21457
21458 if (srv_read_only_mode) {
21459 ib::warn(ER_IB_MSG_578) << "Cannot set innodb_rollback_segments to "
21460 << target << " when in read-only mode";
21461 return;
21462 }
21463
21464 if (srv_force_recovery > 0) {
21465 ib::warn(ER_IB_MSG_579) << "Cannot set innodb_rollback_segments to "
21466 << target << " when in innodb_force_recovery > 0";
21467 return;
21468 }
21469
21470 /* Serialize this adjustment with all undo tablespace DDLs. */
21471 mutex_enter(&undo::ddl_mutex);
21472
21473 if (!trx_rseg_adjust_rollback_segments(target)) {
21474 ib::warn(ER_IB_MSG_580)
21475 << "Failed to set innodb_rollback_segments to " << target;
21476 return;
21477 }
21478
21479 srv_rollback_segments = target;
21480
21481 mutex_exit(&undo::ddl_mutex);
21482 }
21483
21484 /** Parse and enable InnoDB monitor counters during server startup.
21485 User can list the monitor counters/groups to be enable by specifying
21486 "loose-innodb_monitor_enable=monitor_name1;monitor_name2..."
21487 in server configuration file or at the command line. The string
21488 separate could be ";", "," or empty space. */
21489 static void innodb_enable_monitor_at_startup(
21490 char *str) /*!< in/out: monitor counter enable list */
21491 {
21492 static const char *sep = " ;,";
21493 char *last;
21494
21495 ut_a(str);
21496
21497 /* Walk through the string, and separate each monitor counter
21498 and/or counter group name, and calling innodb_monitor_update()
21499 if successfully updated. Please note that the "str" would be
21500 changed by strtok_r() as it walks through it. */
21501 for (char *option = my_strtok_r(str, sep, &last); option;
21502 option = my_strtok_r(nullptr, sep, &last)) {
21503 ulint ret;
21504 char *option_name;
21505
21506 ret = innodb_monitor_valid_byname(&option_name, option);
21507
21508 /* The name is validated if ret == 0 */
21509 if (!ret) {
21510 innodb_monitor_update(nullptr, nullptr, &option, MONITOR_TURN_ON, false);
21511 } else {
21512 log_errlog(WARNING_LEVEL, ER_INNODB_INVALID_MONITOR_COUNTER_NAME, option);
21513 }
21514 }
21515 }
21516
21517 /** Callback function for accessing the InnoDB variables from MySQL:
21518 SHOW VARIABLES. */
21519 static int show_innodb_vars(THD *, SHOW_VAR *var, char *) {
21520 innodb_export_status();
21521 var->type = SHOW_ARRAY;
21522 var->value = (char *)&innodb_status_variables;
21523 var->scope = SHOW_SCOPE_GLOBAL;
21524
21525 return (0);
21526 }
21527
21528 /** This function checks each index name for a table against reserved
21529 system default primary index name 'GEN_CLUST_INDEX'. If a name
21530 matches, this function pushes an warning message to the client,
21531 and returns true.
21532 @return true if the index name matches the reserved name */
21533 bool innobase_index_name_is_reserved(
21534 THD *thd, /*!< in/out: MySQL connection */
21535 const KEY *key_info, /*!< in: Indexes to be created */
21536 ulint num_of_keys) /*!< in: Number of indexes to
21537 be created. */
21538 {
21539 const KEY *key;
21540 uint key_num; /* index number */
21541
21542 for (key_num = 0; key_num < num_of_keys; key_num++) {
21543 key = &key_info[key_num];
21544
21545 if (innobase_strcasecmp(key->name, innobase_index_reserve_name) == 0) {
21546 /* Push warning to mysql */
21547 push_warning_printf(thd, Sql_condition::SL_WARNING,
21548 ER_WRONG_NAME_FOR_INDEX,
21549 "Cannot Create Index with name"
21550 " '%s'. The name is reserved"
21551 " for the system default primary"
21552 " index.",
21553 innobase_index_reserve_name);
21554
21555 my_error(ER_WRONG_NAME_FOR_INDEX, MYF(0), innobase_index_reserve_name);
21556
21557 return (true);
21558 }
21559 }
21560
21561 return (false);
21562 }
21563
21564 /** Retrieve the FTS Relevance Ranking result for doc with doc_id
21565 of m_prebuilt->fts_doc_id
21566 @param[in,out] fts_hdl FTS handler
21567 @return the relevance ranking value */
21568 static float innobase_fts_retrieve_ranking(FT_INFO *fts_hdl) {
21569 fts_result_t *result;
21570 row_prebuilt_t *ft_prebuilt [[maybe_unused]];
21571
21572 result = reinterpret_cast<NEW_FT_INFO *>(fts_hdl)->ft_result;
21573
21574 ft_prebuilt = reinterpret_cast<NEW_FT_INFO *>(fts_hdl)->ft_prebuilt;
21575
21576 fts_ranking_t *ranking = rbt_value(fts_ranking_t, result->current);
21577 assert(ft_prebuilt->fts_doc_id == ranking->doc_id);
21578
21579 return (ranking->rank);
21580 }
21581
21582 /** Free the memory for the FTS handler
21583 @param[in,out] fts_hdl FTS handler */
21584 static void innobase_fts_close_ranking(FT_INFO *fts_hdl) {
21585 fts_result_t *result;
21586
21587 result = reinterpret_cast<NEW_FT_INFO *>(fts_hdl)->ft_result;
21588
21589 fts_query_free_result(result);
21590
21591 my_free((uchar *)fts_hdl);
21592 }
21593
21594 /** Find and Retrieve the FTS Relevance Ranking result for doc with doc_id
21595 of m_prebuilt->fts_doc_id
21596 @param[in,out] fts_hdl FTS handler
21597 @return the relevance ranking value */
21598 static float innobase_fts_find_ranking(FT_INFO *fts_hdl, uchar *, uint) {
21599 fts_result_t *result;
21600 row_prebuilt_t *ft_prebuilt;
21601
21602 ft_prebuilt = reinterpret_cast<NEW_FT_INFO *>(fts_hdl)->ft_prebuilt;
21603 result = reinterpret_cast<NEW_FT_INFO *>(fts_hdl)->ft_result;
21604
21605 /* Retrieve the ranking value for doc_id with value of
21606 m_prebuilt->fts_doc_id */
21607 return (fts_retrieve_ranking(result, ft_prebuilt->fts_doc_id));
21608 }
21609
21610 #ifdef UNIV_DEBUG
21611 static bool innodb_background_drop_list_empty = true;
21612 static bool innodb_purge_run_now = true;
21613 static bool innodb_purge_stop_now = true;
21614 static bool innodb_log_checkpoint_now = true;
21615 static bool innodb_log_checkpoint_fuzzy_now = true;
21616 static bool innodb_log_flush_now = true;
21617 static bool innodb_buf_flush_list_now = true;
21618
21619 static uint innodb_merge_threshold_set_all_debug =
21620 DICT_INDEX_MERGE_THRESHOLD_DEFAULT;
21621
21622 /** Wait for the background drop list to become empty. */
21623 static void wait_background_drop_list_empty(THD *, SYS_VAR *, void *,
21624 const void *) {
21625 row_wait_for_background_drop_list_empty();
21626 }
21627
21628 /** Set the purge state to RUN. If purge is disabled then it
21629 is a no-op. This function is registered as a callback with MySQL.
21630 @param[in] save immediate result from check function */
21631 static void purge_run_now_set(THD *, SYS_VAR *, void *, const void *save) {
21632 if (*(bool *)save && trx_purge_state() != PURGE_STATE_DISABLED) {
21633 trx_purge_run();
21634 }
21635 }
21636
21637 /** Set the purge state to STOP. If purge is disabled then it
21638 is a no-op. This function is registered as a callback with MySQL.
21639 @param[in] save immediate result from check function */
21640 static void purge_stop_now_set(THD *, SYS_VAR *, void *, const void *save) {
21641 if (*(bool *)save && trx_purge_state() != PURGE_STATE_DISABLED) {
21642 trx_purge_stop();
21643 }
21644 }
21645
21646 /** Force InnoDB to flush redo log up to current_lsn.
21647 This function is registered as a callback with MySQL.
21648 @param[in] save immediate result from check function */
21649 static void log_flush_now_set(THD *, SYS_VAR *, void *, const void *save) {
21650 if (!*(bool *)save) {
21651 return;
21652 }
21653
21654 log_buffer_flush_to_disk(true);
21655 }
21656
21657 /** Force InnoDB to do sharp checkpoint. This forces a flush of all
21658 dirty pages.
21659 @param[in] save immediate result from check function */
21660 static void checkpoint_now_set(THD *, SYS_VAR *, void *, const void *save) {
21661 if (*(bool *)save && !srv_checkpoint_disabled) {
21662 /* Note that it's defined only when UNIV_DEBUG is defined.
21663 It seems to be very risky feature. Fortunately it is used
21664 only inside mtr tests. */
21665
21666 while (log_make_latest_checkpoint(*log_sys)) {
21667 /* Creating checkpoint could itself result in
21668 new log records. Hence we repeat until:
21669 last_checkpoint_lsn = log_get_lsn(). */
21670 }
21671
21672 dberr_t err = fil_write_flushed_lsn(log_sys->last_checkpoint_lsn.load());
21673
21674 ut_a(err == DB_SUCCESS);
21675 }
21676 }
21677
21678 /** Force InnoDB to do fuzzy checkpoint. Fuzzy checkpoint does not
21679 force InnoDB to flush dirty pages. It only forces to write the new
21680 checkpoint_lsn to the header of the log file containing that LSN.
21681 This LSN is where the recovery starts. You can read more about the
21682 fuzzy checkpoints in the internet.
21683 @param[in] save immediate result from check function */
21684 static void checkpoint_fuzzy_now_set(THD *, SYS_VAR *, void *,
21685 const void *save) {
21686 if (*(bool *)save && !srv_checkpoint_disabled) {
21687 /* Note that it's defined only when UNIV_DEBUG is defined.
21688 It seems to be very risky feature. Fortunately it is used
21689 only inside mtr tests. */
21690
21691 log_request_checkpoint(*log_sys, true);
21692 }
21693 }
21694
21695 /** Updates srv_checkpoint_disabled - allowing or disallowing checkpoints.
21696 This is called when user invokes SET GLOBAL innodb_checkpoints_disabled=0/1.
21697 After checkpoints are disabled, there will be no write of a checkpoint,
21698 until checkpoints are re-enabled (log_sys->checkpointer_mutex protects that)
21699 @param[in] save immediate result from check function */
21700 static void checkpoint_disabled_update(THD *, SYS_VAR *, void *,
21701 const void *save) {
21702 /* We need to acquire the checkpointer_mutex, to ensure that
21703 after we have finished this function, there will be no new
21704 checkpoint written (e.g. in case there is currently curring
21705 checkpoint). When checkpoint is being written, the same mutex
21706 is acquired, current value of srv_checkpoint_disabled is checked,
21707 and if checkpoints are disabled, we cancel writing the checkpoint. */
21708
21709 log_t &log = *log_sys;
21710
21711 log_checkpointer_mutex_enter(log);
21712 log_limits_mutex_enter(log);
21713
21714 srv_checkpoint_disabled = *static_cast<const bool *>(save);
21715
21716 log_limits_mutex_exit(log);
21717 log_checkpointer_mutex_exit(log);
21718 }
21719
21720 /** Force a dirty pages flush now.
21721 @param[in] save immediate result from check function */
21722 static void buf_flush_list_now_set(THD *, SYS_VAR *, void *, const void *save) {
21723 if (*(bool *)save) {
21724 buf_flush_sync_all_buf_pools();
21725 }
21726 }
21727
21728 /** Override current MERGE_THRESHOLD setting for all indexes at dictionary
21729 now.
21730 @param[in] save immediate result from check function */
21731 static void innodb_merge_threshold_set_all_debug_update(THD *, SYS_VAR *,
21732 void *,
21733 const void *save) {
21734 innodb_merge_threshold_set_all_debug = (*static_cast<const uint *>(save));
21735 dict_set_merge_threshold_all_debug(innodb_merge_threshold_set_all_debug);
21736 }
21737
21738 #endif /* UNIV_DEBUG */
21739
21740 /** Find and Retrieve the FTS doc_id for the current result row
21741 @param[in,out] fts_hdl FTS handler
21742 @return the document ID */
21743 static ulonglong innobase_fts_retrieve_docid(FT_INFO_EXT *fts_hdl) {
21744 fts_result_t *result;
21745 row_prebuilt_t *ft_prebuilt;
21746
21747 ft_prebuilt = reinterpret_cast<NEW_FT_INFO *>(fts_hdl)->ft_prebuilt;
21748 result = reinterpret_cast<NEW_FT_INFO *>(fts_hdl)->ft_result;
21749
21750 if (ft_prebuilt->read_just_key) {
21751 fts_ranking_t *ranking = rbt_value(fts_ranking_t, result->current);
21752
21753 return (ranking->doc_id);
21754 }
21755
21756 return (ft_prebuilt->fts_doc_id);
21757 }
21758
21759 /* These variables are never read by InnoDB or changed. They are a kind of
21760 dummies that are needed by the MySQL infrastructure to call
21761 buffer_pool_dump_now(), buffer_pool_load_now() and buffer_pool_load_abort()
21762 by the user by doing:
21763 SET GLOBAL innodb_buffer_pool_dump_now=ON;
21764 SET GLOBAL innodb_buffer_pool_load_now=ON;
21765 SET GLOBAL innodb_buffer_pool_load_abort=ON;
21766 Their values are read by MySQL and displayed to the user when the variables
21767 are queried, e.g.:
21768 SELECT @@innodb_buffer_pool_dump_now;
21769 SELECT @@innodb_buffer_pool_load_now;
21770 SELECT @@innodb_buffer_pool_load_abort; */
21771 static bool innodb_buffer_pool_dump_now = false;
21772 static bool innodb_buffer_pool_load_now = false;
21773 static bool innodb_buffer_pool_load_abort = false;
21774
21775 /** Trigger a dump of the buffer pool if innodb_buffer_pool_dump_now is set
21776 to ON. This function is registered as a callback with MySQL.
21777 @param[in] save immediate result from check function */
21778 static void buffer_pool_dump_now(THD *, SYS_VAR *, void *, const void *save) {
21779 if (*(bool *)save && !srv_read_only_mode) {
21780 buf_dump_start();
21781 }
21782 }
21783
21784 /** Trigger a load of the buffer pool if innodb_buffer_pool_load_now is set
21785 to ON. This function is registered as a callback with MySQL.
21786 @param[in] save immediate result from check function */
21787 static void buffer_pool_load_now(THD *, SYS_VAR *, void *, const void *save) {
21788 if (*(bool *)save) {
21789 buf_load_start();
21790 }
21791 }
21792
21793 /** Abort a load of the buffer pool if innodb_buffer_pool_load_abort
21794 is set to ON. This function is registered as a callback with MySQL.
21795 @param[in] save immediate result from check function */
21796 static void buffer_pool_load_abort(THD *, SYS_VAR *, void *, const void *save) {
21797 if (*(bool *)save) {
21798 buf_load_abort();
21799 }
21800 }
21801
21802 /** Update the system variable innodb_log_write_ahead_size using the "saved"
21803 value. This function is registered as a callback with MySQL.
21804 @param[in] thd thread handle
21805 @param[in] save immediate result from check function */
21806 static void innodb_log_write_ahead_size_update(THD *thd, SYS_VAR *, void *,
21807 const void *save) {
21808 ulong val = INNODB_LOG_WRITE_AHEAD_SIZE_MIN;
21809 ulong in_val = *static_cast<const ulong *>(save);
21810
21811 while (val < in_val) {
21812 val = val * 2;
21813 }
21814 if (val > INNODB_LOG_WRITE_AHEAD_SIZE_MAX) {
21815 val = INNODB_LOG_WRITE_AHEAD_SIZE_MAX;
21816 }
21817
21818 if (val > UNIV_PAGE_SIZE) {
21819 val = UNIV_PAGE_SIZE;
21820 push_warning_printf(thd, Sql_condition::SL_WARNING, ER_WRONG_ARGUMENTS,
21821 "innodb_log_write_ahead_size cannot"
21822 " be set higher than innodb_page_size.");
21823 } else if (val != in_val) {
21824 push_warning_printf(thd, Sql_condition::SL_WARNING, ER_WRONG_ARGUMENTS,
21825 "innodb_log_write_ahead_size should be"
21826 " set to power of 2, in range [%lu," ULINTPF "]",
21827 INNODB_LOG_WRITE_AHEAD_SIZE_MIN,
21828 INNODB_LOG_WRITE_AHEAD_SIZE_MAX);
21829 }
21830
21831 if (val != in_val) {
21832 push_warning_printf(thd, Sql_condition::SL_WARNING, ER_WRONG_ARGUMENTS,
21833 "Setting innodb_log_write_ahead_size"
21834 " to %lu",
21835 val);
21836 }
21837
21838 log_write_ahead_resize(*log_sys, val);
21839 }
21840
21841 /** Update the system variable innodb_log_buffer_size using the "saved"
21842 value. This function is registered as a callback with MySQL.
21843 @param[in] save immediate result from check function */
21844 static void innodb_log_buffer_size_update(THD *, SYS_VAR *, void *,
21845 const void *save) {
21846 const ulong val = *static_cast<const ulong *>(save);
21847
21848 ib::info(ER_IB_MSG_1255) << "Setting innodb_log_buffer_size to " << val;
21849
21850 if (!log_buffer_resize(*log_sys, val)) {
21851 /* This could happen if we tried to decrease size of the
21852 log buffer but we had more data in the log buffer than
21853 the new size. We could have asked for writing the data to
21854 disk, after x-locking the log buffer, but this could lead
21855 to deadlock if there was no space in log files and checkpoint
21856 was required (because checkpoint writes new redo records
21857 when persisting dd table buffer). That's why we don't ask
21858 for writing to disk. */
21859
21860 ib::error(ER_IB_MSG_1256) << "Failed to change size of the log buffer."
21861 " Try flushing the log buffer first.";
21862 }
21863 }
21864
21865 /** Update the innodb_log_writer_threads parameter.
21866 @param[out] var_ptr current value
21867 @param[in] save immediate result from check function */
21868 static void innodb_log_writer_threads_update(THD *, SYS_VAR *, void *var_ptr,
21869 const void *save) {
21870 *static_cast<bool *>(var_ptr) = *static_cast<const bool *>(save);
21871
21872 /* pause/resume the log writer threads based on innodb_log_writer_threads
21873 value. */
21874 log_control_writer_threads(*log_sys);
21875 }
21876
21877 /** Update the system variable innodb_redo_log_capacity using the "saved"
21878 value. This function is registered as a callback with MySQL.
21879 @param[in] thd thread handle
21880 @param[in] save immediate result from check function */
21881 static void innodb_redo_log_capacity_update(THD *thd, SYS_VAR *, void *,
21882 const void *save) {
21883 const auto new_value = *static_cast<const ulonglong *>(save);
21884
21885 ut_a(LOG_CAPACITY_MIN <= new_value);
21886 ut_a(new_value <= LOG_CAPACITY_MAX);
21887 ut_a(new_value % MB == 0);
21888
21889 if (srv_read_only_mode) {
21890 my_error(ER_CANT_CHANGE_SYS_VAR_IN_READ_ONLY_MODE, MYF(0),
21891 "innodb-redo-log-capacity");
21892 return;
21893 }
21894
21895 srv_redo_log_capacity = new_value;
21896
21897 if (new_value == srv_redo_log_capacity_used) {
21898 return;
21899 }
21900
21901 srv_redo_log_capacity_used = new_value;
21902
21903 ib::info(ER_IB_MSG_LOG_FILES_CAPACITY_CHANGED,
21904 srv_redo_log_capacity_used / MB);
21905
21906 log_files_resize_requested(*log_sys);
21907
21908 if (!log_sys->concurrency_margin_is_safe.load()) {
21909 push_warning_printf(thd, Sql_condition::SL_WARNING, ER_WRONG_ARGUMENTS,
21910 "Current innodb_redo_log_capacity"
21911 " is too small for safety of redo log files."
21912 " Consider increasing it or decreasing"
21913 " innodb_thread_concurrency.");
21914 }
21915 }
21916
21917 /** Update the system variable innodb_thread_concurrency using the "saved"
21918 value. This function is registered as a callback with MySQL.
21919 @param[in] thd thread handle
21920 @param[in] save immediate result from check function */
21921 static void innodb_thread_concurrency_update(THD *thd, SYS_VAR *, void *,
21922 const void *save) {
21923 srv_thread_concurrency = *static_cast<const ulong *>(save);
21924
21925 ib::info(ER_IB_MSG_THREAD_CONCURRENCY_CHANGED, srv_thread_concurrency);
21926
21927 log_files_thread_concurrency_updated(*log_sys);
21928
21929 if (!log_sys->concurrency_margin_is_safe.load()) {
21930 push_warning_printf(thd, Sql_condition::SL_WARNING, ER_WRONG_ARGUMENTS,
21931 "Current innodb_thread_concurrency"
21932 " is too big for safety of redo log files."
21933 " Consider decreasing it or increasing"
21934 " innodb_redo_log_capacity.");
21935 }
21936 }
21937
21938 /** Update the innodb_log_checksums parameter.
21939 @param[out] var_ptr current value
21940 @param[in] save immediate result from check function */
21941 static void innodb_log_checksums_update(THD *, SYS_VAR *, void *var_ptr,
21942 const void *save) {
21943 bool check = *static_cast<bool *>(var_ptr) = *static_cast<const bool *>(save);
21944
21945 /* Make sure we are the only log user */
21946 innodb_log_checksums_func_update(check);
21947 }
21948
21949 static SHOW_VAR innodb_status_variables_export[] = {
21950 {"Innodb", (char *)&show_innodb_vars, SHOW_FUNC, SHOW_SCOPE_GLOBAL},
21951 {NullS, NullS, SHOW_LONG, SHOW_SCOPE_GLOBAL}};
21952
21953 static struct st_mysql_storage_engine innobase_storage_engine = {
21954 MYSQL_HANDLERTON_INTERFACE_VERSION};
21955
21956 /* plugin options */
21957
21958 static MYSQL_SYSVAR_ENUM(
21959 checksum_algorithm, srv_checksum_algorithm, PLUGIN_VAR_RQCMDARG,
21960 "The algorithm InnoDB uses for page checksumming. Possible values are"
21961 " CRC32 (hardware accelerated if the CPU supports it)"
21962 " write crc32, allow any of the other checksums to match when reading;"
21963 " STRICT_CRC32"
21964 " write crc32, do not allow other algorithms to match when reading;"
21965 " INNODB"
21966 " write a software calculated checksum, allow any other checksums"
21967 " to match when reading;"
21968 " STRICT_INNODB"
21969 " write a software calculated checksum, do not allow other algorithms"
21970 " to match when reading;"
21971 " NONE"
21972 " write a constant magic number, do not do any checksum verification"
21973 " when reading;"
21974 " STRICT_NONE"
21975 " write a constant magic number, do not allow values other than that"
21976 " magic number when reading;"
21977 " Files updated when this option is set to crc32 or strict_crc32 will"
21978 " not be readable by MySQL versions older than 5.6.3",
21979 nullptr, nullptr, SRV_CHECKSUM_ALGORITHM_CRC32,
21980 &innodb_checksum_algorithm_typelib);
21981
21982 static MYSQL_SYSVAR_BOOL(
21983 log_checksums, srv_log_checksums, PLUGIN_VAR_RQCMDARG,
21984 "Whether to compute and require checksums for InnoDB redo log blocks",
21985 nullptr, innodb_log_checksums_update, true);
21986
21987 static MYSQL_SYSVAR_STR(data_home_dir, innobase_data_home_dir,
21988 PLUGIN_VAR_READONLY | PLUGIN_VAR_NOPERSIST,
21989 "The common part for InnoDB table spaces.", nullptr,
21990 nullptr, nullptr);
21991
21992 static MYSQL_SYSVAR_BOOL(
21993 stats_include_delete_marked, srv_stats_include_delete_marked,
21994 PLUGIN_VAR_OPCMDARG,
21995 "Include delete marked records when calculating persistent statistics",
21996 nullptr, nullptr, false);
21997
21998 static MYSQL_SYSVAR_ULONG(
21999 io_capacity, srv_io_capacity, PLUGIN_VAR_RQCMDARG,
22000 "Number of IOPs the server can do. Tunes the background IO rate", nullptr,
22001 innodb_io_capacity_update, 200, 100, SRV_MAX_IO_CAPACITY_LIMIT, 0);
22002
22003 static MYSQL_SYSVAR_ULONG(io_capacity_max, srv_max_io_capacity,
22004 PLUGIN_VAR_RQCMDARG,
22005 "Limit to which innodb_io_capacity can be inflated.",
22006 nullptr, innodb_io_capacity_max_update,
22007 SRV_MAX_IO_CAPACITY_DUMMY_DEFAULT, 100,
22008 SRV_MAX_IO_CAPACITY_LIMIT, 0);
22009
22010 #ifdef UNIV_DEBUG
22011 static MYSQL_SYSVAR_BOOL(background_drop_list_empty,
22012 innodb_background_drop_list_empty, PLUGIN_VAR_OPCMDARG,
22013 "Wait for the background drop list to become empty",
22014 nullptr, wait_background_drop_list_empty, false);
22015
22016 static MYSQL_SYSVAR_BOOL(purge_run_now, innodb_purge_run_now,
22017 PLUGIN_VAR_OPCMDARG, "Set purge state to RUN", nullptr,
22018 purge_run_now_set, false);
22019
22020 static MYSQL_SYSVAR_BOOL(purge_stop_now, innodb_purge_stop_now,
22021 PLUGIN_VAR_OPCMDARG, "Set purge state to STOP",
22022 nullptr, purge_stop_now_set, false);
22023
22024 static MYSQL_SYSVAR_BOOL(log_flush_now, innodb_log_flush_now,
22025 PLUGIN_VAR_OPCMDARG,
22026 "Force flush of redo up to current lsn", nullptr,
22027 log_flush_now_set, false);
22028
22029 static MYSQL_SYSVAR_BOOL(log_checkpoint_now, innodb_log_checkpoint_now,
22030 PLUGIN_VAR_OPCMDARG, "Force sharp checkpoint now",
22031 nullptr, checkpoint_now_set, false);
22032
22033 static MYSQL_SYSVAR_BOOL(log_checkpoint_fuzzy_now,
22034 innodb_log_checkpoint_fuzzy_now, PLUGIN_VAR_OPCMDARG,
22035 "Force fuzzy checkpoint now", nullptr,
22036 checkpoint_fuzzy_now_set, false);
22037
22038 static MYSQL_SYSVAR_BOOL(checkpoint_disabled, srv_checkpoint_disabled,
22039 PLUGIN_VAR_OPCMDARG, "Disable checkpoints", nullptr,
22040 checkpoint_disabled_update, false);
22041
22042 static MYSQL_SYSVAR_BOOL(buf_flush_list_now, innodb_buf_flush_list_now,
22043 PLUGIN_VAR_OPCMDARG, "Force dirty page flush now",
22044 nullptr, buf_flush_list_now_set, false);
22045
22046 static MYSQL_SYSVAR_UINT(
22047 merge_threshold_set_all_debug, innodb_merge_threshold_set_all_debug,
22048 PLUGIN_VAR_RQCMDARG,
22049 "Override current MERGE_THRESHOLD setting for all indexes at dictionary"
22050 " cache by the specified value dynamically, at the time.",
22051 nullptr, innodb_merge_threshold_set_all_debug_update,
22052 DICT_INDEX_MERGE_THRESHOLD_DEFAULT, 1, 50, 0);
22053
22054 static MYSQL_SYSVAR_ULONG(
22055 semaphore_wait_timeout_debug, srv_fatal_semaphore_wait_threshold,
22056 PLUGIN_VAR_RQCMDARG,
22057 "Number of seconds that a semaphore can be held. If semaphore wait crosses"
22058 "this value, server will crash",
22059 nullptr, nullptr, 600, 25, 600, 0);
22060 #endif /* UNIV_DEBUG */
22061
22062 static MYSQL_SYSVAR_ULONG(
22063 purge_batch_size, srv_purge_batch_size, PLUGIN_VAR_OPCMDARG,
22064 "Number of UNDO log pages to purge in one batch from the history list.",
22065 nullptr, nullptr, 300, /* Default setting */
22066 1, /* Minimum value */
22067 5000, 0); /* Maximum value */
22068
22069 static MYSQL_SYSVAR_ULONG(purge_threads, srv_n_purge_threads,
22070 PLUGIN_VAR_OPCMDARG | PLUGIN_VAR_READONLY,
22071 "Purge threads can be from 1 to 32. Default is 4.",
22072 nullptr, nullptr, 4, /* Default setting */
22073 1, /* Minimum value */
22074 MAX_PURGE_THREADS, 0); /* Maximum value */
22075
22076 static MYSQL_SYSVAR_ULONG(sync_array_size, srv_sync_array_size,
22077 PLUGIN_VAR_OPCMDARG | PLUGIN_VAR_READONLY,
22078 "Size of the mutex/lock wait array.", nullptr,
22079 nullptr, 1, /* Default setting */
22080 1, /* Minimum value */
22081 1024, 0); /* Maximum value */
22082
22083 static MYSQL_SYSVAR_ULONG(
22084 fast_shutdown, srv_fast_shutdown, PLUGIN_VAR_OPCMDARG,
22085 "Speeds up the shutdown process of the InnoDB storage engine. Possible"
22086 " values are 0, 1 (faster) or 2 (fastest - crash-like).",
22087 nullptr, nullptr, 1, 0, 2, 0);
22088
22089 static MYSQL_SYSVAR_BOOL(
22090 file_per_table, srv_file_per_table, PLUGIN_VAR_NOCMDARG,
22091 "Stores each InnoDB table to an .ibd file in the database dir.", nullptr,
22092 nullptr, true);
22093
22094 static MYSQL_SYSVAR_STR(ft_server_stopword_table,
22095 innobase_server_stopword_table,
22096 PLUGIN_VAR_OPCMDARG | PLUGIN_VAR_MEMALLOC,
22097 "The user supplied stopword table name.",
22098 innodb_stopword_table_validate, nullptr, nullptr);
22099
22100 static MYSQL_SYSVAR_UINT(flush_log_at_timeout, srv_flush_log_at_timeout,
22101 PLUGIN_VAR_OPCMDARG,
22102 "Write and flush logs every (n) second.", nullptr,
22103 nullptr, 1, 0, 2700, 0);
22104
22105 static MYSQL_SYSVAR_ULONG(flush_log_at_trx_commit, srv_flush_log_at_trx_commit,
22106 PLUGIN_VAR_OPCMDARG,
22107 "Set to 0 (write and flush once per second),"
22108 " 1 (write and flush at each commit),"
22109 " or 2 (write at commit, flush once per second).",
22110 nullptr, nullptr, 1, 0, 2, 0);
22111
22112 static MYSQL_SYSVAR_ENUM(flush_method, innodb_flush_method,
22113 PLUGIN_VAR_RQCMDARG | PLUGIN_VAR_READONLY,
22114 "With which method to flush data", nullptr, nullptr, 0,
22115 &innodb_flush_method_typelib);
22116
22117 static MYSQL_SYSVAR_BOOL(force_load_corrupted, srv_load_corrupted,
22118 PLUGIN_VAR_NOCMDARG | PLUGIN_VAR_READONLY |
22119 PLUGIN_VAR_NOPERSIST,
22120 "Force InnoDB to load metadata of corrupted table.",
22121 nullptr, nullptr, false);
22122
22123 static MYSQL_SYSVAR_STR(log_group_home_dir, srv_log_group_home_dir,
22124 PLUGIN_VAR_RQCMDARG | PLUGIN_VAR_READONLY |
22125 PLUGIN_VAR_NOPERSIST,
22126 "Path to InnoDB log files.", nullptr, nullptr, nullptr);
22127
22128 static MYSQL_SYSVAR_ULONG(
22129 page_cleaners, srv_n_page_cleaners,
22130 PLUGIN_VAR_OPCMDARG | PLUGIN_VAR_READONLY,
22131 "Page cleaner threads can be from 1 to 64. Default is 4.", nullptr, nullptr,
22132 4, 1, 64, 0);
22133
22134 static MYSQL_SYSVAR_DOUBLE(max_dirty_pages_pct, srv_max_buf_pool_modified_pct,
22135 PLUGIN_VAR_RQCMDARG,
22136 "Percentage of dirty pages allowed in bufferpool.",
22137 nullptr, innodb_max_dirty_pages_pct_update, 90.0, 0,
22138 99.999, 0);
22139
22140 static MYSQL_SYSVAR_DOUBLE(
22141 max_dirty_pages_pct_lwm, srv_max_dirty_pages_pct_lwm, PLUGIN_VAR_RQCMDARG,
22142 "Percentage of dirty pages at which flushing kicks in.", nullptr,
22143 innodb_max_dirty_pages_pct_lwm_update, 10, 0, 99.999, 0);
22144
22145 static MYSQL_SYSVAR_ULONG(
22146 adaptive_flushing_lwm, srv_adaptive_flushing_lwm, PLUGIN_VAR_RQCMDARG,
22147 "Percentage of log capacity below which no adaptive flushing happens.",
22148 nullptr, nullptr, 10, 0, 70, 0);
22149
22150 static MYSQL_SYSVAR_BOOL(
22151 adaptive_flushing, srv_adaptive_flushing, PLUGIN_VAR_NOCMDARG,
22152 "Attempt flushing dirty pages to avoid IO bursts at checkpoints.", nullptr,
22153 nullptr, true);
22154
22155 static MYSQL_SYSVAR_BOOL(
22156 flush_sync, srv_flush_sync, PLUGIN_VAR_NOCMDARG,
22157 "Allow IO bursts at the checkpoints ignoring io_capacity setting.", nullptr,
22158 nullptr, true);
22159
22160 static MYSQL_SYSVAR_ULONG(
22161 flushing_avg_loops, srv_flushing_avg_loops, PLUGIN_VAR_RQCMDARG,
22162 "Number of iterations over which the background flushing is averaged.",
22163 nullptr, nullptr, 30, 1, 1000, 0);
22164
22165 static MYSQL_SYSVAR_ULONG(
22166 max_purge_lag, srv_max_purge_lag, PLUGIN_VAR_RQCMDARG,
22167 "Desired maximum length of the purge queue (0 = no limit)", nullptr,
22168 nullptr, 0, 0, UINT32_MAX, 0);
22169
22170 static MYSQL_SYSVAR_ULONG(max_purge_lag_delay, srv_max_purge_lag_delay,
22171 PLUGIN_VAR_RQCMDARG,
22172 "Maximum delay of user threads in micro-seconds",
22173 nullptr, nullptr, 0L, /* Default setting */
22174 0L, /* Minimum value */
22175 10000000UL, 0); /* Maximum value */
22176
22177 static MYSQL_SYSVAR_BOOL(rollback_on_timeout, innobase_rollback_on_timeout,
22178 PLUGIN_VAR_OPCMDARG | PLUGIN_VAR_READONLY,
22179 "Roll back the complete transaction on lock wait "
22180 "timeout, for 4.x compatibility (disabled by default)",
22181 nullptr, nullptr, false);
22182
22183 static MYSQL_SYSVAR_BOOL(
22184 status_file, innobase_create_status_file,
22185 PLUGIN_VAR_OPCMDARG | PLUGIN_VAR_NOSYSVAR,
22186 "Enable SHOW ENGINE INNODB STATUS output in the innodb_status.<pid> file",
22187 nullptr, nullptr, false);
22188
22189 static MYSQL_SYSVAR_BOOL(
22190 stats_on_metadata, innobase_stats_on_metadata, PLUGIN_VAR_OPCMDARG,
22191 "Enable statistics gathering for metadata commands such as"
22192 " SHOW TABLE STATUS for tables that use transient statistics (off by "
22193 "default)",
22194 nullptr, nullptr, false);
22195
22196 static MYSQL_SYSVAR_ULONGLONG(
22197 stats_transient_sample_pages, srv_stats_transient_sample_pages,
22198 PLUGIN_VAR_RQCMDARG,
22199 "The number of leaf index pages to sample when calculating transient"
22200 " statistics (if persistent statistics are not used, default 8)",
22201 nullptr, nullptr, 8, 1, ~0ULL, 0);
22202
22203 static MYSQL_SYSVAR_BOOL(
22204 stats_persistent, srv_stats_persistent, PLUGIN_VAR_OPCMDARG,
22205 "InnoDB persistent statistics enabled for all tables unless overridden"
22206 " at table level",
22207 nullptr, nullptr, true);
22208
22209 static MYSQL_SYSVAR_BOOL(
22210 stats_auto_recalc, srv_stats_auto_recalc, PLUGIN_VAR_OPCMDARG,
22211 "InnoDB automatic recalculation of persistent statistics enabled for all"
22212 " tables unless overridden at table level (automatic recalculation is only"
22213 " done when InnoDB decides that the table has changed too much and needs a"
22214 " new statistics)",
22215 nullptr, nullptr, true);
22216
22217 static MYSQL_SYSVAR_ULONGLONG(
22218 stats_persistent_sample_pages, srv_stats_persistent_sample_pages,
22219 PLUGIN_VAR_RQCMDARG,
22220 "The number of leaf index pages to sample when calculating persistent"
22221 " statistics (by ANALYZE, default 20)",
22222 nullptr, nullptr, 20, 1, ~0ULL, 0);
22223
22224 static MYSQL_SYSVAR_BOOL(
22225 adaptive_hash_index, srv_btr_search_enabled, PLUGIN_VAR_OPCMDARG,
22226 "Enable InnoDB adaptive hash index (enabled by default). "
22227 " Disable with --skip-innodb-adaptive-hash-index.",
22228 nullptr, innodb_adaptive_hash_index_update, true);
22229
22230 /** Number of distinct partitions of AHI.
22231 Each partition is protected by its own latch and so we have parts number
22232 of latches protecting complete search system. */
22233 static MYSQL_SYSVAR_ULONG(
22234 adaptive_hash_index_parts, btr_ahi_parts,
22235 PLUGIN_VAR_OPCMDARG | PLUGIN_VAR_READONLY,
22236 "Number of InnoDB Adaptive Hash Index Partitions. (default = 8). ", nullptr,
22237 nullptr, 8, 1, 512, 0);
22238
22239 static MYSQL_SYSVAR_ULONG(
22240 replication_delay, srv_replication_delay, PLUGIN_VAR_RQCMDARG,
22241 "Replication thread delay (ms) on the slave server if"
22242 " innodb_thread_concurrency is reached (0 by default)",
22243 nullptr, nullptr, 0, 0, UINT32_MAX, 0);
22244
22245 static MYSQL_SYSVAR_UINT(
22246 compression_level, page_zip_level, PLUGIN_VAR_RQCMDARG,
22247 "Compression level used for compressed row format. 0 is no compression"
22248 ", 1 is fastest, 9 is best compression and default is 6.",
22249 nullptr, nullptr, DEFAULT_COMPRESSION_LEVEL, 0, 9, 0);
22250
22251 static MYSQL_SYSVAR_BOOL(
22252 log_compressed_pages, page_zip_log_pages, PLUGIN_VAR_OPCMDARG,
22253 "Enables/disables the logging of entire compressed page images."
22254 " InnoDB logs the compressed pages to prevent corruption if"
22255 " the zlib compression algorithm changes."
22256 " When turned OFF, InnoDB will assume that the zlib"
22257 " compression algorithm doesn't change.",
22258 nullptr, nullptr, true);
22259
22260 static MYSQL_SYSVAR_ULONG(autoextend_increment,
22261 sys_tablespace_auto_extend_increment,
22262 PLUGIN_VAR_RQCMDARG,
22263 "Data file autoextend increment in megabytes",
22264 nullptr, nullptr, 64L, 1L, 1000L, 0);
22265
22266 static MYSQL_SYSVAR_BOOL(
22267 dedicated_server, srv_dedicated_server,
22268 PLUGIN_VAR_RQCMDARG | PLUGIN_VAR_NOPERSIST | PLUGIN_VAR_READONLY,
22269 "Automatically scale innodb_buffer_pool_size and innodb_redo_log_capacity "
22270 "based on system memory. Also set innodb_flush_method=O_DIRECT_NO_FSYNC, "
22271 "if supported",
22272 nullptr, nullptr, false);
22273
22274 static MYSQL_SYSVAR_DOUBLE(
22275 segment_reserve_factor, fseg_reserve_pct, PLUGIN_VAR_OPCMDARG,
22276 "The segment_reserve_factor is the ratio x/y expressed in percentage,"
22277 " where x is the number of free pages in the segment, and y is the total"
22278 " number of pages in the segment. The number of used pages in the segment"
22279 " is given by (y-x). The number of free pages in the segment (x) will be"
22280 " maintained such that the actual segment_reserve_factor will be >= the"
22281 " requested segment_reserve_factor, which is contained in this variable.",
22282 nullptr, nullptr, FSEG_RESERVE_PCT_DFLT, FSEG_RESERVE_PCT_MIN,
22283 FSEG_RESERVE_PCT_MAX, 0);
22284
22285 /* If the default value of innodb_buffer_pool_size is increased to be more than
22286 BUF_POOL_SIZE_THRESHOLD (srv/srv0start.cc), then srv_buf_pool_instances_default
22287 can be removed and 8 used instead. The problem with the current setup is that
22288 with 128MiB default buffer pool size and 8 instances by default we would emit
22289 a warning when no options are specified. */
22290 static MYSQL_SYSVAR_LONGLONG(buffer_pool_size, srv_buf_pool_curr_size,
22291 PLUGIN_VAR_RQCMDARG |
22292 PLUGIN_VAR_PERSIST_AS_READ_ONLY,
22293 "The size of the memory buffer InnoDB uses to "
22294 "cache data and indexes of its tables.",
22295 nullptr, innodb_buffer_pool_size_update,
22296 static_cast<longlong>(srv_buf_pool_def_size),
22297 static_cast<longlong>(srv_buf_pool_min_size),
22298 longlong{srv_buf_pool_max_size}, 1024 * 1024L);
22299
22300 static MYSQL_SYSVAR_ULONGLONG(
22301 buffer_pool_chunk_size, srv_buf_pool_chunk_unit,
22302 PLUGIN_VAR_RQCMDARG | PLUGIN_VAR_READONLY,
22303 "Size of a single memory chunk within each buffer pool instance"
22304 " for resizing buffer pool. Online buffer pool resizing happens"
22305 " at this granularity.",
22306 nullptr, nullptr, 128 * 1024 * 1024, ulonglong{srv_buf_pool_chunk_unit_min},
22307 ulonglong{srv_buf_pool_chunk_unit_max},
22308 ulonglong{srv_buf_pool_chunk_unit_blk_sz});
22309
22310 #if defined UNIV_DEBUG || defined UNIV_PERF_DEBUG
22311 static MYSQL_SYSVAR_ULONG(page_hash_locks, srv_n_page_hash_locks,
22312 PLUGIN_VAR_OPCMDARG | PLUGIN_VAR_READONLY,
22313 "Number of rw_locks protecting buffer pool "
22314 "page_hash. Rounded up to the next power of 2",
22315 nullptr, nullptr, 16, 1, MAX_PAGE_HASH_LOCKS, 0);
22316 #endif /* defined UNIV_DEBUG || defined UNIV_PERF_DEBUG */
22317
22318 static MYSQL_SYSVAR_BOOL(
22319 validate_tablespace_paths, srv_validate_tablespace_paths,
22320 PLUGIN_VAR_NOCMDARG | PLUGIN_VAR_READONLY,
22321 "Enable validation of tablespace paths against the DD. (enabled by "
22322 "default)."
22323 " Disable with --skip-innodb-validate-tablespace-paths.",
22324 nullptr, nullptr, true);
22325
22326 static MYSQL_SYSVAR_BOOL(use_fdatasync, srv_use_fdatasync, PLUGIN_VAR_NOCMDARG,
22327 "Use fdatasync() instead of the default fsync().",
22328 nullptr, nullptr, false);
22329
22330 // clang-format off
22331 static MYSQL_SYSVAR_ENUM(
22332 doublewrite, dblwr::g_mode, PLUGIN_VAR_OPCMDARG | PLUGIN_VAR_NOPERSIST,
22333 "Enable InnoDB doublewrite buffer (enabled by default)."
22334 " Disable with --skip-innodb-doublewrite.",
22335 nullptr, doublewrite_update, dblwr::Mode::ON, &innodb_doublewrite_typelib);
22336
22337 static MYSQL_SYSVAR_BOOL(
22338 extend_and_initialize, tbsp_extend_and_initialize, PLUGIN_VAR_NOCMDARG,
22339 "Initialize the allocated space by writing zeros (enabled by default).",
22340 nullptr, innodb_extend_and_initialize_update, true);
22341
22342 static MYSQL_SYSVAR_STR(
22343 doublewrite_dir, innobase_doublewrite_dir, PLUGIN_VAR_READONLY,
22344 "Use a separate directory for the doublewrite buffer files, ", nullptr, nullptr,
22345 nullptr);
22346
22347 static MYSQL_SYSVAR_ULONG(
22348 doublewrite_pages, dblwr::n_pages,
22349 PLUGIN_VAR_RQCMDARG | PLUGIN_VAR_READONLY,
22350 "Number of double write pages per thread" , nullptr, nullptr, 0, 0, 512, 0);
22351
22352 static MYSQL_SYSVAR_ULONG(
22353 doublewrite_files, dblwr::n_files,
22354 PLUGIN_VAR_RQCMDARG | PLUGIN_VAR_READONLY,
22355 "Number of double write files", nullptr, nullptr, 0, 0, 256, 0);
22356
22357 static MYSQL_SYSVAR_ULONG(
22358 doublewrite_batch_size, dblwr::batch_size,
22359 PLUGIN_VAR_RQCMDARG | PLUGIN_VAR_READONLY,
22360 "Number of double write pages to write in a batch", nullptr, nullptr,
22361 0, 0, 256, 0);
22362 // clang-format on
22363
22364 static MYSQL_SYSVAR_ULONG(buffer_pool_instances, srv_buf_pool_instances,
22365 PLUGIN_VAR_RQCMDARG | PLUGIN_VAR_READONLY,
22366 "Number of buffer pool instances, set to higher "
22367 "value on high-end machines to increase scalability",
22368 nullptr, nullptr, srv_buf_pool_instances_default, 0,
22369 MAX_BUFFER_POOLS, 0);
22370
22371 static MYSQL_SYSVAR_STR(
22372 buffer_pool_filename, srv_buf_dump_filename,
22373 PLUGIN_VAR_RQCMDARG | PLUGIN_VAR_MEMALLOC,
22374 "Filename to/from which to dump/load the InnoDB buffer pool",
22375 innodb_srv_buf_dump_filename_validate, nullptr,
22376 SRV_BUF_DUMP_FILENAME_DEFAULT);
22377
22378 static MYSQL_SYSVAR_BOOL(buffer_pool_dump_now, innodb_buffer_pool_dump_now,
22379 PLUGIN_VAR_RQCMDARG,
22380 "Trigger an immediate dump of the buffer pool into a "
22381 "file named @@innodb_buffer_pool_filename",
22382 nullptr, buffer_pool_dump_now, false);
22383
22384 static MYSQL_SYSVAR_BOOL(
22385 buffer_pool_dump_at_shutdown, srv_buffer_pool_dump_at_shutdown,
22386 PLUGIN_VAR_RQCMDARG,
22387 "Dump the buffer pool into a file named @@innodb_buffer_pool_filename",
22388 nullptr, nullptr, true);
22389
22390 static MYSQL_SYSVAR_BOOL(
22391 buffer_pool_in_core_file, srv_buffer_pool_in_core_file, PLUGIN_VAR_NOCMDARG,
22392 "This option has no effect if @@core_file is OFF. "
22393 "If @@core_file is ON, and this option is OFF, then the core dump file will"
22394 " be generated only if it is possible to exclude buffer pool from it. "
22395 "As soon as it will be determined that such exclusion is impossible a "
22396 "warning will be emitted and @@core_file will be set to OFF to prevent "
22397 "generating a core dump. "
22398 "If this option is enabled (which is the default), then core dumping "
22399 "logic will not be affected. ",
22400 nullptr, innodb_srv_buffer_pool_in_core_file_update, true);
22401
22402 static MYSQL_SYSVAR_ULONG(
22403 buffer_pool_dump_pct, srv_buf_pool_dump_pct, PLUGIN_VAR_RQCMDARG,
22404 "Dump only the hottest N% of each buffer pool, defaults to 25", nullptr,
22405 nullptr, 25, 1, 100, 0);
22406
22407 static MYSQL_SYSVAR_ULONG(
22408 idle_flush_pct, srv_idle_flush_pct, PLUGIN_VAR_RQCMDARG,
22409 "Up to what percentage of dirty pages to be flushed when server is found"
22410 " idle.",
22411 nullptr, nullptr, srv_idle_flush_pct_default, 0, 100, 0);
22412
22413 #ifdef UNIV_DEBUG
22414 static MYSQL_SYSVAR_STR(buffer_pool_evict, srv_buffer_pool_evict,
22415 PLUGIN_VAR_RQCMDARG, "Evict pages from the buffer pool",
22416 nullptr, innodb_buffer_pool_evict_update, "");
22417 #endif /* UNIV_DEBUG */
22418
22419 static MYSQL_SYSVAR_BOOL(buffer_pool_load_now, innodb_buffer_pool_load_now,
22420 PLUGIN_VAR_RQCMDARG,
22421 "Trigger an immediate load of the buffer pool from a "
22422 "file named @@innodb_buffer_pool_filename",
22423 nullptr, buffer_pool_load_now, false);
22424
22425 static MYSQL_SYSVAR_BOOL(buffer_pool_load_abort, innodb_buffer_pool_load_abort,
22426 PLUGIN_VAR_RQCMDARG,
22427 "Abort a currently running load of the buffer pool",
22428 nullptr, buffer_pool_load_abort, false);
22429
22430 /* there is no point in changing this during runtime, thus readonly */
22431 static MYSQL_SYSVAR_BOOL(
22432 buffer_pool_load_at_startup, srv_buffer_pool_load_at_startup,
22433 PLUGIN_VAR_RQCMDARG | PLUGIN_VAR_READONLY | PLUGIN_VAR_NOPERSIST,
22434 "Load the buffer pool from a file named @@innodb_buffer_pool_filename",
22435 nullptr, nullptr, true);
22436
22437 static MYSQL_SYSVAR_ULONG(lru_scan_depth, srv_LRU_scan_depth,
22438 PLUGIN_VAR_RQCMDARG,
22439 "How deep to scan LRU to keep it clean", nullptr,
22440 nullptr, 1024, 100, UINT32_MAX, 0);
22441
22442 static MYSQL_SYSVAR_ULONG(flush_neighbors, srv_flush_neighbors,
22443 PLUGIN_VAR_OPCMDARG,
22444 "Set to 0 (don't flush neighbors from buffer pool),"
22445 " 1 (flush contiguous neighbors from buffer pool)"
22446 " or 2 (flush neighbors from buffer pool),"
22447 " when flushing a block",
22448 nullptr, nullptr, 0, 0, 2, 0);
22449
22450 static MYSQL_SYSVAR_ULONG(
22451 commit_concurrency, innobase_commit_concurrency, PLUGIN_VAR_RQCMDARG,
22452 "Helps in performance tuning in heavily concurrent environments.",
22453 innobase_commit_concurrency_validate, nullptr, 0, 0, 1000, 0);
22454
22455 static MYSQL_SYSVAR_ULONG(concurrency_tickets, srv_n_free_tickets_to_enter,
22456 PLUGIN_VAR_RQCMDARG,
22457 "Number of times a thread is allowed to enter InnoDB "
22458 "within the same SQL query after it has once got the "
22459 "ticket",
22460 nullptr, nullptr, 5000L, 1L, UINT32_MAX, 0);
22461
22462 static MYSQL_SYSVAR_BOOL(
22463 deadlock_detect, innobase_deadlock_detect, PLUGIN_VAR_NOCMDARG,
22464 "Enable/disable InnoDB deadlock detector (default ON)."
22465 " if set to OFF, deadlock detection is skipped,"
22466 " and we rely on innodb_lock_wait_timeout in case of deadlock.",
22467 nullptr, innobase_deadlock_detect_update, true);
22468
22469 static MYSQL_SYSVAR_LONG(fill_factor, ddl::fill_factor, PLUGIN_VAR_RQCMDARG,
22470 "Percentage of B-tree page filled during bulk insert",
22471 nullptr, nullptr, 100, 10, 100, 0);
22472
22473 static MYSQL_SYSVAR_BOOL(
22474 ft_enable_diag_print, fts_enable_diag_print, PLUGIN_VAR_OPCMDARG,
22475 "Whether to enable additional FTS diagnostic printout ", nullptr, nullptr,
22476 false);
22477
22478 static MYSQL_SYSVAR_BOOL(disable_sort_file_cache, srv_disable_sort_file_cache,
22479 PLUGIN_VAR_OPCMDARG,
22480 "Whether to disable OS system file cache for sort I/O",
22481 nullptr, nullptr, false);
22482
22483 static MYSQL_SYSVAR_STR(ft_aux_table, fts_internal_tbl_name,
22484 PLUGIN_VAR_NOCMDARG | PLUGIN_VAR_MEMALLOC,
22485 "FTS internal auxiliary table to be checked",
22486 innodb_internal_table_validate, nullptr, nullptr);
22487
22488 static MYSQL_SYSVAR_ULONG(ft_cache_size, fts_max_cache_size,
22489 PLUGIN_VAR_RQCMDARG | PLUGIN_VAR_READONLY,
22490 "InnoDB Fulltext search cache size in bytes", nullptr,
22491 nullptr, 8000000, 1600000, 80000000, 0);
22492
22493 static MYSQL_SYSVAR_ULONG(
22494 ft_total_cache_size, fts_max_total_cache_size,
22495 PLUGIN_VAR_RQCMDARG | PLUGIN_VAR_READONLY,
22496 "Total memory allocated for InnoDB Fulltext Search cache", nullptr, nullptr,
22497 640000000, 32000000, 1600000000, 0);
22498
22499 static MYSQL_SYSVAR_ULONG(
22500 ft_result_cache_limit, fts_result_cache_limit, PLUGIN_VAR_RQCMDARG,
22501 "InnoDB Fulltext search query result cache limit in bytes", nullptr,
22502 nullptr, 2000000000L, 1000000L, 4294967295UL, 0);
22503
22504 static MYSQL_SYSVAR_ULONG(
22505 ft_min_token_size, fts_min_token_size,
22506 PLUGIN_VAR_RQCMDARG | PLUGIN_VAR_READONLY,
22507 "InnoDB Fulltext search minimum token size in characters", nullptr, nullptr,
22508 3, 0, 16, 0);
22509
22510 static MYSQL_SYSVAR_ULONG(
22511 ft_max_token_size, fts_max_token_size,
22512 PLUGIN_VAR_RQCMDARG | PLUGIN_VAR_READONLY,
22513 "InnoDB Fulltext search maximum token size in characters", nullptr, nullptr,
22514 FTS_MAX_WORD_LEN_IN_CHAR, 10, FTS_MAX_WORD_LEN_IN_CHAR, 0);
22515
22516 static MYSQL_SYSVAR_ULONG(ft_num_word_optimize, fts_num_word_optimize,
22517 PLUGIN_VAR_OPCMDARG,
22518 "InnoDB Fulltext search number of words to optimize "
22519 "for each optimize table call ",
22520 nullptr, nullptr, 2000, 1000, 10000, 0);
22521
22522 static MYSQL_SYSVAR_ULONG(ft_sort_pll_degree, ddl::fts_parser_threads,
22523 PLUGIN_VAR_RQCMDARG | PLUGIN_VAR_READONLY,
22524 "InnoDB Fulltext search parallel sort degree, will "
22525 "round up to nearest power of 2 number",
22526 nullptr, nullptr, 2, 1, 16, 0);
22527
22528 static MYSQL_SYSVAR_ULONG(sort_buffer_size, srv_sort_buf_size,
22529 PLUGIN_VAR_RQCMDARG | PLUGIN_VAR_READONLY,
22530 "Memory buffer size for index creation", nullptr,
22531 nullptr, 1048576, 65536, 64 << 20, 0);
22532
22533 static MYSQL_SYSVAR_ULONGLONG(
22534 online_alter_log_max_size, srv_online_max_size, PLUGIN_VAR_RQCMDARG,
22535 "Maximum modification log file size for online index creation", nullptr,
22536 nullptr, 128 << 20, 65536, ~0ULL, 0);
22537
22538 static MYSQL_SYSVAR_BOOL(optimize_fulltext_only, innodb_optimize_fulltext_only,
22539 PLUGIN_VAR_NOCMDARG,
22540 "Only optimize the Fulltext index of the table",
22541 nullptr, nullptr, false);
22542
22543 static MYSQL_SYSVAR_ULONG(read_io_threads, srv_n_read_io_threads,
22544 PLUGIN_VAR_RQCMDARG | PLUGIN_VAR_READONLY,
22545 "Number of background read I/O threads in InnoDB.",
22546 nullptr, nullptr, 4, 1, 64, 0);
22547
22548 static MYSQL_SYSVAR_ULONG(write_io_threads, srv_n_write_io_threads,
22549 PLUGIN_VAR_RQCMDARG | PLUGIN_VAR_READONLY,
22550 "Number of background write I/O threads in InnoDB.",
22551 nullptr, nullptr, 4, 1, 64, 0);
22552
22553 static MYSQL_SYSVAR_ULONG(force_recovery, srv_force_recovery,
22554 PLUGIN_VAR_RQCMDARG | PLUGIN_VAR_READONLY,
22555 "Helps to save your data in case the disk image of "
22556 "the database becomes corrupt.",
22557 nullptr, nullptr, 0, 0, 6, 0);
22558
22559 #ifdef UNIV_DEBUG
22560 static MYSQL_SYSVAR_ULONG(force_recovery_crash, srv_force_recovery_crash,
22561 PLUGIN_VAR_RQCMDARG | PLUGIN_VAR_READONLY,
22562 "Kills the server during crash recovery.", nullptr,
22563 nullptr, 0, 0, 100, 0);
22564 #endif /* UNIV_DEBUG */
22565
22566 static MYSQL_SYSVAR_ULONG(page_size, srv_page_size,
22567 PLUGIN_VAR_OPCMDARG | PLUGIN_VAR_READONLY |
22568 PLUGIN_VAR_NOPERSIST,
22569 "Page size to use for all InnoDB tablespaces.",
22570 nullptr, nullptr, UNIV_PAGE_SIZE_DEF,
22571 UNIV_PAGE_SIZE_MIN, UNIV_PAGE_SIZE_MAX, 0);
22572
22573 static MYSQL_SYSVAR_ULONG(
22574 log_buffer_size, srv_log_buffer_size, PLUGIN_VAR_RQCMDARG,
22575 "The size of the buffer which InnoDB uses to write log to the log files"
22576 " on disk.",
22577 nullptr, innodb_log_buffer_size_update, INNODB_LOG_BUFFER_SIZE_DEFAULT,
22578 INNODB_LOG_BUFFER_SIZE_MIN, INNODB_LOG_BUFFER_SIZE_MAX, 1024);
22579
22580 static MYSQL_SYSVAR_ULONGLONG(
22581 log_file_size, srv_log_file_size, PLUGIN_VAR_RQCMDARG | PLUGIN_VAR_READONLY,
22582 "Size of each log file before upgrading to 8.0.30. Deprecated.", nullptr,
22583 nullptr, 48 * 1024 * 1024L, 4 * 1024 * 1024L, ULLONG_MAX, 1024 * 1024L);
22584
22585 static MYSQL_SYSVAR_ULONG(
22586 log_files_in_group, srv_log_n_files,
22587 PLUGIN_VAR_RQCMDARG | PLUGIN_VAR_READONLY,
22588 "Number of log files before upgrading to 8.0.30. Deprecated.", nullptr,
22589 nullptr, 2, 2, 100, 0);
22590
22591 static MYSQL_SYSVAR_ULONGLONG(
22592 redo_log_capacity, srv_redo_log_capacity,
22593 PLUGIN_VAR_RQCMDARG | PLUGIN_VAR_PERSIST_AS_READ_ONLY,
22594 "Limitation for total size of redo log files on disk (expressed in bytes).",
22595 nullptr, innodb_redo_log_capacity_update, 100 * 1024 * 1024,
22596 LOG_CAPACITY_MIN, LOG_CAPACITY_MAX, MB);
22597
22598 #ifdef UNIV_DEBUG_DEDICATED
22599 static MYSQL_SYSVAR_ULONG(
22600 debug_sys_mem_size, srv_debug_system_mem_size,
22601 PLUGIN_VAR_RQCMDARG | PLUGIN_VAR_READONLY,
22602 "System memory size. It's for debuging dedicated server.", NULL, NULL,
22603 48 * 1024 * 1024L, 4 * 1024 * 1024L, ULLONG_MAX, 1024 * 1024L);
22604 #endif /* UNIV_DEBUG_DEDICATED */
22605
22606 static MYSQL_SYSVAR_ULONG(log_write_ahead_size, srv_log_write_ahead_size,
22607 PLUGIN_VAR_RQCMDARG,
22608 "Log write ahead unit size to avoid read-on-write,"
22609 " it should match the OS cache block IO size.",
22610 nullptr, innodb_log_write_ahead_size_update,
22611 INNODB_LOG_WRITE_AHEAD_SIZE_DEFAULT,
22612 INNODB_LOG_WRITE_AHEAD_SIZE_MIN,
22613 INNODB_LOG_WRITE_AHEAD_SIZE_MAX,
22614 OS_FILE_LOG_BLOCK_SIZE);
22615
22616 static MYSQL_SYSVAR_BOOL(
22617 log_writer_threads, srv_log_writer_threads, PLUGIN_VAR_RQCMDARG,
22618 "Whether the log writer threads should be activated (ON), or write/flush "
22619 "of the redo log should be done by each thread individually (OFF).",
22620 nullptr, innodb_log_writer_threads_update, true);
22621
22622 static MYSQL_SYSVAR_UINT(
22623 log_spin_cpu_abs_lwm, srv_log_spin_cpu_abs_lwm, PLUGIN_VAR_RQCMDARG,
22624 "Minimum value of cpu time for which spin-delay is used."
22625 " Expressed in percentage of single cpu core.",
22626 nullptr, nullptr, INNODB_LOG_SPIN_CPU_ABS_LWM_DEFAULT, 0, UINT32_MAX, 0);
22627
22628 static MYSQL_SYSVAR_UINT(
22629 log_spin_cpu_pct_hwm, srv_log_spin_cpu_pct_hwm, PLUGIN_VAR_RQCMDARG,
22630 "Maximum value of cpu time for which spin-delay is used."
22631 " Expressed in percentage of all cpu cores.",
22632 nullptr, nullptr, INNODB_LOG_SPIN_CPU_PCT_HWM_DEFAULT, 0, 100, 0);
22633
22634 static MYSQL_SYSVAR_ULONG(
22635 log_wait_for_flush_spin_hwm, srv_log_wait_for_flush_spin_hwm,
22636 PLUGIN_VAR_RQCMDARG,
22637 "Maximum value of average log flush time for which spin-delay is used."
22638 " When flushing takes longer, user threads no longer spin when waiting for"
22639 "flushed redo. Expressed in microseconds.",
22640 nullptr, nullptr, INNODB_LOG_WAIT_FOR_FLUSH_SPIN_HWM_DEFAULT, 0, UINT32_MAX,
22641 0);
22642
22643 #ifdef ENABLE_EXPERIMENT_SYSVARS
22644
22645 static MYSQL_SYSVAR_ULONG(
22646 log_write_events, srv_log_write_events,
22647 PLUGIN_VAR_RQCMDARG | PLUGIN_VAR_READONLY,
22648 "Number of events used for notifications about log write.", NULL, NULL,
22649 INNODB_LOG_EVENTS_DEFAULT, INNODB_LOG_EVENTS_MIN, INNODB_LOG_EVENTS_MAX, 0);
22650
22651 static MYSQL_SYSVAR_ULONG(
22652 log_flush_events, srv_log_flush_events,
22653 PLUGIN_VAR_RQCMDARG | PLUGIN_VAR_READONLY,
22654 "Number of events used for notifications about log flush.", NULL, NULL,
22655 INNODB_LOG_EVENTS_DEFAULT, INNODB_LOG_EVENTS_MIN, INNODB_LOG_EVENTS_MAX, 0);
22656
22657 static MYSQL_SYSVAR_ULONG(
22658 log_recent_written_size, srv_log_recent_written_size,
22659 PLUGIN_VAR_RQCMDARG | PLUGIN_VAR_READONLY,
22660 "Size of a small buffer, which allows concurrent writes to log buffer.",
22661 NULL, NULL, INNODB_LOG_RECENT_WRITTEN_SIZE_DEFAULT,
22662 INNODB_LOG_RECENT_WRITTEN_SIZE_MIN, INNODB_LOG_RECENT_WRITTEN_SIZE_MAX, 0);
22663
22664 static MYSQL_SYSVAR_ULONG(
22665 log_recent_closed_size, srv_log_recent_closed_size,
22666 PLUGIN_VAR_RQCMDARG | PLUGIN_VAR_READONLY,
22667 "Size of a small buffer, which allows to break requirement for total order"
22668 " of dirty pages, when they are added to flush lists.",
22669 NULL, NULL, INNODB_LOG_RECENT_CLOSED_SIZE_DEFAULT,
22670 INNODB_LOG_RECENT_CLOSED_SIZE_MIN, INNODB_LOG_RECENT_CLOSED_SIZE_MAX, 0);
22671
22672 static MYSQL_SYSVAR_ULONG(
22673 log_wait_for_write_spin_delay, srv_log_wait_for_write_spin_delay,
22674 PLUGIN_VAR_RQCMDARG,
22675 "Number of spin iterations, when spinning and waiting for log buffer"
22676 " written up to given LSN, before we fallback to loop with sleeps."
22677 " This is not used when user thread has to wait for log flushed to disk.",
22678 NULL, NULL, INNODB_LOG_WAIT_FOR_WRITE_SPIN_DELAY_DEFAULT, 0, UINT32_MAX, 0);
22679
22680 static MYSQL_SYSVAR_ULONG(
22681 log_wait_for_write_timeout, srv_log_wait_for_write_timeout,
22682 PLUGIN_VAR_RQCMDARG,
22683 "Timeout used when waiting for redo write (microseconds).", NULL, NULL,
22684 INNODB_LOG_WAIT_FOR_WRITE_TIMEOUT_DEFAULT, 0, UINT32_MAX, 0);
22685
22686 static MYSQL_SYSVAR_ULONG(
22687 log_wait_for_flush_spin_delay, srv_log_wait_for_flush_spin_delay,
22688 PLUGIN_VAR_RQCMDARG,
22689 "Number of spin iterations, when spinning and waiting for log flushed.",
22690 NULL, NULL, INNODB_LOG_WAIT_FOR_FLUSH_SPIN_DELAY_DEFAULT, 0, UINT32_MAX, 0);
22691
22692 static MYSQL_SYSVAR_ULONG(
22693 log_wait_for_flush_timeout, srv_log_wait_for_flush_timeout,
22694 PLUGIN_VAR_RQCMDARG,
22695 "Timeout used when waiting for redo flush (microseconds).", NULL, NULL,
22696 INNODB_LOG_WAIT_FOR_FLUSH_TIMEOUT_DEFAULT, 0, UINT32_MAX, 0);
22697
22698 static MYSQL_SYSVAR_ULONG(
22699 log_write_max_size, srv_log_write_max_size, PLUGIN_VAR_RQCMDARG,
22700 "Size available for next write, which satisfies log_writer thread"
22701 " when it follows links in recent written buffer.",
22702 NULL, NULL, INNODB_LOG_WRITE_MAX_SIZE_DEFAULT, 0, UINT32_MAX,
22703 OS_FILE_LOG_BLOCK_SIZE);
22704
22705 static MYSQL_SYSVAR_ULONG(
22706 log_writer_spin_delay, srv_log_writer_spin_delay, PLUGIN_VAR_RQCMDARG,
22707 "Number of spin iterations, for which log writer thread is waiting"
22708 " for new data to write without sleeping.",
22709 NULL, NULL, INNODB_LOG_WRITER_SPIN_DELAY_DEFAULT, 0, UINT32_MAX, 0);
22710
22711 static MYSQL_SYSVAR_ULONG(
22712 log_writer_timeout, srv_log_writer_timeout, PLUGIN_VAR_RQCMDARG,
22713 "Initial timeout used to wait on event in log writer thread (microseconds)",
22714 NULL, NULL, INNODB_LOG_WRITER_TIMEOUT_DEFAULT, 0, UINT32_MAX, 0);
22715
22716 static MYSQL_SYSVAR_ULONG(
22717 log_checkpoint_every, srv_log_checkpoint_every, PLUGIN_VAR_RQCMDARG,
22718 "Checkpoints are executed at least every that many milliseconds.", NULL,
22719 NULL, INNODB_LOG_CHECKPOINT_EVERY_DEFAULT, 0, UINT32_MAX, 0);
22720
22721 static MYSQL_SYSVAR_ULONG(
22722 log_flusher_spin_delay, srv_log_flusher_spin_delay, PLUGIN_VAR_RQCMDARG,
22723 "Number of spin iterations, for which log flusher thread is waiting"
22724 " for new data to flush, without sleeping.",
22725 NULL, NULL, INNODB_LOG_FLUSHER_SPIN_DELAY_DEFAULT, 0, UINT32_MAX, 0);
22726
22727 static MYSQL_SYSVAR_ULONG(log_flusher_timeout, srv_log_flusher_timeout,
22728 PLUGIN_VAR_RQCMDARG,
22729 "Initial timeout used to wait on event in log "
22730 "flusher thread (microseconds)",
22731 NULL, NULL, INNODB_LOG_FLUSHER_TIMEOUT_DEFAULT, 0,
22732 UINT32_MAX, 0);
22733
22734 static MYSQL_SYSVAR_ULONG(
22735 log_write_notifier_spin_delay, srv_log_write_notifier_spin_delay,
22736 PLUGIN_VAR_RQCMDARG,
22737 "Number of spin iterations, for which log write notifier thread is waiting"
22738 " for advanced write_lsn, without sleeping.",
22739 NULL, NULL, INNODB_LOG_WRITE_NOTIFIER_SPIN_DELAY_DEFAULT, 0, UINT32_MAX, 0);
22740
22741 static MYSQL_SYSVAR_ULONG(
22742 log_write_notifier_timeout, srv_log_write_notifier_timeout,
22743 PLUGIN_VAR_RQCMDARG,
22744 "Initial timeout used to wait on event in log write notifier thread"
22745 " (microseconds)",
22746 NULL, NULL, INNODB_LOG_WRITE_NOTIFIER_TIMEOUT_DEFAULT, 0, UINT32_MAX, 0);
22747
22748 static MYSQL_SYSVAR_ULONG(
22749 log_flush_notifier_spin_delay, srv_log_flush_notifier_spin_delay,
22750 PLUGIN_VAR_RQCMDARG,
22751 "Number of spin iterations, for which log flush notifier thread is waiting"
22752 " for advanced flushed_to_disk_lsn, without sleeping.",
22753 NULL, NULL, INNODB_LOG_FLUSH_NOTIFIER_SPIN_DELAY_DEFAULT, 0, UINT32_MAX, 0);
22754
22755 static MYSQL_SYSVAR_ULONG(
22756 log_flush_notifier_timeout, srv_log_flush_notifier_timeout,
22757 PLUGIN_VAR_RQCMDARG,
22758 "Initial timeout used to wait on event in log flush notifier thread"
22759 " (microseconds)",
22760 NULL, NULL, INNODB_LOG_FLUSH_NOTIFIER_TIMEOUT_DEFAULT, 0, UINT32_MAX, 0);
22761
22762 #endif /* ENABLE_EXPERIMENT_SYSVARS */
22763
22764 static MYSQL_SYSVAR_UINT(
22765 old_blocks_pct, innobase_old_blocks_pct, PLUGIN_VAR_RQCMDARG,
22766 "Percentage of the buffer pool to reserve for 'old' blocks.", nullptr,
22767 innodb_old_blocks_pct_update, 100 * 3 / 8, 5, 95, 0);
22768
22769 static MYSQL_SYSVAR_UINT(
22770 old_blocks_time, buf_LRU_old_threshold, PLUGIN_VAR_RQCMDARG,
22771 "Move blocks to the 'new' end of the buffer pool if the first access"
22772 " was at least this many milliseconds ago."
22773 " The timeout is disabled if 0.",
22774 nullptr, nullptr, 1000, 0, UINT32_MAX, 0);
22775
22776 static MYSQL_SYSVAR_LONG(
22777 open_files, innobase_open_files, PLUGIN_VAR_RQCMDARG | PLUGIN_VAR_READONLY,
22778 "How many files at the maximum InnoDB keeps open at the same time.",
22779 nullptr, nullptr, 0L, 0L, INT32_MAX, 0);
22780
22781 static MYSQL_SYSVAR_ULONG(
22782 sync_spin_loops, srv_n_spin_wait_rounds, PLUGIN_VAR_RQCMDARG,
22783 "Count of spin-loop rounds in InnoDB mutexes (30 by default)", nullptr,
22784 nullptr, 30L, 0L, UINT32_MAX, 0);
22785
22786 static MYSQL_SYSVAR_ULONG(
22787 spin_wait_delay, srv_spin_wait_delay, PLUGIN_VAR_OPCMDARG,
22788 "Maximum delay between polling for a spin lock (6 by default)", nullptr,
22789 nullptr, 6L, 0L, 1000, 0);
22790
22791 static MYSQL_SYSVAR_ULONG(spin_wait_pause_multiplier,
22792 ut::spin_wait_pause_multiplier, PLUGIN_VAR_RQCMDARG,
22793 "Controls how many times in a row to use a PAUSE "
22794 "instruction to achieve one unit of delay in a spin "
22795 "lock (see @@innodb_spin_wait_delay), defaults to 50",
22796 nullptr, nullptr, 50, 0, 100, 0);
22797
22798 static MYSQL_SYSVAR_ULONGLONG(
22799 fsync_threshold, os_fsync_threshold, PLUGIN_VAR_RQCMDARG,
22800 "The value of this variable determines how often InnoDB calls fsync when "
22801 "creating a new file. Default is zero which would make InnoDB flush the "
22802 "entire file at once before closing it.",
22803 nullptr, nullptr, 0, 0, ~0ULL, UNIV_PAGE_SIZE);
22804
22805 static MYSQL_SYSVAR_ULONG(thread_concurrency, srv_thread_concurrency,
22806 PLUGIN_VAR_RQCMDARG,
22807 "Helps in performance tuning in heavily concurrent "
22808 "environments. Sets the maximum number of threads "
22809 "allowed inside InnoDB. Value 0 will disable the "
22810 "thread throttling.",
22811 nullptr, innodb_thread_concurrency_update, 0, 0, 1000,
22812 0);
22813
22814 static MYSQL_SYSVAR_ULONG(
22815 adaptive_max_sleep_delay, srv_adaptive_max_sleep_delay, PLUGIN_VAR_RQCMDARG,
22816 "The upper limit of the sleep delay in usec. Value of 0 disables it.",
22817 nullptr, nullptr, 150000, /* Default setting */
22818 0, /* Minimum value */
22819 1000000, 0); /* Maximum value */
22820
22821 static MYSQL_SYSVAR_ULONG(
22822 thread_sleep_delay, srv_thread_sleep_delay, PLUGIN_VAR_RQCMDARG,
22823 "Time of innodb thread sleeping before joining InnoDB queue (usec)."
22824 " Value 0 disable a sleep",
22825 nullptr, nullptr, 10000L, 0L, 1000000L, 0);
22826
22827 static MYSQL_SYSVAR_STR(data_file_path, innobase_data_file_path,
22828 PLUGIN_VAR_RQCMDARG | PLUGIN_VAR_READONLY |
22829 PLUGIN_VAR_NOPERSIST,
22830 "Path to individual files and their sizes.", nullptr,
22831 nullptr, (char *)"ibdata1:12M:autoextend");
22832
22833 static MYSQL_SYSVAR_STR(temp_data_file_path, innobase_temp_data_file_path,
22834 PLUGIN_VAR_RQCMDARG | PLUGIN_VAR_READONLY |
22835 PLUGIN_VAR_NOPERSIST,
22836 "Path to files and their sizes making temp-tablespace.",
22837 nullptr, nullptr, (char *)"ibtmp1:12M:autoextend");
22838
22839 static MYSQL_SYSVAR_STR(
22840 undo_directory, srv_undo_dir,
22841 PLUGIN_VAR_RQCMDARG | PLUGIN_VAR_READONLY | PLUGIN_VAR_NOPERSIST,
22842 "Directory where undo tablespace files live, this path can be absolute.",
22843 nullptr, nullptr, nullptr);
22844
22845 static MYSQL_SYSVAR_STR(
22846 temp_tablespaces_dir, ibt::srv_temp_dir,
22847 PLUGIN_VAR_RQCMDARG | PLUGIN_VAR_READONLY | PLUGIN_VAR_NOPERSIST,
22848 "Directory where temp tablespace files live, this path can be absolute.",
22849 nullptr, nullptr, nullptr);
22850
22851 static MYSQL_SYSVAR_ULONG(undo_tablespaces, srv_undo_tablespaces,
22852 PLUGIN_VAR_RQCMDARG | PLUGIN_VAR_NOPERSIST,
22853 "Number of undo tablespaces to use. (deprecated)",
22854 nullptr, innodb_undo_tablespaces_update,
22855 FSP_IMPLICIT_UNDO_TABLESPACES, /* Default setting */
22856 FSP_MIN_UNDO_TABLESPACES, /* Minimum value */
22857 FSP_MAX_UNDO_TABLESPACES, 0); /* Maximum value */
22858
22859 static MYSQL_SYSVAR_ULONGLONG(
22860 max_undo_log_size, srv_max_undo_tablespace_size, PLUGIN_VAR_OPCMDARG,
22861 "Maximum size of an UNDO tablespace in MB (If an UNDO tablespace grows"
22862 " beyond this size it will be truncated in due course). ",
22863 nullptr, nullptr, 1024 * 1024 * 1024L, 10 * 1024 * 1024L, ~0ULL, 0);
22864
22865 static MYSQL_SYSVAR_ULONG(
22866 purge_rseg_truncate_frequency, srv_purge_rseg_truncate_frequency,
22867 PLUGIN_VAR_OPCMDARG,
22868 "Dictates rate at which UNDO records are purged. Value N means"
22869 " purge rollback segment(s) on every Nth iteration of purge invocation",
22870 nullptr, nullptr, 128, 1, 128, 0);
22871
22872 static MYSQL_SYSVAR_BOOL(undo_log_truncate, srv_undo_log_truncate,
22873 PLUGIN_VAR_OPCMDARG,
22874 "Enable or Disable Truncate of UNDO tablespace.",
22875 nullptr, nullptr, true);
22876
22877 /* This is the number of rollback segments per undo tablespace.
22878 This applies to the temporary tablespace, the system tablespace,
22879 and all undo tablespaces. */
22880 static MYSQL_SYSVAR_ULONG(
22881 rollback_segments, srv_rollback_segments, PLUGIN_VAR_OPCMDARG,
22882 "Number of rollback segments per tablespace. This applies to the system"
22883 " tablespace, the temporary tablespace & any undo tablespace.",
22884 nullptr, innodb_rollback_segments_update,
22885 FSP_MAX_ROLLBACK_SEGMENTS, /* Default setting */
22886 1, /* Minimum value */
22887 FSP_MAX_ROLLBACK_SEGMENTS, 0); /* Maximum value */
22888
22889 static MYSQL_SYSVAR_BOOL(undo_log_encrypt, srv_undo_log_encrypt,
22890 PLUGIN_VAR_OPCMDARG,
22891 "Enable or disable Encrypt of UNDO tablespace.",
22892 validate_innodb_undo_log_encrypt, nullptr, false);
22893
22894 static MYSQL_SYSVAR_LONG(
22895 autoinc_lock_mode, innobase_autoinc_lock_mode,
22896 PLUGIN_VAR_RQCMDARG | PLUGIN_VAR_READONLY,
22897 "The AUTOINC lock modes supported by InnoDB:"
22898 " 0 => Old style AUTOINC locking (for backward compatibility);"
22899 " 1 => New style AUTOINC locking;"
22900 " 2 => No AUTOINC locking (unsafe for SBR)",
22901 nullptr, nullptr, AUTOINC_NO_LOCKING, /* Default setting */
22902 AUTOINC_OLD_STYLE_LOCKING, /* Minimum value */
22903 AUTOINC_NO_LOCKING, 0); /* Maximum value */
22904
22905 static MYSQL_SYSVAR_STR(version, innodb_version_str,
22906 PLUGIN_VAR_NOCMDOPT | PLUGIN_VAR_READONLY |
22907 PLUGIN_VAR_NOPERSIST,
22908 "InnoDB version", nullptr, nullptr, INNODB_VERSION_STR);
22909
22910 static MYSQL_SYSVAR_BOOL(use_native_aio, srv_use_native_aio,
22911 PLUGIN_VAR_NOCMDARG | PLUGIN_VAR_READONLY,
22912 "Use native AIO if supported on this platform.",
22913 nullptr, nullptr, true);
22914
22915 #ifdef HAVE_LIBNUMA
22916 static MYSQL_SYSVAR_BOOL(
22917 numa_interleave, srv_numa_interleave,
22918 PLUGIN_VAR_NOCMDARG | PLUGIN_VAR_READONLY,
22919 "Use NUMA interleave memory policy to allocate InnoDB buffer pool.",
22920 nullptr, nullptr, false);
22921 #endif /* HAVE_LIBNUMA */
22922
22923 static MYSQL_SYSVAR_BOOL(
22924 api_enable_binlog, ib_binlog_enabled,
22925 PLUGIN_VAR_NOCMDARG | PLUGIN_VAR_READONLY,
22926 "Enable binlog for applications direct access InnoDB through InnoDB APIs",
22927 nullptr, nullptr, false);
22928
22929 static MYSQL_SYSVAR_BOOL(
22930 api_enable_mdl, ib_mdl_enabled, PLUGIN_VAR_NOCMDARG | PLUGIN_VAR_READONLY,
22931 "Enable MDL for applications direct access InnoDB through InnoDB APIs",
22932 nullptr, nullptr, false);
22933
22934 static MYSQL_SYSVAR_BOOL(
22935 api_disable_rowlock, ib_disable_row_lock,
22936 PLUGIN_VAR_NOCMDARG | PLUGIN_VAR_READONLY,
22937 "Disable row lock when direct access InnoDB through InnoDB APIs", nullptr,
22938 nullptr, false);
22939
22940 static MYSQL_SYSVAR_ULONG(api_trx_level, ib_trx_level_setting,
22941 PLUGIN_VAR_OPCMDARG,
22942 "InnoDB API transaction isolation level", nullptr,
22943 nullptr, 0, /* Default setting */
22944 0, /* Minimum value */
22945 3, 0); /* Maximum value */
22946
22947 static MYSQL_SYSVAR_ULONG(api_bk_commit_interval, ib_bk_commit_interval,
22948 PLUGIN_VAR_OPCMDARG,
22949 "Background commit interval in seconds", nullptr,
22950 nullptr, 5, /* Default setting */
22951 1, /* Minimum value */
22952 1024 * 1024 * 1024, 0); /* Maximum value */
22953
22954 static MYSQL_SYSVAR_ENUM(change_buffering, innodb_change_buffering,
22955 PLUGIN_VAR_RQCMDARG,
22956 "Buffer changes to reduce random access:"
22957 " OFF, ON, inserting, deleting, changing, or purging.",
22958 nullptr, nullptr, IBUF_USE_ALL,
22959 &innodb_change_buffering_typelib);
22960
22961 static MYSQL_SYSVAR_UINT(
22962 change_buffer_max_size, srv_change_buffer_max_size, PLUGIN_VAR_RQCMDARG,
22963 "Maximum on-disk size of change buffer in terms of percentage"
22964 " of the buffer pool.",
22965 nullptr, innodb_change_buffer_max_size_update, CHANGE_BUFFER_DEFAULT_SIZE,
22966 0, 50, 0);
22967
22968 static MYSQL_SYSVAR_ENUM(
22969 stats_method, srv_innodb_stats_method, PLUGIN_VAR_RQCMDARG,
22970 "Specifies how InnoDB index statistics collection code should"
22971 " treat NULLs. Possible values are NULLS_EQUAL (default),"
22972 " NULLS_UNEQUAL and NULLS_IGNORED",
22973 nullptr, nullptr, SRV_STATS_NULLS_EQUAL, &innodb_stats_method_typelib);
22974
22975 #if defined UNIV_DEBUG || defined UNIV_IBUF_DEBUG
22976 static MYSQL_SYSVAR_UINT(
22977 change_buffering_debug, ibuf_debug, PLUGIN_VAR_RQCMDARG,
22978 "Debug flags for InnoDB change buffering (0=none, 1= evict the blocks from "
22979 "the buffer pool as much possible, 2=crash at merge)",
22980 nullptr, nullptr, 0, 0, 2, 0);
22981
22982 static MYSQL_SYSVAR_BOOL(disable_background_merge,
22983 srv_ibuf_disable_background_merge,
22984 PLUGIN_VAR_NOCMDARG | PLUGIN_VAR_RQCMDARG,
22985 "Disable change buffering merges by the master thread",
22986 nullptr, nullptr, false);
22987
22988 static MYSQL_SYSVAR_ENUM(
22989 compress_debug, srv_debug_compress, PLUGIN_VAR_RQCMDARG,
22990 "Compress all tables, without specifying the COMPRESS table attribute",
22991 nullptr, nullptr, Compression::NONE, &innodb_debug_compress_typelib);
22992 #endif /* UNIV_DEBUG || UNIV_IBUF_DEBUG */
22993
22994 static MYSQL_SYSVAR_BOOL(
22995 random_read_ahead, srv_random_read_ahead, PLUGIN_VAR_NOCMDARG,
22996 "Whether to use read ahead for random access within an extent.", nullptr,
22997 nullptr, false);
22998
22999 static MYSQL_SYSVAR_ULONG(
23000 read_ahead_threshold, srv_read_ahead_threshold, PLUGIN_VAR_RQCMDARG,
23001 "Number of pages that must be accessed sequentially for InnoDB to"
23002 " trigger a readahead.",
23003 nullptr, nullptr, 56, 0, 64, 0);
23004
23005 static MYSQL_SYSVAR_STR(monitor_enable, innobase_enable_monitor_counter,
23006 PLUGIN_VAR_RQCMDARG, "Turn on a monitor counter",
23007 innodb_monitor_validate, innodb_enable_monitor_update,
23008 nullptr);
23009
23010 static MYSQL_SYSVAR_STR(monitor_disable, innobase_disable_monitor_counter,
23011 PLUGIN_VAR_RQCMDARG, "Turn off a monitor counter",
23012 innodb_monitor_validate, innodb_disable_monitor_update,
23013 nullptr);
23014
23015 static MYSQL_SYSVAR_STR(monitor_reset, innobase_reset_monitor_counter,
23016 PLUGIN_VAR_RQCMDARG, "Reset a monitor counter",
23017 innodb_monitor_validate, innodb_reset_monitor_update,
23018 nullptr);
23019
23020 static MYSQL_SYSVAR_STR(monitor_reset_all, innobase_reset_all_monitor_counter,
23021 PLUGIN_VAR_RQCMDARG,
23022 "Reset all values for a monitor counter",
23023 innodb_monitor_validate,
23024 innodb_reset_all_monitor_update, nullptr);
23025
23026 static MYSQL_SYSVAR_BOOL(status_output, srv_print_innodb_monitor,
23027 PLUGIN_VAR_OPCMDARG,
23028 "Enable InnoDB monitor output to the error log.",
23029 nullptr, nullptr, false);
23030
23031 static MYSQL_SYSVAR_BOOL(status_output_locks, srv_print_innodb_lock_monitor,
23032 PLUGIN_VAR_OPCMDARG,
23033 "Enable InnoDB lock monitor output to the error log."
23034 " Requires innodb_status_output=ON.",
23035 nullptr, nullptr, false);
23036
23037 static MYSQL_SYSVAR_BOOL(
23038 print_all_deadlocks, srv_print_all_deadlocks, PLUGIN_VAR_OPCMDARG,
23039 "Print all deadlocks to MySQL error log (off by default)", nullptr, nullptr,
23040 false);
23041
23042 static MYSQL_SYSVAR_ULONG(
23043 compression_failure_threshold_pct, zip_failure_threshold_pct,
23044 PLUGIN_VAR_OPCMDARG,
23045 "If the compression failure rate of a table is greater than this number"
23046 " more padding is added to the pages to reduce the failures. A value of"
23047 " zero implies no padding",
23048 nullptr, nullptr, 5, 0, 100, 0);
23049
23050 static MYSQL_SYSVAR_ULONG(
23051 compression_pad_pct_max, zip_pad_max, PLUGIN_VAR_OPCMDARG,
23052 "Percentage of empty space on a data page that can be reserved"
23053 " to make the page compressible.",
23054 nullptr, nullptr, 50, 0, 75, 0);
23055
23056 static MYSQL_SYSVAR_BOOL(read_only, srv_read_only_mode,
23057 PLUGIN_VAR_OPCMDARG | PLUGIN_VAR_READONLY |
23058 PLUGIN_VAR_NOPERSIST,
23059 "Start InnoDB in read only mode (off by default)",
23060 nullptr, nullptr, false);
23061
23062 static MYSQL_SYSVAR_BOOL(
23063 cmp_per_index_enabled, srv_cmp_per_index_enabled, PLUGIN_VAR_OPCMDARG,
23064 "Enable INFORMATION_SCHEMA.innodb_cmp_per_index,"
23065 " may have negative impact on performance (off by default)",
23066 nullptr, innodb_cmp_per_index_update, false);
23067
23068 static MYSQL_SYSVAR_ENUM(
23069 default_row_format, innodb_default_row_format, PLUGIN_VAR_RQCMDARG,
23070 "The default ROW FORMAT for all innodb tables created without explicit"
23071 " ROW_FORMAT. Possible values are REDUNDANT, COMPACT, and DYNAMIC."
23072 " The ROW_FORMAT value COMPRESSED is not allowed",
23073 nullptr, nullptr, DEFAULT_ROW_FORMAT_DYNAMIC,
23074 &innodb_default_row_format_typelib);
23075
23076 static MYSQL_SYSVAR_STR(
23077 redo_log_archive_dirs, meb::redo_log_archive_dirs,
23078 PLUGIN_VAR_RQCMDARG | PLUGIN_VAR_MEMALLOC,
23079 "Limit the location of the redo log archive to the semicolon "
23080 "separated list of labeled directories",
23081 /*validate_func*/ meb::validate_redo_log_archive_dirs,
23082 /*update_func*/ nullptr, /*default*/ nullptr);
23083
23084 static MYSQL_SYSVAR_BOOL(redo_log_encrypt, srv_redo_log_encrypt,
23085 PLUGIN_VAR_OPCMDARG,
23086 "Enable or disable Encryption of REDO tablespace.",
23087 validate_innodb_redo_log_encrypt, nullptr, false);
23088
23089 static MYSQL_SYSVAR_BOOL(
23090 print_ddl_logs, srv_print_ddl_logs, PLUGIN_VAR_OPCMDARG,
23091 "Print all DDl logs to MySQL error log (off by default)", nullptr, nullptr,
23092 false);
23093
23094 #ifdef UNIV_DEBUG
23095 static MYSQL_SYSVAR_UINT(trx_rseg_n_slots_debug, trx_rseg_n_slots_debug,
23096 PLUGIN_VAR_RQCMDARG,
23097 "Debug flags for InnoDB to limit TRX_RSEG_N_SLOTS for "
23098 "trx_rsegf_undo_find_free()",
23099 nullptr, nullptr, 0, 0, 1024, 0);
23100
23101 static MYSQL_SYSVAR_UINT(
23102 limit_optimistic_insert_debug, btr_cur_limit_optimistic_insert_debug,
23103 PLUGIN_VAR_RQCMDARG,
23104 "Artificially limit the number of records per B-tree page (0=unlimited).",
23105 nullptr, nullptr, 0, 0, UINT32_MAX, 0);
23106
23107 static MYSQL_SYSVAR_BOOL(trx_purge_view_update_only_debug,
23108 srv_purge_view_update_only_debug, PLUGIN_VAR_NOCMDARG,
23109 "Pause actual purging any delete-marked records, but "
23110 "merely update the purge view."
23111 " It is to create artificially the situation the "
23112 "purge view have been updated"
23113 " but the each purges were not done yet.",
23114 nullptr, nullptr, false);
23115 // clang-format off
23116 static MYSQL_SYSVAR_ULONG(
23117 fil_make_page_dirty_debug,
23118 srv_fil_make_page_dirty_debug, PLUGIN_VAR_OPCMDARG,
23119 "Make the first page of the given tablespace dirty.",
23120 nullptr, innodb_make_page_dirty, UINT32_MAX, 0, UINT32_MAX, 0);
23121 // clang-format on
23122
23123 static MYSQL_SYSVAR_ULONG(saved_page_number_debug, srv_saved_page_number_debug,
23124 PLUGIN_VAR_OPCMDARG, "An InnoDB page number.",
23125 nullptr, innodb_save_page_no, 0, 0, UINT32_MAX, 0);
23126
23127 static MYSQL_SYSVAR_BOOL(page_cleaner_disabled_debug,
23128 innodb_page_cleaner_disabled_debug,
23129 PLUGIN_VAR_OPCMDARG, "Disable page cleaner", nullptr,
23130 buf_flush_page_cleaner_disabled_debug_update, false);
23131
23132 static MYSQL_SYSVAR_BOOL(dict_stats_disabled_debug,
23133 innodb_dict_stats_disabled_debug, PLUGIN_VAR_OPCMDARG,
23134 "Disable dict_stats thread", nullptr,
23135 dict_stats_disabled_debug_update, false);
23136
23137 static MYSQL_SYSVAR_BOOL(master_thread_disabled_debug,
23138 srv_master_thread_disabled_debug, PLUGIN_VAR_OPCMDARG,
23139 "Disable master thread", nullptr,
23140 srv_master_thread_disabled_debug_update, false);
23141
23142 static MYSQL_SYSVAR_BOOL(sync_debug, srv_sync_debug,
23143 PLUGIN_VAR_OPCMDARG | PLUGIN_VAR_READONLY,
23144 "Enable the sync debug checks", nullptr, nullptr,
23145 false);
23146
23147 static MYSQL_SYSVAR_BOOL(buffer_pool_debug, srv_buf_pool_debug,
23148 PLUGIN_VAR_OPCMDARG | PLUGIN_VAR_READONLY,
23149 "Enable buffer pool debug", nullptr, nullptr, false);
23150
23151 static MYSQL_SYSVAR_BOOL(ddl_log_crash_reset_debug,
23152 innodb_ddl_log_crash_reset_debug, PLUGIN_VAR_OPCMDARG,
23153 "Reset all crash injection counters to 1", nullptr,
23154 ddl_log_crash_reset, false);
23155 #endif /* UNIV_DEBUG */
23156
23157 static MYSQL_SYSVAR_STR(directories, srv_innodb_directories,
23158 PLUGIN_VAR_RQCMDARG | PLUGIN_VAR_READONLY |
23159 PLUGIN_VAR_NOPERSIST,
23160 "List of directories 'dir1;dir2;..;dirN' to scan for "
23161 "tablespace files. Default is to scan "
23162 "'innodb-data-home-dir;innodb-undo-directory;datadir'",
23163 nullptr, nullptr, nullptr);
23164
23165 #ifdef UNIV_DEBUG
23166 /** Use this variable innodb_interpreter to execute debug code within InnoDB.
23167 The output is stored in the innodb_interpreter_output variable. */
23168 static MYSQL_THDVAR_STR(interpreter, PLUGIN_VAR_OPCMDARG | PLUGIN_VAR_NOPERSIST,
23169 "Invoke InnoDB test interpreter with commands"
23170 " to be executed.",
23171 ib_interpreter_check, ib_interpreter_update, "init");
23172
23173 /** When testing commands are executed in the innodb_interpreter variable, the
23174 output is stored in this innodb_interpreter_output variable. */
23175 static MYSQL_THDVAR_STR(interpreter_output,
23176 PLUGIN_VAR_READONLY | PLUGIN_VAR_OPCMDARG |
23177 PLUGIN_VAR_MEMALLOC | PLUGIN_VAR_NOPERSIST,
23178 "Output from InnoDB testing module (ut0test).", nullptr,
23179 nullptr, "The Default Value");
23180
23181 char **thd_innodb_interpreter_output(THD *thd) {
23182 return (MYSQL_SYSVAR_NAME(interpreter_output)
23183 .resolve(thd, MYSQL_SYSVAR_NAME(interpreter_output).offset));
23184 }
23185
23186 char **thd_innodb_interpreter(THD *thd) {
23187 return MYSQL_SYSVAR_NAME(interpreter)
23188 .resolve(thd, MYSQL_SYSVAR_NAME(interpreter).offset);
23189 }
23190 #endif /* UNIV_DEBUG */
23191
23192 static SYS_VAR *innobase_system_variables[] = {
23193 MYSQL_SYSVAR(api_trx_level),
23194 MYSQL_SYSVAR(api_bk_commit_interval),
23195 MYSQL_SYSVAR(autoextend_increment),
23196 MYSQL_SYSVAR(dedicated_server),
23197 MYSQL_SYSVAR(buffer_pool_size),
23198 MYSQL_SYSVAR(buffer_pool_chunk_size),
23199 MYSQL_SYSVAR(buffer_pool_instances),
23200 MYSQL_SYSVAR(buffer_pool_filename),
23201 MYSQL_SYSVAR(buffer_pool_dump_now),
23202 MYSQL_SYSVAR(buffer_pool_dump_at_shutdown),
23203 MYSQL_SYSVAR(buffer_pool_in_core_file),
23204 MYSQL_SYSVAR(buffer_pool_dump_pct),
23205 #ifdef UNIV_DEBUG
23206 MYSQL_SYSVAR(buffer_pool_evict),
23207 #endif /* UNIV_DEBUG */
23208 MYSQL_SYSVAR(buffer_pool_load_now),
23209 MYSQL_SYSVAR(buffer_pool_load_abort),
23210 MYSQL_SYSVAR(buffer_pool_load_at_startup),
23211 MYSQL_SYSVAR(lru_scan_depth),
23212 MYSQL_SYSVAR(flush_neighbors),
23213 MYSQL_SYSVAR(checksum_algorithm),
23214 MYSQL_SYSVAR(log_checksums),
23215 MYSQL_SYSVAR(commit_concurrency),
23216 MYSQL_SYSVAR(concurrency_tickets),
23217 MYSQL_SYSVAR(compression_level),
23218 MYSQL_SYSVAR(ddl_buffer_size),
23219 MYSQL_SYSVAR(ddl_threads),
23220 MYSQL_SYSVAR(data_file_path),
23221 MYSQL_SYSVAR(temp_data_file_path),
23222 MYSQL_SYSVAR(data_home_dir),
23223 MYSQL_SYSVAR(extend_and_initialize),
23224 MYSQL_SYSVAR(doublewrite),
23225 MYSQL_SYSVAR(doublewrite_dir),
23226 MYSQL_SYSVAR(doublewrite_batch_size),
23227 MYSQL_SYSVAR(doublewrite_files),
23228 MYSQL_SYSVAR(doublewrite_pages),
23229 MYSQL_SYSVAR(stats_include_delete_marked),
23230 MYSQL_SYSVAR(api_enable_binlog),
23231 MYSQL_SYSVAR(api_enable_mdl),
23232 MYSQL_SYSVAR(api_disable_rowlock),
23233 MYSQL_SYSVAR(fast_shutdown),
23234 MYSQL_SYSVAR(read_io_threads),
23235 MYSQL_SYSVAR(write_io_threads),
23236 MYSQL_SYSVAR(file_per_table),
23237 MYSQL_SYSVAR(flush_log_at_timeout),
23238 MYSQL_SYSVAR(flush_log_at_trx_commit),
23239 MYSQL_SYSVAR(flush_method),
23240 MYSQL_SYSVAR(force_recovery),
23241 #ifdef UNIV_DEBUG
23242 MYSQL_SYSVAR(force_recovery_crash),
23243 #endif /* UNIV_DEBUG */
23244 MYSQL_SYSVAR(fill_factor),
23245 MYSQL_SYSVAR(ft_cache_size),
23246 MYSQL_SYSVAR(ft_total_cache_size),
23247 MYSQL_SYSVAR(ft_result_cache_limit),
23248 MYSQL_SYSVAR(ft_enable_stopword),
23249 MYSQL_SYSVAR(ft_max_token_size),
23250 MYSQL_SYSVAR(ft_min_token_size),
23251 MYSQL_SYSVAR(ft_num_word_optimize),
23252 MYSQL_SYSVAR(ft_sort_pll_degree),
23253 MYSQL_SYSVAR(force_load_corrupted),
23254 MYSQL_SYSVAR(lock_wait_timeout),
23255 MYSQL_SYSVAR(deadlock_detect),
23256 MYSQL_SYSVAR(page_size),
23257 MYSQL_SYSVAR(log_buffer_size),
23258 MYSQL_SYSVAR(log_file_size),
23259 MYSQL_SYSVAR(log_files_in_group),
23260 MYSQL_SYSVAR(redo_log_capacity),
23261 #ifdef UNIV_DEBUG_DEDICATED
23262 MYSQL_SYSVAR(debug_sys_mem_size),
23263 #endif /* UNIV_DEBUG_DEDICATED */
23264 MYSQL_SYSVAR(log_write_ahead_size),
23265 MYSQL_SYSVAR(log_group_home_dir),
23266 MYSQL_SYSVAR(log_writer_threads),
23267 MYSQL_SYSVAR(log_spin_cpu_abs_lwm),
23268 MYSQL_SYSVAR(log_spin_cpu_pct_hwm),
23269 MYSQL_SYSVAR(log_wait_for_flush_spin_hwm),
23270 #ifdef ENABLE_EXPERIMENT_SYSVARS
23271 MYSQL_SYSVAR(log_write_events),
23272 MYSQL_SYSVAR(log_flush_events),
23273 MYSQL_SYSVAR(log_recent_written_size),
23274 MYSQL_SYSVAR(log_recent_closed_size),
23275 MYSQL_SYSVAR(log_wait_for_write_spin_delay),
23276 MYSQL_SYSVAR(log_wait_for_write_timeout),
23277 MYSQL_SYSVAR(log_wait_for_flush_spin_delay),
23278 MYSQL_SYSVAR(log_wait_for_flush_timeout),
23279 MYSQL_SYSVAR(log_write_max_size),
23280 MYSQL_SYSVAR(log_writer_spin_delay),
23281 MYSQL_SYSVAR(log_writer_timeout),
23282 MYSQL_SYSVAR(log_checkpoint_every),
23283 MYSQL_SYSVAR(log_flusher_spin_delay),
23284 MYSQL_SYSVAR(log_flusher_timeout),
23285 MYSQL_SYSVAR(log_write_notifier_spin_delay),
23286 MYSQL_SYSVAR(log_write_notifier_timeout),
23287 MYSQL_SYSVAR(log_flush_notifier_spin_delay),
23288 MYSQL_SYSVAR(log_flush_notifier_timeout),
23289 #endif /* ENABLE_EXPERIMENT_SYSVARS */
23290 MYSQL_SYSVAR(log_compressed_pages),
23291 MYSQL_SYSVAR(max_dirty_pages_pct),
23292 MYSQL_SYSVAR(max_dirty_pages_pct_lwm),
23293 MYSQL_SYSVAR(adaptive_flushing_lwm),
23294 MYSQL_SYSVAR(adaptive_flushing),
23295 MYSQL_SYSVAR(flush_sync),
23296 MYSQL_SYSVAR(flushing_avg_loops),
23297 MYSQL_SYSVAR(max_purge_lag),
23298 MYSQL_SYSVAR(max_purge_lag_delay),
23299 MYSQL_SYSVAR(old_blocks_pct),
23300 MYSQL_SYSVAR(old_blocks_time),
23301 MYSQL_SYSVAR(open_files),
23302 MYSQL_SYSVAR(optimize_fulltext_only),
23303 MYSQL_SYSVAR(rollback_on_timeout),
23304 MYSQL_SYSVAR(ft_aux_table),
23305 MYSQL_SYSVAR(ft_enable_diag_print),
23306 MYSQL_SYSVAR(ft_server_stopword_table),
23307 MYSQL_SYSVAR(ft_user_stopword_table),
23308 MYSQL_SYSVAR(disable_sort_file_cache),
23309 MYSQL_SYSVAR(stats_on_metadata),
23310 MYSQL_SYSVAR(stats_transient_sample_pages),
23311 MYSQL_SYSVAR(stats_persistent),
23312 MYSQL_SYSVAR(stats_persistent_sample_pages),
23313 MYSQL_SYSVAR(stats_auto_recalc),
23314 MYSQL_SYSVAR(adaptive_hash_index),
23315 MYSQL_SYSVAR(adaptive_hash_index_parts),
23316 MYSQL_SYSVAR(stats_method),
23317 MYSQL_SYSVAR(replication_delay),
23318 MYSQL_SYSVAR(status_file),
23319 MYSQL_SYSVAR(strict_mode),
23320 MYSQL_SYSVAR(sort_buffer_size),
23321 MYSQL_SYSVAR(online_alter_log_max_size),
23322 MYSQL_SYSVAR(directories),
23323 MYSQL_SYSVAR(sync_spin_loops),
23324 MYSQL_SYSVAR(spin_wait_delay),
23325 MYSQL_SYSVAR(spin_wait_pause_multiplier),
23326 MYSQL_SYSVAR(fsync_threshold),
23327 MYSQL_SYSVAR(table_locks),
23328 MYSQL_SYSVAR(thread_concurrency),
23329 MYSQL_SYSVAR(adaptive_max_sleep_delay),
23330 MYSQL_SYSVAR(thread_sleep_delay),
23331 MYSQL_SYSVAR(tmpdir),
23332 MYSQL_SYSVAR(autoinc_lock_mode),
23333 MYSQL_SYSVAR(version),
23334 MYSQL_SYSVAR(use_native_aio),
23335 #ifdef HAVE_LIBNUMA
23336 MYSQL_SYSVAR(numa_interleave),
23337 #endif /* HAVE_LIBNUMA */
23338 MYSQL_SYSVAR(change_buffering),
23339 MYSQL_SYSVAR(change_buffer_max_size),
23340 #if defined UNIV_DEBUG || defined UNIV_IBUF_DEBUG
23341 MYSQL_SYSVAR(change_buffering_debug),
23342 MYSQL_SYSVAR(disable_background_merge),
23343 #endif /* UNIV_DEBUG || UNIV_IBUF_DEBUG */
23344 MYSQL_SYSVAR(random_read_ahead),
23345 MYSQL_SYSVAR(read_ahead_threshold),
23346 MYSQL_SYSVAR(read_only),
23347
23348 MYSQL_SYSVAR(io_capacity),
23349 MYSQL_SYSVAR(io_capacity_max),
23350 MYSQL_SYSVAR(idle_flush_pct),
23351 MYSQL_SYSVAR(page_cleaners),
23352 MYSQL_SYSVAR(monitor_enable),
23353 MYSQL_SYSVAR(monitor_disable),
23354 MYSQL_SYSVAR(monitor_reset),
23355 MYSQL_SYSVAR(monitor_reset_all),
23356 MYSQL_SYSVAR(purge_threads),
23357 MYSQL_SYSVAR(purge_batch_size),
23358 #ifdef UNIV_DEBUG
23359 MYSQL_SYSVAR(background_drop_list_empty),
23360 MYSQL_SYSVAR(purge_run_now),
23361 MYSQL_SYSVAR(purge_stop_now),
23362 MYSQL_SYSVAR(log_flush_now),
23363 MYSQL_SYSVAR(log_checkpoint_now),
23364 MYSQL_SYSVAR(log_checkpoint_fuzzy_now),
23365 MYSQL_SYSVAR(checkpoint_disabled),
23366 MYSQL_SYSVAR(buf_flush_list_now),
23367 MYSQL_SYSVAR(merge_threshold_set_all_debug),
23368 MYSQL_SYSVAR(semaphore_wait_timeout_debug),
23369 #endif /* UNIV_DEBUG */
23370 #if defined UNIV_DEBUG || defined UNIV_PERF_DEBUG
23371 MYSQL_SYSVAR(page_hash_locks),
23372 #endif /* defined UNIV_DEBUG || defined UNIV_PERF_DEBUG */
23373 MYSQL_SYSVAR(validate_tablespace_paths),
23374 MYSQL_SYSVAR(use_fdatasync),
23375 MYSQL_SYSVAR(status_output),
23376 MYSQL_SYSVAR(status_output_locks),
23377 MYSQL_SYSVAR(print_all_deadlocks),
23378 MYSQL_SYSVAR(cmp_per_index_enabled),
23379 MYSQL_SYSVAR(max_undo_log_size),
23380 MYSQL_SYSVAR(purge_rseg_truncate_frequency),
23381 MYSQL_SYSVAR(undo_log_truncate),
23382 MYSQL_SYSVAR(undo_log_encrypt),
23383 MYSQL_SYSVAR(rollback_segments),
23384 MYSQL_SYSVAR(undo_directory),
23385 MYSQL_SYSVAR(temp_tablespaces_dir),
23386 MYSQL_SYSVAR(undo_tablespaces),
23387 MYSQL_SYSVAR(sync_array_size),
23388 MYSQL_SYSVAR(compression_failure_threshold_pct),
23389 MYSQL_SYSVAR(compression_pad_pct_max),
23390 MYSQL_SYSVAR(default_row_format),
23391 MYSQL_SYSVAR(redo_log_archive_dirs),
23392 MYSQL_SYSVAR(redo_log_encrypt),
23393 MYSQL_SYSVAR(print_ddl_logs),
23394 #ifdef UNIV_DEBUG
23395 MYSQL_SYSVAR(trx_rseg_n_slots_debug),
23396 MYSQL_SYSVAR(limit_optimistic_insert_debug),
23397 MYSQL_SYSVAR(trx_purge_view_update_only_debug),
23398 MYSQL_SYSVAR(fil_make_page_dirty_debug),
23399 MYSQL_SYSVAR(saved_page_number_debug),
23400 MYSQL_SYSVAR(compress_debug),
23401 MYSQL_SYSVAR(page_cleaner_disabled_debug),
23402 MYSQL_SYSVAR(dict_stats_disabled_debug),
23403 MYSQL_SYSVAR(master_thread_disabled_debug),
23404 MYSQL_SYSVAR(sync_debug),
23405 MYSQL_SYSVAR(buffer_pool_debug),
23406 MYSQL_SYSVAR(ddl_log_crash_reset_debug),
23407 MYSQL_SYSVAR(interpreter),
23408 MYSQL_SYSVAR(interpreter_output),
23409 #endif /* UNIV_DEBUG */
23410 MYSQL_SYSVAR(parallel_read_threads),
23411 MYSQL_SYSVAR(segment_reserve_factor),
23412 nullptr};
23413
23414 mysql_declare_plugin(innobase){
23415 MYSQL_STORAGE_ENGINE_PLUGIN,
23416 &innobase_storage_engine,
23417 innobase_hton_name,
23418 PLUGIN_AUTHOR_ORACLE,
23419 "Supports transactions, row-level locking, and foreign keys",
23420 PLUGIN_LICENSE_GPL,
23421 innodb_init, /* Plugin Init */
23422 nullptr, /* Plugin Check uninstall */
23423 innodb_deinit, /* Plugin Deinit */
23424 INNODB_VERSION_SHORT,
23425 innodb_status_variables_export, /* status variables */
23426 innobase_system_variables, /* system variables */
23427 nullptr, /* reserved */
23428 0, /* flags */
23429 },
23430 i_s_innodb_trx, i_s_innodb_cmp, i_s_innodb_cmp_reset, i_s_innodb_cmpmem,
23431 i_s_innodb_cmpmem_reset, i_s_innodb_cmp_per_index,
23432 i_s_innodb_cmp_per_index_reset, i_s_innodb_buffer_page,
23433 i_s_innodb_buffer_page_lru, i_s_innodb_buffer_stats,
23434 i_s_innodb_temp_table_info, i_s_innodb_metrics,
23435 i_s_innodb_ft_default_stopword, i_s_innodb_ft_deleted,
23436 i_s_innodb_ft_being_deleted, i_s_innodb_ft_config,
23437 i_s_innodb_ft_index_cache, i_s_innodb_ft_index_table, i_s_innodb_tables,
23438 i_s_innodb_tablestats, i_s_innodb_indexes, i_s_innodb_tablespaces,
23439 i_s_innodb_columns, i_s_innodb_virtual, i_s_innodb_cached_indexes,
23440 i_s_innodb_session_temp_tablespaces
23441
23442 mysql_declare_plugin_end;
23443
23444 /** @brief Initialize the default value of innodb_commit_concurrency.
23445
23446 Once InnoDB is running, the innodb_commit_concurrency must not change
23447 from zero to nonzero. (Bug #42101)
23448
23449 The initial default value is 0, and without this extra initialization,
23450 SET GLOBAL innodb_commit_concurrency=DEFAULT would set the parameter
23451 to 0, even if it was initially set to nonzero at the command line
23452 or configuration file. */
23453 static void innobase_commit_concurrency_init_default() {
23454 MYSQL_SYSVAR_NAME(commit_concurrency).def_val = innobase_commit_concurrency;
23455 }
23456
23457 /****************************************************************************
23458 DS-MRR implementation
23459 ***************************************************************************/
23460
23461 /**
23462 Multi Range Read interface, DS-MRR calls */
23463 int ha_innobase::multi_range_read_init(RANGE_SEQ_IF *seq, void *seq_init_param,
23464 uint n_ranges, uint mode,
23465 HANDLER_BUFFER *buf) {
23466 m_ds_mrr.init(table);
23467
23468 return (m_ds_mrr.dsmrr_init(seq, seq_init_param, n_ranges, mode, buf));
23469 }
23470
23471 int ha_innobase::multi_range_read_next(char **range_info) {
23472 return (m_ds_mrr.dsmrr_next(range_info));
23473 }
23474
23475 ha_rows ha_innobase::multi_range_read_info_const(
23476 uint keyno, RANGE_SEQ_IF *seq, void *seq_init_param, uint n_ranges,
23477 uint *bufsz, uint *flags, bool *force_default_mrr [[maybe_unused]],
23478 Cost_estimate *cost) {
23479 /* See comments in ha_myisam::multi_range_read_info_const */
23480 m_ds_mrr.init(table);
23481
23482 return (m_ds_mrr.dsmrr_info_const(keyno, seq, seq_init_param, n_ranges, bufsz,
23483 flags, cost));
23484 }
23485
23486 ha_rows ha_innobase::multi_range_read_info(uint keyno, uint n_ranges, uint keys,
23487 uint *bufsz, uint *flags,
23488 Cost_estimate *cost) {
23489 m_ds_mrr.init(table);
23490
23491 return (m_ds_mrr.dsmrr_info(keyno, n_ranges, keys, bufsz, flags, cost));
23492 }
23493
23494 /**
23495 Index Condition Pushdown interface implementation */
23496
23497 /** InnoDB index push-down condition check
23498 @return ICP_NO_MATCH, ICP_MATCH, or ICP_OUT_OF_RANGE */
23499 ICP_RESULT
23500 innobase_index_cond(ha_innobase *h) /*!< in/out: pointer to ha_innobase */
23501 {
23502 DBUG_TRACE;
23503
23504 assert(h->pushed_idx_cond);
23505 assert(h->pushed_idx_cond_keyno != MAX_KEY);
23506
23507 if (h->end_range && h->compare_key_icp(h->end_range) > 0) {
23508 /* caller should return HA_ERR_END_OF_FILE already */
23509 return ICP_OUT_OF_RANGE;
23510 }
23511
23512 return h->pushed_idx_cond->val_int() ? ICP_MATCH : ICP_NO_MATCH;
23513 }
23514
23515 /** Get the computed value by supplying the base column values.
23516 @param[in,out] table the table whose virtual column template to be built */
23517 void innobase_init_vc_templ(dict_table_t *table) {
23518 dict_sys_mutex_enter();
23519
23520 if (table->vc_templ != nullptr) {
23521 dict_sys_mutex_exit();
23522
23523 return;
23524 }
23525
23526 table->vc_templ =
23527 ut::new_withkey<dict_vcol_templ_t>(UT_NEW_THIS_FILE_PSI_KEY);
23528 table->vc_templ->vtempl = nullptr;
23529
23530 std::string schema_name;
23531 std::string table_name;
23532
23533 table->get_table_name(schema_name, table_name);
23534
23535 THD *thd = current_thd;
23536
23537 #ifdef UNIV_DEBUG
23538 bool ret =
23539 #endif /* UNIV_DEBUG */
23540 handler::my_prepare_gcolumn_template(
23541 thd, schema_name.c_str(), table_name.c_str(),
23542 &innobase_build_v_templ_callback, static_cast<void *>(table));
23543 ut_ad(!ret);
23544
23545 dict_sys_mutex_exit();
23546 }
23547
23548 /** Change dbname and table name in table->vc_templ.
23549 @param[in,out] table the table whose virtual column template
23550 dbname and tbname to be renamed. */
23551 void innobase_rename_vc_templ(dict_table_t *table) {
23552 std::string schema_name;
23553 std::string table_name;
23554
23555 /* Get table and schema name in system character set. */
23556 table->get_table_name(schema_name, table_name);
23557
23558 table->vc_templ->db_name.assign(schema_name);
23559 table->vc_templ->tb_name.assign(table_name);
23560 }
23561
23562 /** Get the updated field value from an update vector for the given column
23563 number.
23564 @param[in] update the update vector for the table's clustered index
23565 @param[in] col_no the number of the non-virtual column in the table
23566 @return the field's new value if it's updated, otherwise nullptr */
23567 static const dfield_t *innobase_get_field_from_update_vector(
23568 const upd_t *update, uint32_t col_no) {
23569 const dict_index_t *const clustered_index = update->table->first_index();
23570 const auto index_field_pos = clustered_index->get_col_pos(col_no);
23571 const upd_field_t *const upd_field =
23572 upd_get_field_by_field_no(update, index_field_pos, false);
23573 return upd_field ? &upd_field->new_val : nullptr;
23574 }
23575
23576 dfield_t *innobase_get_computed_value(
23577 const dtuple_t *row, const dict_v_col_t *col, const dict_table_t *table,
23578 mem_heap_t **local_heap, mem_heap_t *heap, THD *thd, TABLE *mysql_table,
23579 const dict_field_t *ifield, const dict_table_t *old_table,
23580 upd_t *row_update) {
23581 byte rec_buf1[REC_VERSION_56_MAX_INDEX_COL_LEN];
23582 byte rec_buf2[REC_VERSION_56_MAX_INDEX_COL_LEN];
23583 byte *mysql_rec;
23584 byte *buf;
23585 dfield_t *field;
23586 ulint len;
23587 ulong mv_length = 0;
23588 const char *mv_data_ptr = nullptr;
23589
23590 /* table definition to use for externally stored fields */
23591 const dict_table_t *const ext_src_table = (old_table ? old_table : table);
23592 const page_size_t page_size = dict_table_page_size(ext_src_table);
23593
23594 ulint ret = 0;
23595
23596 ut_ad(table->vc_templ);
23597 ut_ad(thd != nullptr);
23598
23599 const mysql_row_templ_t *vctempl =
23600 table->vc_templ->vtempl[table->vc_templ->n_col + col->v_pos];
23601
23602 if (!heap || table->vc_templ->rec_len >= REC_VERSION_56_MAX_INDEX_COL_LEN) {
23603 if (*local_heap == nullptr) {
23604 *local_heap = mem_heap_create(UNIV_PAGE_SIZE, UT_LOCATION_HERE);
23605 }
23606
23607 mysql_rec = static_cast<byte *>(
23608 mem_heap_alloc(*local_heap, table->vc_templ->rec_len));
23609 buf = static_cast<byte *>(
23610 mem_heap_alloc(*local_heap, table->vc_templ->rec_len));
23611 } else {
23612 mysql_rec = rec_buf1;
23613 buf = rec_buf2;
23614 }
23615
23616 for (ulint i = 0; i < col->num_base; i++) {
23617 dict_col_t *base_col = col->base_col[i];
23618 const dfield_t *row_field = nullptr;
23619 uint32_t col_no = base_col->ind;
23620 const mysql_row_templ_t *const templ = table->vc_templ->vtempl[col_no];
23621 const byte *data;
23622
23623 if (row_update != nullptr) {
23624 row_field = innobase_get_field_from_update_vector(row_update, col_no);
23625 }
23626
23627 if (row_field == nullptr) {
23628 row_field = dtuple_get_nth_field(row, col_no);
23629 }
23630
23631 data = static_cast<const byte *>(row_field->data);
23632 len = row_field->len;
23633
23634 if (row_field->ext) {
23635 if (*local_heap == nullptr) {
23636 *local_heap = mem_heap_create(UNIV_PAGE_SIZE, UT_LOCATION_HERE);
23637 }
23638
23639 data = lob::btr_copy_externally_stored_field(
23640 thd_to_trx(thd), ext_src_table->first_index(), &len, nullptr, data,
23641 page_size, dfield_get_len(row_field), false, *local_heap);
23642 }
23643
23644 if (len == UNIV_SQL_NULL) {
23645 mysql_rec[templ->mysql_null_byte_offset] |=
23646 (byte)templ->mysql_null_bit_mask;
23647 memcpy(mysql_rec + templ->mysql_col_offset,
23648 static_cast<const byte *>(table->vc_templ->default_rec +
23649 templ->mysql_col_offset),
23650 templ->mysql_col_len);
23651 } else {
23652 row_sel_field_store_in_mysql_format(
23653 mysql_rec + templ->mysql_col_offset, templ, table->first_index(),
23654 templ->clust_rec_field_no, (const byte *)data, len, ULINT_UNDEFINED);
23655
23656 if (templ->mysql_null_bit_mask) {
23657 /* It is a nullable column with a
23658 non-NULL value */
23659 mysql_rec[templ->mysql_null_byte_offset] &=
23660 ~(byte)templ->mysql_null_bit_mask;
23661 }
23662 }
23663 }
23664
23665 field = dtuple_get_nth_v_field(row, col->v_pos);
23666
23667 /* Bitmap for specifying which virtual columns the server
23668 should evaluate */
23669 MY_BITMAP column_map;
23670 my_bitmap_map col_map_storage[bitmap_buffer_size(REC_MAX_N_FIELDS)];
23671
23672 bitmap_init(&column_map, col_map_storage, REC_MAX_N_FIELDS);
23673
23674 /* Specify the column the server should evaluate */
23675 bitmap_set_bit(&column_map, col->m_col.ind);
23676
23677 Temp_table_handle tblhdl;
23678
23679 if (mysql_table == nullptr) {
23680 if (vctempl->type == DATA_BLOB) {
23681 ulint max_len;
23682
23683 if (vctempl->mysql_col_len - 8 == 1) {
23684 /* This is for TINYBLOB only, which needs
23685 only 1 byte, other BLOBs won't be affected */
23686 max_len = 255;
23687 } else {
23688 max_len = DICT_MAX_FIELD_LEN_BY_FORMAT(table) + 1;
23689 }
23690
23691 byte *blob_mem = static_cast<byte *>(mem_heap_alloc(heap, max_len));
23692
23693 row_mysql_store_blob_ref(mysql_rec + vctempl->mysql_col_offset,
23694 vctempl->mysql_col_len, blob_mem, max_len);
23695 }
23696
23697 /* open a temporary table handle */
23698 mysql_table = tblhdl.open(thd, table->vc_templ->db_name.c_str(),
23699 table->vc_templ->tb_name.c_str());
23700 }
23701 if (mysql_table) {
23702 ret = handler::my_eval_gcolumn_expr(
23703 thd, mysql_table, &column_map, (uchar *)mysql_rec,
23704 (col->m_col.is_multi_value() ? &mv_data_ptr : nullptr),
23705 (col->m_col.is_multi_value() ? &mv_length : nullptr));
23706 } else {
23707 return nullptr;
23708 }
23709
23710 if (ret != 0) {
23711 #ifdef INNODB_VIRTUAL_DEBUG
23712 ib::warn(ER_IB_MSG_581) << "Compute virtual column values failed ";
23713 fputs("InnoDB: Cannot compute value for following record ", stderr);
23714 dtuple_print(stderr, row);
23715 #endif /* INNODB_VIRTUAL_DEBUG */
23716 return (nullptr);
23717 }
23718
23719 if (vctempl->mysql_null_bit_mask &&
23720 (mysql_rec[vctempl->mysql_null_byte_offset] &
23721 vctempl->mysql_null_bit_mask)) {
23722 dfield_set_null(field);
23723 field->type.prtype |= DATA_VIRTUAL;
23724 if (col->m_col.is_multi_value()) {
23725 field->type.prtype |= DATA_MULTI_VALUE;
23726 }
23727 return (field);
23728 }
23729
23730 if (col->m_col.is_multi_value()) {
23731 Field_typed_array *fld;
23732 fld = down_cast<Field_typed_array *>(mysql_table->field[col->m_col.ind]);
23733 json_binary::Value v(json_binary::parse_binary(mv_data_ptr, mv_length));
23734 multi_value_data *value = nullptr;
23735
23736 bool succ = innobase_store_multi_value(v, value, fld, field,
23737 dict_table_is_comp(table), heap);
23738 if (!succ) {
23739 ut_error;
23740 }
23741
23742 field->type.prtype |= DATA_MULTI_VALUE;
23743 } else {
23744 row_mysql_store_col_in_innobase_format(
23745 field, buf, true, mysql_rec + vctempl->mysql_col_offset,
23746 vctempl->mysql_col_len, dict_table_is_comp(table));
23747 }
23748 field->type.prtype |= DATA_VIRTUAL;
23749
23750 ulint max_prefix = col->m_col.max_prefix;
23751
23752 if (max_prefix && ifield &&
23753 (ifield->prefix_len == 0 || ifield->prefix_len > col->m_col.max_prefix)) {
23754 max_prefix = ifield->prefix_len;
23755 }
23756
23757 /* If this is a prefix index, we only need a portion of the field */
23758 if (max_prefix) {
23759 len = dtype_get_at_most_n_mbchars(
23760 col->m_col.prtype, col->m_col.mbminmaxlen, max_prefix, field->len,
23761 static_cast<char *>(dfield_get_data(field)));
23762 dfield_set_len(field, len);
23763 }
23764
23765 if (heap != nullptr && !dfield_is_multi_value(field)) {
23766 dfield_dup(field, heap);
23767 }
23768
23769 return (field);
23770 }
23771
23772 /** Attempt to push down an index condition.
23773 @param[in] keyno MySQL key number
23774 @param[in] idx_cond Index condition to be checked
23775 @return idx_cond if pushed; NULL if not pushed */
23776 class Item *ha_innobase::idx_cond_push(uint keyno, class Item *idx_cond) {
23777 DBUG_TRACE;
23778 assert(keyno != MAX_KEY);
23779 assert(idx_cond != nullptr);
23780
23781 pushed_idx_cond = idx_cond;
23782 pushed_idx_cond_keyno = keyno;
23783 in_range_check_pushed_down = true;
23784 /* We will evaluate the condition entirely */
23785 return nullptr;
23786 }
23787
23788 /** Find out if a Record_buffer is wanted by this handler, and what is the
23789 maximum buffer size the handler wants.
23790
23791 @param[out] max_rows gets set to the maximum number of records to allocate
23792 space for in the buffer
23793 @retval true if the handler wants a buffer
23794 @retval false if the handler does not want a buffer */
23795 bool ha_innobase::is_record_buffer_wanted(ha_rows *const max_rows) const {
23796 /* If the scan won't be able to utilize the record buffer, return that
23797 we don't want one. The decision on whether to use a buffer is taken in
23798 row_search_mvcc(), look for the comment that starts with "Decide
23799 whether to prefetch extra rows." Let's do the same check here. */
23800
23801 if (!m_prebuilt->can_prefetch_records()) {
23802 *max_rows = 0;
23803 return false;
23804 }
23805
23806 /* Limit the number of rows in the buffer to 100 for now. We may want
23807 to fine-tune this later, possibly taking record size and page size into
23808 account. The optimizer might allocate an even smaller buffer if it
23809 thinks a smaller number of rows will be fetched. */
23810 *max_rows = 100;
23811 return true;
23812 }
23813
23814 /** Return max limits for a single set of multi-valued keys
23815 @param[out] num_keys number of keys to store
23816 @param[out] keys_length total length of keys, bytes
23817 */
23818 void ha_innobase::mv_key_capacity(uint *num_keys, size_t *keys_length) const {
23819 /* The limit of multi-value should be checked against undo page size,
23820 because a record length can not be longer than an undo page size.
23821 Actually, it should not be longer than half of a page size, but this
23822 can be checked for the full record.
23823
23824 The problem is, even if the number of multi-value fields are known,
23825 the actual number of multiple values per field are not known until
23826 the record itself gets inserted. So it's impossible to estimate the
23827 accurate max number of multiple values. Meanwhile, since other fields
23828 are not known in advance, so it's also impossible to estimate the
23829 accurate total key length.
23830
23831 Therefore, only the best effort can be done in this function.
23832 That is the estimation will be based on the INSERT to the table.
23833 And excluding all must have space, the left length is regarded
23834 as the keys_length. And the number of the keys would be got by
23835 keys_length / min(multi-value fields' length). Note if it is a
23836 variable length field, then it's data length is regarded as 1.
23837
23838 Furthermore, to make the calculation as simple as possible, some
23839 space cost would be ignored. This should not be a big deal, since
23840 the whole estimation is only a rough one.
23841
23842 So it's the greedy estimation which will try to give a most relaxed
23843 restriction on the table, to allow insert and update go as more as
23844 possible. The DB_UNDO_RECORD_TOO_BIG error would be raised if the
23845 actual user record exceeds the undo page size. */
23846
23847 size_t free_space = trx_undo_max_free_space();
23848
23849 /* PK always takes place in log page, take that into account */
23850 uint pk = table->s->primary_key;
23851 if (pk != MAX_KEY) {
23852 free_space -= table->s->key_info[pk].key_length;
23853 } else {
23854 /* Deduct default InnoDB's PK length */
23855 free_space -= DATA_ROW_ID_LEN;
23856 }
23857
23858 /* Maybe the space for any normal virtual columns etc. should be
23859 considered here, however, no details can be know at this time point,
23860 so just ignore them all */
23861
23862 /* Find out the minimum key length so to get the maximum number
23863 of keys */
23864 uint16_t min_mv_key_length = std::numeric_limits<uint16_t>::max();
23865
23866 for (uint16_t i = 0; i < table->s->fields; ++i) {
23867 Field *field = table->field[i];
23868 if (!innobase_is_multi_value_fld(field)) {
23869 continue;
23870 }
23871
23872 /* In case of variable length type, assume the minimum length of data,
23873 to make a maximum estimation of keys and allow users to insert as
23874 many keys as possible, under the constraint of total key length. */
23875 if (field->type() == MYSQL_TYPE_VARCHAR) {
23876 min_mv_key_length = 1;
23877 break;
23878 }
23879
23880 if (min_mv_key_length > field->key_length()) {
23881 min_mv_key_length = field->key_length();
23882 }
23883 }
23884
23885 *keys_length = Multi_value_logger::get_keys_capacity(
23886 static_cast<uint32_t>(free_space), min_mv_key_length, num_keys);
23887 }
23888
23889 /** Use this when the args are passed to the format string from
23890 messages_to_clients.txt directly as is.
23891
23892 Push a warning message to the client, it is a wrapper around:
23893
23894 void push_warning_printf(
23895 THD *thd, Sql_condition::enum_condition_level level,
23896 uint code, const char *format, ...);
23897 */
23898 void ib_senderrf(THD *thd, /*!< in/out: session */
23899 ib_log_level_t level, /*!< in: warning level */
23900 uint32_t code, /*!< MySQL error code */
23901 ...) /*!< Args */
23902 {
23903 va_list args;
23904 char *str = nullptr;
23905 const char *format = innobase_get_err_msg(code);
23906
23907 /* If the caller wants to push a message to the client then
23908 the caller must pass a valid session handle. */
23909
23910 ut_a(thd != nullptr);
23911
23912 /* The error code must exist in the messages_to_clients.txt file. */
23913 ut_a(format != nullptr);
23914
23915 va_start(args, code);
23916
23917 #ifdef _WIN32
23918 int size = _vscprintf(format, args) + 1;
23919 if (size > 0) {
23920 str = static_cast<char *>(malloc(size));
23921 }
23922 if (str == NULL) {
23923 va_end(args);
23924 return; /* Watch for Out-Of-Memory */
23925 }
23926 str[size - 1] = 0x0;
23927 vsnprintf(str, size, format, args);
23928 #elif HAVE_VASPRINTF
23929 int ret;
23930 ret = vasprintf(&str, format, args);
23931 if (ret < 0) {
23932 va_end(args);
23933 return; /* Watch for Out-Of-Memory */
23934 }
23935 #else
23936 /* Use a fixed length string. */
23937 str = static_cast<char *>(malloc(BUFSIZ));
23938 if (str == NULL) {
23939 va_end(args);
23940 return; /* Watch for Out-Of-Memory */
23941 }
23942 vsnprintf(str, BUFSIZ, format, args);
23943 #endif /* _WIN32 */
23944
23945 Sql_condition::enum_severity_level l;
23946
23947 l = Sql_condition::SL_NOTE;
23948
23949 switch (level) {
23950 case IB_LOG_LEVEL_INFO:
23951 break;
23952 case IB_LOG_LEVEL_WARN:
23953 l = Sql_condition::SL_WARNING;
23954 break;
23955 case IB_LOG_LEVEL_ERROR:
23956 /* We can't use push_warning_printf(), it is a hard error. */
23957 my_printf_error(code, "%s", MYF(0), str);
23958 break;
23959 case IB_LOG_LEVEL_FATAL:
23960 l = Sql_condition::SEVERITY_END;
23961 break;
23962 #ifdef UNIV_HOTBACKUP
23963 default:
23964 break;
23965 #endif /* UNIV_HOTBACKUP */
23966 }
23967
23968 if (level != IB_LOG_LEVEL_ERROR) {
23969 push_warning_printf(thd, l, code, "InnoDB: %s", str);
23970 }
23971
23972 va_end(args);
23973 free(str);
23974
23975 if (level == IB_LOG_LEVEL_FATAL) {
23976 ut_error;
23977 }
23978 }
23979
23980 /** Use this when the args are first converted to a formatted string and then
23981 passed to the format string from messages_to_clients.txt. The error message
23982 format must be: "Some string ... %s".
23983
23984 Push a warning message to the client, it is a wrapper around:
23985
23986 void push_warning_printf(
23987 THD *thd, Sql_condition::enum_condition_level level,
23988 uint code, const char *format, ...);
23989 */
23990 void ib_errf(THD *thd, /*!< in/out: session */
23991 ib_log_level_t level, /*!< in: warning level */
23992 uint32_t code, /*!< MySQL error code */
23993 const char *format, /*!< printf format */
23994 ...) /*!< Args */
23995 {
23996 char *str = nullptr;
23997 va_list args;
23998
23999 /* If the caller wants to push a message to the client then
24000 the caller must pass a valid session handle. */
24001
24002 ut_a(thd != nullptr);
24003 ut_a(format != nullptr);
24004
24005 va_start(args, format);
24006
24007 #ifdef _WIN32
24008 int size = _vscprintf(format, args) + 1;
24009 if (size > 0) {
24010 str = static_cast<char *>(malloc(size));
24011 }
24012 if (str == NULL) {
24013 va_end(args);
24014 return; /* Watch for Out-Of-Memory */
24015 }
24016 str[size - 1] = 0x0;
24017 vsnprintf(str, size, format, args);
24018 #elif HAVE_VASPRINTF
24019 int ret;
24020 ret = vasprintf(&str, format, args);
24021 if (ret < 0) {
24022 va_end(args);
24023 return; /* Watch for Out-Of-Memory */
24024 }
24025 #else
24026 /* Use a fixed length string. */
24027 str = static_cast<char *>(malloc(BUFSIZ));
24028 if (str == NULL) {
24029 va_end(args);
24030 return; /* Watch for Out-Of-Memory */
24031 }
24032 vsnprintf(str, BUFSIZ, format, args);
24033 #endif /* _WIN32 */
24034
24035 ib_senderrf(thd, level, code, str);
24036
24037 va_end(args);
24038 free(str);
24039 }
24040 #endif /* !UNIV_HOTBACKUP */
24041
24042 /* Keep the first 16 characters as-is, since the url is sometimes used
24043 as an offset from this.*/
24044 const char *TROUBLESHOOTING_MSG = "Please refer to " REFMAN
24045 "innodb-troubleshooting.html"
24046 " for how to resolve the issue.";
24047
24048 const char *TROUBLESHOOT_DATADICT_MSG = "Please refer to " REFMAN
24049 "innodb-troubleshooting-datadict.html"
24050 " for how to resolve the issue.";
24051
24052 const char *BUG_REPORT_MSG =
24053 "Submit a detailed bug report to http://bugs.mysql.com";
24054
24055 const char *FORCE_RECOVERY_MSG = "Please refer to " REFMAN
24056 "forcing-innodb-recovery.html"
24057 " for information about forcing recovery.";
24058
24059 const char *ERROR_CREATING_MSG =
24060 "Please refer to " REFMAN "error-creating-innodb.html";
24061
24062 const char *OPERATING_SYSTEM_ERROR_MSG =
24063 "Refer to your operating system documentation for operating"
24064 " system error code information.";
24065
24066 const char *FOREIGN_KEY_CONSTRAINTS_MSG =
24067 "Please refer to " REFMAN
24068 "create-table-foreign-keys.html"
24069 " for correct foreign key definition.";
24070
24071 const char *INNODB_PARAMETERS_MSG =
24072 "Please refer to " REFMAN "innodb-parameters.html";
24073
24074 #ifndef UNIV_HOTBACKUP
24075 /**********************************************************************
24076 Converts an identifier from my_charset_filename to UTF-8 charset.
24077 @return result string length, as returned by strconvert() */
24078 uint innobase_convert_to_filename_charset(
24079 char *to, /* out: converted identifier */
24080 const char *from, /* in: identifier to convert */
24081 ulint len) /* in: length of 'to', in bytes */
24082 {
24083 uint errors;
24084 CHARSET_INFO *cs_to = &my_charset_filename;
24085 CHARSET_INFO *cs_from = system_charset_info;
24086
24087 return (static_cast<uint>(
24088 strconvert(cs_from, from, cs_to, to, static_cast<size_t>(len), &errors)));
24089 }
24090
24091 /**********************************************************************
24092 Converts an identifier from my_charset_filename to UTF-8 charset.
24093 @return result string length, as returned by strconvert() */
24094 uint innobase_convert_to_system_charset(
24095 char *to, /* out: converted identifier */
24096 const char *from, /* in: identifier to convert */
24097 ulint len, /* in: length of 'to', in bytes */
24098 uint *errors) /* out: error return */
24099 {
24100 CHARSET_INFO *cs1 = &my_charset_filename;
24101 CHARSET_INFO *cs2 = system_charset_info;
24102
24103 return (static_cast<uint>(
24104 strconvert(cs1, from, cs2, to, static_cast<size_t>(len), errors)));
24105 }
24106
24107 /**********************************************************************
24108 Issue a warning that the row is too big. */
24109 void ib_warn_row_too_big(const dict_table_t *table) {
24110 /* If prefix is true then a 768-byte prefix is stored
24111 locally for BLOB fields. */
24112 const bool prefix = !dict_table_has_atomic_blobs(table);
24113
24114 const ulint free_space =
24115 page_get_free_space_of_empty(table->flags & DICT_TF_COMPACT) / 2;
24116
24117 THD *thd = current_thd;
24118
24119 push_warning_printf(
24120 thd, Sql_condition::SL_WARNING, HA_ERR_TOO_BIG_ROW,
24121 "Row size too large (> " ULINTPF
24122 "). Changing some columns to TEXT"
24123 " or BLOB %smay help. In current row format, BLOB prefix of"
24124 " %d bytes is stored inline.",
24125 free_space,
24126 prefix ? "or using ROW_FORMAT=DYNAMIC or"
24127 " ROW_FORMAT=COMPRESSED "
24128 : "",
24129 prefix ? DICT_MAX_FIXED_COL_LEN : 0);
24130 }
24131
24132 /** Constructs fake dict_col_t describing column for foreign key type
24133 compatibility check from column description in Ha_fk_column_type form.
24134
24135 @note dict_col_t which is produced by this call is not valid for general
24136 purposes.
24137 @param[out] col dict_col_t filled by this function
24138 @param[in] fk_col_type foreign key type information */
24139 static void innodb_fill_fake_column_struct(
24140 dict_col_t *col, const Ha_fk_column_type *fk_col_type) {
24141 ulint unsigned_type;
24142 ulint binary_type;
24143 ulint charset_no;
24144
24145 ulint mtype = get_innobase_type_from_mysql_dd_type(
24146 &unsigned_type, &binary_type, &charset_no, fk_col_type->type,
24147 fk_col_type->field_charset, fk_col_type->is_unsigned);
24148
24149 /* Fake prtype only contains info which is relevant for foreign key
24150 type compatibility check, especially the info used in cmp_cols_are_equal. */
24151 ulint fake_prtype =
24152 dtype_form_prtype(unsigned_type | binary_type, charset_no);
24153
24154 ulint col_len = calc_pack_length(
24155 fk_col_type->type, fk_col_type->char_length, fk_col_type->elements_count,
24156 /* InnoDB always treats BIT as char. */
24157 true, fk_col_type->numeric_scale, fk_col_type->is_unsigned);
24158
24159 dict_mem_fill_column_struct(col, 0 /* fake col_pos */, mtype, fake_prtype,
24160 col_len, true, UINT32_UNDEFINED, 0, 0);
24161 }
24162
24163 /** Check if types of child and parent columns in foreign key are compatible.
24164
24165 @param[in] child_column_type Child column type description.
24166 @param[in] parent_column_type Parent column type description.
24167 @param[in] check_charsets Indicates whether we need to check
24168 that charsets of string columns
24169 match. Which is true in most cases.
24170
24171 @return True if types are compatible, False if not. */
24172 static bool innodb_check_fk_column_compat(
24173 const Ha_fk_column_type *child_column_type,
24174 const Ha_fk_column_type *parent_column_type, bool check_charsets) {
24175 dict_col_t dict_child_col, dict_parent_col;
24176
24177 innodb_fill_fake_column_struct(&dict_child_col, child_column_type);
24178 innodb_fill_fake_column_struct(&dict_parent_col, parent_column_type);
24179
24180 return (
24181 cmp_cols_are_equal(&dict_child_col, &dict_parent_col, check_charsets));
24182 }
24183
24184 static bool innobase_check_reserved_file_name(handlerton *, const char *name) {
24185 CHARSET_INFO *ci = system_charset_info;
24186 size_t logname_size = strlen(log_pre_8_0_30::FILE_BASE_NAME);
24187
24188 /* Name is smaller than reserved name */
24189 if (strlen(name) < logname_size) {
24190 return (false);
24191 }
24192 /* Do case insensitive comparison for name. */
24193 for (uint i = 0; i < logname_size; i++) {
24194 ut_ad(!my_isalpha(ci, log_pre_8_0_30::FILE_BASE_NAME[i]) ||
24195 my_islower(ci, log_pre_8_0_30::FILE_BASE_NAME[i]));
24196
24197 if (my_tolower(ci, name[i]) != log_pre_8_0_30::FILE_BASE_NAME[i]) {
24198 return (false);
24199 }
24200 }
24201 return (true);
24202 }
24203 #endif /* !UNIV_HOTBACKUP */