You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

5455 lines
147 KiB

10 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
12 years ago
10 years ago
10 years ago
12 years ago
12 years ago
11 years ago
11 years ago
11 years ago
10 years ago
11 years ago
11 years ago
11 years ago
10 years ago
11 years ago
9 years ago
9 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
12 years ago
11 years ago
12 years ago
12 years ago
12 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
9 years ago
11 years ago
11 years ago
10 years ago
9 years ago
10 years ago
10 years ago
10 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
  1. /*****************************************************************************
  2. Copyright (c) 2000, 2016, Oracle and/or its affiliates. All Rights Reserved.
  3. This program is free software; you can redistribute it and/or modify it under
  4. the terms of the GNU General Public License as published by the Free Software
  5. Foundation; version 2 of the License.
  6. This program is distributed in the hope that it will be useful, but WITHOUT
  7. ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
  8. FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
  9. You should have received a copy of the GNU General Public License along with
  10. this program; if not, write to the Free Software Foundation, Inc.,
  11. 51 Franklin Street, Suite 500, Boston, MA 02110-1335 USA
  12. *****************************************************************************/
  13. /**************************************************//**
  14. @file row/row0mysql.cc
  15. Interface between Innobase row operations and MySQL.
  16. Contains also create table and other data dictionary operations.
  17. Created 9/17/2000 Heikki Tuuri
  18. *******************************************************/
  19. #include "row0mysql.h"
  20. #ifdef UNIV_NONINL
  21. #include "row0mysql.ic"
  22. #endif
  23. #include <debug_sync.h>
  24. #include <my_dbug.h>
  25. #include <sql_const.h>
  26. #include "row0ins.h"
  27. #include "row0merge.h"
  28. #include "row0sel.h"
  29. #include "row0upd.h"
  30. #include "row0row.h"
  31. #include "que0que.h"
  32. #include "pars0pars.h"
  33. #include "dict0dict.h"
  34. #include "dict0crea.h"
  35. #include "dict0load.h"
  36. #include "dict0boot.h"
  37. #include "dict0stats.h"
  38. #include "dict0stats_bg.h"
  39. #include "trx0roll.h"
  40. #include "trx0purge.h"
  41. #include "trx0rec.h"
  42. #include "trx0undo.h"
  43. #include "lock0lock.h"
  44. #include "rem0cmp.h"
  45. #include "log0log.h"
  46. #include "btr0sea.h"
  47. #include "fil0fil.h"
  48. #include "ibuf0ibuf.h"
  49. #include "fts0fts.h"
  50. #include "fts0types.h"
  51. #include "srv0start.h"
  52. #include "row0import.h"
  53. #include "m_string.h"
  54. #include "my_sys.h"
  55. #include "ha_prototypes.h"
  56. #include <algorithm>
  57. /** Provide optional 4.x backwards compatibility for 5.0 and above */
  58. UNIV_INTERN ibool row_rollback_on_timeout = FALSE;
  59. /** Chain node of the list of tables to drop in the background. */
  60. struct row_mysql_drop_t{
  61. char* table_name; /*!< table name */
  62. UT_LIST_NODE_T(row_mysql_drop_t)row_mysql_drop_list;
  63. /*!< list chain node */
  64. };
  65. #ifdef UNIV_PFS_MUTEX
  66. /* Key to register drop list mutex with performance schema */
  67. UNIV_INTERN mysql_pfs_key_t row_drop_list_mutex_key;
  68. #endif /* UNIV_PFS_MUTEX */
  69. /** @brief List of tables we should drop in background.
  70. ALTER TABLE in MySQL requires that the table handler can drop the
  71. table in background when there are no queries to it any
  72. more. Protected by row_drop_list_mutex. */
  73. static UT_LIST_BASE_NODE_T(row_mysql_drop_t) row_mysql_drop_list;
  74. /** Mutex protecting the background table drop list. */
  75. static ib_mutex_t row_drop_list_mutex;
  76. /** Flag: has row_mysql_drop_list been initialized? */
  77. static ibool row_mysql_drop_list_inited = FALSE;
  78. /** Magic table names for invoking various monitor threads */
  79. /* @{ */
  80. static const char S_innodb_monitor[] = "innodb_monitor";
  81. static const char S_innodb_lock_monitor[] = "innodb_lock_monitor";
  82. static const char S_innodb_tablespace_monitor[] = "innodb_tablespace_monitor";
  83. static const char S_innodb_table_monitor[] = "innodb_table_monitor";
  84. #ifdef UNIV_MEM_DEBUG
  85. static const char S_innodb_mem_validate[] = "innodb_mem_validate";
  86. #endif /* UNIV_MEM_DEBUG */
  87. /* @} */
  88. /** Evaluates to true if str1 equals str2_onstack, used for comparing
  89. the magic table names.
  90. @param str1 in: string to compare
  91. @param str1_len in: length of str1, in bytes, including terminating NUL
  92. @param str2_onstack in: char[] array containing a NUL terminated string
  93. @return TRUE if str1 equals str2_onstack */
  94. #define STR_EQ(str1, str1_len, str2_onstack) \
  95. ((str1_len) == sizeof(str2_onstack) \
  96. && memcmp(str1, str2_onstack, sizeof(str2_onstack)) == 0)
  97. /*******************************************************************//**
  98. Determine if the given name is a name reserved for MySQL system tables.
  99. @return TRUE if name is a MySQL system table name */
  100. static
  101. ibool
  102. row_mysql_is_system_table(
  103. /*======================*/
  104. const char* name)
  105. {
  106. if (strncmp(name, "mysql/", 6) != 0) {
  107. return(FALSE);
  108. }
  109. return(0 == strcmp(name + 6, "host")
  110. || 0 == strcmp(name + 6, "user")
  111. || 0 == strcmp(name + 6, "db"));
  112. }
  113. /*********************************************************************//**
  114. If a table is not yet in the drop list, adds the table to the list of tables
  115. which the master thread drops in background. We need this on Unix because in
  116. ALTER TABLE MySQL may call drop table even if the table has running queries on
  117. it. Also, if there are running foreign key checks on the table, we drop the
  118. table lazily.
  119. @return TRUE if the table was not yet in the drop list, and was added there */
  120. static
  121. ibool
  122. row_add_table_to_background_drop_list(
  123. /*==================================*/
  124. const char* name); /*!< in: table name */
  125. /*******************************************************************//**
  126. Delays an INSERT, DELETE or UPDATE operation if the purge is lagging. */
  127. static
  128. void
  129. row_mysql_delay_if_needed(void)
  130. /*===========================*/
  131. {
  132. if (srv_dml_needed_delay) {
  133. os_thread_sleep(srv_dml_needed_delay);
  134. }
  135. }
  136. /*******************************************************************//**
  137. Frees the blob heap in prebuilt when no longer needed. */
  138. UNIV_INTERN
  139. void
  140. row_mysql_prebuilt_free_blob_heap(
  141. /*==============================*/
  142. row_prebuilt_t* prebuilt) /*!< in: prebuilt struct of a
  143. ha_innobase:: table handle */
  144. {
  145. mem_heap_free(prebuilt->blob_heap);
  146. prebuilt->blob_heap = NULL;
  147. }
  148. /*******************************************************************//**
  149. Stores a >= 5.0.3 format true VARCHAR length to dest, in the MySQL row
  150. format.
  151. @return pointer to the data, we skip the 1 or 2 bytes at the start
  152. that are used to store the len */
  153. UNIV_INTERN
  154. byte*
  155. row_mysql_store_true_var_len(
  156. /*=========================*/
  157. byte* dest, /*!< in: where to store */
  158. ulint len, /*!< in: length, must fit in two bytes */
  159. ulint lenlen) /*!< in: storage length of len: either 1 or 2 bytes */
  160. {
  161. if (lenlen == 2) {
  162. ut_a(len < 256 * 256);
  163. mach_write_to_2_little_endian(dest, len);
  164. return(dest + 2);
  165. }
  166. ut_a(lenlen == 1);
  167. ut_a(len < 256);
  168. mach_write_to_1(dest, len);
  169. return(dest + 1);
  170. }
  171. /*******************************************************************//**
  172. Reads a >= 5.0.3 format true VARCHAR length, in the MySQL row format, and
  173. returns a pointer to the data.
  174. @return pointer to the data, we skip the 1 or 2 bytes at the start
  175. that are used to store the len */
  176. UNIV_INTERN
  177. const byte*
  178. row_mysql_read_true_varchar(
  179. /*========================*/
  180. ulint* len, /*!< out: variable-length field length */
  181. const byte* field, /*!< in: field in the MySQL format */
  182. ulint lenlen) /*!< in: storage length of len: either 1
  183. or 2 bytes */
  184. {
  185. if (lenlen == 2) {
  186. *len = mach_read_from_2_little_endian(field);
  187. return(field + 2);
  188. }
  189. ut_a(lenlen == 1);
  190. *len = mach_read_from_1(field);
  191. return(field + 1);
  192. }
  193. /*******************************************************************//**
  194. Stores a reference to a BLOB in the MySQL format. */
  195. UNIV_INTERN
  196. void
  197. row_mysql_store_blob_ref(
  198. /*=====================*/
  199. byte* dest, /*!< in: where to store */
  200. ulint col_len,/*!< in: dest buffer size: determines into
  201. how many bytes the BLOB length is stored,
  202. the space for the length may vary from 1
  203. to 4 bytes */
  204. const void* data, /*!< in: BLOB data; if the value to store
  205. is SQL NULL this should be NULL pointer */
  206. ulint len) /*!< in: BLOB length; if the value to store
  207. is SQL NULL this should be 0; remember
  208. also to set the NULL bit in the MySQL record
  209. header! */
  210. {
  211. /* MySQL might assume the field is set to zero except the length and
  212. the pointer fields */
  213. memset(dest, '\0', col_len);
  214. /* In dest there are 1 - 4 bytes reserved for the BLOB length,
  215. and after that 8 bytes reserved for the pointer to the data.
  216. In 32-bit architectures we only use the first 4 bytes of the pointer
  217. slot. */
  218. ut_a(col_len - 8 > 1 || len < 256);
  219. ut_a(col_len - 8 > 2 || len < 256 * 256);
  220. ut_a(col_len - 8 > 3 || len < 256 * 256 * 256);
  221. mach_write_to_n_little_endian(dest, col_len - 8, len);
  222. memcpy(dest + col_len - 8, &data, sizeof data);
  223. }
  224. /*******************************************************************//**
  225. Reads a reference to a BLOB in the MySQL format.
  226. @return pointer to BLOB data */
  227. UNIV_INTERN
  228. const byte*
  229. row_mysql_read_blob_ref(
  230. /*====================*/
  231. ulint* len, /*!< out: BLOB length */
  232. const byte* ref, /*!< in: BLOB reference in the
  233. MySQL format */
  234. ulint col_len) /*!< in: BLOB reference length
  235. (not BLOB length) */
  236. {
  237. byte* data;
  238. *len = mach_read_from_n_little_endian(ref, col_len - 8);
  239. memcpy(&data, ref + col_len - 8, sizeof data);
  240. return(data);
  241. }
  242. /**************************************************************//**
  243. Pad a column with spaces. */
  244. UNIV_INTERN
  245. void
  246. row_mysql_pad_col(
  247. /*==============*/
  248. ulint mbminlen, /*!< in: minimum size of a character,
  249. in bytes */
  250. byte* pad, /*!< out: padded buffer */
  251. ulint len) /*!< in: number of bytes to pad */
  252. {
  253. const byte* pad_end;
  254. switch (UNIV_EXPECT(mbminlen, 1)) {
  255. default:
  256. ut_error;
  257. case 1:
  258. /* space=0x20 */
  259. memset(pad, 0x20, len);
  260. break;
  261. case 2:
  262. /* space=0x0020 */
  263. pad_end = pad + len;
  264. ut_a(!(len % 2));
  265. while (pad < pad_end) {
  266. *pad++ = 0x00;
  267. *pad++ = 0x20;
  268. };
  269. break;
  270. case 4:
  271. /* space=0x00000020 */
  272. pad_end = pad + len;
  273. ut_a(!(len % 4));
  274. while (pad < pad_end) {
  275. *pad++ = 0x00;
  276. *pad++ = 0x00;
  277. *pad++ = 0x00;
  278. *pad++ = 0x20;
  279. }
  280. break;
  281. }
  282. }
  283. /**************************************************************//**
  284. Stores a non-SQL-NULL field given in the MySQL format in the InnoDB format.
  285. The counterpart of this function is row_sel_field_store_in_mysql_format() in
  286. row0sel.cc.
  287. @return up to which byte we used buf in the conversion */
  288. UNIV_INTERN
  289. byte*
  290. row_mysql_store_col_in_innobase_format(
  291. /*===================================*/
  292. dfield_t* dfield, /*!< in/out: dfield where dtype
  293. information must be already set when
  294. this function is called! */
  295. byte* buf, /*!< in/out: buffer for a converted
  296. integer value; this must be at least
  297. col_len long then! NOTE that dfield
  298. may also get a pointer to 'buf',
  299. therefore do not discard this as long
  300. as dfield is used! */
  301. ibool row_format_col, /*!< TRUE if the mysql_data is from
  302. a MySQL row, FALSE if from a MySQL
  303. key value;
  304. in MySQL, a true VARCHAR storage
  305. format differs in a row and in a
  306. key value: in a key value the length
  307. is always stored in 2 bytes! */
  308. const byte* mysql_data, /*!< in: MySQL column value, not
  309. SQL NULL; NOTE that dfield may also
  310. get a pointer to mysql_data,
  311. therefore do not discard this as long
  312. as dfield is used! */
  313. ulint col_len, /*!< in: MySQL column length; NOTE that
  314. this is the storage length of the
  315. column in the MySQL format row, not
  316. necessarily the length of the actual
  317. payload data; if the column is a true
  318. VARCHAR then this is irrelevant */
  319. ulint comp) /*!< in: nonzero=compact format */
  320. {
  321. const byte* ptr = mysql_data;
  322. const dtype_t* dtype;
  323. ulint type;
  324. ulint lenlen;
  325. dtype = dfield_get_type(dfield);
  326. type = dtype->mtype;
  327. if (type == DATA_INT) {
  328. /* Store integer data in Innobase in a big-endian format,
  329. sign bit negated if the data is a signed integer. In MySQL,
  330. integers are stored in a little-endian format. */
  331. byte* p = buf + col_len;
  332. for (;;) {
  333. p--;
  334. *p = *mysql_data;
  335. if (p == buf) {
  336. break;
  337. }
  338. mysql_data++;
  339. }
  340. if (!(dtype->prtype & DATA_UNSIGNED)) {
  341. *buf ^= 128;
  342. }
  343. ptr = buf;
  344. buf += col_len;
  345. } else if ((type == DATA_VARCHAR
  346. || type == DATA_VARMYSQL
  347. || type == DATA_BINARY)) {
  348. if (dtype_get_mysql_type(dtype) == DATA_MYSQL_TRUE_VARCHAR) {
  349. /* The length of the actual data is stored to 1 or 2
  350. bytes at the start of the field */
  351. if (row_format_col) {
  352. if (dtype->prtype & DATA_LONG_TRUE_VARCHAR) {
  353. lenlen = 2;
  354. } else {
  355. lenlen = 1;
  356. }
  357. } else {
  358. /* In a MySQL key value, lenlen is always 2 */
  359. lenlen = 2;
  360. }
  361. ptr = row_mysql_read_true_varchar(&col_len, mysql_data,
  362. lenlen);
  363. } else {
  364. /* Remove trailing spaces from old style VARCHAR
  365. columns. */
  366. /* Handle Unicode strings differently. */
  367. ulint mbminlen = dtype_get_mbminlen(dtype);
  368. ptr = mysql_data;
  369. switch (mbminlen) {
  370. default:
  371. ut_error;
  372. case 4:
  373. /* space=0x00000020 */
  374. /* Trim "half-chars", just in case. */
  375. col_len &= ~3;
  376. while (col_len >= 4
  377. && ptr[col_len - 4] == 0x00
  378. && ptr[col_len - 3] == 0x00
  379. && ptr[col_len - 2] == 0x00
  380. && ptr[col_len - 1] == 0x20) {
  381. col_len -= 4;
  382. }
  383. break;
  384. case 2:
  385. /* space=0x0020 */
  386. /* Trim "half-chars", just in case. */
  387. col_len &= ~1;
  388. while (col_len >= 2 && ptr[col_len - 2] == 0x00
  389. && ptr[col_len - 1] == 0x20) {
  390. col_len -= 2;
  391. }
  392. break;
  393. case 1:
  394. /* space=0x20 */
  395. while (col_len > 0
  396. && ptr[col_len - 1] == 0x20) {
  397. col_len--;
  398. }
  399. }
  400. }
  401. } else if (comp && type == DATA_MYSQL
  402. && dtype_get_mbminlen(dtype) == 1
  403. && dtype_get_mbmaxlen(dtype) > 1) {
  404. /* In some cases we strip trailing spaces from UTF-8 and other
  405. multibyte charsets, from FIXED-length CHAR columns, to save
  406. space. UTF-8 would otherwise normally use 3 * the string length
  407. bytes to store an ASCII string! */
  408. /* We assume that this CHAR field is encoded in a
  409. variable-length character set where spaces have
  410. 1:1 correspondence to 0x20 bytes, such as UTF-8.
  411. Consider a CHAR(n) field, a field of n characters.
  412. It will contain between n * mbminlen and n * mbmaxlen bytes.
  413. We will try to truncate it to n bytes by stripping
  414. space padding. If the field contains single-byte
  415. characters only, it will be truncated to n characters.
  416. Consider a CHAR(5) field containing the string ".a "
  417. where "." denotes a 3-byte character represented by
  418. the bytes "$%&". After our stripping, the string will
  419. be stored as "$%&a " (5 bytes). The string ".abc "
  420. will be stored as "$%&abc" (6 bytes).
  421. The space padding will be restored in row0sel.cc, function
  422. row_sel_field_store_in_mysql_format(). */
  423. ulint n_chars;
  424. ut_a(!(dtype_get_len(dtype) % dtype_get_mbmaxlen(dtype)));
  425. n_chars = dtype_get_len(dtype) / dtype_get_mbmaxlen(dtype);
  426. /* Strip space padding. */
  427. while (col_len > n_chars && ptr[col_len - 1] == 0x20) {
  428. col_len--;
  429. }
  430. } else if (type == DATA_BLOB && row_format_col) {
  431. ptr = row_mysql_read_blob_ref(&col_len, mysql_data, col_len);
  432. }
  433. dfield_set_data(dfield, ptr, col_len);
  434. return(buf);
  435. }
  436. /**************************************************************//**
  437. Convert a row in the MySQL format to a row in the Innobase format. Note that
  438. the function to convert a MySQL format key value to an InnoDB dtuple is
  439. row_sel_convert_mysql_key_to_innobase() in row0sel.cc. */
  440. static
  441. void
  442. row_mysql_convert_row_to_innobase(
  443. /*==============================*/
  444. dtuple_t* row, /*!< in/out: Innobase row where the
  445. field type information is already
  446. copied there! */
  447. row_prebuilt_t* prebuilt, /*!< in: prebuilt struct where template
  448. must be of type ROW_MYSQL_WHOLE_ROW */
  449. byte* mysql_rec) /*!< in: row in the MySQL format;
  450. NOTE: do not discard as long as
  451. row is used, as row may contain
  452. pointers to this record! */
  453. {
  454. const mysql_row_templ_t*templ;
  455. dfield_t* dfield;
  456. ulint i;
  457. ut_ad(prebuilt->template_type == ROW_MYSQL_WHOLE_ROW);
  458. ut_ad(prebuilt->mysql_template);
  459. for (i = 0; i < prebuilt->n_template; i++) {
  460. templ = prebuilt->mysql_template + i;
  461. dfield = dtuple_get_nth_field(row, i);
  462. if (templ->mysql_null_bit_mask != 0) {
  463. /* Column may be SQL NULL */
  464. if (mysql_rec[templ->mysql_null_byte_offset]
  465. & (byte) (templ->mysql_null_bit_mask)) {
  466. /* It is SQL NULL */
  467. dfield_set_null(dfield);
  468. goto next_column;
  469. }
  470. }
  471. row_mysql_store_col_in_innobase_format(
  472. dfield,
  473. prebuilt->ins_upd_rec_buff + templ->mysql_col_offset,
  474. TRUE, /* MySQL row format data */
  475. mysql_rec + templ->mysql_col_offset,
  476. templ->mysql_col_len,
  477. dict_table_is_comp(prebuilt->table));
  478. next_column:
  479. ;
  480. }
  481. /* If there is a FTS doc id column and it is not user supplied (
  482. generated by server) then assign it a new doc id. */
  483. if (prebuilt->table->fts) {
  484. ut_a(prebuilt->table->fts->doc_col != ULINT_UNDEFINED);
  485. fts_create_doc_id(prebuilt->table, row, prebuilt->heap);
  486. }
  487. }
  488. /****************************************************************//**
  489. Handles user errors and lock waits detected by the database engine.
  490. @return true if it was a lock wait and we should continue running the
  491. query thread and in that case the thr is ALREADY in the running state. */
  492. UNIV_INTERN
  493. bool
  494. row_mysql_handle_errors(
  495. /*====================*/
  496. dberr_t* new_err,/*!< out: possible new error encountered in
  497. lock wait, or if no new error, the value
  498. of trx->error_state at the entry of this
  499. function */
  500. trx_t* trx, /*!< in: transaction */
  501. que_thr_t* thr, /*!< in: query thread, or NULL */
  502. trx_savept_t* savept) /*!< in: savepoint, or NULL */
  503. {
  504. dberr_t err;
  505. handle_new_error:
  506. err = trx->error_state;
  507. ut_a(err != DB_SUCCESS);
  508. trx->error_state = DB_SUCCESS;
  509. switch (err) {
  510. case DB_LOCK_WAIT_TIMEOUT:
  511. if (row_rollback_on_timeout) {
  512. trx_rollback_to_savepoint(trx, NULL);
  513. break;
  514. }
  515. /* fall through */
  516. case DB_DUPLICATE_KEY:
  517. case DB_FOREIGN_DUPLICATE_KEY:
  518. case DB_TOO_BIG_RECORD:
  519. case DB_TOO_BIG_FOR_REDO:
  520. case DB_UNDO_RECORD_TOO_BIG:
  521. case DB_ROW_IS_REFERENCED:
  522. case DB_NO_REFERENCED_ROW:
  523. case DB_CANNOT_ADD_CONSTRAINT:
  524. case DB_TOO_MANY_CONCURRENT_TRXS:
  525. case DB_OUT_OF_FILE_SPACE:
  526. case DB_READ_ONLY:
  527. case DB_FTS_INVALID_DOCID:
  528. case DB_INTERRUPTED:
  529. case DB_DICT_CHANGED:
  530. if (savept) {
  531. /* Roll back the latest, possibly incomplete insertion
  532. or update */
  533. trx_rollback_to_savepoint(trx, savept);
  534. }
  535. /* MySQL will roll back the latest SQL statement */
  536. break;
  537. case DB_LOCK_WAIT:
  538. lock_wait_suspend_thread(thr);
  539. if (trx->error_state != DB_SUCCESS) {
  540. que_thr_stop_for_mysql(thr);
  541. goto handle_new_error;
  542. }
  543. *new_err = err;
  544. return(true);
  545. case DB_DEADLOCK:
  546. case DB_LOCK_TABLE_FULL:
  547. /* Roll back the whole transaction; this resolution was added
  548. to version 3.23.43 */
  549. trx_rollback_to_savepoint(trx, NULL);
  550. break;
  551. case DB_MUST_GET_MORE_FILE_SPACE:
  552. fputs("InnoDB: The database cannot continue"
  553. " operation because of\n"
  554. "InnoDB: lack of space. You must add"
  555. " a new data file to\n"
  556. "InnoDB: my.cnf and restart the database.\n", stderr);
  557. ut_ad(0);
  558. exit(1);
  559. case DB_CORRUPTION:
  560. fputs("InnoDB: We detected index corruption"
  561. " in an InnoDB type table.\n"
  562. "InnoDB: You have to dump + drop + reimport"
  563. " the table or, in\n"
  564. "InnoDB: a case of widespread corruption,"
  565. " dump all InnoDB\n"
  566. "InnoDB: tables and recreate the"
  567. " whole InnoDB tablespace.\n"
  568. "InnoDB: If the mysqld server crashes"
  569. " after the startup or when\n"
  570. "InnoDB: you dump the tables, look at\n"
  571. "InnoDB: " REFMAN "forcing-innodb-recovery.html"
  572. " for help.\n", stderr);
  573. break;
  574. case DB_FOREIGN_EXCEED_MAX_CASCADE:
  575. fprintf(stderr, "InnoDB: Cannot delete/update rows with"
  576. " cascading foreign key constraints that exceed max"
  577. " depth of %lu\n"
  578. "Please drop excessive foreign constraints"
  579. " and try again\n", (ulong) DICT_FK_MAX_RECURSIVE_LOAD);
  580. break;
  581. default:
  582. fprintf(stderr, "InnoDB: unknown error code %lu\n",
  583. (ulong) err);
  584. ut_error;
  585. }
  586. if (trx->error_state != DB_SUCCESS) {
  587. *new_err = trx->error_state;
  588. } else {
  589. *new_err = err;
  590. }
  591. trx->error_state = DB_SUCCESS;
  592. return(false);
  593. }
  594. /********************************************************************//**
  595. Create a prebuilt struct for a MySQL table handle.
  596. @return own: a prebuilt struct */
  597. UNIV_INTERN
  598. row_prebuilt_t*
  599. row_create_prebuilt(
  600. /*================*/
  601. dict_table_t* table, /*!< in: Innobase table handle */
  602. ulint mysql_row_len) /*!< in: length in bytes of a row in
  603. the MySQL format */
  604. {
  605. row_prebuilt_t* prebuilt;
  606. mem_heap_t* heap;
  607. dict_index_t* clust_index;
  608. dict_index_t* temp_index;
  609. dtuple_t* ref;
  610. ulint ref_len;
  611. uint srch_key_len = 0;
  612. ulint search_tuple_n_fields;
  613. search_tuple_n_fields = 2 * dict_table_get_n_cols(table);
  614. clust_index = dict_table_get_first_index(table);
  615. /* Make sure that search_tuple is long enough for clustered index */
  616. ut_a(2 * dict_table_get_n_cols(table) >= clust_index->n_fields);
  617. ref_len = dict_index_get_n_unique(clust_index);
  618. /* Maximum size of the buffer needed for conversion of INTs from
  619. little endian format to big endian format in an index. An index
  620. can have maximum 16 columns (MAX_REF_PARTS) in it. Therfore
  621. Max size for PK: 16 * 8 bytes (BIGINT's size) = 128 bytes
  622. Max size Secondary index: 16 * 8 bytes + PK = 256 bytes. */
  623. #define MAX_SRCH_KEY_VAL_BUFFER 2* (8 * MAX_REF_PARTS)
  624. #define PREBUILT_HEAP_INITIAL_SIZE \
  625. ( \
  626. sizeof(*prebuilt) \
  627. /* allocd in this function */ \
  628. + DTUPLE_EST_ALLOC(search_tuple_n_fields) \
  629. + DTUPLE_EST_ALLOC(ref_len) \
  630. /* allocd in row_prebuild_sel_graph() */ \
  631. + sizeof(sel_node_t) \
  632. + sizeof(que_fork_t) \
  633. + sizeof(que_thr_t) \
  634. /* allocd in row_get_prebuilt_update_vector() */ \
  635. + sizeof(upd_node_t) \
  636. + sizeof(upd_t) \
  637. + sizeof(upd_field_t) \
  638. * dict_table_get_n_cols(table) \
  639. + sizeof(que_fork_t) \
  640. + sizeof(que_thr_t) \
  641. /* allocd in row_get_prebuilt_insert_row() */ \
  642. + sizeof(ins_node_t) \
  643. /* mysql_row_len could be huge and we are not \
  644. sure if this prebuilt instance is going to be \
  645. used in inserts */ \
  646. + (mysql_row_len < 256 ? mysql_row_len : 0) \
  647. + DTUPLE_EST_ALLOC(dict_table_get_n_cols(table)) \
  648. + sizeof(que_fork_t) \
  649. + sizeof(que_thr_t) \
  650. )
  651. /* Calculate size of key buffer used to store search key in
  652. InnoDB format. MySQL stores INTs in little endian format and
  653. InnoDB stores INTs in big endian format with the sign bit
  654. flipped. All other field types are stored/compared the same
  655. in MySQL and InnoDB, so we must create a buffer containing
  656. the INT key parts in InnoDB format.We need two such buffers
  657. since both start and end keys are used in records_in_range(). */
  658. for (temp_index = dict_table_get_first_index(table); temp_index;
  659. temp_index = dict_table_get_next_index(temp_index)) {
  660. DBUG_EXECUTE_IF("innodb_srch_key_buffer_max_value",
  661. ut_a(temp_index->n_user_defined_cols
  662. == MAX_REF_PARTS););
  663. uint temp_len = 0;
  664. for (uint i = 0; i < temp_index->n_uniq; i++) {
  665. if (temp_index->fields[i].col->mtype == DATA_INT) {
  666. temp_len +=
  667. temp_index->fields[i].fixed_len;
  668. }
  669. }
  670. srch_key_len = max(srch_key_len,temp_len);
  671. }
  672. ut_a(srch_key_len <= MAX_SRCH_KEY_VAL_BUFFER);
  673. DBUG_EXECUTE_IF("innodb_srch_key_buffer_max_value",
  674. ut_a(srch_key_len == MAX_SRCH_KEY_VAL_BUFFER););
  675. /* We allocate enough space for the objects that are likely to
  676. be created later in order to minimize the number of malloc()
  677. calls */
  678. heap = mem_heap_create(PREBUILT_HEAP_INITIAL_SIZE + 2 * srch_key_len);
  679. prebuilt = static_cast<row_prebuilt_t*>(
  680. mem_heap_zalloc(heap, sizeof(*prebuilt)));
  681. prebuilt->magic_n = ROW_PREBUILT_ALLOCATED;
  682. prebuilt->magic_n2 = ROW_PREBUILT_ALLOCATED;
  683. prebuilt->table = table;
  684. prebuilt->sql_stat_start = TRUE;
  685. prebuilt->heap = heap;
  686. prebuilt->srch_key_val_len = srch_key_len;
  687. if (prebuilt->srch_key_val_len) {
  688. prebuilt->srch_key_val1 = static_cast<byte*>(
  689. mem_heap_alloc(prebuilt->heap,
  690. 2 * prebuilt->srch_key_val_len));
  691. prebuilt->srch_key_val2 = prebuilt->srch_key_val1 +
  692. prebuilt->srch_key_val_len;
  693. } else {
  694. prebuilt->srch_key_val1 = NULL;
  695. prebuilt->srch_key_val2 = NULL;
  696. }
  697. btr_pcur_reset(&prebuilt->pcur);
  698. btr_pcur_reset(&prebuilt->clust_pcur);
  699. prebuilt->select_lock_type = LOCK_NONE;
  700. prebuilt->stored_select_lock_type = LOCK_NONE_UNSET;
  701. prebuilt->search_tuple = dtuple_create(heap, search_tuple_n_fields);
  702. ref = dtuple_create(heap, ref_len);
  703. dict_index_copy_types(ref, clust_index, ref_len);
  704. prebuilt->clust_ref = ref;
  705. prebuilt->autoinc_error = DB_SUCCESS;
  706. prebuilt->autoinc_offset = 0;
  707. /* Default to 1, we will set the actual value later in
  708. ha_innobase::get_auto_increment(). */
  709. prebuilt->autoinc_increment = 1;
  710. prebuilt->autoinc_last_value = 0;
  711. /* During UPDATE and DELETE we need the doc id. */
  712. prebuilt->fts_doc_id = 0;
  713. prebuilt->mysql_row_len = mysql_row_len;
  714. return(prebuilt);
  715. }
  716. /********************************************************************//**
  717. Free a prebuilt struct for a MySQL table handle. */
  718. UNIV_INTERN
  719. void
  720. row_prebuilt_free(
  721. /*==============*/
  722. row_prebuilt_t* prebuilt, /*!< in, own: prebuilt struct */
  723. ibool dict_locked) /*!< in: TRUE=data dictionary locked */
  724. {
  725. ulint i;
  726. if (UNIV_UNLIKELY
  727. (prebuilt->magic_n != ROW_PREBUILT_ALLOCATED
  728. || prebuilt->magic_n2 != ROW_PREBUILT_ALLOCATED)) {
  729. fprintf(stderr,
  730. "InnoDB: Error: trying to free a corrupt\n"
  731. "InnoDB: table handle. Magic n %lu,"
  732. " magic n2 %lu, table name ",
  733. (ulong) prebuilt->magic_n,
  734. (ulong) prebuilt->magic_n2);
  735. ut_print_name(stderr, NULL, TRUE, prebuilt->table->name);
  736. putc('\n', stderr);
  737. mem_analyze_corruption(prebuilt);
  738. ut_error;
  739. }
  740. prebuilt->magic_n = ROW_PREBUILT_FREED;
  741. prebuilt->magic_n2 = ROW_PREBUILT_FREED;
  742. btr_pcur_reset(&prebuilt->pcur);
  743. btr_pcur_reset(&prebuilt->clust_pcur);
  744. if (prebuilt->mysql_template) {
  745. mem_free(prebuilt->mysql_template);
  746. }
  747. if (prebuilt->ins_graph) {
  748. que_graph_free_recursive(prebuilt->ins_graph);
  749. }
  750. if (prebuilt->sel_graph) {
  751. que_graph_free_recursive(prebuilt->sel_graph);
  752. }
  753. if (prebuilt->upd_graph) {
  754. que_graph_free_recursive(prebuilt->upd_graph);
  755. }
  756. if (prebuilt->blob_heap) {
  757. mem_heap_free(prebuilt->blob_heap);
  758. }
  759. if (prebuilt->old_vers_heap) {
  760. mem_heap_free(prebuilt->old_vers_heap);
  761. }
  762. if (prebuilt->fetch_cache[0] != NULL) {
  763. byte* base = prebuilt->fetch_cache[0] - 4;
  764. byte* ptr = base;
  765. for (i = 0; i < MYSQL_FETCH_CACHE_SIZE; i++) {
  766. byte* row;
  767. ulint magic1;
  768. ulint magic2;
  769. magic1 = mach_read_from_4(ptr);
  770. ptr += 4;
  771. row = ptr;
  772. ptr += prebuilt->mysql_row_len;
  773. magic2 = mach_read_from_4(ptr);
  774. ptr += 4;
  775. if (ROW_PREBUILT_FETCH_MAGIC_N != magic1
  776. || row != prebuilt->fetch_cache[i]
  777. || ROW_PREBUILT_FETCH_MAGIC_N != magic2) {
  778. fputs("InnoDB: Error: trying to free"
  779. " a corrupt fetch buffer.\n", stderr);
  780. mem_analyze_corruption(base);
  781. ut_error;
  782. }
  783. }
  784. mem_free(base);
  785. }
  786. dict_table_close(prebuilt->table, dict_locked, TRUE);
  787. mem_heap_free(prebuilt->heap);
  788. }
  789. /*********************************************************************//**
  790. Updates the transaction pointers in query graphs stored in the prebuilt
  791. struct. */
  792. UNIV_INTERN
  793. void
  794. row_update_prebuilt_trx(
  795. /*====================*/
  796. row_prebuilt_t* prebuilt, /*!< in/out: prebuilt struct
  797. in MySQL handle */
  798. trx_t* trx) /*!< in: transaction handle */
  799. {
  800. if (trx->magic_n != TRX_MAGIC_N) {
  801. fprintf(stderr,
  802. "InnoDB: Error: trying to use a corrupt\n"
  803. "InnoDB: trx handle. Magic n %lu\n",
  804. (ulong) trx->magic_n);
  805. mem_analyze_corruption(trx);
  806. ut_error;
  807. }
  808. if (prebuilt->magic_n != ROW_PREBUILT_ALLOCATED) {
  809. fprintf(stderr,
  810. "InnoDB: Error: trying to use a corrupt\n"
  811. "InnoDB: table handle. Magic n %lu, table name ",
  812. (ulong) prebuilt->magic_n);
  813. ut_print_name(stderr, trx, TRUE, prebuilt->table->name);
  814. putc('\n', stderr);
  815. mem_analyze_corruption(prebuilt);
  816. ut_error;
  817. }
  818. prebuilt->trx = trx;
  819. if (prebuilt->ins_graph) {
  820. prebuilt->ins_graph->trx = trx;
  821. }
  822. if (prebuilt->upd_graph) {
  823. prebuilt->upd_graph->trx = trx;
  824. }
  825. if (prebuilt->sel_graph) {
  826. prebuilt->sel_graph->trx = trx;
  827. }
  828. }
  829. /*********************************************************************//**
  830. Gets pointer to a prebuilt dtuple used in insertions. If the insert graph
  831. has not yet been built in the prebuilt struct, then this function first
  832. builds it.
  833. @return prebuilt dtuple; the column type information is also set in it */
  834. static
  835. dtuple_t*
  836. row_get_prebuilt_insert_row(
  837. /*========================*/
  838. row_prebuilt_t* prebuilt) /*!< in: prebuilt struct in MySQL
  839. handle */
  840. {
  841. dict_table_t* table = prebuilt->table;
  842. ut_ad(prebuilt && table && prebuilt->trx);
  843. if (prebuilt->ins_node != 0) {
  844. /* Check if indexes have been dropped or added and we
  845. may need to rebuild the row insert template. */
  846. if (prebuilt->trx_id == table->def_trx_id
  847. && UT_LIST_GET_LEN(prebuilt->ins_node->entry_list)
  848. == UT_LIST_GET_LEN(table->indexes)) {
  849. return(prebuilt->ins_node->row);
  850. }
  851. ut_ad(prebuilt->trx_id < table->def_trx_id);
  852. que_graph_free_recursive(prebuilt->ins_graph);
  853. prebuilt->ins_graph = 0;
  854. }
  855. /* Create an insert node and query graph to the prebuilt struct */
  856. ins_node_t* node;
  857. node = ins_node_create(INS_DIRECT, table, prebuilt->heap);
  858. prebuilt->ins_node = node;
  859. if (prebuilt->ins_upd_rec_buff == 0) {
  860. prebuilt->ins_upd_rec_buff = static_cast<byte*>(
  861. mem_heap_alloc(
  862. prebuilt->heap,
  863. prebuilt->mysql_row_len));
  864. }
  865. dtuple_t* row;
  866. row = dtuple_create(prebuilt->heap, dict_table_get_n_cols(table));
  867. dict_table_copy_types(row, table);
  868. ins_node_set_new_row(node, row);
  869. prebuilt->ins_graph = static_cast<que_fork_t*>(
  870. que_node_get_parent(
  871. pars_complete_graph_for_exec(
  872. node,
  873. prebuilt->trx, prebuilt->heap)));
  874. prebuilt->ins_graph->state = QUE_FORK_ACTIVE;
  875. prebuilt->trx_id = table->def_trx_id;
  876. return(prebuilt->ins_node->row);
  877. }
  878. /*********************************************************************//**
  879. Updates the table modification counter and calculates new estimates
  880. for table and index statistics if necessary. */
  881. UNIV_INLINE
  882. void
  883. row_update_statistics_if_needed(
  884. /*============================*/
  885. dict_table_t* table) /*!< in: table */
  886. {
  887. ib_uint64_t counter;
  888. ib_uint64_t n_rows;
  889. if (!table->stat_initialized) {
  890. DBUG_EXECUTE_IF(
  891. "test_upd_stats_if_needed_not_inited",
  892. fprintf(stderr, "test_upd_stats_if_needed_not_inited "
  893. "was executed\n");
  894. );
  895. return;
  896. }
  897. counter = table->stat_modified_counter++;
  898. n_rows = dict_table_get_n_rows(table);
  899. if (dict_stats_is_persistent_enabled(table)) {
  900. if (counter > n_rows / 10 /* 10% */
  901. && dict_stats_auto_recalc_is_enabled(table)) {
  902. dict_stats_recalc_pool_add(table);
  903. table->stat_modified_counter = 0;
  904. }
  905. return;
  906. }
  907. /* Calculate new statistics if 1 / 16 of table has been modified
  908. since the last time a statistics batch was run.
  909. We calculate statistics at most every 16th round, since we may have
  910. a counter table which is very small and updated very often. */
  911. if (counter > 16 + n_rows / 16 /* 6.25% */) {
  912. ut_ad(!mutex_own(&dict_sys->mutex));
  913. /* this will reset table->stat_modified_counter to 0 */
  914. dict_stats_update(table, DICT_STATS_RECALC_TRANSIENT);
  915. }
  916. }
  917. /*********************************************************************//**
  918. Sets an AUTO_INC type lock on the table mentioned in prebuilt. The
  919. AUTO_INC lock gives exclusive access to the auto-inc counter of the
  920. table. The lock is reserved only for the duration of an SQL statement.
  921. It is not compatible with another AUTO_INC or exclusive lock on the
  922. table.
  923. @return error code or DB_SUCCESS */
  924. UNIV_INTERN
  925. dberr_t
  926. row_lock_table_autoinc_for_mysql(
  927. /*=============================*/
  928. row_prebuilt_t* prebuilt) /*!< in: prebuilt struct in the MySQL
  929. table handle */
  930. {
  931. trx_t* trx = prebuilt->trx;
  932. ins_node_t* node = prebuilt->ins_node;
  933. const dict_table_t* table = prebuilt->table;
  934. que_thr_t* thr;
  935. dberr_t err;
  936. ibool was_lock_wait;
  937. ut_ad(trx);
  938. /* If we already hold an AUTOINC lock on the table then do nothing.
  939. Note: We peek at the value of the current owner without acquiring
  940. the lock mutex. **/
  941. if (trx == table->autoinc_trx) {
  942. return(DB_SUCCESS);
  943. }
  944. trx->op_info = "setting auto-inc lock";
  945. row_get_prebuilt_insert_row(prebuilt);
  946. node = prebuilt->ins_node;
  947. /* We use the insert query graph as the dummy graph needed
  948. in the lock module call */
  949. thr = que_fork_get_first_thr(prebuilt->ins_graph);
  950. que_thr_move_to_run_state_for_mysql(thr, trx);
  951. run_again:
  952. thr->run_node = node;
  953. thr->prev_node = node;
  954. /* It may be that the current session has not yet started
  955. its transaction, or it has been committed: */
  956. trx_start_if_not_started_xa(trx);
  957. err = lock_table(0, prebuilt->table, LOCK_AUTO_INC, thr);
  958. trx->error_state = err;
  959. if (err != DB_SUCCESS) {
  960. que_thr_stop_for_mysql(thr);
  961. was_lock_wait = row_mysql_handle_errors(&err, trx, thr, NULL);
  962. if (was_lock_wait) {
  963. goto run_again;
  964. }
  965. trx->op_info = "";
  966. return(err);
  967. }
  968. que_thr_stop_for_mysql_no_error(thr, trx);
  969. trx->op_info = "";
  970. return(err);
  971. }
  972. /*********************************************************************//**
  973. Sets a table lock on the table mentioned in prebuilt.
  974. @return error code or DB_SUCCESS */
  975. UNIV_INTERN
  976. dberr_t
  977. row_lock_table_for_mysql(
  978. /*=====================*/
  979. row_prebuilt_t* prebuilt, /*!< in: prebuilt struct in the MySQL
  980. table handle */
  981. dict_table_t* table, /*!< in: table to lock, or NULL
  982. if prebuilt->table should be
  983. locked as
  984. prebuilt->select_lock_type */
  985. ulint mode) /*!< in: lock mode of table
  986. (ignored if table==NULL) */
  987. {
  988. trx_t* trx = prebuilt->trx;
  989. que_thr_t* thr;
  990. dberr_t err;
  991. ibool was_lock_wait;
  992. ut_ad(trx);
  993. trx->op_info = "setting table lock";
  994. if (prebuilt->sel_graph == NULL) {
  995. /* Build a dummy select query graph */
  996. row_prebuild_sel_graph(prebuilt);
  997. }
  998. /* We use the select query graph as the dummy graph needed
  999. in the lock module call */
  1000. thr = que_fork_get_first_thr(prebuilt->sel_graph);
  1001. que_thr_move_to_run_state_for_mysql(thr, trx);
  1002. run_again:
  1003. thr->run_node = thr;
  1004. thr->prev_node = thr->common.parent;
  1005. /* It may be that the current session has not yet started
  1006. its transaction, or it has been committed: */
  1007. trx_start_if_not_started_xa(trx);
  1008. if (table) {
  1009. err = lock_table(
  1010. 0, table,
  1011. static_cast<enum lock_mode>(mode), thr);
  1012. } else {
  1013. err = lock_table(
  1014. 0, prebuilt->table,
  1015. static_cast<enum lock_mode>(
  1016. prebuilt->select_lock_type),
  1017. thr);
  1018. }
  1019. trx->error_state = err;
  1020. if (err != DB_SUCCESS) {
  1021. que_thr_stop_for_mysql(thr);
  1022. was_lock_wait = row_mysql_handle_errors(&err, trx, thr, NULL);
  1023. if (was_lock_wait) {
  1024. goto run_again;
  1025. }
  1026. trx->op_info = "";
  1027. return(err);
  1028. }
  1029. que_thr_stop_for_mysql_no_error(thr, trx);
  1030. trx->op_info = "";
  1031. return(err);
  1032. }
  1033. /*********************************************************************//**
  1034. Does an insert for MySQL.
  1035. @return error code or DB_SUCCESS */
  1036. UNIV_INTERN
  1037. dberr_t
  1038. row_insert_for_mysql(
  1039. /*=================*/
  1040. byte* mysql_rec, /*!< in: row in the MySQL format */
  1041. row_prebuilt_t* prebuilt) /*!< in: prebuilt struct in MySQL
  1042. handle */
  1043. {
  1044. trx_savept_t savept;
  1045. que_thr_t* thr;
  1046. dberr_t err;
  1047. ibool was_lock_wait;
  1048. trx_t* trx = prebuilt->trx;
  1049. ins_node_t* node = prebuilt->ins_node;
  1050. dict_table_t* table = prebuilt->table;
  1051. ut_ad(trx);
  1052. if (dict_table_is_discarded(prebuilt->table)) {
  1053. ib_logf(IB_LOG_LEVEL_ERROR,
  1054. "The table %s doesn't have a corresponding "
  1055. "tablespace, it was discarded.",
  1056. prebuilt->table->name);
  1057. return(DB_TABLESPACE_DELETED);
  1058. } else if (prebuilt->table->ibd_file_missing) {
  1059. ib_logf(IB_LOG_LEVEL_ERROR,
  1060. ".ibd file is missing for table %s",
  1061. prebuilt->table->name);
  1062. return(DB_TABLESPACE_NOT_FOUND);
  1063. } else if (prebuilt->magic_n != ROW_PREBUILT_ALLOCATED) {
  1064. fprintf(stderr,
  1065. "InnoDB: Error: trying to free a corrupt\n"
  1066. "InnoDB: table handle. Magic n %lu, table name ",
  1067. (ulong) prebuilt->magic_n);
  1068. ut_print_name(stderr, trx, TRUE, prebuilt->table->name);
  1069. putc('\n', stderr);
  1070. mem_analyze_corruption(prebuilt);
  1071. ut_error;
  1072. } else if (srv_force_recovery) {
  1073. fputs("InnoDB: innodb_force_recovery is on: we do not allow\n"
  1074. "InnoDB: database modifications by the user. Shut down\n"
  1075. "InnoDB: mysqld and edit my.cnf so that"
  1076. "InnoDB: innodb_force_... is removed.\n",
  1077. stderr);
  1078. return(DB_READ_ONLY);
  1079. }
  1080. trx->op_info = "inserting";
  1081. row_mysql_delay_if_needed();
  1082. trx_start_if_not_started_xa(trx);
  1083. row_get_prebuilt_insert_row(prebuilt);
  1084. node = prebuilt->ins_node;
  1085. row_mysql_convert_row_to_innobase(node->row, prebuilt, mysql_rec);
  1086. savept = trx_savept_take(trx);
  1087. thr = que_fork_get_first_thr(prebuilt->ins_graph);
  1088. if (prebuilt->sql_stat_start) {
  1089. node->state = INS_NODE_SET_IX_LOCK;
  1090. prebuilt->sql_stat_start = FALSE;
  1091. } else {
  1092. node->state = INS_NODE_ALLOC_ROW_ID;
  1093. }
  1094. que_thr_move_to_run_state_for_mysql(thr, trx);
  1095. run_again:
  1096. thr->run_node = node;
  1097. thr->prev_node = node;
  1098. row_ins_step(thr);
  1099. err = trx->error_state;
  1100. if (err != DB_SUCCESS) {
  1101. error_exit:
  1102. que_thr_stop_for_mysql(thr);
  1103. /* FIXME: What's this ? */
  1104. thr->lock_state = QUE_THR_LOCK_ROW;
  1105. was_lock_wait = row_mysql_handle_errors(
  1106. &err, trx, thr, &savept);
  1107. thr->lock_state = QUE_THR_LOCK_NOLOCK;
  1108. if (was_lock_wait) {
  1109. ut_ad(node->state == INS_NODE_INSERT_ENTRIES
  1110. || node->state == INS_NODE_ALLOC_ROW_ID);
  1111. goto run_again;
  1112. }
  1113. trx->op_info = "";
  1114. return(err);
  1115. }
  1116. if (dict_table_has_fts_index(table)) {
  1117. doc_id_t doc_id;
  1118. /* Extract the doc id from the hidden FTS column */
  1119. doc_id = fts_get_doc_id_from_row(table, node->row);
  1120. if (doc_id <= 0) {
  1121. fprintf(stderr,
  1122. "InnoDB: FTS Doc ID must be large than 0 \n");
  1123. err = DB_FTS_INVALID_DOCID;
  1124. trx->error_state = DB_FTS_INVALID_DOCID;
  1125. goto error_exit;
  1126. }
  1127. if (!DICT_TF2_FLAG_IS_SET(table, DICT_TF2_FTS_HAS_DOC_ID)) {
  1128. doc_id_t next_doc_id
  1129. = table->fts->cache->next_doc_id;
  1130. if (doc_id < next_doc_id) {
  1131. fprintf(stderr,
  1132. "InnoDB: FTS Doc ID must be large than"
  1133. " " UINT64PF " for table",
  1134. next_doc_id - 1);
  1135. ut_print_name(stderr, trx, TRUE, table->name);
  1136. putc('\n', stderr);
  1137. err = DB_FTS_INVALID_DOCID;
  1138. trx->error_state = DB_FTS_INVALID_DOCID;
  1139. goto error_exit;
  1140. }
  1141. /* Difference between Doc IDs are restricted within
  1142. 4 bytes integer. See fts_get_encoded_len(). Consecutive
  1143. doc_ids difference should not exceed
  1144. FTS_DOC_ID_MAX_STEP value. */
  1145. if (next_doc_id > 1
  1146. && doc_id - next_doc_id >= FTS_DOC_ID_MAX_STEP) {
  1147. fprintf(stderr,
  1148. "InnoDB: Doc ID " UINT64PF " is too"
  1149. " big. Its difference with largest"
  1150. " used Doc ID " UINT64PF " cannot"
  1151. " exceed or equal to %d\n",
  1152. doc_id, next_doc_id - 1,
  1153. FTS_DOC_ID_MAX_STEP);
  1154. err = DB_FTS_INVALID_DOCID;
  1155. trx->error_state = DB_FTS_INVALID_DOCID;
  1156. goto error_exit;
  1157. }
  1158. }
  1159. /* Pass NULL for the columns affected, since an INSERT affects
  1160. all FTS indexes. */
  1161. fts_trx_add_op(trx, table, doc_id, FTS_INSERT, NULL);
  1162. }
  1163. que_thr_stop_for_mysql_no_error(thr, trx);
  1164. srv_stats.n_rows_inserted.add((size_t)trx->id, 1);
  1165. /* Not protected by dict_table_stats_lock() for performance
  1166. reasons, we would rather get garbage in stat_n_rows (which is
  1167. just an estimate anyway) than protecting the following code
  1168. with a latch. */
  1169. dict_table_n_rows_inc(table);
  1170. row_update_statistics_if_needed(table);
  1171. trx->op_info = "";
  1172. return(err);
  1173. }
  1174. /*********************************************************************//**
  1175. Builds a dummy query graph used in selects. */
  1176. UNIV_INTERN
  1177. void
  1178. row_prebuild_sel_graph(
  1179. /*===================*/
  1180. row_prebuilt_t* prebuilt) /*!< in: prebuilt struct in MySQL
  1181. handle */
  1182. {
  1183. sel_node_t* node;
  1184. ut_ad(prebuilt && prebuilt->trx);
  1185. if (prebuilt->sel_graph == NULL) {
  1186. node = sel_node_create(prebuilt->heap);
  1187. prebuilt->sel_graph = static_cast<que_fork_t*>(
  1188. que_node_get_parent(
  1189. pars_complete_graph_for_exec(
  1190. static_cast<sel_node_t*>(node),
  1191. prebuilt->trx, prebuilt->heap)));
  1192. prebuilt->sel_graph->state = QUE_FORK_ACTIVE;
  1193. }
  1194. }
  1195. /*********************************************************************//**
  1196. Creates an query graph node of 'update' type to be used in the MySQL
  1197. interface.
  1198. @return own: update node */
  1199. UNIV_INTERN
  1200. upd_node_t*
  1201. row_create_update_node_for_mysql(
  1202. /*=============================*/
  1203. dict_table_t* table, /*!< in: table to update */
  1204. mem_heap_t* heap) /*!< in: mem heap from which allocated */
  1205. {
  1206. upd_node_t* node;
  1207. node = upd_node_create(heap);
  1208. node->in_mysql_interface = TRUE;
  1209. node->is_delete = FALSE;
  1210. node->searched_update = FALSE;
  1211. node->select = NULL;
  1212. node->pcur = btr_pcur_create_for_mysql();
  1213. node->table = table;
  1214. node->update = upd_create(dict_table_get_n_cols(table), heap);
  1215. node->update_n_fields = dict_table_get_n_cols(table);
  1216. UT_LIST_INIT(node->columns);
  1217. node->has_clust_rec_x_lock = TRUE;
  1218. node->cmpl_info = 0;
  1219. node->table_sym = NULL;
  1220. node->col_assign_list = NULL;
  1221. return(node);
  1222. }
  1223. /*********************************************************************//**
  1224. Gets pointer to a prebuilt update vector used in updates. If the update
  1225. graph has not yet been built in the prebuilt struct, then this function
  1226. first builds it.
  1227. @return prebuilt update vector */
  1228. UNIV_INTERN
  1229. upd_t*
  1230. row_get_prebuilt_update_vector(
  1231. /*===========================*/
  1232. row_prebuilt_t* prebuilt) /*!< in: prebuilt struct in MySQL
  1233. handle */
  1234. {
  1235. dict_table_t* table = prebuilt->table;
  1236. upd_node_t* node;
  1237. ut_ad(prebuilt && table && prebuilt->trx);
  1238. if (prebuilt->upd_node == NULL) {
  1239. /* Not called before for this handle: create an update node
  1240. and query graph to the prebuilt struct */
  1241. node = row_create_update_node_for_mysql(table, prebuilt->heap);
  1242. prebuilt->upd_node = node;
  1243. prebuilt->upd_graph = static_cast<que_fork_t*>(
  1244. que_node_get_parent(
  1245. pars_complete_graph_for_exec(
  1246. static_cast<upd_node_t*>(node),
  1247. prebuilt->trx, prebuilt->heap)));
  1248. prebuilt->upd_graph->state = QUE_FORK_ACTIVE;
  1249. }
  1250. return(prebuilt->upd_node->update);
  1251. }
  1252. /********************************************************************
  1253. Handle an update of a column that has an FTS index. */
  1254. static
  1255. void
  1256. row_fts_do_update(
  1257. /*==============*/
  1258. trx_t* trx, /* in: transaction */
  1259. dict_table_t* table, /* in: Table with FTS index */
  1260. doc_id_t old_doc_id, /* in: old document id */
  1261. doc_id_t new_doc_id) /* in: new document id */
  1262. {
  1263. if (trx->fts_next_doc_id) {
  1264. fts_trx_add_op(trx, table, old_doc_id, FTS_DELETE, NULL);
  1265. fts_trx_add_op(trx, table, new_doc_id, FTS_INSERT, NULL);
  1266. }
  1267. }
  1268. /************************************************************************
  1269. Handles FTS matters for an update or a delete.
  1270. NOTE: should not be called if the table does not have an FTS index. .*/
  1271. static
  1272. dberr_t
  1273. row_fts_update_or_delete(
  1274. /*=====================*/
  1275. row_prebuilt_t* prebuilt) /* in: prebuilt struct in MySQL
  1276. handle */
  1277. {
  1278. trx_t* trx = prebuilt->trx;
  1279. dict_table_t* table = prebuilt->table;
  1280. upd_node_t* node = prebuilt->upd_node;
  1281. doc_id_t old_doc_id = prebuilt->fts_doc_id;
  1282. ut_a(dict_table_has_fts_index(prebuilt->table));
  1283. /* Deletes are simple; get them out of the way first. */
  1284. if (node->is_delete) {
  1285. /* A delete affects all FTS indexes, so we pass NULL */
  1286. fts_trx_add_op(trx, table, old_doc_id, FTS_DELETE, NULL);
  1287. } else {
  1288. doc_id_t new_doc_id;
  1289. new_doc_id = fts_read_doc_id((byte*) &trx->fts_next_doc_id);
  1290. if (new_doc_id == 0) {
  1291. fprintf(stderr, " InnoDB FTS: Doc ID cannot be 0 \n");
  1292. return(DB_FTS_INVALID_DOCID);
  1293. }
  1294. row_fts_do_update(trx, table, old_doc_id, new_doc_id);
  1295. }
  1296. return(DB_SUCCESS);
  1297. }
  1298. /*********************************************************************//**
  1299. Initialize the Doc ID system for FK table with FTS index */
  1300. static
  1301. void
  1302. init_fts_doc_id_for_ref(
  1303. /*====================*/
  1304. dict_table_t* table, /*!< in: table */
  1305. ulint* depth) /*!< in: recusive call depth */
  1306. {
  1307. dict_foreign_t* foreign;
  1308. table->fk_max_recusive_level = 0;
  1309. (*depth)++;
  1310. /* Limit on tables involved in cascading delete/update */
  1311. if (*depth > FK_MAX_CASCADE_DEL) {
  1312. return;
  1313. }
  1314. /* Loop through this table's referenced list and also
  1315. recursively traverse each table's foreign table list */
  1316. for (dict_foreign_set::iterator it = table->referenced_set.begin();
  1317. it != table->referenced_set.end();
  1318. ++it) {
  1319. foreign = *it;
  1320. if (foreign->foreign_table == NULL) {
  1321. break;
  1322. }
  1323. if (foreign->foreign_table->fts != NULL) {
  1324. fts_init_doc_id(foreign->foreign_table);
  1325. }
  1326. if (!foreign->foreign_table->referenced_set.empty()
  1327. && foreign->foreign_table != table) {
  1328. init_fts_doc_id_for_ref(
  1329. foreign->foreign_table, depth);
  1330. }
  1331. }
  1332. }
  1333. /*********************************************************************//**
  1334. Does an update or delete of a row for MySQL.
  1335. @return error code or DB_SUCCESS */
  1336. UNIV_INTERN
  1337. dberr_t
  1338. row_update_for_mysql(
  1339. /*=================*/
  1340. byte* mysql_rec, /*!< in: the row to be updated, in
  1341. the MySQL format */
  1342. row_prebuilt_t* prebuilt) /*!< in: prebuilt struct in MySQL
  1343. handle */
  1344. {
  1345. trx_savept_t savept;
  1346. dberr_t err;
  1347. que_thr_t* thr;
  1348. ibool was_lock_wait;
  1349. dict_index_t* clust_index;
  1350. /* ulint ref_len; */
  1351. upd_node_t* node;
  1352. dict_table_t* table = prebuilt->table;
  1353. trx_t* trx = prebuilt->trx;
  1354. ulint fk_depth = 0;
  1355. ut_ad(prebuilt != NULL);
  1356. ut_ad(trx != NULL);
  1357. UT_NOT_USED(mysql_rec);
  1358. if (prebuilt->table->ibd_file_missing) {
  1359. ut_print_timestamp(stderr);
  1360. fprintf(stderr, " InnoDB: Error:\n"
  1361. "InnoDB: MySQL is trying to use a table handle"
  1362. " but the .ibd file for\n"
  1363. "InnoDB: table %s does not exist.\n"
  1364. "InnoDB: Have you deleted the .ibd file"
  1365. " from the database directory under\n"
  1366. "InnoDB: the MySQL datadir, or have you"
  1367. " used DISCARD TABLESPACE?\n"
  1368. "InnoDB: Look from\n"
  1369. "InnoDB: " REFMAN "innodb-troubleshooting.html\n"
  1370. "InnoDB: how you can resolve the problem.\n",
  1371. prebuilt->table->name);
  1372. return(DB_ERROR);
  1373. }
  1374. if (UNIV_UNLIKELY(prebuilt->magic_n != ROW_PREBUILT_ALLOCATED)) {
  1375. fprintf(stderr,
  1376. "InnoDB: Error: trying to free a corrupt\n"
  1377. "InnoDB: table handle. Magic n %lu, table name ",
  1378. (ulong) prebuilt->magic_n);
  1379. ut_print_name(stderr, trx, TRUE, prebuilt->table->name);
  1380. putc('\n', stderr);
  1381. mem_analyze_corruption(prebuilt);
  1382. ut_error;
  1383. }
  1384. if (UNIV_UNLIKELY(srv_force_recovery)) {
  1385. fputs("InnoDB: innodb_force_recovery is on: we do not allow\n"
  1386. "InnoDB: database modifications by the user. Shut down\n"
  1387. "InnoDB: mysqld and edit my.cnf so that"
  1388. "InnoDB: innodb_force_... is removed.\n",
  1389. stderr);
  1390. return(DB_READ_ONLY);
  1391. }
  1392. DEBUG_SYNC_C("innodb_row_update_for_mysql_begin");
  1393. trx->op_info = "updating or deleting";
  1394. row_mysql_delay_if_needed();
  1395. trx_start_if_not_started_xa(trx);
  1396. if (dict_table_is_referenced_by_foreign_key(table)) {
  1397. /* Share lock the data dictionary to prevent any
  1398. table dictionary (for foreign constraint) change.
  1399. This is similar to row_ins_check_foreign_constraint
  1400. check protect by the dictionary lock as well.
  1401. In the future, this can be removed once the Foreign
  1402. key MDL is implemented */
  1403. row_mysql_freeze_data_dictionary(trx);
  1404. init_fts_doc_id_for_ref(table, &fk_depth);
  1405. row_mysql_unfreeze_data_dictionary(trx);
  1406. }
  1407. node = prebuilt->upd_node;
  1408. clust_index = dict_table_get_first_index(table);
  1409. if (prebuilt->pcur.btr_cur.index == clust_index) {
  1410. btr_pcur_copy_stored_position(node->pcur, &prebuilt->pcur);
  1411. } else {
  1412. btr_pcur_copy_stored_position(node->pcur,
  1413. &prebuilt->clust_pcur);
  1414. }
  1415. ut_a(node->pcur->rel_pos == BTR_PCUR_ON);
  1416. /* MySQL seems to call rnd_pos before updating each row it
  1417. has cached: we can get the correct cursor position from
  1418. prebuilt->pcur; NOTE that we cannot build the row reference
  1419. from mysql_rec if the clustered index was automatically
  1420. generated for the table: MySQL does not know anything about
  1421. the row id used as the clustered index key */
  1422. savept = trx_savept_take(trx);
  1423. thr = que_fork_get_first_thr(prebuilt->upd_graph);
  1424. node->state = UPD_NODE_UPDATE_CLUSTERED;
  1425. ut_ad(!prebuilt->sql_stat_start);
  1426. que_thr_move_to_run_state_for_mysql(thr, trx);
  1427. run_again:
  1428. thr->run_node = node;
  1429. thr->prev_node = node;
  1430. thr->fk_cascade_depth = 0;
  1431. row_upd_step(thr);
  1432. err = trx->error_state;
  1433. /* Reset fk_cascade_depth back to 0 */
  1434. thr->fk_cascade_depth = 0;
  1435. if (err != DB_SUCCESS) {
  1436. que_thr_stop_for_mysql(thr);
  1437. if (err == DB_RECORD_NOT_FOUND) {
  1438. trx->error_state = DB_SUCCESS;
  1439. trx->op_info = "";
  1440. return(err);
  1441. }
  1442. thr->lock_state= QUE_THR_LOCK_ROW;
  1443. DEBUG_SYNC(trx->mysql_thd, "row_update_for_mysql_error");
  1444. was_lock_wait = row_mysql_handle_errors(&err, trx, thr,
  1445. &savept);
  1446. thr->lock_state= QUE_THR_LOCK_NOLOCK;
  1447. if (was_lock_wait) {
  1448. goto run_again;
  1449. }
  1450. trx->op_info = "";
  1451. return(err);
  1452. }
  1453. que_thr_stop_for_mysql_no_error(thr, trx);
  1454. if (dict_table_has_fts_index(table)
  1455. && trx->fts_next_doc_id != UINT64_UNDEFINED) {
  1456. err = row_fts_update_or_delete(prebuilt);
  1457. if (err != DB_SUCCESS) {
  1458. trx->op_info = "";
  1459. return(err);
  1460. }
  1461. }
  1462. if (node->is_delete) {
  1463. /* Not protected by dict_table_stats_lock() for performance
  1464. reasons, we would rather get garbage in stat_n_rows (which is
  1465. just an estimate anyway) than protecting the following code
  1466. with a latch. */
  1467. dict_table_n_rows_dec(prebuilt->table);
  1468. srv_stats.n_rows_deleted.add((size_t)trx->id, 1);
  1469. } else {
  1470. srv_stats.n_rows_updated.add((size_t)trx->id, 1);
  1471. }
  1472. /* We update table statistics only if it is a DELETE or UPDATE
  1473. that changes indexed columns, UPDATEs that change only non-indexed
  1474. columns would not affect statistics. */
  1475. if (node->is_delete || !(node->cmpl_info & UPD_NODE_NO_ORD_CHANGE)) {
  1476. row_update_statistics_if_needed(prebuilt->table);
  1477. }
  1478. trx->op_info = "";
  1479. return(err);
  1480. }
  1481. /*********************************************************************//**
  1482. This can only be used when srv_locks_unsafe_for_binlog is TRUE or this
  1483. session is using a READ COMMITTED or READ UNCOMMITTED isolation level.
  1484. Before calling this function row_search_for_mysql() must have
  1485. initialized prebuilt->new_rec_locks to store the information which new
  1486. record locks really were set. This function removes a newly set
  1487. clustered index record lock under prebuilt->pcur or
  1488. prebuilt->clust_pcur. Thus, this implements a 'mini-rollback' that
  1489. releases the latest clustered index record lock we set.
  1490. @return error code or DB_SUCCESS */
  1491. UNIV_INTERN
  1492. void
  1493. row_unlock_for_mysql(
  1494. /*=================*/
  1495. row_prebuilt_t* prebuilt, /*!< in/out: prebuilt struct in MySQL
  1496. handle */
  1497. ibool has_latches_on_recs)/*!< in: TRUE if called so
  1498. that we have the latches on
  1499. the records under pcur and
  1500. clust_pcur, and we do not need
  1501. to reposition the cursors. */
  1502. {
  1503. btr_pcur_t* pcur = &prebuilt->pcur;
  1504. btr_pcur_t* clust_pcur = &prebuilt->clust_pcur;
  1505. trx_t* trx = prebuilt->trx;
  1506. ut_ad(prebuilt != NULL);
  1507. ut_ad(trx != NULL);
  1508. if (UNIV_UNLIKELY
  1509. (!srv_locks_unsafe_for_binlog
  1510. && trx->isolation_level > TRX_ISO_READ_COMMITTED)) {
  1511. fprintf(stderr,
  1512. "InnoDB: Error: calling row_unlock_for_mysql though\n"
  1513. "InnoDB: innodb_locks_unsafe_for_binlog is FALSE and\n"
  1514. "InnoDB: this session is not using"
  1515. " READ COMMITTED isolation level.\n");
  1516. return;
  1517. }
  1518. trx->op_info = "unlock_row";
  1519. if (prebuilt->new_rec_locks >= 1) {
  1520. const rec_t* rec;
  1521. dict_index_t* index;
  1522. trx_id_t rec_trx_id;
  1523. mtr_t mtr;
  1524. mtr_start(&mtr);
  1525. /* Restore the cursor position and find the record */
  1526. if (!has_latches_on_recs) {
  1527. btr_pcur_restore_position(BTR_SEARCH_LEAF, pcur, &mtr);
  1528. }
  1529. rec = btr_pcur_get_rec(pcur);
  1530. index = btr_pcur_get_btr_cur(pcur)->index;
  1531. if (prebuilt->new_rec_locks >= 2) {
  1532. /* Restore the cursor position and find the record
  1533. in the clustered index. */
  1534. if (!has_latches_on_recs) {
  1535. btr_pcur_restore_position(BTR_SEARCH_LEAF,
  1536. clust_pcur, &mtr);
  1537. }
  1538. rec = btr_pcur_get_rec(clust_pcur);
  1539. index = btr_pcur_get_btr_cur(clust_pcur)->index;
  1540. }
  1541. if (!dict_index_is_clust(index)) {
  1542. /* This is not a clustered index record. We
  1543. do not know how to unlock the record. */
  1544. goto no_unlock;
  1545. }
  1546. /* If the record has been modified by this
  1547. transaction, do not unlock it. */
  1548. if (index->trx_id_offset) {
  1549. rec_trx_id = trx_read_trx_id(rec
  1550. + index->trx_id_offset);
  1551. } else {
  1552. mem_heap_t* heap = NULL;
  1553. ulint offsets_[REC_OFFS_NORMAL_SIZE];
  1554. ulint* offsets = offsets_;
  1555. rec_offs_init(offsets_);
  1556. offsets = rec_get_offsets(rec, index, offsets,
  1557. ULINT_UNDEFINED, &heap);
  1558. rec_trx_id = row_get_rec_trx_id(rec, index, offsets);
  1559. if (UNIV_LIKELY_NULL(heap)) {
  1560. mem_heap_free(heap);
  1561. }
  1562. }
  1563. if (rec_trx_id != trx->id) {
  1564. /* We did not update the record: unlock it */
  1565. rec = btr_pcur_get_rec(pcur);
  1566. lock_rec_unlock(
  1567. trx,
  1568. btr_pcur_get_block(pcur),
  1569. rec,
  1570. static_cast<enum lock_mode>(
  1571. prebuilt->select_lock_type));
  1572. if (prebuilt->new_rec_locks >= 2) {
  1573. rec = btr_pcur_get_rec(clust_pcur);
  1574. lock_rec_unlock(
  1575. trx,
  1576. btr_pcur_get_block(clust_pcur),
  1577. rec,
  1578. static_cast<enum lock_mode>(
  1579. prebuilt->select_lock_type));
  1580. }
  1581. }
  1582. no_unlock:
  1583. mtr_commit(&mtr);
  1584. }
  1585. trx->op_info = "";
  1586. }
  1587. /**********************************************************************//**
  1588. Does a cascaded delete or set null in a foreign key operation.
  1589. @return error code or DB_SUCCESS */
  1590. UNIV_INTERN
  1591. dberr_t
  1592. row_update_cascade_for_mysql(
  1593. /*=========================*/
  1594. que_thr_t* thr, /*!< in: query thread */
  1595. upd_node_t* node, /*!< in: update node used in the cascade
  1596. or set null operation */
  1597. dict_table_t* table) /*!< in: table where we do the operation */
  1598. {
  1599. dberr_t err;
  1600. trx_t* trx;
  1601. trx = thr_get_trx(thr);
  1602. /* Increment fk_cascade_depth to record the recursive call depth on
  1603. a single update/delete that affects multiple tables chained
  1604. together with foreign key relations. */
  1605. thr->fk_cascade_depth++;
  1606. if (thr->fk_cascade_depth > FK_MAX_CASCADE_DEL) {
  1607. return(DB_FOREIGN_EXCEED_MAX_CASCADE);
  1608. }
  1609. run_again:
  1610. thr->run_node = node;
  1611. thr->prev_node = node;
  1612. DEBUG_SYNC_C("foreign_constraint_update_cascade");
  1613. row_upd_step(thr);
  1614. /* The recursive call for cascading update/delete happens
  1615. in above row_upd_step(), reset the counter once we come
  1616. out of the recursive call, so it does not accumulate for
  1617. different row deletes */
  1618. thr->fk_cascade_depth = 0;
  1619. err = trx->error_state;
  1620. /* Note that the cascade node is a subnode of another InnoDB
  1621. query graph node. We do a normal lock wait in this node, but
  1622. all errors are handled by the parent node. */
  1623. if (err == DB_LOCK_WAIT) {
  1624. /* Handle lock wait here */
  1625. que_thr_stop_for_mysql(thr);
  1626. lock_wait_suspend_thread(thr);
  1627. /* Note that a lock wait may also end in a lock wait timeout,
  1628. or this transaction is picked as a victim in selective
  1629. deadlock resolution */
  1630. if (trx->error_state != DB_SUCCESS) {
  1631. return(trx->error_state);
  1632. }
  1633. /* Retry operation after a normal lock wait */
  1634. goto run_again;
  1635. }
  1636. if (err != DB_SUCCESS) {
  1637. return(err);
  1638. }
  1639. if (node->is_delete) {
  1640. /* Not protected by dict_table_stats_lock() for performance
  1641. reasons, we would rather get garbage in stat_n_rows (which is
  1642. just an estimate anyway) than protecting the following code
  1643. with a latch. */
  1644. dict_table_n_rows_dec(table);
  1645. srv_stats.n_rows_deleted.add((size_t)trx->id, 1);
  1646. } else {
  1647. srv_stats.n_rows_updated.add((size_t)trx->id, 1);
  1648. }
  1649. row_update_statistics_if_needed(table);
  1650. return(err);
  1651. }
  1652. /*********************************************************************//**
  1653. Checks if a table is such that we automatically created a clustered
  1654. index on it (on row id).
  1655. @return TRUE if the clustered index was generated automatically */
  1656. UNIV_INTERN
  1657. ibool
  1658. row_table_got_default_clust_index(
  1659. /*==============================*/
  1660. const dict_table_t* table) /*!< in: table */
  1661. {
  1662. const dict_index_t* clust_index;
  1663. clust_index = dict_table_get_first_index(table);
  1664. return(dict_index_get_nth_col(clust_index, 0)->mtype == DATA_SYS);
  1665. }
  1666. /*********************************************************************//**
  1667. Locks the data dictionary in shared mode from modifications, for performing
  1668. foreign key check, rollback, or other operation invisible to MySQL. */
  1669. UNIV_INTERN
  1670. void
  1671. row_mysql_freeze_data_dictionary_func(
  1672. /*==================================*/
  1673. trx_t* trx, /*!< in/out: transaction */
  1674. const char* file, /*!< in: file name */
  1675. ulint line) /*!< in: line number */
  1676. {
  1677. ut_a(trx->dict_operation_lock_mode == 0);
  1678. rw_lock_s_lock_inline(&dict_operation_lock, 0, file, line);
  1679. trx->dict_operation_lock_mode = RW_S_LATCH;
  1680. }
  1681. /*********************************************************************//**
  1682. Unlocks the data dictionary shared lock. */
  1683. UNIV_INTERN
  1684. void
  1685. row_mysql_unfreeze_data_dictionary(
  1686. /*===============================*/
  1687. trx_t* trx) /*!< in/out: transaction */
  1688. {
  1689. ut_ad(lock_trx_has_sys_table_locks(trx) == NULL);
  1690. ut_a(trx->dict_operation_lock_mode == RW_S_LATCH);
  1691. rw_lock_s_unlock(&dict_operation_lock);
  1692. trx->dict_operation_lock_mode = 0;
  1693. }
  1694. /*********************************************************************//**
  1695. Locks the data dictionary exclusively for performing a table create or other
  1696. data dictionary modification operation. */
  1697. UNIV_INTERN
  1698. void
  1699. row_mysql_lock_data_dictionary_func(
  1700. /*================================*/
  1701. trx_t* trx, /*!< in/out: transaction */
  1702. const char* file, /*!< in: file name */
  1703. ulint line) /*!< in: line number */
  1704. {
  1705. ut_a(trx->dict_operation_lock_mode == 0
  1706. || trx->dict_operation_lock_mode == RW_X_LATCH);
  1707. /* Serialize data dictionary operations with dictionary mutex:
  1708. no deadlocks or lock waits can occur then in these operations */
  1709. rw_lock_x_lock_inline(&dict_operation_lock, 0, file, line);
  1710. trx->dict_operation_lock_mode = RW_X_LATCH;
  1711. mutex_enter(&(dict_sys->mutex));
  1712. }
  1713. /*********************************************************************//**
  1714. Unlocks the data dictionary exclusive lock. */
  1715. UNIV_INTERN
  1716. void
  1717. row_mysql_unlock_data_dictionary(
  1718. /*=============================*/
  1719. trx_t* trx) /*!< in/out: transaction */
  1720. {
  1721. ut_ad(lock_trx_has_sys_table_locks(trx) == NULL);
  1722. ut_a(trx->dict_operation_lock_mode == RW_X_LATCH);
  1723. /* Serialize data dictionary operations with dictionary mutex:
  1724. no deadlocks can occur then in these operations */
  1725. mutex_exit(&(dict_sys->mutex));
  1726. rw_lock_x_unlock(&dict_operation_lock);
  1727. trx->dict_operation_lock_mode = 0;
  1728. }
  1729. /*********************************************************************//**
  1730. Creates a table for MySQL. If the name of the table ends in
  1731. one of "innodb_monitor", "innodb_lock_monitor", "innodb_tablespace_monitor",
  1732. "innodb_table_monitor", then this will also start the printing of monitor
  1733. output by the master thread. If the table name ends in "innodb_mem_validate",
  1734. InnoDB will try to invoke mem_validate(). On failure the transaction will
  1735. be rolled back and the 'table' object will be freed.
  1736. @return error code or DB_SUCCESS */
  1737. UNIV_INTERN
  1738. dberr_t
  1739. row_create_table_for_mysql(
  1740. /*=======================*/
  1741. dict_table_t* table, /*!< in, own: table definition
  1742. (will be freed, or on DB_SUCCESS
  1743. added to the data dictionary cache) */
  1744. trx_t* trx, /*!< in/out: transaction */
  1745. bool commit) /*!< in: if true, commit the transaction */
  1746. {
  1747. tab_node_t* node;
  1748. mem_heap_t* heap;
  1749. que_thr_t* thr;
  1750. const char* table_name;
  1751. ulint table_name_len;
  1752. dberr_t err;
  1753. #ifdef UNIV_SYNC_DEBUG
  1754. ut_ad(rw_lock_own(&dict_operation_lock, RW_LOCK_EX));
  1755. #endif /* UNIV_SYNC_DEBUG */
  1756. ut_ad(mutex_own(&(dict_sys->mutex)));
  1757. ut_ad(trx->dict_operation_lock_mode == RW_X_LATCH);
  1758. DBUG_EXECUTE_IF(
  1759. "ib_create_table_fail_at_start_of_row_create_table_for_mysql",
  1760. goto err_exit;
  1761. );
  1762. trx->op_info = "creating table";
  1763. if (row_mysql_is_system_table(table->name)) {
  1764. fprintf(stderr,
  1765. "InnoDB: Error: trying to create a MySQL system"
  1766. " table %s of type InnoDB.\n"
  1767. "InnoDB: MySQL system tables must be"
  1768. " of the MyISAM type!\n",
  1769. table->name);
  1770. #ifndef DBUG_OFF
  1771. err_exit:
  1772. #endif /* !DBUG_OFF */
  1773. dict_mem_table_free(table);
  1774. if (commit) {
  1775. trx_commit_for_mysql(trx);
  1776. }
  1777. trx->op_info = "";
  1778. return(DB_ERROR);
  1779. }
  1780. trx_start_if_not_started_xa(trx);
  1781. /* The table name is prefixed with the database name and a '/'.
  1782. Certain table names starting with 'innodb_' have their special
  1783. meaning regardless of the database name. Thus, we need to
  1784. ignore the database name prefix in the comparisons. */
  1785. table_name = dict_remove_db_name(table->name);
  1786. table_name_len = strlen(table_name) + 1;
  1787. if (STR_EQ(table_name, table_name_len, S_innodb_monitor)) {
  1788. /* Table equals "innodb_monitor":
  1789. start monitor prints */
  1790. srv_print_innodb_monitor = TRUE;
  1791. /* The lock timeout monitor thread also takes care
  1792. of InnoDB monitor prints */
  1793. os_event_set(lock_sys->timeout_event);
  1794. } else if (STR_EQ(table_name, table_name_len,
  1795. S_innodb_lock_monitor)) {
  1796. srv_print_innodb_monitor = TRUE;
  1797. srv_print_innodb_lock_monitor = TRUE;
  1798. os_event_set(lock_sys->timeout_event);
  1799. } else if (STR_EQ(table_name, table_name_len,
  1800. S_innodb_tablespace_monitor)) {
  1801. srv_print_innodb_tablespace_monitor = TRUE;
  1802. os_event_set(lock_sys->timeout_event);
  1803. } else if (STR_EQ(table_name, table_name_len,
  1804. S_innodb_table_monitor)) {
  1805. srv_print_innodb_table_monitor = TRUE;
  1806. os_event_set(lock_sys->timeout_event);
  1807. #ifdef UNIV_MEM_DEBUG
  1808. } else if (STR_EQ(table_name, table_name_len,
  1809. S_innodb_mem_validate)) {
  1810. /* We define here a debugging feature intended for
  1811. developers */
  1812. fputs("Validating InnoDB memory:\n"
  1813. "to use this feature you must compile InnoDB with\n"
  1814. "UNIV_MEM_DEBUG defined in univ.i and"
  1815. " the server must be\n"
  1816. "quiet because allocation from a mem heap"
  1817. " is not protected\n"
  1818. "by any semaphore.\n", stderr);
  1819. ut_a(mem_validate());
  1820. fputs("Memory validated\n", stderr);
  1821. #endif /* UNIV_MEM_DEBUG */
  1822. }
  1823. heap = mem_heap_create(512);
  1824. switch (trx_get_dict_operation(trx)) {
  1825. case TRX_DICT_OP_NONE:
  1826. trx_set_dict_operation(trx, TRX_DICT_OP_TABLE);
  1827. case TRX_DICT_OP_TABLE:
  1828. break;
  1829. case TRX_DICT_OP_INDEX:
  1830. /* If the transaction was previously flagged as
  1831. TRX_DICT_OP_INDEX, we should be creating auxiliary
  1832. tables for full-text indexes. */
  1833. ut_ad(strstr(table->name, "/FTS_") != NULL);
  1834. }
  1835. node = tab_create_graph_create(table, heap, commit);
  1836. thr = pars_complete_graph_for_exec(node, trx, heap);
  1837. ut_a(thr == que_fork_start_command(
  1838. static_cast<que_fork_t*>(que_node_get_parent(thr))));
  1839. que_run_threads(thr);
  1840. err = trx->error_state;
  1841. if (table->space != TRX_SYS_SPACE) {
  1842. ut_a(DICT_TF2_FLAG_IS_SET(table, DICT_TF2_USE_TABLESPACE));
  1843. /* Update SYS_TABLESPACES and SYS_DATAFILES if a new
  1844. tablespace was created. */
  1845. if (err == DB_SUCCESS) {
  1846. char* path;
  1847. path = fil_space_get_first_path(table->space);
  1848. err = dict_create_add_tablespace_to_dictionary(
  1849. table->space, table->name,
  1850. fil_space_get_flags(table->space),
  1851. path, trx, commit);
  1852. mem_free(path);
  1853. }
  1854. if (err != DB_SUCCESS) {
  1855. /* We must delete the link file. */
  1856. fil_delete_link_file(table->name);
  1857. }
  1858. }
  1859. switch (err) {
  1860. case DB_SUCCESS:
  1861. break;
  1862. case DB_OUT_OF_FILE_SPACE:
  1863. trx->error_state = DB_SUCCESS;
  1864. trx_rollback_to_savepoint(trx, NULL);
  1865. ut_print_timestamp(stderr);
  1866. fputs(" InnoDB: Warning: cannot create table ",
  1867. stderr);
  1868. ut_print_name(stderr, trx, TRUE, table->name);
  1869. fputs(" because tablespace full\n", stderr);
  1870. if (dict_table_open_on_name(table->name, TRUE, FALSE,
  1871. DICT_ERR_IGNORE_NONE)) {
  1872. /* Make things easy for the drop table code. */
  1873. if (table->can_be_evicted) {
  1874. dict_table_move_from_lru_to_non_lru(table);
  1875. }
  1876. dict_table_close(table, TRUE, FALSE);
  1877. row_drop_table_for_mysql(table->name, trx, FALSE);
  1878. if (commit) {
  1879. trx_commit_for_mysql(trx);
  1880. }
  1881. } else {
  1882. dict_mem_table_free(table);
  1883. }
  1884. break;
  1885. case DB_TOO_MANY_CONCURRENT_TRXS:
  1886. /* We already have .ibd file here. it should be deleted. */
  1887. if (table->space
  1888. && fil_delete_tablespace(
  1889. table->space,
  1890. BUF_REMOVE_FLUSH_NO_WRITE)
  1891. != DB_SUCCESS) {
  1892. ut_print_timestamp(stderr);
  1893. fprintf(stderr,
  1894. " InnoDB: Error: not able to"
  1895. " delete tablespace %lu of table ",
  1896. (ulong) table->space);
  1897. ut_print_name(stderr, trx, TRUE, table->name);
  1898. fputs("!\n", stderr);
  1899. }
  1900. /* fall through */
  1901. case DB_DUPLICATE_KEY:
  1902. case DB_TABLESPACE_EXISTS:
  1903. default:
  1904. trx->error_state = DB_SUCCESS;
  1905. trx_rollback_to_savepoint(trx, NULL);
  1906. dict_mem_table_free(table);
  1907. break;
  1908. }
  1909. que_graph_free((que_t*) que_node_get_parent(thr));
  1910. trx->op_info = "";
  1911. return(err);
  1912. }
  1913. /*********************************************************************//**
  1914. Does an index creation operation for MySQL. TODO: currently failure
  1915. to create an index results in dropping the whole table! This is no problem
  1916. currently as all indexes must be created at the same time as the table.
  1917. @return error number or DB_SUCCESS */
  1918. UNIV_INTERN
  1919. dberr_t
  1920. row_create_index_for_mysql(
  1921. /*=======================*/
  1922. dict_index_t* index, /*!< in, own: index definition
  1923. (will be freed) */
  1924. trx_t* trx, /*!< in: transaction handle */
  1925. const ulint* field_lengths) /*!< in: if not NULL, must contain
  1926. dict_index_get_n_fields(index)
  1927. actual field lengths for the
  1928. index columns, which are
  1929. then checked for not being too
  1930. large. */
  1931. {
  1932. ind_node_t* node;
  1933. mem_heap_t* heap;
  1934. que_thr_t* thr;
  1935. dberr_t err;
  1936. ulint i;
  1937. ulint len;
  1938. char* table_name;
  1939. char* index_name;
  1940. dict_table_t* table;
  1941. ibool is_fts;
  1942. #ifdef UNIV_SYNC_DEBUG
  1943. ut_ad(rw_lock_own(&dict_operation_lock, RW_LOCK_EX));
  1944. #endif /* UNIV_SYNC_DEBUG */
  1945. ut_ad(mutex_own(&(dict_sys->mutex)));
  1946. trx->op_info = "creating index";
  1947. /* Copy the table name because we may want to drop the
  1948. table later, after the index object is freed (inside
  1949. que_run_threads()) and thus index->table_name is not available. */
  1950. table_name = mem_strdup(index->table_name);
  1951. index_name = mem_strdup(index->name);
  1952. is_fts = (index->type == DICT_FTS);
  1953. table = dict_table_open_on_name(table_name, TRUE, TRUE,
  1954. DICT_ERR_IGNORE_NONE);
  1955. trx_start_if_not_started_xa(trx);
  1956. for (i = 0; i < index->n_def; i++) {
  1957. /* Check that prefix_len and actual length
  1958. < DICT_MAX_INDEX_COL_LEN */
  1959. len = dict_index_get_nth_field(index, i)->prefix_len;
  1960. if (field_lengths && field_lengths[i]) {
  1961. len = ut_max(len, field_lengths[i]);
  1962. }
  1963. DBUG_EXECUTE_IF(
  1964. "ib_create_table_fail_at_create_index",
  1965. len = DICT_MAX_FIELD_LEN_BY_FORMAT(table) + 1;
  1966. );
  1967. /* Column or prefix length exceeds maximum column length */
  1968. if (len > (ulint) DICT_MAX_FIELD_LEN_BY_FORMAT(table)) {
  1969. err = DB_TOO_BIG_INDEX_COL;
  1970. dict_mem_index_free(index);
  1971. goto error_handling;
  1972. }
  1973. }
  1974. heap = mem_heap_create(512);
  1975. trx_set_dict_operation(trx, TRX_DICT_OP_TABLE);
  1976. /* Note that the space id where we store the index is inherited from
  1977. the table in dict_build_index_def_step() in dict0crea.cc. */
  1978. node = ind_create_graph_create(index, heap, true);
  1979. thr = pars_complete_graph_for_exec(node, trx, heap);
  1980. ut_a(thr == que_fork_start_command(
  1981. static_cast<que_fork_t*>(que_node_get_parent(thr))));
  1982. que_run_threads(thr);
  1983. err = trx->error_state;
  1984. que_graph_free((que_t*) que_node_get_parent(thr));
  1985. /* Create the index specific FTS auxiliary tables. */
  1986. if (err == DB_SUCCESS && is_fts) {
  1987. dict_index_t* idx;
  1988. idx = dict_table_get_index_on_name(table, index_name);
  1989. ut_ad(idx);
  1990. err = fts_create_index_tables(trx, idx);
  1991. }
  1992. error_handling:
  1993. dict_table_close(table, TRUE, FALSE);
  1994. if (err != DB_SUCCESS) {
  1995. /* We have special error handling here */
  1996. trx->error_state = DB_SUCCESS;
  1997. trx_rollback_to_savepoint(trx, NULL);
  1998. row_drop_table_for_mysql(table_name, trx, FALSE);
  1999. trx_commit_for_mysql(trx);
  2000. trx->error_state = DB_SUCCESS;
  2001. }
  2002. trx->op_info = "";
  2003. mem_free(table_name);
  2004. mem_free(index_name);
  2005. return(err);
  2006. }
  2007. /*********************************************************************//**
  2008. Scans a table create SQL string and adds to the data dictionary
  2009. the foreign key constraints declared in the string. This function
  2010. should be called after the indexes for a table have been created.
  2011. Each foreign key constraint must be accompanied with indexes in
  2012. both participating tables. The indexes are allowed to contain more
  2013. fields than mentioned in the constraint. Check also that foreign key
  2014. constraints which reference this table are ok.
  2015. @return error code or DB_SUCCESS */
  2016. UNIV_INTERN
  2017. dberr_t
  2018. row_table_add_foreign_constraints(
  2019. /*==============================*/
  2020. trx_t* trx, /*!< in: transaction */
  2021. const char* sql_string, /*!< in: table create statement where
  2022. foreign keys are declared like:
  2023. FOREIGN KEY (a, b) REFERENCES table2(c, d),
  2024. table2 can be written also with the
  2025. database name before it: test.table2 */
  2026. size_t sql_length, /*!< in: length of sql_string */
  2027. const char* name, /*!< in: table full name in the
  2028. normalized form
  2029. database_name/table_name */
  2030. ibool reject_fks) /*!< in: if TRUE, fail with error
  2031. code DB_CANNOT_ADD_CONSTRAINT if
  2032. any foreign keys are found. */
  2033. {
  2034. dberr_t err;
  2035. ut_ad(mutex_own(&(dict_sys->mutex)));
  2036. #ifdef UNIV_SYNC_DEBUG
  2037. ut_ad(rw_lock_own(&dict_operation_lock, RW_LOCK_EX));
  2038. #endif /* UNIV_SYNC_DEBUG */
  2039. ut_a(sql_string);
  2040. trx->op_info = "adding foreign keys";
  2041. trx_start_if_not_started_xa(trx);
  2042. trx_set_dict_operation(trx, TRX_DICT_OP_TABLE);
  2043. err = dict_create_foreign_constraints(trx, sql_string, sql_length,
  2044. name, reject_fks);
  2045. DBUG_EXECUTE_IF("ib_table_add_foreign_fail",
  2046. err = DB_DUPLICATE_KEY;);
  2047. DEBUG_SYNC_C("table_add_foreign_constraints");
  2048. if (err == DB_SUCCESS) {
  2049. /* Check that also referencing constraints are ok */
  2050. err = dict_load_foreigns(name, NULL, false, true,
  2051. DICT_ERR_IGNORE_NONE);
  2052. }
  2053. if (err != DB_SUCCESS) {
  2054. /* We have special error handling here */
  2055. trx->error_state = DB_SUCCESS;
  2056. trx_rollback_to_savepoint(trx, NULL);
  2057. row_drop_table_for_mysql(name, trx, FALSE);
  2058. trx_commit_for_mysql(trx);
  2059. trx->error_state = DB_SUCCESS;
  2060. }
  2061. return(err);
  2062. }
  2063. /*********************************************************************//**
  2064. Drops a table for MySQL as a background operation. MySQL relies on Unix
  2065. in ALTER TABLE to the fact that the table handler does not remove the
  2066. table before all handles to it has been removed. Furhermore, the MySQL's
  2067. call to drop table must be non-blocking. Therefore we do the drop table
  2068. as a background operation, which is taken care of by the master thread
  2069. in srv0srv.cc.
  2070. @return error code or DB_SUCCESS */
  2071. static
  2072. dberr_t
  2073. row_drop_table_for_mysql_in_background(
  2074. /*===================================*/
  2075. const char* name) /*!< in: table name */
  2076. {
  2077. dberr_t error;
  2078. trx_t* trx;
  2079. trx = trx_allocate_for_background();
  2080. /* If the original transaction was dropping a table referenced by
  2081. foreign keys, we must set the following to be able to drop the
  2082. table: */
  2083. trx->check_foreigns = FALSE;
  2084. /* fputs("InnoDB: Error: Dropping table ", stderr);
  2085. ut_print_name(stderr, trx, TRUE, name);
  2086. fputs(" in background drop list\n", stderr); */
  2087. /* Try to drop the table in InnoDB */
  2088. error = row_drop_table_for_mysql(name, trx, FALSE);
  2089. /* Flush the log to reduce probability that the .frm files and
  2090. the InnoDB data dictionary get out-of-sync if the user runs
  2091. with innodb_flush_log_at_trx_commit = 0 */
  2092. log_buffer_flush_to_disk();
  2093. trx_commit_for_mysql(trx);
  2094. trx_free_for_background(trx);
  2095. return(error);
  2096. }
  2097. /*********************************************************************//**
  2098. The master thread in srv0srv.cc calls this regularly to drop tables which
  2099. we must drop in background after queries to them have ended. Such lazy
  2100. dropping of tables is needed in ALTER TABLE on Unix.
  2101. @return how many tables dropped + remaining tables in list */
  2102. UNIV_INTERN
  2103. ulint
  2104. row_drop_tables_for_mysql_in_background(void)
  2105. /*=========================================*/
  2106. {
  2107. row_mysql_drop_t* drop;
  2108. dict_table_t* table;
  2109. ulint n_tables;
  2110. ulint n_tables_dropped = 0;
  2111. loop:
  2112. mutex_enter(&row_drop_list_mutex);
  2113. ut_a(row_mysql_drop_list_inited);
  2114. drop = UT_LIST_GET_FIRST(row_mysql_drop_list);
  2115. n_tables = UT_LIST_GET_LEN(row_mysql_drop_list);
  2116. mutex_exit(&row_drop_list_mutex);
  2117. if (drop == NULL) {
  2118. /* All tables dropped */
  2119. return(n_tables + n_tables_dropped);
  2120. }
  2121. DBUG_EXECUTE_IF("row_drop_tables_in_background_sleep",
  2122. os_thread_sleep(5000000);
  2123. );
  2124. table = dict_table_open_on_name(drop->table_name, FALSE, FALSE,
  2125. DICT_ERR_IGNORE_NONE);
  2126. if (table == NULL) {
  2127. /* If for some reason the table has already been dropped
  2128. through some other mechanism, do not try to drop it */
  2129. goto already_dropped;
  2130. }
  2131. if (!table->to_be_dropped) {
  2132. /* There is a scenario: the old table is dropped
  2133. just after it's added into drop list, and new
  2134. table with the same name is created, then we try
  2135. to drop the new table in background. */
  2136. dict_table_close(table, FALSE, FALSE);
  2137. goto already_dropped;
  2138. }
  2139. ut_a(!table->can_be_evicted);
  2140. dict_table_close(table, FALSE, FALSE);
  2141. if (DB_SUCCESS != row_drop_table_for_mysql_in_background(
  2142. drop->table_name)) {
  2143. /* If the DROP fails for some table, we return, and let the
  2144. main thread retry later */
  2145. return(n_tables + n_tables_dropped);
  2146. }
  2147. n_tables_dropped++;
  2148. already_dropped:
  2149. mutex_enter(&row_drop_list_mutex);
  2150. UT_LIST_REMOVE(row_mysql_drop_list, row_mysql_drop_list, drop);
  2151. MONITOR_DEC(MONITOR_BACKGROUND_DROP_TABLE);
  2152. ut_print_timestamp(stderr);
  2153. fputs(" InnoDB: Dropped table ", stderr);
  2154. ut_print_name(stderr, NULL, TRUE, drop->table_name);
  2155. fputs(" in background drop queue.\n", stderr);
  2156. mem_free(drop->table_name);
  2157. mem_free(drop);
  2158. mutex_exit(&row_drop_list_mutex);
  2159. goto loop;
  2160. }
  2161. /*********************************************************************//**
  2162. Get the background drop list length. NOTE: the caller must own the
  2163. drop list mutex!
  2164. @return how many tables in list */
  2165. UNIV_INTERN
  2166. ulint
  2167. row_get_background_drop_list_len_low(void)
  2168. /*======================================*/
  2169. {
  2170. ulint len;
  2171. mutex_enter(&row_drop_list_mutex);
  2172. ut_a(row_mysql_drop_list_inited);
  2173. len = UT_LIST_GET_LEN(row_mysql_drop_list);
  2174. mutex_exit(&row_drop_list_mutex);
  2175. return(len);
  2176. }
  2177. /*********************************************************************//**
  2178. If a table is not yet in the drop list, adds the table to the list of tables
  2179. which the master thread drops in background. We need this on Unix because in
  2180. ALTER TABLE MySQL may call drop table even if the table has running queries on
  2181. it. Also, if there are running foreign key checks on the table, we drop the
  2182. table lazily.
  2183. @return TRUE if the table was not yet in the drop list, and was added there */
  2184. static
  2185. ibool
  2186. row_add_table_to_background_drop_list(
  2187. /*==================================*/
  2188. const char* name) /*!< in: table name */
  2189. {
  2190. row_mysql_drop_t* drop;
  2191. mutex_enter(&row_drop_list_mutex);
  2192. ut_a(row_mysql_drop_list_inited);
  2193. /* Look if the table already is in the drop list */
  2194. for (drop = UT_LIST_GET_FIRST(row_mysql_drop_list);
  2195. drop != NULL;
  2196. drop = UT_LIST_GET_NEXT(row_mysql_drop_list, drop)) {
  2197. if (strcmp(drop->table_name, name) == 0) {
  2198. /* Already in the list */
  2199. mutex_exit(&row_drop_list_mutex);
  2200. return(FALSE);
  2201. }
  2202. }
  2203. drop = static_cast<row_mysql_drop_t*>(
  2204. mem_alloc(sizeof(row_mysql_drop_t)));
  2205. drop->table_name = mem_strdup(name);
  2206. UT_LIST_ADD_LAST(row_mysql_drop_list, row_mysql_drop_list, drop);
  2207. MONITOR_INC(MONITOR_BACKGROUND_DROP_TABLE);
  2208. /* fputs("InnoDB: Adding table ", stderr);
  2209. ut_print_name(stderr, trx, TRUE, drop->table_name);
  2210. fputs(" to background drop list\n", stderr); */
  2211. mutex_exit(&row_drop_list_mutex);
  2212. return(TRUE);
  2213. }
  2214. /*********************************************************************//**
  2215. Reassigns the table identifier of a table.
  2216. @return error code or DB_SUCCESS */
  2217. UNIV_INTERN
  2218. dberr_t
  2219. row_mysql_table_id_reassign(
  2220. /*========================*/
  2221. dict_table_t* table, /*!< in/out: table */
  2222. trx_t* trx, /*!< in/out: transaction */
  2223. table_id_t* new_id) /*!< out: new table id */
  2224. {
  2225. dberr_t err;
  2226. pars_info_t* info = pars_info_create();
  2227. dict_hdr_get_new_id(new_id, NULL, NULL);
  2228. /* Remove all locks except the table-level S and X locks. */
  2229. lock_remove_all_on_table(table, FALSE);
  2230. pars_info_add_ull_literal(info, "old_id", table->id);
  2231. pars_info_add_ull_literal(info, "new_id", *new_id);
  2232. err = que_eval_sql(
  2233. info,
  2234. "PROCEDURE RENUMBER_TABLE_PROC () IS\n"
  2235. "BEGIN\n"
  2236. "UPDATE SYS_TABLES SET ID = :new_id\n"
  2237. " WHERE ID = :old_id;\n"
  2238. "UPDATE SYS_COLUMNS SET TABLE_ID = :new_id\n"
  2239. " WHERE TABLE_ID = :old_id;\n"
  2240. "UPDATE SYS_INDEXES SET TABLE_ID = :new_id\n"
  2241. " WHERE TABLE_ID = :old_id;\n"
  2242. "END;\n", FALSE, trx);
  2243. return(err);
  2244. }
  2245. /*********************************************************************//**
  2246. Setup the pre-requisites for DISCARD TABLESPACE. It will start the transaction,
  2247. acquire the data dictionary lock in X mode and open the table.
  2248. @return table instance or 0 if not found. */
  2249. static
  2250. dict_table_t*
  2251. row_discard_tablespace_begin(
  2252. /*=========================*/
  2253. const char* name, /*!< in: table name */
  2254. trx_t* trx) /*!< in: transaction handle */
  2255. {
  2256. trx->op_info = "discarding tablespace";
  2257. trx_set_dict_operation(trx, TRX_DICT_OP_TABLE);
  2258. trx_start_if_not_started_xa(trx);
  2259. /* Serialize data dictionary operations with dictionary mutex:
  2260. this is to avoid deadlocks during data dictionary operations */
  2261. row_mysql_lock_data_dictionary(trx);
  2262. dict_table_t* table;
  2263. table = dict_table_open_on_name(
  2264. name, TRUE, FALSE, DICT_ERR_IGNORE_NONE);
  2265. if (table) {
  2266. dict_stats_wait_bg_to_stop_using_table(table, trx);
  2267. ut_a(table->space != TRX_SYS_SPACE);
  2268. ut_a(table->n_foreign_key_checks_running == 0);
  2269. }
  2270. return(table);
  2271. }
  2272. /*********************************************************************//**
  2273. Do the foreign key constraint checks.
  2274. @return DB_SUCCESS or error code. */
  2275. static
  2276. dberr_t
  2277. row_discard_tablespace_foreign_key_checks(
  2278. /*======================================*/
  2279. const trx_t* trx, /*!< in: transaction handle */
  2280. const dict_table_t* table) /*!< in: table to be discarded */
  2281. {
  2282. if (srv_read_only_mode || !trx->check_foreigns) {
  2283. return(DB_SUCCESS);
  2284. }
  2285. /* Check if the table is referenced by foreign key constraints from
  2286. some other table (not the table itself) */
  2287. dict_foreign_set::iterator it
  2288. = std::find_if(table->referenced_set.begin(),
  2289. table->referenced_set.end(),
  2290. dict_foreign_different_tables());
  2291. if (it == table->referenced_set.end()) {
  2292. return(DB_SUCCESS);
  2293. }
  2294. const dict_foreign_t* foreign = *it;
  2295. FILE* ef = dict_foreign_err_file;
  2296. ut_ad(foreign->foreign_table != table);
  2297. ut_ad(foreign->referenced_table == table);
  2298. /* We only allow discarding a referenced table if
  2299. FOREIGN_KEY_CHECKS is set to 0 */
  2300. mutex_enter(&dict_foreign_err_mutex);
  2301. rewind(ef);
  2302. ut_print_timestamp(ef);
  2303. fputs(" Cannot DISCARD table ", ef);
  2304. ut_print_name(stderr, trx, TRUE, table->name);
  2305. fputs("\n"
  2306. "because it is referenced by ", ef);
  2307. ut_print_name(stderr, trx, TRUE, foreign->foreign_table_name);
  2308. putc('\n', ef);
  2309. mutex_exit(&dict_foreign_err_mutex);
  2310. return(DB_CANNOT_DROP_CONSTRAINT);
  2311. }
  2312. /*********************************************************************//**
  2313. Cleanup after the DISCARD TABLESPACE operation.
  2314. @return error code. */
  2315. static
  2316. dberr_t
  2317. row_discard_tablespace_end(
  2318. /*=======================*/
  2319. trx_t* trx, /*!< in/out: transaction handle */
  2320. dict_table_t* table, /*!< in/out: table to be discarded */
  2321. dberr_t err) /*!< in: error code */
  2322. {
  2323. if (table != 0) {
  2324. dict_table_close(table, TRUE, FALSE);
  2325. }
  2326. DBUG_EXECUTE_IF("ib_discard_before_commit_crash",
  2327. log_make_checkpoint_at(LSN_MAX, TRUE);
  2328. DBUG_SUICIDE(););
  2329. trx_commit_for_mysql(trx);
  2330. DBUG_EXECUTE_IF("ib_discard_after_commit_crash",
  2331. log_make_checkpoint_at(LSN_MAX, TRUE);
  2332. DBUG_SUICIDE(););
  2333. row_mysql_unlock_data_dictionary(trx);
  2334. trx->op_info = "";
  2335. return(err);
  2336. }
  2337. /*********************************************************************//**
  2338. Do the DISCARD TABLESPACE operation.
  2339. @return DB_SUCCESS or error code. */
  2340. static
  2341. dberr_t
  2342. row_discard_tablespace(
  2343. /*===================*/
  2344. trx_t* trx, /*!< in/out: transaction handle */
  2345. dict_table_t* table) /*!< in/out: table to be discarded */
  2346. {
  2347. dberr_t err;
  2348. /* How do we prevent crashes caused by ongoing operations on
  2349. the table? Old operations could try to access non-existent
  2350. pages. MySQL will block all DML on the table using MDL and a
  2351. DISCARD will not start unless all existing operations on the
  2352. table to be discarded are completed.
  2353. 1) Acquire the data dictionary latch in X mode. To prevent any
  2354. internal operations that MySQL is not aware off and also for
  2355. the internal SQL parser.
  2356. 2) Purge and rollback: we assign a new table id for the
  2357. table. Since purge and rollback look for the table based on
  2358. the table id, they see the table as 'dropped' and discard
  2359. their operations.
  2360. 3) Insert buffer: we remove all entries for the tablespace in
  2361. the insert buffer tree.
  2362. 4) FOREIGN KEY operations: if table->n_foreign_key_checks_running > 0,
  2363. we do not allow the discard. */
  2364. /* Play safe and remove all insert buffer entries, though we should
  2365. have removed them already when DISCARD TABLESPACE was called */
  2366. ibuf_delete_for_discarded_space(table->space);
  2367. table_id_t new_id;
  2368. /* Set the TABLESPACE DISCARD flag in the table definition on disk. */
  2369. err = row_import_update_discarded_flag(trx, table->id, true, true);
  2370. if (err != DB_SUCCESS) {
  2371. return(err);
  2372. }
  2373. /* Update the index root pages in the system tables, on disk */
  2374. err = row_import_update_index_root(trx, table, true, true);
  2375. if (err != DB_SUCCESS) {
  2376. return(err);
  2377. }
  2378. /* Drop all the FTS auxiliary tables. */
  2379. if (dict_table_has_fts_index(table)
  2380. || DICT_TF2_FLAG_IS_SET(table, DICT_TF2_FTS_HAS_DOC_ID)) {
  2381. fts_drop_tables(trx, table);
  2382. }
  2383. /* Assign a new space ID to the table definition so that purge
  2384. can ignore the changes. Update the system table on disk. */
  2385. err = row_mysql_table_id_reassign(table, trx, &new_id);
  2386. if (err != DB_SUCCESS) {
  2387. return(err);
  2388. }
  2389. /* Discard the physical file that is used for the tablespace. */
  2390. err = fil_discard_tablespace(table->space);
  2391. switch(err) {
  2392. case DB_SUCCESS:
  2393. case DB_IO_ERROR:
  2394. case DB_TABLESPACE_NOT_FOUND:
  2395. /* All persistent operations successful, update the
  2396. data dictionary memory cache. */
  2397. table->ibd_file_missing = TRUE;
  2398. table->flags2 |= DICT_TF2_DISCARDED;
  2399. dict_table_change_id_in_cache(table, new_id);
  2400. /* Reset the root page numbers. */
  2401. for (dict_index_t* index = UT_LIST_GET_FIRST(table->indexes);
  2402. index != 0;
  2403. index = UT_LIST_GET_NEXT(indexes, index)) {
  2404. index->page = FIL_NULL;
  2405. index->space = FIL_NULL;
  2406. }
  2407. /* If the tablespace did not already exist or we couldn't
  2408. write to it, we treat that as a successful DISCARD. It is
  2409. unusable anyway. */
  2410. err = DB_SUCCESS;
  2411. break;
  2412. default:
  2413. /* We need to rollback the disk changes, something failed. */
  2414. trx->error_state = DB_SUCCESS;
  2415. trx_rollback_to_savepoint(trx, NULL);
  2416. trx->error_state = DB_SUCCESS;
  2417. }
  2418. return(err);
  2419. }
  2420. /*********************************************************************//**
  2421. Discards the tablespace of a table which stored in an .ibd file. Discarding
  2422. means that this function renames the .ibd file and assigns a new table id for
  2423. the table. Also the flag table->ibd_file_missing is set to TRUE.
  2424. @return error code or DB_SUCCESS */
  2425. UNIV_INTERN
  2426. dberr_t
  2427. row_discard_tablespace_for_mysql(
  2428. /*=============================*/
  2429. const char* name, /*!< in: table name */
  2430. trx_t* trx) /*!< in: transaction handle */
  2431. {
  2432. dberr_t err;
  2433. dict_table_t* table;
  2434. /* Open the table and start the transaction if not started. */
  2435. table = row_discard_tablespace_begin(name, trx);
  2436. if (table == 0) {
  2437. err = DB_TABLE_NOT_FOUND;
  2438. } else if (table->space == TRX_SYS_SPACE) {
  2439. char table_name[MAX_FULL_NAME_LEN + 1];
  2440. innobase_format_name(
  2441. table_name, sizeof(table_name), table->name, FALSE);
  2442. ib_senderrf(trx->mysql_thd, IB_LOG_LEVEL_ERROR,
  2443. ER_TABLE_IN_SYSTEM_TABLESPACE, table_name);
  2444. err = DB_ERROR;
  2445. } else if (table->n_foreign_key_checks_running > 0) {
  2446. char table_name[MAX_FULL_NAME_LEN + 1];
  2447. innobase_format_name(
  2448. table_name, sizeof(table_name), table->name, FALSE);
  2449. ib_senderrf(trx->mysql_thd, IB_LOG_LEVEL_ERROR,
  2450. ER_DISCARD_FK_CHECKS_RUNNING, table_name);
  2451. err = DB_ERROR;
  2452. } else {
  2453. /* Do foreign key constraint checks. */
  2454. err = row_discard_tablespace_foreign_key_checks(trx, table);
  2455. if (err == DB_SUCCESS) {
  2456. err = row_discard_tablespace(trx, table);
  2457. }
  2458. }
  2459. return(row_discard_tablespace_end(trx, table, err));
  2460. }
  2461. /*********************************************************************//**
  2462. Sets an exclusive lock on a table.
  2463. @return error code or DB_SUCCESS */
  2464. UNIV_INTERN
  2465. dberr_t
  2466. row_mysql_lock_table(
  2467. /*=================*/
  2468. trx_t* trx, /*!< in/out: transaction */
  2469. dict_table_t* table, /*!< in: table to lock */
  2470. enum lock_mode mode, /*!< in: LOCK_X or LOCK_S */
  2471. const char* op_info) /*!< in: string for trx->op_info */
  2472. {
  2473. mem_heap_t* heap;
  2474. que_thr_t* thr;
  2475. dberr_t err;
  2476. sel_node_t* node;
  2477. ut_ad(trx);
  2478. ut_ad(mode == LOCK_X || mode == LOCK_S);
  2479. heap = mem_heap_create(512);
  2480. trx->op_info = op_info;
  2481. node = sel_node_create(heap);
  2482. thr = pars_complete_graph_for_exec(node, trx, heap);
  2483. thr->graph->state = QUE_FORK_ACTIVE;
  2484. /* We use the select query graph as the dummy graph needed
  2485. in the lock module call */
  2486. thr = que_fork_get_first_thr(
  2487. static_cast<que_fork_t*>(que_node_get_parent(thr)));
  2488. que_thr_move_to_run_state_for_mysql(thr, trx);
  2489. run_again:
  2490. thr->run_node = thr;
  2491. thr->prev_node = thr->common.parent;
  2492. err = lock_table(0, table, mode, thr);
  2493. trx->error_state = err;
  2494. if (err == DB_SUCCESS) {
  2495. que_thr_stop_for_mysql_no_error(thr, trx);
  2496. } else {
  2497. que_thr_stop_for_mysql(thr);
  2498. if (err != DB_QUE_THR_SUSPENDED) {
  2499. ibool was_lock_wait;
  2500. was_lock_wait = row_mysql_handle_errors(
  2501. &err, trx, thr, NULL);
  2502. if (was_lock_wait) {
  2503. goto run_again;
  2504. }
  2505. } else {
  2506. que_thr_t* run_thr;
  2507. que_node_t* parent;
  2508. parent = que_node_get_parent(thr);
  2509. run_thr = que_fork_start_command(
  2510. static_cast<que_fork_t*>(parent));
  2511. ut_a(run_thr == thr);
  2512. /* There was a lock wait but the thread was not
  2513. in a ready to run or running state. */
  2514. trx->error_state = DB_LOCK_WAIT;
  2515. goto run_again;
  2516. }
  2517. }
  2518. que_graph_free(thr->graph);
  2519. trx->op_info = "";
  2520. return(err);
  2521. }
  2522. /*********************************************************************//**
  2523. Truncates a table for MySQL.
  2524. @return error code or DB_SUCCESS */
  2525. UNIV_INTERN
  2526. dberr_t
  2527. row_truncate_table_for_mysql(
  2528. /*=========================*/
  2529. dict_table_t* table, /*!< in: table handle */
  2530. trx_t* trx) /*!< in: transaction handle */
  2531. {
  2532. dberr_t err;
  2533. mem_heap_t* heap;
  2534. byte* buf;
  2535. dtuple_t* tuple;
  2536. dfield_t* dfield;
  2537. dict_index_t* sys_index;
  2538. btr_pcur_t pcur;
  2539. mtr_t mtr;
  2540. table_id_t new_id;
  2541. ulint recreate_space = 0;
  2542. pars_info_t* info = NULL;
  2543. ibool has_internal_doc_id;
  2544. ulint old_space = table->space;
  2545. /* How do we prevent crashes caused by ongoing operations on
  2546. the table? Old operations could try to access non-existent
  2547. pages.
  2548. 1) SQL queries, INSERT, SELECT, ...: we must get an exclusive
  2549. InnoDB table lock on the table before we can do TRUNCATE
  2550. TABLE. Then there are no running queries on the table.
  2551. 2) Purge and rollback: we assign a new table id for the
  2552. table. Since purge and rollback look for the table based on
  2553. the table id, they see the table as 'dropped' and discard
  2554. their operations.
  2555. 3) Insert buffer: TRUNCATE TABLE is analogous to DROP TABLE,
  2556. so we do not have to remove insert buffer records, as the
  2557. insert buffer works at a low level. If a freed page is later
  2558. reallocated, the allocator will remove the ibuf entries for
  2559. it.
  2560. When we truncate *.ibd files by recreating them (analogous to
  2561. DISCARD TABLESPACE), we remove all entries for the table in the
  2562. insert buffer tree. This is not strictly necessary, because
  2563. in 6) we will assign a new tablespace identifier, but we can
  2564. free up some space in the system tablespace.
  2565. 4) Linear readahead and random readahead: we use the same
  2566. method as in 3) to discard ongoing operations. (This is only
  2567. relevant for TRUNCATE TABLE by DISCARD TABLESPACE.)
  2568. 5) FOREIGN KEY operations: if
  2569. table->n_foreign_key_checks_running > 0, we do not allow the
  2570. TRUNCATE. We also reserve the data dictionary latch.
  2571. 6) Crash recovery: To prevent the application of pre-truncation
  2572. redo log records on the truncated tablespace, we will assign
  2573. a new tablespace identifier to the truncated tablespace. */
  2574. ut_ad(table);
  2575. if (dict_table_is_discarded(table)) {
  2576. return(DB_TABLESPACE_DELETED);
  2577. } else if (table->ibd_file_missing) {
  2578. return(DB_TABLESPACE_NOT_FOUND);
  2579. }
  2580. trx_start_for_ddl(trx, TRX_DICT_OP_TABLE);
  2581. trx->op_info = "truncating table";
  2582. /* Serialize data dictionary operations with dictionary mutex:
  2583. no deadlocks can occur then in these operations */
  2584. ut_a(trx->dict_operation_lock_mode == 0);
  2585. /* Prevent foreign key checks etc. while we are truncating the
  2586. table */
  2587. row_mysql_lock_data_dictionary(trx);
  2588. ut_ad(mutex_own(&(dict_sys->mutex)));
  2589. #ifdef UNIV_SYNC_DEBUG
  2590. ut_ad(rw_lock_own(&dict_operation_lock, RW_LOCK_EX));
  2591. #endif /* UNIV_SYNC_DEBUG */
  2592. dict_stats_wait_bg_to_stop_using_table(table, trx);
  2593. /* Check if the table is referenced by foreign key constraints from
  2594. some other table (not the table itself) */
  2595. dict_foreign_set::iterator it
  2596. = std::find_if(table->referenced_set.begin(),
  2597. table->referenced_set.end(),
  2598. dict_foreign_different_tables());
  2599. if (!srv_read_only_mode
  2600. && it != table->referenced_set.end()
  2601. && trx->check_foreigns) {
  2602. FILE* ef = dict_foreign_err_file;
  2603. dict_foreign_t* foreign = *it;
  2604. /* We only allow truncating a referenced table if
  2605. FOREIGN_KEY_CHECKS is set to 0 */
  2606. mutex_enter(&dict_foreign_err_mutex);
  2607. rewind(ef);
  2608. ut_print_timestamp(ef);
  2609. fputs(" Cannot truncate table ", ef);
  2610. ut_print_name(ef, trx, TRUE, table->name);
  2611. fputs(" by DROP+CREATE\n"
  2612. "InnoDB: because it is referenced by ", ef);
  2613. ut_print_name(ef, trx, TRUE, foreign->foreign_table_name);
  2614. putc('\n', ef);
  2615. mutex_exit(&dict_foreign_err_mutex);
  2616. err = DB_ERROR;
  2617. goto funct_exit;
  2618. }
  2619. /* TODO: could we replace the counter n_foreign_key_checks_running
  2620. with lock checks on the table? Acquire here an exclusive lock on the
  2621. table, and rewrite lock0lock.cc and the lock wait in srv0srv.cc so that
  2622. they can cope with the table having been truncated here? Foreign key
  2623. checks take an IS or IX lock on the table. */
  2624. if (table->n_foreign_key_checks_running > 0) {
  2625. ut_print_timestamp(stderr);
  2626. fputs(" InnoDB: Cannot truncate table ", stderr);
  2627. ut_print_name(stderr, trx, TRUE, table->name);
  2628. fputs(" by DROP+CREATE\n"
  2629. "InnoDB: because there is a foreign key check"
  2630. " running on it.\n",
  2631. stderr);
  2632. err = DB_ERROR;
  2633. goto funct_exit;
  2634. }
  2635. /* Check if memcached plugin is running on this table. if is, we don't
  2636. allow truncate this table. */
  2637. if (table->memcached_sync_count != 0) {
  2638. ut_print_timestamp(stderr);
  2639. fputs(" InnoDB: Cannot truncate table ", stderr);
  2640. ut_print_name(stderr, trx, TRUE, table->name);
  2641. fputs(" by DROP+CREATE\n"
  2642. "InnoDB: because there are memcached operations"
  2643. " running on it.\n",
  2644. stderr);
  2645. err = DB_ERROR;
  2646. goto funct_exit;
  2647. } else {
  2648. /* We need to set this counter to -1 for blocking
  2649. memcached operations. */
  2650. table->memcached_sync_count = DICT_TABLE_IN_DDL;
  2651. }
  2652. /* Remove all locks except the table-level X lock. */
  2653. lock_remove_all_on_table(table, FALSE);
  2654. /* Ensure that the table will be dropped by
  2655. trx_rollback_active() in case of a crash. */
  2656. trx->table_id = table->id;
  2657. trx_set_dict_operation(trx, TRX_DICT_OP_TABLE);
  2658. /* Assign an undo segment for the transaction, so that the
  2659. transaction will be recovered after a crash. */
  2660. mutex_enter(&trx->undo_mutex);
  2661. err = trx_undo_assign_undo(trx, TRX_UNDO_UPDATE);
  2662. mutex_exit(&trx->undo_mutex);
  2663. if (err != DB_SUCCESS) {
  2664. goto funct_exit;
  2665. }
  2666. if (table->space && !DICT_TF2_FLAG_IS_SET(table, DICT_TF2_TEMPORARY)) {
  2667. /* Discard and create the single-table tablespace. */
  2668. ulint space = table->space;
  2669. ulint flags = fil_space_get_flags(space);
  2670. dict_get_and_save_data_dir_path(table, true);
  2671. if (flags != ULINT_UNDEFINED
  2672. && fil_discard_tablespace(space) == DB_SUCCESS) {
  2673. dict_index_t* index;
  2674. dict_hdr_get_new_id(NULL, NULL, &space);
  2675. /* Lock all index trees for this table. We must
  2676. do so after dict_hdr_get_new_id() to preserve
  2677. the latch order */
  2678. dict_table_x_lock_indexes(table);
  2679. if (space == ULINT_UNDEFINED
  2680. || fil_create_new_single_table_tablespace(
  2681. space, table->name,
  2682. table->data_dir_path,
  2683. flags, table->flags2,
  2684. FIL_IBD_FILE_INITIAL_SIZE)
  2685. != DB_SUCCESS) {
  2686. dict_table_x_unlock_indexes(table);
  2687. ib_logf(IB_LOG_LEVEL_ERROR,
  2688. "TRUNCATE TABLE %s failed to "
  2689. "create a new tablespace",
  2690. table->name);
  2691. table->ibd_file_missing = 1;
  2692. err = DB_ERROR;
  2693. goto funct_exit;
  2694. }
  2695. recreate_space = space;
  2696. /* Replace the space_id in the data dictionary cache.
  2697. The persisent data dictionary (SYS_TABLES.SPACE
  2698. and SYS_INDEXES.SPACE) are updated later in this
  2699. function. */
  2700. table->space = space;
  2701. index = dict_table_get_first_index(table);
  2702. do {
  2703. index->space = space;
  2704. index = dict_table_get_next_index(index);
  2705. } while (index);
  2706. mtr_start(&mtr);
  2707. fsp_header_init(space,
  2708. FIL_IBD_FILE_INITIAL_SIZE, &mtr);
  2709. mtr_commit(&mtr);
  2710. }
  2711. } else {
  2712. /* Lock all index trees for this table, as we will
  2713. truncate the table/index and possibly change their metadata.
  2714. All DML/DDL are blocked by table level lock, with
  2715. a few exceptions such as queries into information schema
  2716. about the table, MySQL could try to access index stats
  2717. for this kind of query, we need to use index locks to
  2718. sync up */
  2719. dict_table_x_lock_indexes(table);
  2720. }
  2721. /* scan SYS_INDEXES for all indexes of the table */
  2722. heap = mem_heap_create(800);
  2723. tuple = dtuple_create(heap, 1);
  2724. dfield = dtuple_get_nth_field(tuple, 0);
  2725. buf = static_cast<byte*>(mem_heap_alloc(heap, 8));
  2726. mach_write_to_8(buf, table->id);
  2727. dfield_set_data(dfield, buf, 8);
  2728. sys_index = dict_table_get_first_index(dict_sys->sys_indexes);
  2729. dict_index_copy_types(tuple, sys_index, 1);
  2730. mtr_start(&mtr);
  2731. btr_pcur_open_on_user_rec(sys_index, tuple, PAGE_CUR_GE,
  2732. BTR_MODIFY_LEAF, &pcur, &mtr);
  2733. for (;;) {
  2734. rec_t* rec;
  2735. const byte* field;
  2736. ulint len;
  2737. ulint root_page_no;
  2738. if (!btr_pcur_is_on_user_rec(&pcur)) {
  2739. /* The end of SYS_INDEXES has been reached. */
  2740. break;
  2741. }
  2742. rec = btr_pcur_get_rec(&pcur);
  2743. field = rec_get_nth_field_old(
  2744. rec, DICT_FLD__SYS_INDEXES__TABLE_ID, &len);
  2745. ut_ad(len == 8);
  2746. if (memcmp(buf, field, len) != 0) {
  2747. /* End of indexes for the table (TABLE_ID mismatch). */
  2748. break;
  2749. }
  2750. if (rec_get_deleted_flag(rec, FALSE)) {
  2751. /* The index has been dropped. */
  2752. goto next_rec;
  2753. }
  2754. /* This call may commit and restart mtr
  2755. and reposition pcur. */
  2756. root_page_no = dict_truncate_index_tree(table, recreate_space,
  2757. &pcur, &mtr);
  2758. rec = btr_pcur_get_rec(&pcur);
  2759. if (root_page_no != FIL_NULL) {
  2760. page_rec_write_field(
  2761. rec, DICT_FLD__SYS_INDEXES__PAGE_NO,
  2762. root_page_no, &mtr);
  2763. /* We will need to commit and restart the
  2764. mini-transaction in order to avoid deadlocks.
  2765. The dict_truncate_index_tree() call has allocated
  2766. a page in this mini-transaction, and the rest of
  2767. this loop could latch another index page. */
  2768. mtr_commit(&mtr);
  2769. mtr_start(&mtr);
  2770. btr_pcur_restore_position(BTR_MODIFY_LEAF,
  2771. &pcur, &mtr);
  2772. }
  2773. next_rec:
  2774. btr_pcur_move_to_next_user_rec(&pcur, &mtr);
  2775. }
  2776. btr_pcur_close(&pcur);
  2777. mtr_commit(&mtr);
  2778. mem_heap_free(heap);
  2779. /* Done with index truncation, release index tree locks,
  2780. subsequent work relates to table level metadata change */
  2781. dict_table_x_unlock_indexes(table);
  2782. dict_hdr_get_new_id(&new_id, NULL, NULL);
  2783. /* Create new FTS auxiliary tables with the new_id, and
  2784. drop the old index later, only if everything runs successful. */
  2785. has_internal_doc_id = dict_table_has_fts_index(table)
  2786. || DICT_TF2_FLAG_IS_SET(
  2787. table, DICT_TF2_FTS_HAS_DOC_ID);
  2788. if (has_internal_doc_id) {
  2789. dict_table_t fts_table;
  2790. ulint i;
  2791. fts_table.name = table->name;
  2792. fts_table.id = new_id;
  2793. fts_table.flags2 = table->flags2;
  2794. err = fts_create_common_tables(
  2795. trx, &fts_table, table->name, TRUE);
  2796. for (i = 0;
  2797. i < ib_vector_size(table->fts->indexes)
  2798. && err == DB_SUCCESS;
  2799. i++) {
  2800. dict_index_t* fts_index;
  2801. fts_index = static_cast<dict_index_t*>(
  2802. ib_vector_getp(table->fts->indexes, i));
  2803. err = fts_create_index_tables_low(
  2804. trx, fts_index, table->name, new_id);
  2805. }
  2806. if (err != DB_SUCCESS) {
  2807. trx->error_state = DB_SUCCESS;
  2808. trx_rollback_to_savepoint(trx, NULL);
  2809. trx->error_state = DB_SUCCESS;
  2810. ut_print_timestamp(stderr);
  2811. fputs(" InnoDB: Unable to truncate FTS index for"
  2812. " table", stderr);
  2813. ut_print_name(stderr, trx, TRUE, table->name);
  2814. fputs("\n", stderr);
  2815. goto funct_exit;
  2816. } else {
  2817. ut_ad(trx->state != TRX_STATE_NOT_STARTED);
  2818. }
  2819. }
  2820. info = pars_info_create();
  2821. pars_info_add_int4_literal(info, "new_space", (lint) table->space);
  2822. pars_info_add_ull_literal(info, "old_id", table->id);
  2823. pars_info_add_ull_literal(info, "new_id", new_id);
  2824. err = que_eval_sql(info,
  2825. "PROCEDURE RENUMBER_TABLE_ID_PROC () IS\n"
  2826. "BEGIN\n"
  2827. "UPDATE SYS_TABLES"
  2828. " SET ID = :new_id, SPACE = :new_space\n"
  2829. " WHERE ID = :old_id;\n"
  2830. "UPDATE SYS_COLUMNS SET TABLE_ID = :new_id\n"
  2831. " WHERE TABLE_ID = :old_id;\n"
  2832. "UPDATE SYS_INDEXES"
  2833. " SET TABLE_ID = :new_id, SPACE = :new_space\n"
  2834. " WHERE TABLE_ID = :old_id;\n"
  2835. "END;\n"
  2836. , FALSE, trx);
  2837. if (err == DB_SUCCESS && old_space != table->space) {
  2838. info = pars_info_create();
  2839. pars_info_add_int4_literal(info, "old_space", (lint) old_space);
  2840. pars_info_add_int4_literal(
  2841. info, "new_space", (lint) table->space);
  2842. err = que_eval_sql(info,
  2843. "PROCEDURE RENUMBER_TABLESPACE_PROC () IS\n"
  2844. "BEGIN\n"
  2845. "UPDATE SYS_TABLESPACES"
  2846. " SET SPACE = :new_space\n"
  2847. " WHERE SPACE = :old_space;\n"
  2848. "UPDATE SYS_DATAFILES"
  2849. " SET SPACE = :new_space"
  2850. " WHERE SPACE = :old_space;\n"
  2851. "END;\n"
  2852. , FALSE, trx);
  2853. }
  2854. DBUG_EXECUTE_IF("ib_ddl_crash_before_fts_truncate", err = DB_ERROR;);
  2855. if (err != DB_SUCCESS) {
  2856. trx->error_state = DB_SUCCESS;
  2857. trx_rollback_to_savepoint(trx, NULL);
  2858. trx->error_state = DB_SUCCESS;
  2859. /* Update system table failed. Table in memory metadata
  2860. could be in an inconsistent state, mark the in-memory
  2861. table->corrupted to be true. In the long run, this should
  2862. be fixed by atomic truncate table */
  2863. table->corrupted = true;
  2864. ut_print_timestamp(stderr);
  2865. fputs(" InnoDB: Unable to assign a new identifier to table ",
  2866. stderr);
  2867. ut_print_name(stderr, trx, TRUE, table->name);
  2868. fputs("\n"
  2869. "InnoDB: after truncating it. Background processes"
  2870. " may corrupt the table!\n", stderr);
  2871. /* Failed to update the table id, so drop the new
  2872. FTS auxiliary tables */
  2873. if (has_internal_doc_id) {
  2874. ut_ad(trx->state == TRX_STATE_NOT_STARTED);
  2875. table_id_t id = table->id;
  2876. table->id = new_id;
  2877. fts_drop_tables(trx, table);
  2878. table->id = id;
  2879. ut_ad(trx->state != TRX_STATE_NOT_STARTED);
  2880. }
  2881. err = DB_ERROR;
  2882. } else {
  2883. /* Drop the old FTS index */
  2884. if (has_internal_doc_id) {
  2885. ut_ad(trx->state != TRX_STATE_NOT_STARTED);
  2886. fts_drop_tables(trx, table);
  2887. ut_ad(trx->state != TRX_STATE_NOT_STARTED);
  2888. }
  2889. DBUG_EXECUTE_IF("ib_truncate_crash_after_fts_drop",
  2890. DBUG_SUICIDE(););
  2891. dict_table_change_id_in_cache(table, new_id);
  2892. /* Reset the Doc ID in cache to 0 */
  2893. if (has_internal_doc_id && table->fts->cache) {
  2894. table->fts->fts_status |= TABLE_DICT_LOCKED;
  2895. fts_update_next_doc_id(trx, table, NULL, 0);
  2896. fts_cache_clear(table->fts->cache);
  2897. fts_cache_init(table->fts->cache);
  2898. table->fts->fts_status &= ~TABLE_DICT_LOCKED;
  2899. }
  2900. }
  2901. /* Reset auto-increment. */
  2902. dict_table_autoinc_lock(table);
  2903. dict_table_autoinc_initialize(table, 1);
  2904. dict_table_autoinc_unlock(table);
  2905. trx_commit_for_mysql(trx);
  2906. funct_exit:
  2907. if (table->memcached_sync_count == DICT_TABLE_IN_DDL) {
  2908. /* We need to set the memcached sync back to 0, unblock
  2909. memcached operationse. */
  2910. table->memcached_sync_count = 0;
  2911. }
  2912. row_mysql_unlock_data_dictionary(trx);
  2913. dict_stats_update(table, DICT_STATS_EMPTY_TABLE);
  2914. trx->op_info = "";
  2915. srv_wake_master_thread();
  2916. return(err);
  2917. }
  2918. /*********************************************************************//**
  2919. Drops a table for MySQL. If the name of the dropped table ends in
  2920. one of "innodb_monitor", "innodb_lock_monitor", "innodb_tablespace_monitor",
  2921. "innodb_table_monitor", then this will also stop the printing of monitor
  2922. output by the master thread. If the data dictionary was not already locked
  2923. by the transaction, the transaction will be committed. Otherwise, the
  2924. data dictionary will remain locked.
  2925. @return error code or DB_SUCCESS */
  2926. UNIV_INTERN
  2927. dberr_t
  2928. row_drop_table_for_mysql(
  2929. /*=====================*/
  2930. const char* name, /*!< in: table name */
  2931. trx_t* trx, /*!< in: transaction handle */
  2932. bool drop_db,/*!< in: true=dropping whole database */
  2933. bool nonatomic)
  2934. /*!< in: whether it is permitted
  2935. to release and reacquire dict_operation_lock */
  2936. {
  2937. dberr_t err;
  2938. dict_foreign_t* foreign;
  2939. dict_table_t* table;
  2940. ibool print_msg;
  2941. ulint space_id;
  2942. char* filepath = NULL;
  2943. const char* tablename_minus_db;
  2944. char* tablename = NULL;
  2945. bool ibd_file_missing;
  2946. ulint namelen;
  2947. bool locked_dictionary = false;
  2948. pars_info_t* info = NULL;
  2949. mem_heap_t* heap = NULL;
  2950. DBUG_ENTER("row_drop_table_for_mysql");
  2951. DBUG_PRINT("row_drop_table_for_mysql", ("table: %s", name));
  2952. ut_a(name != NULL);
  2953. /* The table name is prefixed with the database name and a '/'.
  2954. Certain table names starting with 'innodb_' have their special
  2955. meaning regardless of the database name. Thus, we need to
  2956. ignore the database name prefix in the comparisons. */
  2957. tablename_minus_db = strchr(name, '/');
  2958. if (tablename_minus_db) {
  2959. tablename_minus_db++;
  2960. } else {
  2961. /* Ancillary FTS tables don't have '/' characters. */
  2962. tablename_minus_db = name;
  2963. }
  2964. namelen = strlen(tablename_minus_db) + 1;
  2965. if (namelen == sizeof S_innodb_monitor
  2966. && !memcmp(tablename_minus_db, S_innodb_monitor,
  2967. sizeof S_innodb_monitor)) {
  2968. /* Table name equals "innodb_monitor":
  2969. stop monitor prints */
  2970. srv_print_innodb_monitor = FALSE;
  2971. srv_print_innodb_lock_monitor = FALSE;
  2972. } else if (namelen == sizeof S_innodb_lock_monitor
  2973. && !memcmp(tablename_minus_db, S_innodb_lock_monitor,
  2974. sizeof S_innodb_lock_monitor)) {
  2975. srv_print_innodb_monitor = FALSE;
  2976. srv_print_innodb_lock_monitor = FALSE;
  2977. } else if (namelen == sizeof S_innodb_tablespace_monitor
  2978. && !memcmp(tablename_minus_db, S_innodb_tablespace_monitor,
  2979. sizeof S_innodb_tablespace_monitor)) {
  2980. srv_print_innodb_tablespace_monitor = FALSE;
  2981. } else if (namelen == sizeof S_innodb_table_monitor
  2982. && !memcmp(tablename_minus_db, S_innodb_table_monitor,
  2983. sizeof S_innodb_table_monitor)) {
  2984. srv_print_innodb_table_monitor = FALSE;
  2985. }
  2986. /* Serialize data dictionary operations with dictionary mutex:
  2987. no deadlocks can occur then in these operations */
  2988. trx->op_info = "dropping table";
  2989. /* This function is called recursively via fts_drop_tables(). */
  2990. if (trx->state == TRX_STATE_NOT_STARTED) {
  2991. trx_start_for_ddl(trx, TRX_DICT_OP_TABLE);
  2992. }
  2993. if (trx->dict_operation_lock_mode != RW_X_LATCH) {
  2994. /* Prevent foreign key checks etc. while we are dropping the
  2995. table */
  2996. row_mysql_lock_data_dictionary(trx);
  2997. locked_dictionary = true;
  2998. nonatomic = true;
  2999. }
  3000. ut_ad(mutex_own(&(dict_sys->mutex)));
  3001. #ifdef UNIV_SYNC_DEBUG
  3002. ut_ad(rw_lock_own(&dict_operation_lock, RW_LOCK_EX));
  3003. #endif /* UNIV_SYNC_DEBUG */
  3004. table = dict_table_open_on_name(
  3005. name, TRUE, FALSE,
  3006. static_cast<dict_err_ignore_t>(
  3007. DICT_ERR_IGNORE_INDEX_ROOT | DICT_ERR_IGNORE_CORRUPT));
  3008. if (!table) {
  3009. err = DB_TABLE_NOT_FOUND;
  3010. ut_print_timestamp(stderr);
  3011. fputs(" InnoDB: Error: table ", stderr);
  3012. ut_print_name(stderr, trx, TRUE, name);
  3013. fputs(" does not exist in the InnoDB internal\n"
  3014. "InnoDB: data dictionary though MySQL is"
  3015. " trying to drop it.\n"
  3016. "InnoDB: Have you copied the .frm file"
  3017. " of the table to the\n"
  3018. "InnoDB: MySQL database directory"
  3019. " from another database?\n"
  3020. "InnoDB: You can look for further help from\n"
  3021. "InnoDB: " REFMAN "innodb-troubleshooting.html\n",
  3022. stderr);
  3023. goto funct_exit;
  3024. }
  3025. /* Turn on this drop bit before we could release the dictionary
  3026. latch */
  3027. table->to_be_dropped = true;
  3028. if (nonatomic) {
  3029. /* This trx did not acquire any locks on dictionary
  3030. table records yet. Thus it is safe to release and
  3031. reacquire the data dictionary latches. */
  3032. if (table->fts) {
  3033. ut_ad(!table->fts->add_wq);
  3034. ut_ad(lock_trx_has_sys_table_locks(trx) == 0);
  3035. row_mysql_unlock_data_dictionary(trx);
  3036. fts_optimize_remove_table(table);
  3037. row_mysql_lock_data_dictionary(trx);
  3038. }
  3039. /* Do not bother to deal with persistent stats for temp
  3040. tables since we know temp tables do not use persistent
  3041. stats. */
  3042. if (!dict_table_is_temporary(table)) {
  3043. dict_stats_wait_bg_to_stop_using_table(
  3044. table, trx);
  3045. }
  3046. }
  3047. /* make sure background stats thread is not running on the table */
  3048. ut_ad(!(table->stats_bg_flag & BG_STAT_IN_PROGRESS));
  3049. /* Delete the link file if used. */
  3050. if (DICT_TF_HAS_DATA_DIR(table->flags)) {
  3051. fil_delete_link_file(name);
  3052. }
  3053. if (!dict_table_is_temporary(table)) {
  3054. dict_stats_recalc_pool_del(table);
  3055. /* Remove stats for this table and all of its indexes from the
  3056. persistent storage if it exists and if there are stats for this
  3057. table in there. This function creates its own trx and commits
  3058. it. */
  3059. char errstr[1024];
  3060. err = dict_stats_drop_table(name, errstr, sizeof(errstr));
  3061. if (err != DB_SUCCESS) {
  3062. ib_logf(IB_LOG_LEVEL_WARN, "%s", errstr);
  3063. }
  3064. }
  3065. /* Move the table the the non-LRU list so that it isn't
  3066. considered for eviction. */
  3067. if (table->can_be_evicted) {
  3068. dict_table_move_from_lru_to_non_lru(table);
  3069. }
  3070. dict_table_close(table, TRUE, FALSE);
  3071. /* Check if the table is referenced by foreign key constraints from
  3072. some other table (not the table itself) */
  3073. if (!srv_read_only_mode && trx->check_foreigns) {
  3074. for (dict_foreign_set::iterator it
  3075. = table->referenced_set.begin();
  3076. it != table->referenced_set.end();
  3077. ++it) {
  3078. foreign = *it;
  3079. const bool ref_ok = drop_db
  3080. && dict_tables_have_same_db(
  3081. name,
  3082. foreign->foreign_table_name_lookup);
  3083. if (foreign->foreign_table != table && !ref_ok) {
  3084. FILE* ef = dict_foreign_err_file;
  3085. /* We only allow dropping a referenced table
  3086. if FOREIGN_KEY_CHECKS is set to 0 */
  3087. err = DB_CANNOT_DROP_CONSTRAINT;
  3088. mutex_enter(&dict_foreign_err_mutex);
  3089. rewind(ef);
  3090. ut_print_timestamp(ef);
  3091. fputs(" Cannot drop table ", ef);
  3092. ut_print_name(ef, trx, TRUE, name);
  3093. fputs("\n"
  3094. "because it is referenced by ", ef);
  3095. ut_print_name(ef, trx, TRUE,
  3096. foreign->foreign_table_name);
  3097. putc('\n', ef);
  3098. mutex_exit(&dict_foreign_err_mutex);
  3099. goto funct_exit;
  3100. }
  3101. }
  3102. }
  3103. DBUG_EXECUTE_IF("row_drop_table_add_to_background",
  3104. row_add_table_to_background_drop_list(table->name);
  3105. err = DB_SUCCESS;
  3106. goto funct_exit;
  3107. );
  3108. /* TODO: could we replace the counter n_foreign_key_checks_running
  3109. with lock checks on the table? Acquire here an exclusive lock on the
  3110. table, and rewrite lock0lock.cc and the lock wait in srv0srv.cc so that
  3111. they can cope with the table having been dropped here? Foreign key
  3112. checks take an IS or IX lock on the table. */
  3113. if (table->n_foreign_key_checks_running > 0) {
  3114. const char* save_tablename = table->name;
  3115. ibool added;
  3116. added = row_add_table_to_background_drop_list(save_tablename);
  3117. if (added) {
  3118. ut_print_timestamp(stderr);
  3119. fputs(" InnoDB: You are trying to drop table ",
  3120. stderr);
  3121. ut_print_name(stderr, trx, TRUE, save_tablename);
  3122. fputs("\n"
  3123. "InnoDB: though there is a"
  3124. " foreign key check running on it.\n"
  3125. "InnoDB: Adding the table to"
  3126. " the background drop queue.\n",
  3127. stderr);
  3128. /* We return DB_SUCCESS to MySQL though the drop will
  3129. happen lazily later */
  3130. err = DB_SUCCESS;
  3131. } else {
  3132. /* The table is already in the background drop list */
  3133. err = DB_ERROR;
  3134. }
  3135. goto funct_exit;
  3136. }
  3137. /* Remove all locks that are on the table or its records, if there
  3138. are no refernces to the table but it has record locks, we release
  3139. the record locks unconditionally. One use case is:
  3140. CREATE TABLE t2 (PRIMARY KEY (a)) SELECT * FROM t1;
  3141. If after the user transaction has done the SELECT and there is a
  3142. problem in completing the CREATE TABLE operation, MySQL will drop
  3143. the table. InnoDB will create a new background transaction to do the
  3144. actual drop, the trx instance that is passed to this function. To
  3145. preserve existing behaviour we remove the locks but ideally we
  3146. shouldn't have to. There should never be record locks on a table
  3147. that is going to be dropped. */
  3148. if (table->n_ref_count == 0) {
  3149. lock_remove_all_on_table(table, TRUE);
  3150. ut_a(table->n_rec_locks == 0);
  3151. } else if (table->n_ref_count > 0 || table->n_rec_locks > 0) {
  3152. ibool added;
  3153. added = row_add_table_to_background_drop_list(table->name);
  3154. if (added) {
  3155. ut_print_timestamp(stderr);
  3156. fputs(" InnoDB: Warning: MySQL is"
  3157. " trying to drop table ", stderr);
  3158. ut_print_name(stderr, trx, TRUE, table->name);
  3159. fputs("\n"
  3160. "InnoDB: though there are still"
  3161. " open handles to it.\n"
  3162. "InnoDB: Adding the table to the"
  3163. " background drop queue.\n",
  3164. stderr);
  3165. /* We return DB_SUCCESS to MySQL though the drop will
  3166. happen lazily later */
  3167. err = DB_SUCCESS;
  3168. } else {
  3169. /* The table is already in the background drop list */
  3170. err = DB_ERROR;
  3171. }
  3172. goto funct_exit;
  3173. }
  3174. /* The "to_be_dropped" marks table that is to be dropped, but
  3175. has not been dropped, instead, was put in the background drop
  3176. list due to being used by concurrent DML operations. Clear it
  3177. here since there are no longer any concurrent activities on it,
  3178. and it is free to be dropped */
  3179. table->to_be_dropped = false;
  3180. /* If we get this far then the table to be dropped must not have
  3181. any table or record locks on it. */
  3182. ut_a(!lock_table_has_locks(table));
  3183. switch (trx_get_dict_operation(trx)) {
  3184. case TRX_DICT_OP_NONE:
  3185. trx_set_dict_operation(trx, TRX_DICT_OP_TABLE);
  3186. trx->table_id = table->id;
  3187. case TRX_DICT_OP_TABLE:
  3188. break;
  3189. case TRX_DICT_OP_INDEX:
  3190. /* If the transaction was previously flagged as
  3191. TRX_DICT_OP_INDEX, we should be dropping auxiliary
  3192. tables for full-text indexes. */
  3193. ut_ad(strstr(table->name, "/FTS_") != NULL);
  3194. }
  3195. /* Mark all indexes unavailable in the data dictionary cache
  3196. before starting to drop the table. */
  3197. unsigned* page_no;
  3198. unsigned* page_nos;
  3199. heap = mem_heap_create(
  3200. 200 + UT_LIST_GET_LEN(table->indexes) * sizeof *page_nos);
  3201. tablename = mem_heap_strdup(heap, name);
  3202. page_no = page_nos = static_cast<unsigned*>(
  3203. mem_heap_alloc(
  3204. heap,
  3205. UT_LIST_GET_LEN(table->indexes) * sizeof *page_no));
  3206. for (dict_index_t* index = dict_table_get_first_index(table);
  3207. index != NULL;
  3208. index = dict_table_get_next_index(index)) {
  3209. rw_lock_x_lock(dict_index_get_lock(index));
  3210. /* Save the page numbers so that we can restore them
  3211. if the operation fails. */
  3212. *page_no++ = index->page;
  3213. /* Mark the index unusable. */
  3214. index->page = FIL_NULL;
  3215. rw_lock_x_unlock(dict_index_get_lock(index));
  3216. }
  3217. /* We use the private SQL parser of Innobase to generate the
  3218. query graphs needed in deleting the dictionary data from system
  3219. tables in Innobase. Deleting a row from SYS_INDEXES table also
  3220. frees the file segments of the B-tree associated with the index. */
  3221. info = pars_info_create();
  3222. pars_info_add_str_literal(info, "table_name", name);
  3223. err = que_eval_sql(info,
  3224. "PROCEDURE DROP_TABLE_PROC () IS\n"
  3225. "sys_foreign_id CHAR;\n"
  3226. "table_id CHAR;\n"
  3227. "index_id CHAR;\n"
  3228. "foreign_id CHAR;\n"
  3229. "space_id INT;\n"
  3230. "found INT;\n"
  3231. "DECLARE CURSOR cur_fk IS\n"
  3232. "SELECT ID FROM SYS_FOREIGN\n"
  3233. "WHERE FOR_NAME = :table_name\n"
  3234. "AND TO_BINARY(FOR_NAME)\n"
  3235. " = TO_BINARY(:table_name)\n"
  3236. "LOCK IN SHARE MODE;\n"
  3237. "DECLARE CURSOR cur_idx IS\n"
  3238. "SELECT ID FROM SYS_INDEXES\n"
  3239. "WHERE TABLE_ID = table_id\n"
  3240. "LOCK IN SHARE MODE;\n"
  3241. "BEGIN\n"
  3242. "SELECT ID INTO table_id\n"
  3243. "FROM SYS_TABLES\n"
  3244. "WHERE NAME = :table_name\n"
  3245. "LOCK IN SHARE MODE;\n"
  3246. "IF (SQL % NOTFOUND) THEN\n"
  3247. " RETURN;\n"
  3248. "END IF;\n"
  3249. "SELECT SPACE INTO space_id\n"
  3250. "FROM SYS_TABLES\n"
  3251. "WHERE NAME = :table_name;\n"
  3252. "IF (SQL % NOTFOUND) THEN\n"
  3253. " RETURN;\n"
  3254. "END IF;\n"
  3255. "found := 1;\n"
  3256. "SELECT ID INTO sys_foreign_id\n"
  3257. "FROM SYS_TABLES\n"
  3258. "WHERE NAME = 'SYS_FOREIGN'\n"
  3259. "LOCK IN SHARE MODE;\n"
  3260. "IF (SQL % NOTFOUND) THEN\n"
  3261. " found := 0;\n"
  3262. "END IF;\n"
  3263. "IF (:table_name = 'SYS_FOREIGN') THEN\n"
  3264. " found := 0;\n"
  3265. "END IF;\n"
  3266. "IF (:table_name = 'SYS_FOREIGN_COLS') THEN\n"
  3267. " found := 0;\n"
  3268. "END IF;\n"
  3269. "OPEN cur_fk;\n"
  3270. "WHILE found = 1 LOOP\n"
  3271. " FETCH cur_fk INTO foreign_id;\n"
  3272. " IF (SQL % NOTFOUND) THEN\n"
  3273. " found := 0;\n"
  3274. " ELSE\n"
  3275. " DELETE FROM SYS_FOREIGN_COLS\n"
  3276. " WHERE ID = foreign_id;\n"
  3277. " DELETE FROM SYS_FOREIGN\n"
  3278. " WHERE ID = foreign_id;\n"
  3279. " END IF;\n"
  3280. "END LOOP;\n"
  3281. "CLOSE cur_fk;\n"
  3282. "found := 1;\n"
  3283. "OPEN cur_idx;\n"
  3284. "WHILE found = 1 LOOP\n"
  3285. " FETCH cur_idx INTO index_id;\n"
  3286. " IF (SQL % NOTFOUND) THEN\n"
  3287. " found := 0;\n"
  3288. " ELSE\n"
  3289. " DELETE FROM SYS_FIELDS\n"
  3290. " WHERE INDEX_ID = index_id;\n"
  3291. " DELETE FROM SYS_INDEXES\n"
  3292. " WHERE ID = index_id\n"
  3293. " AND TABLE_ID = table_id;\n"
  3294. " END IF;\n"
  3295. "END LOOP;\n"
  3296. "CLOSE cur_idx;\n"
  3297. "DELETE FROM SYS_TABLESPACES\n"
  3298. "WHERE SPACE = space_id;\n"
  3299. "DELETE FROM SYS_DATAFILES\n"
  3300. "WHERE SPACE = space_id;\n"
  3301. "DELETE FROM SYS_COLUMNS\n"
  3302. "WHERE TABLE_ID = table_id;\n"
  3303. "DELETE FROM SYS_TABLES\n"
  3304. "WHERE NAME = :table_name;\n"
  3305. "END;\n"
  3306. , FALSE, trx);
  3307. switch (err) {
  3308. ibool is_temp;
  3309. case DB_SUCCESS:
  3310. /* Clone the name, in case it has been allocated
  3311. from table->heap, which will be freed by
  3312. dict_table_remove_from_cache(table) below. */
  3313. space_id = table->space;
  3314. ibd_file_missing = table->ibd_file_missing;
  3315. is_temp = DICT_TF2_FLAG_IS_SET(table, DICT_TF2_TEMPORARY);
  3316. /* If there is a temp path then the temp flag is set.
  3317. However, during recovery or reloading the table object
  3318. after eviction from data dictionary cache, we might
  3319. have a temp flag but not know the temp path */
  3320. ut_a(table->dir_path_of_temp_table == NULL || is_temp);
  3321. if (dict_table_is_discarded(table)
  3322. || table->ibd_file_missing) {
  3323. /* Do not attempt to drop known-to-be-missing
  3324. tablespaces. */
  3325. space_id = 0;
  3326. }
  3327. /* We do not allow temporary tables with a remote path. */
  3328. ut_a(!(is_temp && DICT_TF_HAS_DATA_DIR(table->flags)));
  3329. if (space_id && DICT_TF_HAS_DATA_DIR(table->flags)) {
  3330. dict_get_and_save_data_dir_path(table, true);
  3331. ut_a(table->data_dir_path);
  3332. filepath = os_file_make_remote_pathname(
  3333. table->data_dir_path, table->name, "ibd");
  3334. } else if (table->dir_path_of_temp_table) {
  3335. filepath = fil_make_ibd_name(
  3336. table->dir_path_of_temp_table, true);
  3337. } else {
  3338. filepath = fil_make_ibd_name(tablename, false);
  3339. }
  3340. if (dict_table_has_fts_index(table)
  3341. || DICT_TF2_FLAG_IS_SET(table, DICT_TF2_FTS_HAS_DOC_ID)) {
  3342. ut_ad(table->n_ref_count == 0);
  3343. ut_ad(trx->state != TRX_STATE_NOT_STARTED);
  3344. err = fts_drop_tables(trx, table);
  3345. if (err != DB_SUCCESS) {
  3346. ut_print_timestamp(stderr);
  3347. fprintf(stderr," InnoDB: Error: (%s) not "
  3348. "able to remove ancillary FTS tables "
  3349. "for table ", ut_strerr(err));
  3350. ut_print_name(stderr, trx, TRUE, tablename);
  3351. fputs("\n", stderr);
  3352. goto funct_exit;
  3353. }
  3354. }
  3355. /* The table->fts flag can be set on the table for which
  3356. the cluster index is being rebuilt. Such table might not have
  3357. DICT_TF2_FTS flag set. So keep this out of above
  3358. dict_table_has_fts_index condition */
  3359. if (table->fts) {
  3360. /* Need to set TABLE_DICT_LOCKED bit, since
  3361. fts_que_graph_free_check_lock would try to acquire
  3362. dict mutex lock */
  3363. table->fts->fts_status |= TABLE_DICT_LOCKED;
  3364. fts_free(table);
  3365. }
  3366. dict_table_remove_from_cache(table);
  3367. if (dict_load_table(tablename, TRUE,
  3368. DICT_ERR_IGNORE_NONE) != NULL) {
  3369. ut_print_timestamp(stderr);
  3370. fputs(" InnoDB: Error: not able to remove table ",
  3371. stderr);
  3372. ut_print_name(stderr, trx, TRUE, tablename);
  3373. fputs(" from the dictionary cache!\n", stderr);
  3374. err = DB_ERROR;
  3375. }
  3376. /* Do not drop possible .ibd tablespace if something went
  3377. wrong: we do not want to delete valuable data of the user */
  3378. /* Don't spam the log if we can't find the tablespace of
  3379. a temp table or if the tablesace has been discarded. */
  3380. print_msg = !(is_temp || ibd_file_missing);
  3381. if (err == DB_SUCCESS && space_id > TRX_SYS_SPACE) {
  3382. if (!is_temp
  3383. && !fil_space_for_table_exists_in_mem(
  3384. space_id, tablename, FALSE,
  3385. print_msg, false, NULL, 0)) {
  3386. /* This might happen if we are dropping a
  3387. discarded tablespace */
  3388. err = DB_SUCCESS;
  3389. if (print_msg) {
  3390. char msg_tablename[MAX_FULL_NAME_LEN + 1];
  3391. innobase_format_name(
  3392. msg_tablename, sizeof(tablename),
  3393. tablename, FALSE);
  3394. ib_logf(IB_LOG_LEVEL_INFO,
  3395. "Removed the table %s from "
  3396. "InnoDB's data dictionary",
  3397. msg_tablename);
  3398. }
  3399. /* Force a delete of any discarded
  3400. or temporary files. */
  3401. fil_delete_file(filepath);
  3402. } else if (fil_delete_tablespace(
  3403. space_id,
  3404. BUF_REMOVE_FLUSH_NO_WRITE)
  3405. != DB_SUCCESS) {
  3406. fprintf(stderr,
  3407. "InnoDB: We removed now the InnoDB"
  3408. " internal data dictionary entry\n"
  3409. "InnoDB: of table ");
  3410. ut_print_name(stderr, trx, TRUE, tablename);
  3411. fprintf(stderr, ".\n");
  3412. ut_print_timestamp(stderr);
  3413. fprintf(stderr,
  3414. " InnoDB: Error: not able to"
  3415. " delete tablespace %lu of table ",
  3416. (ulong) space_id);
  3417. ut_print_name(stderr, trx, TRUE, tablename);
  3418. fputs("!\n", stderr);
  3419. err = DB_ERROR;
  3420. }
  3421. }
  3422. break;
  3423. case DB_OUT_OF_FILE_SPACE:
  3424. err = DB_MUST_GET_MORE_FILE_SPACE;
  3425. row_mysql_handle_errors(&err, trx, NULL, NULL);
  3426. /* raise error */
  3427. ut_error;
  3428. break;
  3429. case DB_TOO_MANY_CONCURRENT_TRXS:
  3430. /* Cannot even find a free slot for the
  3431. the undo log. We can directly exit here
  3432. and return the DB_TOO_MANY_CONCURRENT_TRXS
  3433. error. */
  3434. default:
  3435. /* This is some error we do not expect. Print
  3436. the error number and rollback transaction */
  3437. ut_print_timestamp(stderr);
  3438. fprintf(stderr, "InnoDB: unknown error code %lu"
  3439. " while dropping table:", (ulong) err);
  3440. ut_print_name(stderr, trx, TRUE, tablename);
  3441. fprintf(stderr, ".\n");
  3442. trx->error_state = DB_SUCCESS;
  3443. trx_rollback_to_savepoint(trx, NULL);
  3444. trx->error_state = DB_SUCCESS;
  3445. /* Mark all indexes available in the data dictionary
  3446. cache again. */
  3447. page_no = page_nos;
  3448. for (dict_index_t* index = dict_table_get_first_index(table);
  3449. index != NULL;
  3450. index = dict_table_get_next_index(index)) {
  3451. rw_lock_x_lock(dict_index_get_lock(index));
  3452. ut_a(index->page == FIL_NULL);
  3453. index->page = *page_no++;
  3454. rw_lock_x_unlock(dict_index_get_lock(index));
  3455. }
  3456. }
  3457. funct_exit:
  3458. if (heap) {
  3459. mem_heap_free(heap);
  3460. }
  3461. if (filepath) {
  3462. mem_free(filepath);
  3463. }
  3464. if (locked_dictionary) {
  3465. trx_commit_for_mysql(trx);
  3466. row_mysql_unlock_data_dictionary(trx);
  3467. }
  3468. trx->op_info = "";
  3469. srv_wake_master_thread();
  3470. DBUG_RETURN(err);
  3471. }
  3472. /*********************************************************************//**
  3473. Drop all temporary tables during crash recovery. */
  3474. UNIV_INTERN
  3475. void
  3476. row_mysql_drop_temp_tables(void)
  3477. /*============================*/
  3478. {
  3479. trx_t* trx;
  3480. btr_pcur_t pcur;
  3481. mtr_t mtr;
  3482. mem_heap_t* heap;
  3483. trx = trx_allocate_for_background();
  3484. trx->op_info = "dropping temporary tables";
  3485. row_mysql_lock_data_dictionary(trx);
  3486. heap = mem_heap_create(200);
  3487. mtr_start(&mtr);
  3488. btr_pcur_open_at_index_side(
  3489. true,
  3490. dict_table_get_first_index(dict_sys->sys_tables),
  3491. BTR_SEARCH_LEAF, &pcur, true, 0, &mtr);
  3492. for (;;) {
  3493. const rec_t* rec;
  3494. const byte* field;
  3495. ulint len;
  3496. const char* table_name;
  3497. dict_table_t* table;
  3498. btr_pcur_move_to_next_user_rec(&pcur, &mtr);
  3499. if (!btr_pcur_is_on_user_rec(&pcur)) {
  3500. break;
  3501. }
  3502. /* The high order bit of N_COLS is set unless
  3503. ROW_FORMAT=REDUNDANT. */
  3504. rec = btr_pcur_get_rec(&pcur);
  3505. field = rec_get_nth_field_old(
  3506. rec, DICT_FLD__SYS_TABLES__NAME, &len);
  3507. field = rec_get_nth_field_old(
  3508. rec, DICT_FLD__SYS_TABLES__N_COLS, &len);
  3509. if (len != 4
  3510. || !(mach_read_from_4(field) & DICT_N_COLS_COMPACT)) {
  3511. continue;
  3512. }
  3513. /* Older versions of InnoDB, which only supported tables
  3514. in ROW_FORMAT=REDUNDANT could write garbage to
  3515. SYS_TABLES.MIX_LEN, where we now store the is_temp flag.
  3516. Above, we assumed is_temp=0 if ROW_FORMAT=REDUNDANT. */
  3517. field = rec_get_nth_field_old(
  3518. rec, DICT_FLD__SYS_TABLES__MIX_LEN, &len);
  3519. if (len != 4
  3520. || !(mach_read_from_4(field) & DICT_TF2_TEMPORARY)) {
  3521. continue;
  3522. }
  3523. /* This is a temporary table. */
  3524. field = rec_get_nth_field_old(
  3525. rec, DICT_FLD__SYS_TABLES__NAME, &len);
  3526. if (len == UNIV_SQL_NULL || len == 0) {
  3527. /* Corrupted SYS_TABLES.NAME */
  3528. continue;
  3529. }
  3530. table_name = mem_heap_strdupl(heap, (const char*) field, len);
  3531. btr_pcur_store_position(&pcur, &mtr);
  3532. btr_pcur_commit_specify_mtr(&pcur, &mtr);
  3533. table = dict_load_table(table_name, TRUE, DICT_ERR_IGNORE_NONE);
  3534. if (table) {
  3535. row_drop_table_for_mysql(table_name, trx, FALSE);
  3536. trx_commit_for_mysql(trx);
  3537. }
  3538. mtr_start(&mtr);
  3539. btr_pcur_restore_position(BTR_SEARCH_LEAF,
  3540. &pcur, &mtr);
  3541. }
  3542. btr_pcur_close(&pcur);
  3543. mtr_commit(&mtr);
  3544. mem_heap_free(heap);
  3545. row_mysql_unlock_data_dictionary(trx);
  3546. trx_free_for_background(trx);
  3547. }
  3548. /*******************************************************************//**
  3549. Drop all foreign keys in a database, see Bug#18942.
  3550. Called at the end of row_drop_database_for_mysql().
  3551. @return error code or DB_SUCCESS */
  3552. static MY_ATTRIBUTE((nonnull, warn_unused_result))
  3553. dberr_t
  3554. drop_all_foreign_keys_in_db(
  3555. /*========================*/
  3556. const char* name, /*!< in: database name which ends to '/' */
  3557. trx_t* trx) /*!< in: transaction handle */
  3558. {
  3559. pars_info_t* pinfo;
  3560. dberr_t err;
  3561. ut_a(name[strlen(name) - 1] == '/');
  3562. pinfo = pars_info_create();
  3563. pars_info_add_str_literal(pinfo, "dbname", name);
  3564. /** true if for_name is not prefixed with dbname */
  3565. #define TABLE_NOT_IN_THIS_DB \
  3566. "SUBSTR(for_name, 0, LENGTH(:dbname)) <> :dbname"
  3567. err = que_eval_sql(pinfo,
  3568. "PROCEDURE DROP_ALL_FOREIGN_KEYS_PROC () IS\n"
  3569. "foreign_id CHAR;\n"
  3570. "for_name CHAR;\n"
  3571. "found INT;\n"
  3572. "DECLARE CURSOR cur IS\n"
  3573. "SELECT ID, FOR_NAME FROM SYS_FOREIGN\n"
  3574. "WHERE FOR_NAME >= :dbname\n"
  3575. "LOCK IN SHARE MODE\n"
  3576. "ORDER BY FOR_NAME;\n"
  3577. "BEGIN\n"
  3578. "found := 1;\n"
  3579. "OPEN cur;\n"
  3580. "WHILE found = 1 LOOP\n"
  3581. " FETCH cur INTO foreign_id, for_name;\n"
  3582. " IF (SQL % NOTFOUND) THEN\n"
  3583. " found := 0;\n"
  3584. " ELSIF (" TABLE_NOT_IN_THIS_DB ") THEN\n"
  3585. " found := 0;\n"
  3586. " ELSIF (1=1) THEN\n"
  3587. " DELETE FROM SYS_FOREIGN_COLS\n"
  3588. " WHERE ID = foreign_id;\n"
  3589. " DELETE FROM SYS_FOREIGN\n"
  3590. " WHERE ID = foreign_id;\n"
  3591. " END IF;\n"
  3592. "END LOOP;\n"
  3593. "CLOSE cur;\n"
  3594. "COMMIT WORK;\n"
  3595. "END;\n",
  3596. FALSE, /* do not reserve dict mutex,
  3597. we are already holding it */
  3598. trx);
  3599. return(err);
  3600. }
  3601. /*********************************************************************//**
  3602. Drops a database for MySQL.
  3603. @return error code or DB_SUCCESS */
  3604. UNIV_INTERN
  3605. dberr_t
  3606. row_drop_database_for_mysql(
  3607. /*========================*/
  3608. const char* name, /*!< in: database name which ends to '/' */
  3609. trx_t* trx) /*!< in: transaction handle */
  3610. {
  3611. dict_table_t* table;
  3612. char* table_name;
  3613. dberr_t err = DB_SUCCESS;
  3614. ulint namelen = strlen(name);
  3615. ut_a(name != NULL);
  3616. ut_a(name[namelen - 1] == '/');
  3617. trx->op_info = "dropping database";
  3618. trx_set_dict_operation(trx, TRX_DICT_OP_TABLE);
  3619. trx_start_if_not_started_xa(trx);
  3620. loop:
  3621. row_mysql_lock_data_dictionary(trx);
  3622. while ((table_name = dict_get_first_table_name_in_db(name))) {
  3623. /* Drop parent table if it is a fts aux table, to
  3624. avoid accessing dropped fts aux tables in information
  3625. scheam when parent table still exists.
  3626. Note: Drop parent table will drop fts aux tables. */
  3627. char* parent_table_name;
  3628. parent_table_name = fts_get_parent_table_name(
  3629. table_name, strlen(table_name));
  3630. if (parent_table_name != NULL) {
  3631. mem_free(table_name);
  3632. table_name = parent_table_name;
  3633. }
  3634. ut_a(memcmp(table_name, name, namelen) == 0);
  3635. table = dict_table_open_on_name(
  3636. table_name, TRUE, FALSE, static_cast<dict_err_ignore_t>(
  3637. DICT_ERR_IGNORE_INDEX_ROOT
  3638. | DICT_ERR_IGNORE_CORRUPT));
  3639. if (!table) {
  3640. ib_logf(IB_LOG_LEVEL_ERROR,
  3641. "Cannot load table %s from InnoDB internal "
  3642. "data dictionary during drop database",
  3643. table_name);
  3644. mem_free(table_name);
  3645. err = DB_TABLE_NOT_FOUND;
  3646. break;
  3647. }
  3648. if (!row_is_mysql_tmp_table_name(table->name)) {
  3649. /* There could be orphan temp tables left from
  3650. interrupted alter table. Leave them, and handle
  3651. the rest.*/
  3652. if (table->can_be_evicted) {
  3653. ib_logf(IB_LOG_LEVEL_WARN,
  3654. "Orphan table encountered during "
  3655. "DROP DATABASE. This is possible if "
  3656. "'%s.frm' was lost.", table->name);
  3657. }
  3658. if (table->ibd_file_missing) {
  3659. ib_logf(IB_LOG_LEVEL_WARN,
  3660. "Missing %s.ibd file for table %s.",
  3661. table->name, table->name);
  3662. }
  3663. }
  3664. dict_table_close(table, TRUE, FALSE);
  3665. /* The dict_table_t object must not be accessed before
  3666. dict_table_open() or after dict_table_close(). But this is OK
  3667. if we are holding, the dict_sys->mutex. */
  3668. ut_ad(mutex_own(&dict_sys->mutex));
  3669. /* Wait until MySQL does not have any queries running on
  3670. the table */
  3671. if (table->n_ref_count > 0) {
  3672. row_mysql_unlock_data_dictionary(trx);
  3673. ut_print_timestamp(stderr);
  3674. fputs(" InnoDB: Warning: MySQL is trying to"
  3675. " drop database ", stderr);
  3676. ut_print_name(stderr, trx, TRUE, name);
  3677. fputs("\n"
  3678. "InnoDB: though there are still"
  3679. " open handles to table ", stderr);
  3680. ut_print_name(stderr, trx, TRUE, table_name);
  3681. fputs(".\n", stderr);
  3682. os_thread_sleep(1000000);
  3683. mem_free(table_name);
  3684. goto loop;
  3685. }
  3686. err = row_drop_table_for_mysql(table_name, trx, TRUE);
  3687. trx_commit_for_mysql(trx);
  3688. if (err != DB_SUCCESS) {
  3689. fputs("InnoDB: DROP DATABASE ", stderr);
  3690. ut_print_name(stderr, trx, TRUE, name);
  3691. fprintf(stderr, " failed with error (%s) for table ",
  3692. ut_strerr(err));
  3693. ut_print_name(stderr, trx, TRUE, table_name);
  3694. putc('\n', stderr);
  3695. mem_free(table_name);
  3696. break;
  3697. }
  3698. mem_free(table_name);
  3699. }
  3700. if (err == DB_SUCCESS) {
  3701. /* after dropping all tables try to drop all leftover
  3702. foreign keys in case orphaned ones exist */
  3703. err = drop_all_foreign_keys_in_db(name, trx);
  3704. if (err != DB_SUCCESS) {
  3705. fputs("InnoDB: DROP DATABASE ", stderr);
  3706. ut_print_name(stderr, trx, TRUE, name);
  3707. fprintf(stderr, " failed with error %d while "
  3708. "dropping all foreign keys", err);
  3709. }
  3710. }
  3711. trx_commit_for_mysql(trx);
  3712. row_mysql_unlock_data_dictionary(trx);
  3713. trx->op_info = "";
  3714. return(err);
  3715. }
  3716. /*********************************************************************//**
  3717. Checks if a table name contains the string "/#sql" which denotes temporary
  3718. tables in MySQL.
  3719. @return true if temporary table */
  3720. UNIV_INTERN MY_ATTRIBUTE((warn_unused_result))
  3721. bool
  3722. row_is_mysql_tmp_table_name(
  3723. /*========================*/
  3724. const char* name) /*!< in: table name in the form
  3725. 'database/tablename' */
  3726. {
  3727. return(strstr(name, "/#sql") != NULL);
  3728. /* return(strstr(name, "/@0023sql") != NULL); */
  3729. }
  3730. /****************************************************************//**
  3731. Delete a single constraint.
  3732. @return error code or DB_SUCCESS */
  3733. static MY_ATTRIBUTE((nonnull, warn_unused_result))
  3734. dberr_t
  3735. row_delete_constraint_low(
  3736. /*======================*/
  3737. const char* id, /*!< in: constraint id */
  3738. trx_t* trx) /*!< in: transaction handle */
  3739. {
  3740. pars_info_t* info = pars_info_create();
  3741. pars_info_add_str_literal(info, "id", id);
  3742. return(que_eval_sql(info,
  3743. "PROCEDURE DELETE_CONSTRAINT () IS\n"
  3744. "BEGIN\n"
  3745. "DELETE FROM SYS_FOREIGN_COLS WHERE ID = :id;\n"
  3746. "DELETE FROM SYS_FOREIGN WHERE ID = :id;\n"
  3747. "END;\n"
  3748. , FALSE, trx));
  3749. }
  3750. /****************************************************************//**
  3751. Delete a single constraint.
  3752. @return error code or DB_SUCCESS */
  3753. static MY_ATTRIBUTE((nonnull, warn_unused_result))
  3754. dberr_t
  3755. row_delete_constraint(
  3756. /*==================*/
  3757. const char* id, /*!< in: constraint id */
  3758. const char* database_name, /*!< in: database name, with the
  3759. trailing '/' */
  3760. mem_heap_t* heap, /*!< in: memory heap */
  3761. trx_t* trx) /*!< in: transaction handle */
  3762. {
  3763. dberr_t err;
  3764. /* New format constraints have ids <databasename>/<constraintname>. */
  3765. err = row_delete_constraint_low(
  3766. mem_heap_strcat(heap, database_name, id), trx);
  3767. if ((err == DB_SUCCESS) && !strchr(id, '/')) {
  3768. /* Old format < 4.0.18 constraints have constraint ids
  3769. NUMBER_NUMBER. We only try deleting them if the
  3770. constraint name does not contain a '/' character, otherwise
  3771. deleting a new format constraint named 'foo/bar' from
  3772. database 'baz' would remove constraint 'bar' from database
  3773. 'foo', if it existed. */
  3774. err = row_delete_constraint_low(id, trx);
  3775. }
  3776. return(err);
  3777. }
  3778. /*********************************************************************//**
  3779. Renames a table for MySQL.
  3780. @return error code or DB_SUCCESS */
  3781. UNIV_INTERN
  3782. dberr_t
  3783. row_rename_table_for_mysql(
  3784. /*=======================*/
  3785. const char* old_name, /*!< in: old table name */
  3786. const char* new_name, /*!< in: new table name */
  3787. trx_t* trx, /*!< in/out: transaction */
  3788. bool commit) /*!< in: whether to commit trx */
  3789. {
  3790. dict_table_t* table = NULL;
  3791. ibool dict_locked = FALSE;
  3792. dberr_t err = DB_ERROR;
  3793. mem_heap_t* heap = NULL;
  3794. const char** constraints_to_drop = NULL;
  3795. ulint n_constraints_to_drop = 0;
  3796. ibool old_is_tmp, new_is_tmp;
  3797. pars_info_t* info = NULL;
  3798. int retry;
  3799. bool aux_fts_rename = false;
  3800. ut_a(old_name != NULL);
  3801. ut_a(new_name != NULL);
  3802. ut_ad(trx->state == TRX_STATE_ACTIVE);
  3803. if (srv_force_recovery) {
  3804. fputs("InnoDB: innodb_force_recovery is on: we do not allow\n"
  3805. "InnoDB: database modifications by the user. Shut down\n"
  3806. "InnoDB: mysqld and edit my.cnf so that"
  3807. "InnoDB: innodb_force_... is removed.\n",
  3808. stderr);
  3809. err = DB_READ_ONLY;
  3810. goto funct_exit;
  3811. } else if (row_mysql_is_system_table(new_name)) {
  3812. fprintf(stderr,
  3813. "InnoDB: Error: trying to create a MySQL"
  3814. " system table %s of type InnoDB.\n"
  3815. "InnoDB: MySQL system tables must be"
  3816. " of the MyISAM type!\n",
  3817. new_name);
  3818. goto funct_exit;
  3819. }
  3820. trx->op_info = "renaming table";
  3821. old_is_tmp = row_is_mysql_tmp_table_name(old_name);
  3822. new_is_tmp = row_is_mysql_tmp_table_name(new_name);
  3823. dict_locked = trx->dict_operation_lock_mode == RW_X_LATCH;
  3824. table = dict_table_open_on_name(old_name, dict_locked, FALSE,
  3825. DICT_ERR_IGNORE_NONE);
  3826. if (!table) {
  3827. err = DB_TABLE_NOT_FOUND;
  3828. ut_print_timestamp(stderr);
  3829. fputs(" InnoDB: Error: table ", stderr);
  3830. ut_print_name(stderr, trx, TRUE, old_name);
  3831. fputs(" does not exist in the InnoDB internal\n"
  3832. "InnoDB: data dictionary though MySQL is"
  3833. " trying to rename the table.\n"
  3834. "InnoDB: Have you copied the .frm file"
  3835. " of the table to the\n"
  3836. "InnoDB: MySQL database directory"
  3837. " from another database?\n"
  3838. "InnoDB: You can look for further help from\n"
  3839. "InnoDB: " REFMAN "innodb-troubleshooting.html\n",
  3840. stderr);
  3841. goto funct_exit;
  3842. } else if (table->ibd_file_missing
  3843. && !dict_table_is_discarded(table)) {
  3844. err = DB_TABLE_NOT_FOUND;
  3845. ib_logf(IB_LOG_LEVEL_ERROR,
  3846. "Table %s does not have an .ibd file in the database "
  3847. "directory. See " REFMAN "innodb-troubleshooting.html",
  3848. old_name);
  3849. goto funct_exit;
  3850. } else if (new_is_tmp) {
  3851. /* MySQL is doing an ALTER TABLE command and it renames the
  3852. original table to a temporary table name. We want to preserve
  3853. the original foreign key constraint definitions despite the
  3854. name change. An exception is those constraints for which
  3855. the ALTER TABLE contained DROP FOREIGN KEY <foreign key id>.*/
  3856. heap = mem_heap_create(100);
  3857. err = dict_foreign_parse_drop_constraints(
  3858. heap, trx, table, &n_constraints_to_drop,
  3859. &constraints_to_drop);
  3860. if (err != DB_SUCCESS) {
  3861. goto funct_exit;
  3862. }
  3863. }
  3864. /* Is a foreign key check running on this table? */
  3865. for (retry = 0; retry < 100
  3866. && table->n_foreign_key_checks_running > 0; ++retry) {
  3867. row_mysql_unlock_data_dictionary(trx);
  3868. os_thread_yield();
  3869. row_mysql_lock_data_dictionary(trx);
  3870. }
  3871. if (table->n_foreign_key_checks_running > 0) {
  3872. ut_print_timestamp(stderr);
  3873. fputs(" InnoDB: Error: in ALTER TABLE ", stderr);
  3874. ut_print_name(stderr, trx, TRUE, old_name);
  3875. fprintf(stderr, "\n"
  3876. "InnoDB: a FOREIGN KEY check is running.\n"
  3877. "InnoDB: Cannot rename table.\n");
  3878. err = DB_TABLE_IN_FK_CHECK;
  3879. goto funct_exit;
  3880. }
  3881. /* We use the private SQL parser of Innobase to generate the query
  3882. graphs needed in updating the dictionary data from system tables. */
  3883. info = pars_info_create();
  3884. pars_info_add_str_literal(info, "new_table_name", new_name);
  3885. pars_info_add_str_literal(info, "old_table_name", old_name);
  3886. err = que_eval_sql(info,
  3887. "PROCEDURE RENAME_TABLE () IS\n"
  3888. "BEGIN\n"
  3889. "UPDATE SYS_TABLES"
  3890. " SET NAME = :new_table_name\n"
  3891. " WHERE NAME = :old_table_name;\n"
  3892. "END;\n"
  3893. , FALSE, trx);
  3894. /* SYS_TABLESPACES and SYS_DATAFILES track non-system tablespaces
  3895. which have space IDs > 0. */
  3896. if (err == DB_SUCCESS
  3897. && table->space != TRX_SYS_SPACE
  3898. && !table->ibd_file_missing) {
  3899. /* Make a new pathname to update SYS_DATAFILES. */
  3900. char* new_path = row_make_new_pathname(table, new_name);
  3901. info = pars_info_create();
  3902. pars_info_add_str_literal(info, "new_table_name", new_name);
  3903. pars_info_add_str_literal(info, "new_path_name", new_path);
  3904. pars_info_add_int4_literal(info, "space_id", table->space);
  3905. err = que_eval_sql(info,
  3906. "PROCEDURE RENAME_SPACE () IS\n"
  3907. "BEGIN\n"
  3908. "UPDATE SYS_TABLESPACES"
  3909. " SET NAME = :new_table_name\n"
  3910. " WHERE SPACE = :space_id;\n"
  3911. "UPDATE SYS_DATAFILES"
  3912. " SET PATH = :new_path_name\n"
  3913. " WHERE SPACE = :space_id;\n"
  3914. "END;\n"
  3915. , FALSE, trx);
  3916. mem_free(new_path);
  3917. }
  3918. if (err != DB_SUCCESS) {
  3919. goto end;
  3920. }
  3921. if (!new_is_tmp) {
  3922. /* Rename all constraints. */
  3923. char new_table_name[MAX_TABLE_NAME_LEN] = "";
  3924. char old_table_utf8[MAX_TABLE_NAME_LEN] = "";
  3925. uint errors = 0;
  3926. strncpy(old_table_utf8, old_name, MAX_TABLE_NAME_LEN);
  3927. innobase_convert_to_system_charset(
  3928. strchr(old_table_utf8, '/') + 1,
  3929. strchr(old_name, '/') +1,
  3930. MAX_TABLE_NAME_LEN, &errors);
  3931. if (errors) {
  3932. /* Table name could not be converted from charset
  3933. my_charset_filename to UTF-8. This means that the
  3934. table name is already in UTF-8 (#mysql#50). */
  3935. strncpy(old_table_utf8, old_name, MAX_TABLE_NAME_LEN);
  3936. }
  3937. info = pars_info_create();
  3938. pars_info_add_str_literal(info, "new_table_name", new_name);
  3939. pars_info_add_str_literal(info, "old_table_name", old_name);
  3940. pars_info_add_str_literal(info, "old_table_name_utf8",
  3941. old_table_utf8);
  3942. strncpy(new_table_name, new_name, MAX_TABLE_NAME_LEN);
  3943. innobase_convert_to_system_charset(
  3944. strchr(new_table_name, '/') + 1,
  3945. strchr(new_name, '/') +1,
  3946. MAX_TABLE_NAME_LEN, &errors);
  3947. if (errors) {
  3948. /* Table name could not be converted from charset
  3949. my_charset_filename to UTF-8. This means that the
  3950. table name is already in UTF-8 (#mysql#50). */
  3951. strncpy(new_table_name, new_name, MAX_TABLE_NAME_LEN);
  3952. }
  3953. pars_info_add_str_literal(info, "new_table_utf8", new_table_name);
  3954. err = que_eval_sql(
  3955. info,
  3956. "PROCEDURE RENAME_CONSTRAINT_IDS () IS\n"
  3957. "gen_constr_prefix CHAR;\n"
  3958. "new_db_name CHAR;\n"
  3959. "foreign_id CHAR;\n"
  3960. "new_foreign_id CHAR;\n"
  3961. "old_db_name_len INT;\n"
  3962. "old_t_name_len INT;\n"
  3963. "new_db_name_len INT;\n"
  3964. "id_len INT;\n"
  3965. "offset INT;\n"
  3966. "found INT;\n"
  3967. "BEGIN\n"
  3968. "found := 1;\n"
  3969. "old_db_name_len := INSTR(:old_table_name, '/')-1;\n"
  3970. "new_db_name_len := INSTR(:new_table_name, '/')-1;\n"
  3971. "new_db_name := SUBSTR(:new_table_name, 0,\n"
  3972. " new_db_name_len);\n"
  3973. "old_t_name_len := LENGTH(:old_table_name);\n"
  3974. "gen_constr_prefix := CONCAT(:old_table_name_utf8,\n"
  3975. " '_ibfk_');\n"
  3976. "WHILE found = 1 LOOP\n"
  3977. " SELECT ID INTO foreign_id\n"
  3978. " FROM SYS_FOREIGN\n"
  3979. " WHERE FOR_NAME = :old_table_name\n"
  3980. " AND TO_BINARY(FOR_NAME)\n"
  3981. " = TO_BINARY(:old_table_name)\n"
  3982. " LOCK IN SHARE MODE;\n"
  3983. " IF (SQL % NOTFOUND) THEN\n"
  3984. " found := 0;\n"
  3985. " ELSE\n"
  3986. " UPDATE SYS_FOREIGN\n"
  3987. " SET FOR_NAME = :new_table_name\n"
  3988. " WHERE ID = foreign_id;\n"
  3989. " id_len := LENGTH(foreign_id);\n"
  3990. " IF (INSTR(foreign_id, '/') > 0) THEN\n"
  3991. " IF (INSTR(foreign_id,\n"
  3992. " gen_constr_prefix) > 0)\n"
  3993. " THEN\n"
  3994. " offset := INSTR(foreign_id, '_ibfk_') - 1;\n"
  3995. " new_foreign_id :=\n"
  3996. " CONCAT(:new_table_utf8,\n"
  3997. " SUBSTR(foreign_id, offset,\n"
  3998. " id_len - offset));\n"
  3999. " ELSE\n"
  4000. " new_foreign_id :=\n"
  4001. " CONCAT(new_db_name,\n"
  4002. " SUBSTR(foreign_id,\n"
  4003. " old_db_name_len,\n"
  4004. " id_len - old_db_name_len));\n"
  4005. " END IF;\n"
  4006. " UPDATE SYS_FOREIGN\n"
  4007. " SET ID = new_foreign_id\n"
  4008. " WHERE ID = foreign_id;\n"
  4009. " UPDATE SYS_FOREIGN_COLS\n"
  4010. " SET ID = new_foreign_id\n"
  4011. " WHERE ID = foreign_id;\n"
  4012. " END IF;\n"
  4013. " END IF;\n"
  4014. "END LOOP;\n"
  4015. "UPDATE SYS_FOREIGN SET REF_NAME = :new_table_name\n"
  4016. "WHERE REF_NAME = :old_table_name\n"
  4017. " AND TO_BINARY(REF_NAME)\n"
  4018. " = TO_BINARY(:old_table_name);\n"
  4019. "END;\n"
  4020. , FALSE, trx);
  4021. } else if (n_constraints_to_drop > 0) {
  4022. /* Drop some constraints of tmp tables. */
  4023. ulint db_name_len = dict_get_db_name_len(old_name) + 1;
  4024. char* db_name = mem_heap_strdupl(heap, old_name,
  4025. db_name_len);
  4026. ulint i;
  4027. for (i = 0; i < n_constraints_to_drop; i++) {
  4028. err = row_delete_constraint(constraints_to_drop[i],
  4029. db_name, heap, trx);
  4030. if (err != DB_SUCCESS) {
  4031. break;
  4032. }
  4033. }
  4034. }
  4035. if (dict_table_has_fts_index(table)
  4036. && !dict_tables_have_same_db(old_name, new_name)) {
  4037. err = fts_rename_aux_tables(table, new_name, trx);
  4038. if (err != DB_TABLE_NOT_FOUND) {
  4039. aux_fts_rename = true;
  4040. }
  4041. }
  4042. end:
  4043. if (err != DB_SUCCESS) {
  4044. if (err == DB_DUPLICATE_KEY) {
  4045. ut_print_timestamp(stderr);
  4046. fputs(" InnoDB: Error; possible reasons:\n"
  4047. "InnoDB: 1) Table rename would cause"
  4048. " two FOREIGN KEY constraints\n"
  4049. "InnoDB: to have the same internal name"
  4050. " in case-insensitive comparison.\n"
  4051. "InnoDB: 2) table ", stderr);
  4052. ut_print_name(stderr, trx, TRUE, new_name);
  4053. fputs(" exists in the InnoDB internal data\n"
  4054. "InnoDB: dictionary though MySQL is"
  4055. " trying to rename table ", stderr);
  4056. ut_print_name(stderr, trx, TRUE, old_name);
  4057. fputs(" to it.\n"
  4058. "InnoDB: Have you deleted the .frm file"
  4059. " and not used DROP TABLE?\n"
  4060. "InnoDB: You can look for further help from\n"
  4061. "InnoDB: " REFMAN "innodb-troubleshooting.html\n"
  4062. "InnoDB: If table ", stderr);
  4063. ut_print_name(stderr, trx, TRUE, new_name);
  4064. fputs(" is a temporary table #sql..., then"
  4065. " it can be that\n"
  4066. "InnoDB: there are still queries running"
  4067. " on the table, and it will be\n"
  4068. "InnoDB: dropped automatically when"
  4069. " the queries end.\n"
  4070. "InnoDB: You can drop the orphaned table"
  4071. " inside InnoDB by\n"
  4072. "InnoDB: creating an InnoDB table with"
  4073. " the same name in another\n"
  4074. "InnoDB: database and copying the .frm file"
  4075. " to the current database.\n"
  4076. "InnoDB: Then MySQL thinks the table exists,"
  4077. " and DROP TABLE will\n"
  4078. "InnoDB: succeed.\n", stderr);
  4079. }
  4080. trx->error_state = DB_SUCCESS;
  4081. trx_rollback_to_savepoint(trx, NULL);
  4082. trx->error_state = DB_SUCCESS;
  4083. } else {
  4084. /* The following call will also rename the .ibd data file if
  4085. the table is stored in a single-table tablespace */
  4086. err = dict_table_rename_in_cache(
  4087. table, new_name, !new_is_tmp);
  4088. if (err != DB_SUCCESS) {
  4089. trx->error_state = DB_SUCCESS;
  4090. trx_rollback_to_savepoint(trx, NULL);
  4091. trx->error_state = DB_SUCCESS;
  4092. goto funct_exit;
  4093. }
  4094. /* We only want to switch off some of the type checking in
  4095. an ALTER, not in a RENAME. */
  4096. err = dict_load_foreigns(
  4097. new_name, NULL,
  4098. false, !old_is_tmp || trx->check_foreigns,
  4099. DICT_ERR_IGNORE_NONE);
  4100. if (err != DB_SUCCESS) {
  4101. ut_print_timestamp(stderr);
  4102. if (old_is_tmp) {
  4103. fputs(" InnoDB: Error: in ALTER TABLE ",
  4104. stderr);
  4105. ut_print_name(stderr, trx, TRUE, new_name);
  4106. fputs("\n"
  4107. "InnoDB: has or is referenced"
  4108. " in foreign key constraints\n"
  4109. "InnoDB: which are not compatible"
  4110. " with the new table definition.\n",
  4111. stderr);
  4112. } else {
  4113. fputs(" InnoDB: Error: in RENAME TABLE"
  4114. " table ",
  4115. stderr);
  4116. ut_print_name(stderr, trx, TRUE, new_name);
  4117. fputs("\n"
  4118. "InnoDB: is referenced in"
  4119. " foreign key constraints\n"
  4120. "InnoDB: which are not compatible"
  4121. " with the new table definition.\n",
  4122. stderr);
  4123. }
  4124. ut_a(DB_SUCCESS == dict_table_rename_in_cache(
  4125. table, old_name, FALSE));
  4126. trx->error_state = DB_SUCCESS;
  4127. trx_rollback_to_savepoint(trx, NULL);
  4128. trx->error_state = DB_SUCCESS;
  4129. }
  4130. }
  4131. funct_exit:
  4132. if (aux_fts_rename && err != DB_SUCCESS
  4133. && table != NULL && (table->space != 0)) {
  4134. char* orig_name = table->name;
  4135. trx_t* trx_bg = trx_allocate_for_background();
  4136. /* If the first fts_rename fails, the trx would
  4137. be rolled back and committed, we can't use it any more,
  4138. so we have to start a new background trx here. */
  4139. ut_a(trx_state_eq(trx_bg, TRX_STATE_NOT_STARTED));
  4140. trx_bg->op_info = "Revert the failing rename "
  4141. "for fts aux tables";
  4142. trx_bg->dict_operation_lock_mode = RW_X_LATCH;
  4143. trx_start_for_ddl(trx_bg, TRX_DICT_OP_TABLE);
  4144. /* If rename fails and table has its own tablespace,
  4145. we need to call fts_rename_aux_tables again to
  4146. revert the ibd file rename, which is not under the
  4147. control of trx. Also notice the parent table name
  4148. in cache is not changed yet. If the reverting fails,
  4149. the ibd data may be left in the new database, which
  4150. can be fixed only manually. */
  4151. table->name = const_cast<char*>(new_name);
  4152. fts_rename_aux_tables(table, old_name, trx_bg);
  4153. table->name = orig_name;
  4154. trx_bg->dict_operation_lock_mode = 0;
  4155. trx_commit_for_mysql(trx_bg);
  4156. trx_free_for_background(trx_bg);
  4157. }
  4158. if (table != NULL) {
  4159. dict_table_close(table, dict_locked, FALSE);
  4160. }
  4161. if (commit) {
  4162. trx_commit_for_mysql(trx);
  4163. }
  4164. if (UNIV_LIKELY_NULL(heap)) {
  4165. mem_heap_free(heap);
  4166. }
  4167. trx->op_info = "";
  4168. return(err);
  4169. }
  4170. /*********************************************************************//**
  4171. Checks that the index contains entries in an ascending order, unique
  4172. constraint is not broken, and calculates the number of index entries
  4173. in the read view of the current transaction.
  4174. @return true if ok */
  4175. UNIV_INTERN
  4176. bool
  4177. row_check_index_for_mysql(
  4178. /*======================*/
  4179. row_prebuilt_t* prebuilt, /*!< in: prebuilt struct
  4180. in MySQL handle */
  4181. const dict_index_t* index, /*!< in: index */
  4182. ulint* n_rows) /*!< out: number of entries
  4183. seen in the consistent read */
  4184. {
  4185. dtuple_t* prev_entry = NULL;
  4186. ulint matched_fields;
  4187. ulint matched_bytes;
  4188. byte* buf;
  4189. ulint ret;
  4190. rec_t* rec;
  4191. bool is_ok = true;
  4192. int cmp;
  4193. ibool contains_null;
  4194. ulint i;
  4195. ulint cnt;
  4196. mem_heap_t* heap = NULL;
  4197. ulint n_ext;
  4198. ulint offsets_[REC_OFFS_NORMAL_SIZE];
  4199. ulint* offsets;
  4200. rec_offs_init(offsets_);
  4201. *n_rows = 0;
  4202. if (dict_index_is_clust(index)) {
  4203. /* The clustered index of a table is always available.
  4204. During online ALTER TABLE that rebuilds the table, the
  4205. clustered index in the old table will have
  4206. index->online_log pointing to the new table. All
  4207. indexes of the old table will remain valid and the new
  4208. table will be unaccessible to MySQL until the
  4209. completion of the ALTER TABLE. */
  4210. } else if (dict_index_is_online_ddl(index)
  4211. || (index->type & DICT_FTS)) {
  4212. /* Full Text index are implemented by auxiliary tables,
  4213. not the B-tree. We also skip secondary indexes that are
  4214. being created online. */
  4215. return(true);
  4216. }
  4217. buf = static_cast<byte*>(mem_alloc(UNIV_PAGE_SIZE));
  4218. heap = mem_heap_create(100);
  4219. cnt = 1000;
  4220. ret = row_search_for_mysql(buf, PAGE_CUR_G, prebuilt, 0, 0);
  4221. loop:
  4222. /* Check thd->killed every 1,000 scanned rows */
  4223. if (--cnt == 0) {
  4224. if (trx_is_interrupted(prebuilt->trx)) {
  4225. goto func_exit;
  4226. }
  4227. cnt = 1000;
  4228. }
  4229. switch (ret) {
  4230. case DB_SUCCESS:
  4231. break;
  4232. default:
  4233. ut_print_timestamp(stderr);
  4234. fputs(" InnoDB: Warning: CHECK TABLE on ", stderr);
  4235. dict_index_name_print(stderr, prebuilt->trx, index);
  4236. fprintf(stderr, " returned %lu\n", ret);
  4237. /* fall through (this error is ignored by CHECK TABLE) */
  4238. case DB_END_OF_INDEX:
  4239. func_exit:
  4240. mem_free(buf);
  4241. mem_heap_free(heap);
  4242. return(is_ok);
  4243. }
  4244. *n_rows = *n_rows + 1;
  4245. /* row_search... returns the index record in buf, record origin offset
  4246. within buf stored in the first 4 bytes, because we have built a dummy
  4247. template */
  4248. rec = buf + mach_read_from_4(buf);
  4249. offsets = rec_get_offsets(rec, index, offsets_,
  4250. ULINT_UNDEFINED, &heap);
  4251. if (prev_entry != NULL) {
  4252. matched_fields = 0;
  4253. matched_bytes = 0;
  4254. cmp = cmp_dtuple_rec_with_match(prev_entry, rec, offsets,
  4255. &matched_fields,
  4256. &matched_bytes);
  4257. contains_null = FALSE;
  4258. /* In a unique secondary index we allow equal key values if
  4259. they contain SQL NULLs */
  4260. for (i = 0;
  4261. i < dict_index_get_n_ordering_defined_by_user(index);
  4262. i++) {
  4263. if (UNIV_SQL_NULL == dfield_get_len(
  4264. dtuple_get_nth_field(prev_entry, i))) {
  4265. contains_null = TRUE;
  4266. break;
  4267. }
  4268. }
  4269. if (cmp > 0) {
  4270. fputs("InnoDB: index records in a wrong order in ",
  4271. stderr);
  4272. not_ok:
  4273. dict_index_name_print(stderr,
  4274. prebuilt->trx, index);
  4275. fputs("\n"
  4276. "InnoDB: prev record ", stderr);
  4277. dtuple_print(stderr, prev_entry);
  4278. fputs("\n"
  4279. "InnoDB: record ", stderr);
  4280. rec_print_new(stderr, rec, offsets);
  4281. putc('\n', stderr);
  4282. is_ok = false;
  4283. } else if (dict_index_is_unique(index)
  4284. && !contains_null
  4285. && matched_fields
  4286. >= dict_index_get_n_ordering_defined_by_user(
  4287. index)) {
  4288. fputs("InnoDB: duplicate key in ", stderr);
  4289. goto not_ok;
  4290. }
  4291. }
  4292. {
  4293. mem_heap_t* tmp_heap = NULL;
  4294. /* Empty the heap on each round. But preserve offsets[]
  4295. for the row_rec_to_index_entry() call, by copying them
  4296. into a separate memory heap when needed. */
  4297. if (UNIV_UNLIKELY(offsets != offsets_)) {
  4298. ulint size = rec_offs_get_n_alloc(offsets)
  4299. * sizeof *offsets;
  4300. tmp_heap = mem_heap_create(size);
  4301. offsets = static_cast<ulint*>(
  4302. mem_heap_dup(tmp_heap, offsets, size));
  4303. }
  4304. mem_heap_empty(heap);
  4305. prev_entry = row_rec_to_index_entry(
  4306. rec, index, offsets, &n_ext, heap);
  4307. if (UNIV_LIKELY_NULL(tmp_heap)) {
  4308. mem_heap_free(tmp_heap);
  4309. }
  4310. }
  4311. ret = row_search_for_mysql(buf, PAGE_CUR_G, prebuilt, 0, ROW_SEL_NEXT);
  4312. goto loop;
  4313. }
  4314. /*********************************************************************//**
  4315. Determines if a table is a magic monitor table.
  4316. @return true if monitor table */
  4317. UNIV_INTERN
  4318. bool
  4319. row_is_magic_monitor_table(
  4320. /*=======================*/
  4321. const char* table_name) /*!< in: name of the table, in the
  4322. form database/table_name */
  4323. {
  4324. const char* name; /* table_name without database/ */
  4325. ulint len;
  4326. name = dict_remove_db_name(table_name);
  4327. len = strlen(name) + 1;
  4328. return(STR_EQ(name, len, S_innodb_monitor)
  4329. || STR_EQ(name, len, S_innodb_lock_monitor)
  4330. || STR_EQ(name, len, S_innodb_tablespace_monitor)
  4331. || STR_EQ(name, len, S_innodb_table_monitor)
  4332. #ifdef UNIV_MEM_DEBUG
  4333. || STR_EQ(name, len, S_innodb_mem_validate)
  4334. #endif /* UNIV_MEM_DEBUG */
  4335. );
  4336. }
  4337. /*********************************************************************//**
  4338. Initialize this module */
  4339. UNIV_INTERN
  4340. void
  4341. row_mysql_init(void)
  4342. /*================*/
  4343. {
  4344. mutex_create(
  4345. row_drop_list_mutex_key,
  4346. &row_drop_list_mutex, SYNC_NO_ORDER_CHECK);
  4347. UT_LIST_INIT(row_mysql_drop_list);
  4348. row_mysql_drop_list_inited = TRUE;
  4349. }
  4350. /*********************************************************************//**
  4351. Close this module */
  4352. UNIV_INTERN
  4353. void
  4354. row_mysql_close(void)
  4355. /*================*/
  4356. {
  4357. ut_a(UT_LIST_GET_LEN(row_mysql_drop_list) == 0);
  4358. mutex_free(&row_drop_list_mutex);
  4359. row_mysql_drop_list_inited = FALSE;
  4360. }