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.

5481 lines
149 KiB

17 years ago
17 years ago
17 years ago
16 years ago
15 years ago
16 years ago
16 years ago
16 years ago
15 years ago
16 years ago
16 years ago
15 years ago
16 years ago
16 years ago
16 years ago
16 years ago
15 years ago
15 years ago
16 years ago
16 years ago
16 years ago
16 years ago
16 years ago
16 years ago
16 years ago
16 years ago
16 years ago
16 years ago
16 years ago
16 years ago
16 years ago
16 years ago
16 years ago
16 years ago
16 years ago
16 years ago
16 years ago
16 years ago
16 years ago
16 years ago
16 years ago
16 years ago
16 years ago
16 years ago
16 years ago
16 years ago
16 years ago
16 years ago
16 years ago
16 years ago
16 years ago
16 years ago
16 years ago
16 years ago
16 years ago
16 years ago
16 years ago
16 years ago
16 years ago
16 years ago
17 years ago
16 years ago
16 years ago
16 years ago
16 years ago
16 years ago
16 years ago
16 years ago
17 years ago
17 years ago
16 years ago
16 years ago
17 years ago
16 years ago
16 years ago
16 years ago
16 years ago
16 years ago
16 years ago
17 years ago
16 years ago
16 years ago
17 years ago
17 years ago
17 years ago
15 years ago
15 years ago
15 years ago
16 years ago
16 years ago
16 years ago
16 years ago
16 years ago
16 years ago
16 years ago
16 years ago
16 years ago
16 years ago
16 years ago
16 years ago
16 years ago
16 years ago
16 years ago
16 years ago
16 years ago
16 years ago
16 years ago
15 years ago
15 years ago
15 years ago
15 years ago
15 years ago
15 years ago
15 years ago
16 years ago
17 years ago
17 years ago
17 years ago
16 years ago
17 years ago
16 years ago
16 years ago
16 years ago
16 years ago
16 years ago
16 years ago
16 years ago
16 years ago
16 years ago
16 years ago
16 years ago
16 years ago
17 years ago
16 years ago
16 years ago
16 years ago
16 years ago
16 years ago
16 years ago
16 years ago
16 years ago
16 years ago
16 years ago
16 years ago
16 years ago
16 years ago
16 years ago
16 years ago
16 years ago
16 years ago
Fix for lp:711565 "Index Condition Pushdown can make a thread hold MyISAM locks as well as be unKILLable for long time" - In Maria/MyISAM: Release/re-acquire locks to give queries that wait on them a chance to make progress - In Maria/MyISAM: Change from numeric constants to ICP_RES values. - In Maria: Do check index condition in maria_rprev() (was lost in the merge/backport?) - In Maria/MyISAM/XtraDB: Check if the query was killed, and return immediately if it was. Added new storage engine error: HA_ERR_ABORTED_BY_USER, for handler to signal that it detected a kill of the query and aborted Authors: Sergey Petrunia & Monty include/my_base.h: Added HA_ERR_ABORTED_BY_USER, for handler to signal that it detected a kill of the query and aborted include/my_handler.h: Added comment mysql-test/r/myisam_icp.result: Updated test mysql-test/t/myisam_icp.test: Drop used tables at start of test Added test case that can help with manual testing of killing index condition pushdown query. mysys/my_handler_errors.h: Text for new storage engine error sql/handler.cc: If engine got HA_ERR_ABORTED_BY_USER, send kill message. sql/multi_range_read.cc: Return error code storage/maria/ha_maria.cc: Added ma_killed_in_mariadb() to detect kill. Ensure that file->external_ref points to TABLE object. storage/maria/ma_extra.c: Dummy test-if-killed for standalone storage/maria/ma_key.c: If ma_check_index_cond() fails, set my_errno and info->cur_row.lastpos storage/maria/ma_rkey.c: Release/re-acquire locks to give queries that wait on them a chance to make progress Check if the query was killed, and return immediately if it was storage/maria/ma_rnext.c: Check if the query was killed, and return immediately if it was Added missing fast_ma_writeinfo(info) storage/maria/ma_rnext_same.c: Check if the query was killed, and return immediately if it was Added missing fast_ma_writeinfo(info) storage/maria/ma_rprev.c: Check if the query was killed, and return immediately if it was Added missing fast_ma_writeinfo(info) and ma_check_index_cond() storage/maria/ma_search.c: Give error message if we find a wrong key storage/maria/ma_static.c: Added pointer to test-if-killed function storage/maria/maria_def.h: New prototypes storage/myisam/ha_myisam.cc: Added mi_killed_in_mariadb() Ensure that file->external_ref points to TABLE object. storage/myisam/mi_extra.c: Dummy test-if-killed for standalone storage/myisam/mi_key.c: If ma_check_index_cond() fails, set my_errno and info->lastpos storage/myisam/mi_rkey.c: Ensure that info->lastpos= HA_OFFSET_ERROR in case of error Release/re-acquire locks to give queries that wait on them a chance to make progress Check if the query was killed, and return immediately if it was Reorder code to do less things in case of error. Added missing fast_mi_writeinfo() storage/myisam/mi_rnext.c: Check if the query was killed, and return immediately if it was Simplify old ICP code Added missing fast_ma_writeinfo(info) storage/myisam/mi_rnext_same.c: Check if the query was killed, and return immediately if it was Added missing fast_mi_writeinfo(info) storage/myisam/mi_rprev.c: Check if the query was killed, and return immediately if it was Simplify error handling of ICP Added missing fast_mi_writeinfo(info) storage/myisam/mi_search.c: Give error message if we find a wrong key storage/myisam/mi_static.c: Added pointer to test-if-killed function storage/myisam/myisamdef.h: New prototypes storage/xtradb/handler/ha_innodb.cc: Added DB_SEARCH_ABORTED_BY_USER and ha_innobase::is_thd_killed() Check if the query was killed, and return immediately if it was storage/xtradb/handler/ha_innodb.h: Added prototype storage/xtradb/include/db0err.h: Added DB_SEARCH_ABORTED_BY_USER storage/xtradb/include/row0mysql.h: Added possible ICP errors storage/xtradb/row/row0sel.c: Use ICP errors instead of constants. Detect if killed and return B_SEARCH_ABORTED_BY_USER
15 years ago
16 years ago
16 years ago
16 years ago
16 years ago
16 years ago
17 years ago
15 years ago
17 years ago
17 years ago
17 years ago
17 years ago
15 years ago
15 years ago
15 years ago
16 years ago
16 years ago
16 years ago
15 years ago
16 years ago
16 years ago
16 years ago
16 years ago
16 years ago
16 years ago
  1. /*****************************************************************************
  2. Copyright (c) 1997, 2013, Oracle and/or its affiliates. All Rights Reserved.
  3. Copyright (c) 2008, Google Inc.
  4. Portions of this file contain modifications contributed and copyrighted by
  5. Google, Inc. Those modifications are gratefully acknowledged and are described
  6. briefly in the InnoDB documentation. The contributions by Google are
  7. incorporated with their permission, and subject to the conditions contained in
  8. the file COPYING.Google.
  9. This program is free software; you can redistribute it and/or modify it under
  10. the terms of the GNU General Public License as published by the Free Software
  11. Foundation; version 2 of the License.
  12. This program is distributed in the hope that it will be useful, but WITHOUT
  13. ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
  14. FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
  15. You should have received a copy of the GNU General Public License along with
  16. this program; if not, write to the Free Software Foundation, Inc.,
  17. 51 Franklin Street, Suite 500, Boston, MA 02110-1335 USA
  18. *****************************************************************************/
  19. /***************************************************//**
  20. @file row/row0sel.cc
  21. Select
  22. Created 12/19/1997 Heikki Tuuri
  23. *******************************************************/
  24. #include "row0sel.h"
  25. #ifdef UNIV_NONINL
  26. #include "row0sel.ic"
  27. #endif
  28. #include "dict0dict.h"
  29. #include "dict0boot.h"
  30. #include "trx0undo.h"
  31. #include "trx0trx.h"
  32. #include "btr0btr.h"
  33. #include "btr0cur.h"
  34. #include "btr0sea.h"
  35. #include "mach0data.h"
  36. #include "que0que.h"
  37. #include "row0upd.h"
  38. #include "row0row.h"
  39. #include "row0vers.h"
  40. #include "rem0cmp.h"
  41. #include "lock0lock.h"
  42. #include "eval0eval.h"
  43. #include "pars0sym.h"
  44. #include "pars0pars.h"
  45. #include "row0mysql.h"
  46. #include "read0read.h"
  47. #include "buf0lru.h"
  48. #include "srv0srv.h"
  49. #include "ha_prototypes.h"
  50. #include "srv0start.h"
  51. #include "m_string.h" /* for my_sys.h */
  52. #include "my_sys.h" /* DEBUG_SYNC_C */
  53. #include "my_compare.h" /* enum icp_result */
  54. /* Maximum number of rows to prefetch; MySQL interface has another parameter */
  55. #define SEL_MAX_N_PREFETCH 16
  56. /* Number of rows fetched, after which to start prefetching; MySQL interface
  57. has another parameter */
  58. #define SEL_PREFETCH_LIMIT 1
  59. /* When a select has accessed about this many pages, it returns control back
  60. to que_run_threads: this is to allow canceling runaway queries */
  61. #define SEL_COST_LIMIT 100
  62. /* Flags for search shortcut */
  63. #define SEL_FOUND 0
  64. #define SEL_EXHAUSTED 1
  65. #define SEL_RETRY 2
  66. /********************************************************************//**
  67. Returns TRUE if the user-defined column in a secondary index record
  68. is alphabetically the same as the corresponding BLOB column in the clustered
  69. index record.
  70. NOTE: the comparison is NOT done as a binary comparison, but character
  71. fields are compared with collation!
  72. @return TRUE if the columns are equal */
  73. static
  74. ibool
  75. row_sel_sec_rec_is_for_blob(
  76. /*========================*/
  77. ulint mtype, /*!< in: main type */
  78. ulint prtype, /*!< in: precise type */
  79. ulint mbminmaxlen, /*!< in: minimum and maximum length of
  80. a multi-byte character */
  81. const byte* clust_field, /*!< in: the locally stored part of
  82. the clustered index column, including
  83. the BLOB pointer; the clustered
  84. index record must be covered by
  85. a lock or a page latch to protect it
  86. against deletion (rollback or purge) */
  87. ulint clust_len, /*!< in: length of clust_field */
  88. const byte* sec_field, /*!< in: column in secondary index */
  89. ulint sec_len, /*!< in: length of sec_field */
  90. ulint prefix_len, /*!< in: index column prefix length
  91. in bytes */
  92. dict_table_t* table) /*!< in: table */
  93. {
  94. ulint len;
  95. byte buf[REC_VERSION_56_MAX_INDEX_COL_LEN];
  96. ulint zip_size = dict_tf_get_zip_size(table->flags);
  97. /* This function should never be invoked on an Antelope format
  98. table, because they should always contain enough prefix in the
  99. clustered index record. */
  100. ut_ad(dict_table_get_format(table) >= UNIV_FORMAT_B);
  101. ut_a(clust_len >= BTR_EXTERN_FIELD_REF_SIZE);
  102. ut_ad(prefix_len >= sec_len);
  103. ut_ad(prefix_len > 0);
  104. ut_a(prefix_len <= sizeof buf);
  105. if (UNIV_UNLIKELY
  106. (!memcmp(clust_field + clust_len - BTR_EXTERN_FIELD_REF_SIZE,
  107. field_ref_zero, BTR_EXTERN_FIELD_REF_SIZE))) {
  108. /* The externally stored field was not written yet.
  109. This record should only be seen by
  110. recv_recovery_rollback_active() or any
  111. TRX_ISO_READ_UNCOMMITTED transactions. */
  112. return(FALSE);
  113. }
  114. len = btr_copy_externally_stored_field_prefix(buf, prefix_len,
  115. zip_size,
  116. clust_field, clust_len);
  117. if (UNIV_UNLIKELY(len == 0)) {
  118. /* The BLOB was being deleted as the server crashed.
  119. There should not be any secondary index records
  120. referring to this clustered index record, because
  121. btr_free_externally_stored_field() is called after all
  122. secondary index entries of the row have been purged. */
  123. return(FALSE);
  124. }
  125. len = dtype_get_at_most_n_mbchars(prtype, mbminmaxlen,
  126. prefix_len, len, (const char*) buf);
  127. return(!cmp_data_data(mtype, prtype, buf, len, sec_field, sec_len));
  128. }
  129. /********************************************************************//**
  130. Returns TRUE if the user-defined column values in a secondary index record
  131. are alphabetically the same as the corresponding columns in the clustered
  132. index record.
  133. NOTE: the comparison is NOT done as a binary comparison, but character
  134. fields are compared with collation!
  135. @return TRUE if the secondary record is equal to the corresponding
  136. fields in the clustered record, when compared with collation;
  137. FALSE if not equal or if the clustered record has been marked for deletion */
  138. static
  139. ibool
  140. row_sel_sec_rec_is_for_clust_rec(
  141. /*=============================*/
  142. const rec_t* sec_rec, /*!< in: secondary index record */
  143. dict_index_t* sec_index, /*!< in: secondary index */
  144. const rec_t* clust_rec, /*!< in: clustered index record;
  145. must be protected by a lock or
  146. a page latch against deletion
  147. in rollback or purge */
  148. dict_index_t* clust_index) /*!< in: clustered index */
  149. {
  150. const byte* sec_field;
  151. ulint sec_len;
  152. const byte* clust_field;
  153. ulint n;
  154. ulint i;
  155. mem_heap_t* heap = NULL;
  156. ulint clust_offsets_[REC_OFFS_NORMAL_SIZE];
  157. ulint sec_offsets_[REC_OFFS_SMALL_SIZE];
  158. ulint* clust_offs = clust_offsets_;
  159. ulint* sec_offs = sec_offsets_;
  160. ibool is_equal = TRUE;
  161. rec_offs_init(clust_offsets_);
  162. rec_offs_init(sec_offsets_);
  163. if (rec_get_deleted_flag(clust_rec,
  164. dict_table_is_comp(clust_index->table))) {
  165. /* The clustered index record is delete-marked;
  166. it is not visible in the read view. Besides,
  167. if there are any externally stored columns,
  168. some of them may have already been purged. */
  169. return(FALSE);
  170. }
  171. clust_offs = rec_get_offsets(clust_rec, clust_index, clust_offs,
  172. ULINT_UNDEFINED, &heap);
  173. sec_offs = rec_get_offsets(sec_rec, sec_index, sec_offs,
  174. ULINT_UNDEFINED, &heap);
  175. n = dict_index_get_n_ordering_defined_by_user(sec_index);
  176. for (i = 0; i < n; i++) {
  177. const dict_field_t* ifield;
  178. const dict_col_t* col;
  179. ulint clust_pos;
  180. ulint clust_len;
  181. ulint len;
  182. ifield = dict_index_get_nth_field(sec_index, i);
  183. col = dict_field_get_col(ifield);
  184. clust_pos = dict_col_get_clust_pos(col, clust_index);
  185. clust_field = rec_get_nth_field(
  186. clust_rec, clust_offs, clust_pos, &clust_len);
  187. sec_field = rec_get_nth_field(sec_rec, sec_offs, i, &sec_len);
  188. len = clust_len;
  189. if (ifield->prefix_len > 0 && len != UNIV_SQL_NULL
  190. && sec_len != UNIV_SQL_NULL) {
  191. if (rec_offs_nth_extern(clust_offs, clust_pos)) {
  192. len -= BTR_EXTERN_FIELD_REF_SIZE;
  193. }
  194. len = dtype_get_at_most_n_mbchars(
  195. col->prtype, col->mbminmaxlen,
  196. ifield->prefix_len, len, (char*) clust_field);
  197. if (rec_offs_nth_extern(clust_offs, clust_pos)
  198. && len < sec_len) {
  199. if (!row_sel_sec_rec_is_for_blob(
  200. col->mtype, col->prtype,
  201. col->mbminmaxlen,
  202. clust_field, clust_len,
  203. sec_field, sec_len,
  204. ifield->prefix_len,
  205. clust_index->table)) {
  206. goto inequal;
  207. }
  208. continue;
  209. }
  210. }
  211. if (0 != cmp_data_data(col->mtype, col->prtype,
  212. clust_field, len,
  213. sec_field, sec_len)) {
  214. inequal:
  215. is_equal = FALSE;
  216. goto func_exit;
  217. }
  218. }
  219. func_exit:
  220. if (UNIV_LIKELY_NULL(heap)) {
  221. mem_heap_free(heap);
  222. }
  223. return(is_equal);
  224. }
  225. /*********************************************************************//**
  226. Creates a select node struct.
  227. @return own: select node struct */
  228. UNIV_INTERN
  229. sel_node_t*
  230. sel_node_create(
  231. /*============*/
  232. mem_heap_t* heap) /*!< in: memory heap where created */
  233. {
  234. sel_node_t* node;
  235. node = static_cast<sel_node_t*>(
  236. mem_heap_alloc(heap, sizeof(sel_node_t)));
  237. node->common.type = QUE_NODE_SELECT;
  238. node->state = SEL_NODE_OPEN;
  239. node->plans = NULL;
  240. return(node);
  241. }
  242. /*********************************************************************//**
  243. Frees the memory private to a select node when a query graph is freed,
  244. does not free the heap where the node was originally created. */
  245. UNIV_INTERN
  246. void
  247. sel_node_free_private(
  248. /*==================*/
  249. sel_node_t* node) /*!< in: select node struct */
  250. {
  251. ulint i;
  252. plan_t* plan;
  253. if (node->plans != NULL) {
  254. for (i = 0; i < node->n_tables; i++) {
  255. plan = sel_node_get_nth_plan(node, i);
  256. btr_pcur_close(&(plan->pcur));
  257. btr_pcur_close(&(plan->clust_pcur));
  258. if (plan->old_vers_heap) {
  259. mem_heap_free(plan->old_vers_heap);
  260. }
  261. }
  262. }
  263. }
  264. /*********************************************************************//**
  265. Evaluates the values in a select list. If there are aggregate functions,
  266. their argument value is added to the aggregate total. */
  267. UNIV_INLINE
  268. void
  269. sel_eval_select_list(
  270. /*=================*/
  271. sel_node_t* node) /*!< in: select node */
  272. {
  273. que_node_t* exp;
  274. exp = node->select_list;
  275. while (exp) {
  276. eval_exp(exp);
  277. exp = que_node_get_next(exp);
  278. }
  279. }
  280. /*********************************************************************//**
  281. Assigns the values in the select list to the possible into-variables in
  282. SELECT ... INTO ... */
  283. UNIV_INLINE
  284. void
  285. sel_assign_into_var_values(
  286. /*=======================*/
  287. sym_node_t* var, /*!< in: first variable in a list of
  288. variables */
  289. sel_node_t* node) /*!< in: select node */
  290. {
  291. que_node_t* exp;
  292. if (var == NULL) {
  293. return;
  294. }
  295. for (exp = node->select_list;
  296. var != 0;
  297. var = static_cast<sym_node_t*>(que_node_get_next(var))) {
  298. ut_ad(exp);
  299. eval_node_copy_val(var->alias, exp);
  300. exp = que_node_get_next(exp);
  301. }
  302. }
  303. /*********************************************************************//**
  304. Resets the aggregate value totals in the select list of an aggregate type
  305. query. */
  306. UNIV_INLINE
  307. void
  308. sel_reset_aggregate_vals(
  309. /*=====================*/
  310. sel_node_t* node) /*!< in: select node */
  311. {
  312. func_node_t* func_node;
  313. ut_ad(node->is_aggregate);
  314. for (func_node = static_cast<func_node_t*>(node->select_list);
  315. func_node != 0;
  316. func_node = static_cast<func_node_t*>(
  317. que_node_get_next(func_node))) {
  318. eval_node_set_int_val(func_node, 0);
  319. }
  320. node->aggregate_already_fetched = FALSE;
  321. }
  322. /*********************************************************************//**
  323. Copies the input variable values when an explicit cursor is opened. */
  324. UNIV_INLINE
  325. void
  326. row_sel_copy_input_variable_vals(
  327. /*=============================*/
  328. sel_node_t* node) /*!< in: select node */
  329. {
  330. sym_node_t* var;
  331. var = UT_LIST_GET_FIRST(node->copy_variables);
  332. while (var) {
  333. eval_node_copy_val(var, var->alias);
  334. var->indirection = NULL;
  335. var = UT_LIST_GET_NEXT(col_var_list, var);
  336. }
  337. }
  338. /*********************************************************************//**
  339. Fetches the column values from a record. */
  340. static
  341. void
  342. row_sel_fetch_columns(
  343. /*==================*/
  344. dict_index_t* index, /*!< in: record index */
  345. const rec_t* rec, /*!< in: record in a clustered or non-clustered
  346. index; must be protected by a page latch */
  347. const ulint* offsets,/*!< in: rec_get_offsets(rec, index) */
  348. sym_node_t* column) /*!< in: first column in a column list, or
  349. NULL */
  350. {
  351. dfield_t* val;
  352. ulint index_type;
  353. ulint field_no;
  354. const byte* data;
  355. ulint len;
  356. ut_ad(rec_offs_validate(rec, index, offsets));
  357. if (dict_index_is_clust(index)) {
  358. index_type = SYM_CLUST_FIELD_NO;
  359. } else {
  360. index_type = SYM_SEC_FIELD_NO;
  361. }
  362. while (column) {
  363. mem_heap_t* heap = NULL;
  364. ibool needs_copy;
  365. field_no = column->field_nos[index_type];
  366. if (field_no != ULINT_UNDEFINED) {
  367. if (UNIV_UNLIKELY(rec_offs_nth_extern(offsets,
  368. field_no))) {
  369. /* Copy an externally stored field to the
  370. temporary heap, if possible. */
  371. heap = mem_heap_create(1);
  372. data = btr_rec_copy_externally_stored_field(
  373. rec, offsets,
  374. dict_table_zip_size(index->table),
  375. field_no, &len, heap);
  376. /* data == NULL means that the
  377. externally stored field was not
  378. written yet. This record
  379. should only be seen by
  380. recv_recovery_rollback_active() or any
  381. TRX_ISO_READ_UNCOMMITTED
  382. transactions. The InnoDB SQL parser
  383. (the sole caller of this function)
  384. does not implement READ UNCOMMITTED,
  385. and it is not involved during rollback. */
  386. ut_a(data);
  387. ut_a(len != UNIV_SQL_NULL);
  388. needs_copy = TRUE;
  389. } else {
  390. data = rec_get_nth_field(rec, offsets,
  391. field_no, &len);
  392. needs_copy = column->copy_val;
  393. }
  394. if (needs_copy) {
  395. eval_node_copy_and_alloc_val(column, data,
  396. len);
  397. } else {
  398. val = que_node_get_val(column);
  399. dfield_set_data(val, data, len);
  400. }
  401. if (UNIV_LIKELY_NULL(heap)) {
  402. mem_heap_free(heap);
  403. }
  404. }
  405. column = UT_LIST_GET_NEXT(col_var_list, column);
  406. }
  407. }
  408. /*********************************************************************//**
  409. Allocates a prefetch buffer for a column when prefetch is first time done. */
  410. static
  411. void
  412. sel_col_prefetch_buf_alloc(
  413. /*=======================*/
  414. sym_node_t* column) /*!< in: symbol table node for a column */
  415. {
  416. sel_buf_t* sel_buf;
  417. ulint i;
  418. ut_ad(que_node_get_type(column) == QUE_NODE_SYMBOL);
  419. column->prefetch_buf = static_cast<sel_buf_t*>(
  420. mem_alloc(SEL_MAX_N_PREFETCH * sizeof(sel_buf_t)));
  421. for (i = 0; i < SEL_MAX_N_PREFETCH; i++) {
  422. sel_buf = column->prefetch_buf + i;
  423. sel_buf->data = NULL;
  424. sel_buf->len = 0;
  425. sel_buf->val_buf_size = 0;
  426. }
  427. }
  428. /*********************************************************************//**
  429. Frees a prefetch buffer for a column, including the dynamically allocated
  430. memory for data stored there. */
  431. UNIV_INTERN
  432. void
  433. sel_col_prefetch_buf_free(
  434. /*======================*/
  435. sel_buf_t* prefetch_buf) /*!< in, own: prefetch buffer */
  436. {
  437. sel_buf_t* sel_buf;
  438. ulint i;
  439. for (i = 0; i < SEL_MAX_N_PREFETCH; i++) {
  440. sel_buf = prefetch_buf + i;
  441. if (sel_buf->val_buf_size > 0) {
  442. mem_free(sel_buf->data);
  443. }
  444. }
  445. mem_free(prefetch_buf);
  446. }
  447. /*********************************************************************//**
  448. Pops the column values for a prefetched, cached row from the column prefetch
  449. buffers and places them to the val fields in the column nodes. */
  450. static
  451. void
  452. sel_dequeue_prefetched_row(
  453. /*=======================*/
  454. plan_t* plan) /*!< in: plan node for a table */
  455. {
  456. sym_node_t* column;
  457. sel_buf_t* sel_buf;
  458. dfield_t* val;
  459. byte* data;
  460. ulint len;
  461. ulint val_buf_size;
  462. ut_ad(plan->n_rows_prefetched > 0);
  463. column = UT_LIST_GET_FIRST(plan->columns);
  464. while (column) {
  465. val = que_node_get_val(column);
  466. if (!column->copy_val) {
  467. /* We did not really push any value for the
  468. column */
  469. ut_ad(!column->prefetch_buf);
  470. ut_ad(que_node_get_val_buf_size(column) == 0);
  471. ut_d(dfield_set_null(val));
  472. goto next_col;
  473. }
  474. ut_ad(column->prefetch_buf);
  475. ut_ad(!dfield_is_ext(val));
  476. sel_buf = column->prefetch_buf + plan->first_prefetched;
  477. data = sel_buf->data;
  478. len = sel_buf->len;
  479. val_buf_size = sel_buf->val_buf_size;
  480. /* We must keep track of the allocated memory for
  481. column values to be able to free it later: therefore
  482. we swap the values for sel_buf and val */
  483. sel_buf->data = static_cast<byte*>(dfield_get_data(val));
  484. sel_buf->len = dfield_get_len(val);
  485. sel_buf->val_buf_size = que_node_get_val_buf_size(column);
  486. dfield_set_data(val, data, len);
  487. que_node_set_val_buf_size(column, val_buf_size);
  488. next_col:
  489. column = UT_LIST_GET_NEXT(col_var_list, column);
  490. }
  491. plan->n_rows_prefetched--;
  492. plan->first_prefetched++;
  493. }
  494. /*********************************************************************//**
  495. Pushes the column values for a prefetched, cached row to the column prefetch
  496. buffers from the val fields in the column nodes. */
  497. UNIV_INLINE
  498. void
  499. sel_enqueue_prefetched_row(
  500. /*=======================*/
  501. plan_t* plan) /*!< in: plan node for a table */
  502. {
  503. sym_node_t* column;
  504. sel_buf_t* sel_buf;
  505. dfield_t* val;
  506. byte* data;
  507. ulint len;
  508. ulint pos;
  509. ulint val_buf_size;
  510. if (plan->n_rows_prefetched == 0) {
  511. pos = 0;
  512. plan->first_prefetched = 0;
  513. } else {
  514. pos = plan->n_rows_prefetched;
  515. /* We have the convention that pushing new rows starts only
  516. after the prefetch stack has been emptied: */
  517. ut_ad(plan->first_prefetched == 0);
  518. }
  519. plan->n_rows_prefetched++;
  520. ut_ad(pos < SEL_MAX_N_PREFETCH);
  521. for (column = UT_LIST_GET_FIRST(plan->columns);
  522. column != 0;
  523. column = UT_LIST_GET_NEXT(col_var_list, column)) {
  524. if (!column->copy_val) {
  525. /* There is no sense to push pointers to database
  526. page fields when we do not keep latch on the page! */
  527. continue;
  528. }
  529. if (!column->prefetch_buf) {
  530. /* Allocate a new prefetch buffer */
  531. sel_col_prefetch_buf_alloc(column);
  532. }
  533. sel_buf = column->prefetch_buf + pos;
  534. val = que_node_get_val(column);
  535. data = static_cast<byte*>(dfield_get_data(val));
  536. len = dfield_get_len(val);
  537. val_buf_size = que_node_get_val_buf_size(column);
  538. /* We must keep track of the allocated memory for
  539. column values to be able to free it later: therefore
  540. we swap the values for sel_buf and val */
  541. dfield_set_data(val, sel_buf->data, sel_buf->len);
  542. que_node_set_val_buf_size(column, sel_buf->val_buf_size);
  543. sel_buf->data = data;
  544. sel_buf->len = len;
  545. sel_buf->val_buf_size = val_buf_size;
  546. }
  547. }
  548. /*********************************************************************//**
  549. Builds a previous version of a clustered index record for a consistent read
  550. @return DB_SUCCESS or error code */
  551. static __attribute__((nonnull, warn_unused_result))
  552. dberr_t
  553. row_sel_build_prev_vers(
  554. /*====================*/
  555. read_view_t* read_view, /*!< in: read view */
  556. dict_index_t* index, /*!< in: plan node for table */
  557. rec_t* rec, /*!< in: record in a clustered index */
  558. ulint** offsets, /*!< in/out: offsets returned by
  559. rec_get_offsets(rec, plan->index) */
  560. mem_heap_t** offset_heap, /*!< in/out: memory heap from which
  561. the offsets are allocated */
  562. mem_heap_t** old_vers_heap, /*!< out: old version heap to use */
  563. rec_t** old_vers, /*!< out: old version, or NULL if the
  564. record does not exist in the view:
  565. i.e., it was freshly inserted
  566. afterwards */
  567. mtr_t* mtr) /*!< in: mtr */
  568. {
  569. dberr_t err;
  570. if (*old_vers_heap) {
  571. mem_heap_empty(*old_vers_heap);
  572. } else {
  573. *old_vers_heap = mem_heap_create(512);
  574. }
  575. err = row_vers_build_for_consistent_read(
  576. rec, mtr, index, offsets, read_view, offset_heap,
  577. *old_vers_heap, old_vers);
  578. return(err);
  579. }
  580. /*********************************************************************//**
  581. Builds the last committed version of a clustered index record for a
  582. semi-consistent read. */
  583. static __attribute__((nonnull))
  584. void
  585. row_sel_build_committed_vers_for_mysql(
  586. /*===================================*/
  587. dict_index_t* clust_index, /*!< in: clustered index */
  588. row_prebuilt_t* prebuilt, /*!< in: prebuilt struct */
  589. const rec_t* rec, /*!< in: record in a clustered index */
  590. ulint** offsets, /*!< in/out: offsets returned by
  591. rec_get_offsets(rec, clust_index) */
  592. mem_heap_t** offset_heap, /*!< in/out: memory heap from which
  593. the offsets are allocated */
  594. const rec_t** old_vers, /*!< out: old version, or NULL if the
  595. record does not exist in the view:
  596. i.e., it was freshly inserted
  597. afterwards */
  598. mtr_t* mtr) /*!< in: mtr */
  599. {
  600. if (prebuilt->old_vers_heap) {
  601. mem_heap_empty(prebuilt->old_vers_heap);
  602. } else {
  603. prebuilt->old_vers_heap = mem_heap_create(
  604. rec_offs_size(*offsets));
  605. }
  606. row_vers_build_for_semi_consistent_read(
  607. rec, mtr, clust_index, offsets, offset_heap,
  608. prebuilt->old_vers_heap, old_vers);
  609. }
  610. /*********************************************************************//**
  611. Tests the conditions which determine when the index segment we are searching
  612. through has been exhausted.
  613. @return TRUE if row passed the tests */
  614. UNIV_INLINE
  615. ibool
  616. row_sel_test_end_conds(
  617. /*===================*/
  618. plan_t* plan) /*!< in: plan for the table; the column values must
  619. already have been retrieved and the right sides of
  620. comparisons evaluated */
  621. {
  622. func_node_t* cond;
  623. /* All conditions in end_conds are comparisons of a column to an
  624. expression */
  625. for (cond = UT_LIST_GET_FIRST(plan->end_conds);
  626. cond != 0;
  627. cond = UT_LIST_GET_NEXT(cond_list, cond)) {
  628. /* Evaluate the left side of the comparison, i.e., get the
  629. column value if there is an indirection */
  630. eval_sym(static_cast<sym_node_t*>(cond->args));
  631. /* Do the comparison */
  632. if (!eval_cmp(cond)) {
  633. return(FALSE);
  634. }
  635. }
  636. return(TRUE);
  637. }
  638. /*********************************************************************//**
  639. Tests the other conditions.
  640. @return TRUE if row passed the tests */
  641. UNIV_INLINE
  642. ibool
  643. row_sel_test_other_conds(
  644. /*=====================*/
  645. plan_t* plan) /*!< in: plan for the table; the column values must
  646. already have been retrieved */
  647. {
  648. func_node_t* cond;
  649. cond = UT_LIST_GET_FIRST(plan->other_conds);
  650. while (cond) {
  651. eval_exp(cond);
  652. if (!eval_node_get_ibool_val(cond)) {
  653. return(FALSE);
  654. }
  655. cond = UT_LIST_GET_NEXT(cond_list, cond);
  656. }
  657. return(TRUE);
  658. }
  659. /*********************************************************************//**
  660. Retrieves the clustered index record corresponding to a record in a
  661. non-clustered index. Does the necessary locking.
  662. @return DB_SUCCESS or error code */
  663. static __attribute__((nonnull, warn_unused_result))
  664. dberr_t
  665. row_sel_get_clust_rec(
  666. /*==================*/
  667. sel_node_t* node, /*!< in: select_node */
  668. plan_t* plan, /*!< in: plan node for table */
  669. rec_t* rec, /*!< in: record in a non-clustered index */
  670. que_thr_t* thr, /*!< in: query thread */
  671. rec_t** out_rec,/*!< out: clustered record or an old version of
  672. it, NULL if the old version did not exist
  673. in the read view, i.e., it was a fresh
  674. inserted version */
  675. mtr_t* mtr) /*!< in: mtr used to get access to the
  676. non-clustered record; the same mtr is used to
  677. access the clustered index */
  678. {
  679. dict_index_t* index;
  680. rec_t* clust_rec;
  681. rec_t* old_vers;
  682. dberr_t err;
  683. mem_heap_t* heap = NULL;
  684. ulint offsets_[REC_OFFS_NORMAL_SIZE];
  685. ulint* offsets = offsets_;
  686. rec_offs_init(offsets_);
  687. *out_rec = NULL;
  688. offsets = rec_get_offsets(rec,
  689. btr_pcur_get_btr_cur(&plan->pcur)->index,
  690. offsets, ULINT_UNDEFINED, &heap);
  691. row_build_row_ref_fast(plan->clust_ref, plan->clust_map, rec, offsets);
  692. index = dict_table_get_first_index(plan->table);
  693. btr_pcur_open_with_no_init(index, plan->clust_ref, PAGE_CUR_LE,
  694. BTR_SEARCH_LEAF, &plan->clust_pcur,
  695. 0, mtr);
  696. clust_rec = btr_pcur_get_rec(&(plan->clust_pcur));
  697. /* Note: only if the search ends up on a non-infimum record is the
  698. low_match value the real match to the search tuple */
  699. if (!page_rec_is_user_rec(clust_rec)
  700. || btr_pcur_get_low_match(&(plan->clust_pcur))
  701. < dict_index_get_n_unique(index)) {
  702. ut_a(rec_get_deleted_flag(rec,
  703. dict_table_is_comp(plan->table)));
  704. ut_a(node->read_view);
  705. /* In a rare case it is possible that no clust rec is found
  706. for a delete-marked secondary index record: if in row0umod.cc
  707. in row_undo_mod_remove_clust_low() we have already removed
  708. the clust rec, while purge is still cleaning and removing
  709. secondary index records associated with earlier versions of
  710. the clustered index record. In that case we know that the
  711. clustered index record did not exist in the read view of
  712. trx. */
  713. goto func_exit;
  714. }
  715. offsets = rec_get_offsets(clust_rec, index, offsets,
  716. ULINT_UNDEFINED, &heap);
  717. if (!node->read_view) {
  718. /* Try to place a lock on the index record */
  719. ulint lock_type;
  720. trx_t* trx;
  721. trx = thr_get_trx(thr);
  722. /* If innodb_locks_unsafe_for_binlog option is used
  723. or this session is using READ COMMITTED or lower isolation level
  724. we lock only the record, i.e., next-key locking is
  725. not used. */
  726. if (srv_locks_unsafe_for_binlog
  727. || trx->isolation_level <= TRX_ISO_READ_COMMITTED) {
  728. lock_type = LOCK_REC_NOT_GAP;
  729. } else {
  730. lock_type = LOCK_ORDINARY;
  731. }
  732. err = lock_clust_rec_read_check_and_lock(
  733. 0, btr_pcur_get_block(&plan->clust_pcur),
  734. clust_rec, index, offsets,
  735. static_cast<enum lock_mode>(node->row_lock_mode),
  736. lock_type,
  737. thr);
  738. switch (err) {
  739. case DB_SUCCESS:
  740. case DB_SUCCESS_LOCKED_REC:
  741. /* Declare the variable uninitialized in Valgrind.
  742. It should be set to DB_SUCCESS at func_exit. */
  743. UNIV_MEM_INVALID(&err, sizeof err);
  744. break;
  745. default:
  746. goto err_exit;
  747. }
  748. } else {
  749. /* This is a non-locking consistent read: if necessary, fetch
  750. a previous version of the record */
  751. old_vers = NULL;
  752. if (!lock_clust_rec_cons_read_sees(clust_rec, index, offsets,
  753. node->read_view)) {
  754. err = row_sel_build_prev_vers(
  755. node->read_view, index, clust_rec,
  756. &offsets, &heap, &plan->old_vers_heap,
  757. &old_vers, mtr);
  758. if (err != DB_SUCCESS) {
  759. goto err_exit;
  760. }
  761. clust_rec = old_vers;
  762. if (clust_rec == NULL) {
  763. goto func_exit;
  764. }
  765. }
  766. /* If we had to go to an earlier version of row or the
  767. secondary index record is delete marked, then it may be that
  768. the secondary index record corresponding to clust_rec
  769. (or old_vers) is not rec; in that case we must ignore
  770. such row because in our snapshot rec would not have existed.
  771. Remember that from rec we cannot see directly which transaction
  772. id corresponds to it: we have to go to the clustered index
  773. record. A query where we want to fetch all rows where
  774. the secondary index value is in some interval would return
  775. a wrong result if we would not drop rows which we come to
  776. visit through secondary index records that would not really
  777. exist in our snapshot. */
  778. if ((old_vers
  779. || rec_get_deleted_flag(rec, dict_table_is_comp(
  780. plan->table)))
  781. && !row_sel_sec_rec_is_for_clust_rec(rec, plan->index,
  782. clust_rec, index)) {
  783. goto func_exit;
  784. }
  785. }
  786. /* Fetch the columns needed in test conditions. The clustered
  787. index record is protected by a page latch that was acquired
  788. when plan->clust_pcur was positioned. The latch will not be
  789. released until mtr_commit(mtr). */
  790. ut_ad(!rec_get_deleted_flag(clust_rec, rec_offs_comp(offsets)));
  791. row_sel_fetch_columns(index, clust_rec, offsets,
  792. UT_LIST_GET_FIRST(plan->columns));
  793. *out_rec = clust_rec;
  794. func_exit:
  795. err = DB_SUCCESS;
  796. err_exit:
  797. if (UNIV_LIKELY_NULL(heap)) {
  798. mem_heap_free(heap);
  799. }
  800. return(err);
  801. }
  802. /*********************************************************************//**
  803. Sets a lock on a record.
  804. @return DB_SUCCESS, DB_SUCCESS_LOCKED_REC, or error code */
  805. UNIV_INLINE
  806. dberr_t
  807. sel_set_rec_lock(
  808. /*=============*/
  809. const buf_block_t* block, /*!< in: buffer block of rec */
  810. const rec_t* rec, /*!< in: record */
  811. dict_index_t* index, /*!< in: index */
  812. const ulint* offsets,/*!< in: rec_get_offsets(rec, index) */
  813. ulint mode, /*!< in: lock mode */
  814. ulint type, /*!< in: LOCK_ORDINARY, LOCK_GAP, or
  815. LOC_REC_NOT_GAP */
  816. que_thr_t* thr) /*!< in: query thread */
  817. {
  818. trx_t* trx;
  819. dberr_t err;
  820. trx = thr_get_trx(thr);
  821. if (UT_LIST_GET_LEN(trx->lock.trx_locks) > 10000) {
  822. if (buf_LRU_buf_pool_running_out()) {
  823. return(DB_LOCK_TABLE_FULL);
  824. }
  825. }
  826. if (dict_index_is_clust(index)) {
  827. err = lock_clust_rec_read_check_and_lock(
  828. 0, block, rec, index, offsets,
  829. static_cast<enum lock_mode>(mode), type, thr);
  830. } else {
  831. err = lock_sec_rec_read_check_and_lock(
  832. 0, block, rec, index, offsets,
  833. static_cast<enum lock_mode>(mode), type, thr);
  834. }
  835. return(err);
  836. }
  837. /*********************************************************************//**
  838. Opens a pcur to a table index. */
  839. static
  840. void
  841. row_sel_open_pcur(
  842. /*==============*/
  843. plan_t* plan, /*!< in: table plan */
  844. ibool search_latch_locked,
  845. /*!< in: TRUE if the thread currently
  846. has the search latch locked in
  847. s-mode */
  848. mtr_t* mtr) /*!< in: mtr */
  849. {
  850. dict_index_t* index;
  851. func_node_t* cond;
  852. que_node_t* exp;
  853. ulint n_fields;
  854. ulint has_search_latch = 0; /* RW_S_LATCH or 0 */
  855. ulint i;
  856. if (search_latch_locked) {
  857. has_search_latch = RW_S_LATCH;
  858. }
  859. index = plan->index;
  860. /* Calculate the value of the search tuple: the exact match columns
  861. get their expressions evaluated when we evaluate the right sides of
  862. end_conds */
  863. cond = UT_LIST_GET_FIRST(plan->end_conds);
  864. while (cond) {
  865. eval_exp(que_node_get_next(cond->args));
  866. cond = UT_LIST_GET_NEXT(cond_list, cond);
  867. }
  868. if (plan->tuple) {
  869. n_fields = dtuple_get_n_fields(plan->tuple);
  870. if (plan->n_exact_match < n_fields) {
  871. /* There is a non-exact match field which must be
  872. evaluated separately */
  873. eval_exp(plan->tuple_exps[n_fields - 1]);
  874. }
  875. for (i = 0; i < n_fields; i++) {
  876. exp = plan->tuple_exps[i];
  877. dfield_copy_data(dtuple_get_nth_field(plan->tuple, i),
  878. que_node_get_val(exp));
  879. }
  880. /* Open pcur to the index */
  881. btr_pcur_open_with_no_init(index, plan->tuple, plan->mode,
  882. BTR_SEARCH_LEAF, &plan->pcur,
  883. has_search_latch, mtr);
  884. } else {
  885. /* Open the cursor to the start or the end of the index
  886. (FALSE: no init) */
  887. btr_pcur_open_at_index_side(plan->asc, index, BTR_SEARCH_LEAF,
  888. &(plan->pcur), false, 0, mtr);
  889. }
  890. ut_ad(plan->n_rows_prefetched == 0);
  891. ut_ad(plan->n_rows_fetched == 0);
  892. ut_ad(plan->cursor_at_end == FALSE);
  893. plan->pcur_is_open = TRUE;
  894. }
  895. /*********************************************************************//**
  896. Restores a stored pcur position to a table index.
  897. @return TRUE if the cursor should be moved to the next record after we
  898. return from this function (moved to the previous, in the case of a
  899. descending cursor) without processing again the current cursor
  900. record */
  901. static
  902. ibool
  903. row_sel_restore_pcur_pos(
  904. /*=====================*/
  905. plan_t* plan, /*!< in: table plan */
  906. mtr_t* mtr) /*!< in: mtr */
  907. {
  908. ibool equal_position;
  909. ulint relative_position;
  910. ut_ad(!plan->cursor_at_end);
  911. relative_position = btr_pcur_get_rel_pos(&(plan->pcur));
  912. equal_position = btr_pcur_restore_position(BTR_SEARCH_LEAF,
  913. &(plan->pcur), mtr);
  914. /* If the cursor is traveling upwards, and relative_position is
  915. (1) BTR_PCUR_BEFORE: this is not allowed, as we did not have a lock
  916. yet on the successor of the page infimum;
  917. (2) BTR_PCUR_AFTER: btr_pcur_restore_position placed the cursor on the
  918. first record GREATER than the predecessor of a page supremum; we have
  919. not yet processed the cursor record: no need to move the cursor to the
  920. next record;
  921. (3) BTR_PCUR_ON: btr_pcur_restore_position placed the cursor on the
  922. last record LESS or EQUAL to the old stored user record; (a) if
  923. equal_position is FALSE, this means that the cursor is now on a record
  924. less than the old user record, and we must move to the next record;
  925. (b) if equal_position is TRUE, then if
  926. plan->stored_cursor_rec_processed is TRUE, we must move to the next
  927. record, else there is no need to move the cursor. */
  928. if (plan->asc) {
  929. if (relative_position == BTR_PCUR_ON) {
  930. if (equal_position) {
  931. return(plan->stored_cursor_rec_processed);
  932. }
  933. return(TRUE);
  934. }
  935. ut_ad(relative_position == BTR_PCUR_AFTER
  936. || relative_position == BTR_PCUR_AFTER_LAST_IN_TREE);
  937. return(FALSE);
  938. }
  939. /* If the cursor is traveling downwards, and relative_position is
  940. (1) BTR_PCUR_BEFORE: btr_pcur_restore_position placed the cursor on
  941. the last record LESS than the successor of a page infimum; we have not
  942. processed the cursor record: no need to move the cursor;
  943. (2) BTR_PCUR_AFTER: btr_pcur_restore_position placed the cursor on the
  944. first record GREATER than the predecessor of a page supremum; we have
  945. processed the cursor record: we should move the cursor to the previous
  946. record;
  947. (3) BTR_PCUR_ON: btr_pcur_restore_position placed the cursor on the
  948. last record LESS or EQUAL to the old stored user record; (a) if
  949. equal_position is FALSE, this means that the cursor is now on a record
  950. less than the old user record, and we need not move to the previous
  951. record; (b) if equal_position is TRUE, then if
  952. plan->stored_cursor_rec_processed is TRUE, we must move to the previous
  953. record, else there is no need to move the cursor. */
  954. if (relative_position == BTR_PCUR_BEFORE
  955. || relative_position == BTR_PCUR_BEFORE_FIRST_IN_TREE) {
  956. return(FALSE);
  957. }
  958. if (relative_position == BTR_PCUR_ON) {
  959. if (equal_position) {
  960. return(plan->stored_cursor_rec_processed);
  961. }
  962. return(FALSE);
  963. }
  964. ut_ad(relative_position == BTR_PCUR_AFTER
  965. || relative_position == BTR_PCUR_AFTER_LAST_IN_TREE);
  966. return(TRUE);
  967. }
  968. /*********************************************************************//**
  969. Resets a plan cursor to a closed state. */
  970. UNIV_INLINE
  971. void
  972. plan_reset_cursor(
  973. /*==============*/
  974. plan_t* plan) /*!< in: plan */
  975. {
  976. plan->pcur_is_open = FALSE;
  977. plan->cursor_at_end = FALSE;
  978. plan->n_rows_fetched = 0;
  979. plan->n_rows_prefetched = 0;
  980. }
  981. /*********************************************************************//**
  982. Tries to do a shortcut to fetch a clustered index record with a unique key,
  983. using the hash index if possible (not always).
  984. @return SEL_FOUND, SEL_EXHAUSTED, SEL_RETRY */
  985. static
  986. ulint
  987. row_sel_try_search_shortcut(
  988. /*========================*/
  989. sel_node_t* node, /*!< in: select node for a consistent read */
  990. plan_t* plan, /*!< in: plan for a unique search in clustered
  991. index */
  992. ibool search_latch_locked,
  993. /*!< in: whether the search holds
  994. btr_search_latch */
  995. mtr_t* mtr) /*!< in: mtr */
  996. {
  997. dict_index_t* index;
  998. rec_t* rec;
  999. mem_heap_t* heap = NULL;
  1000. ulint offsets_[REC_OFFS_NORMAL_SIZE];
  1001. ulint* offsets = offsets_;
  1002. ulint ret;
  1003. rec_offs_init(offsets_);
  1004. index = plan->index;
  1005. ut_ad(node->read_view);
  1006. ut_ad(plan->unique_search);
  1007. ut_ad(!plan->must_get_clust);
  1008. #ifdef UNIV_SYNC_DEBUG
  1009. if (search_latch_locked) {
  1010. ut_ad(rw_lock_own(btr_search_get_latch(index),
  1011. RW_LOCK_SHARED));
  1012. }
  1013. #endif /* UNIV_SYNC_DEBUG */
  1014. row_sel_open_pcur(plan, search_latch_locked, mtr);
  1015. rec = btr_pcur_get_rec(&(plan->pcur));
  1016. if (!page_rec_is_user_rec(rec)) {
  1017. return(SEL_RETRY);
  1018. }
  1019. ut_ad(plan->mode == PAGE_CUR_GE);
  1020. /* As the cursor is now placed on a user record after a search with
  1021. the mode PAGE_CUR_GE, the up_match field in the cursor tells how many
  1022. fields in the user record matched to the search tuple */
  1023. if (btr_pcur_get_up_match(&(plan->pcur)) < plan->n_exact_match) {
  1024. return(SEL_EXHAUSTED);
  1025. }
  1026. /* This is a non-locking consistent read: if necessary, fetch
  1027. a previous version of the record */
  1028. offsets = rec_get_offsets(rec, index, offsets, ULINT_UNDEFINED, &heap);
  1029. if (dict_index_is_clust(index)) {
  1030. if (!lock_clust_rec_cons_read_sees(rec, index, offsets,
  1031. node->read_view)) {
  1032. ret = SEL_RETRY;
  1033. goto func_exit;
  1034. }
  1035. } else if (!lock_sec_rec_cons_read_sees(rec, node->read_view)) {
  1036. ret = SEL_RETRY;
  1037. goto func_exit;
  1038. }
  1039. /* Test the deleted flag. */
  1040. if (rec_get_deleted_flag(rec, dict_table_is_comp(plan->table))) {
  1041. ret = SEL_EXHAUSTED;
  1042. goto func_exit;
  1043. }
  1044. /* Fetch the columns needed in test conditions. The index
  1045. record is protected by a page latch that was acquired when
  1046. plan->pcur was positioned. The latch will not be released
  1047. until mtr_commit(mtr). */
  1048. row_sel_fetch_columns(index, rec, offsets,
  1049. UT_LIST_GET_FIRST(plan->columns));
  1050. /* Test the rest of search conditions */
  1051. if (!row_sel_test_other_conds(plan)) {
  1052. ret = SEL_EXHAUSTED;
  1053. goto func_exit;
  1054. }
  1055. ut_ad(plan->pcur.latch_mode == BTR_SEARCH_LEAF);
  1056. plan->n_rows_fetched++;
  1057. ret = SEL_FOUND;
  1058. func_exit:
  1059. if (UNIV_LIKELY_NULL(heap)) {
  1060. mem_heap_free(heap);
  1061. }
  1062. return(ret);
  1063. }
  1064. /*********************************************************************//**
  1065. Performs a select step.
  1066. @return DB_SUCCESS or error code */
  1067. static __attribute__((nonnull, warn_unused_result))
  1068. dberr_t
  1069. row_sel(
  1070. /*====*/
  1071. sel_node_t* node, /*!< in: select node */
  1072. que_thr_t* thr) /*!< in: query thread */
  1073. {
  1074. dict_index_t* index;
  1075. plan_t* plan;
  1076. mtr_t mtr;
  1077. ibool moved;
  1078. rec_t* rec;
  1079. rec_t* old_vers;
  1080. rec_t* clust_rec;
  1081. ibool search_latch_locked;
  1082. ibool consistent_read;
  1083. /* The following flag becomes TRUE when we are doing a
  1084. consistent read from a non-clustered index and we must look
  1085. at the clustered index to find out the previous delete mark
  1086. state of the non-clustered record: */
  1087. ibool cons_read_requires_clust_rec = FALSE;
  1088. ulint cost_counter = 0;
  1089. ibool cursor_just_opened;
  1090. ibool must_go_to_next;
  1091. ibool mtr_has_extra_clust_latch = FALSE;
  1092. /* TRUE if the search was made using
  1093. a non-clustered index, and we had to
  1094. access the clustered record: now &mtr
  1095. contains a clustered index latch, and
  1096. &mtr must be committed before we move
  1097. to the next non-clustered record */
  1098. ulint found_flag;
  1099. dberr_t err;
  1100. mem_heap_t* heap = NULL;
  1101. ulint offsets_[REC_OFFS_NORMAL_SIZE];
  1102. ulint* offsets = offsets_;
  1103. rec_offs_init(offsets_);
  1104. ut_ad(thr->run_node == node);
  1105. search_latch_locked = FALSE;
  1106. if (node->read_view) {
  1107. /* In consistent reads, we try to do with the hash index and
  1108. not to use the buffer page get. This is to reduce memory bus
  1109. load resulting from semaphore operations. The search latch
  1110. will be s-locked when we access an index with a unique search
  1111. condition, but not locked when we access an index with a
  1112. less selective search condition. */
  1113. consistent_read = TRUE;
  1114. } else {
  1115. consistent_read = FALSE;
  1116. }
  1117. table_loop:
  1118. /* TABLE LOOP
  1119. ----------
  1120. This is the outer major loop in calculating a join. We come here when
  1121. node->fetch_table changes, and after adding a row to aggregate totals
  1122. and, of course, when this function is called. */
  1123. ut_ad(mtr_has_extra_clust_latch == FALSE);
  1124. plan = sel_node_get_nth_plan(node, node->fetch_table);
  1125. index = plan->index;
  1126. if (plan->n_rows_prefetched > 0) {
  1127. sel_dequeue_prefetched_row(plan);
  1128. goto next_table_no_mtr;
  1129. }
  1130. if (plan->cursor_at_end) {
  1131. /* The cursor has already reached the result set end: no more
  1132. rows to process for this table cursor, as also the prefetch
  1133. stack was empty */
  1134. ut_ad(plan->pcur_is_open);
  1135. goto table_exhausted_no_mtr;
  1136. }
  1137. /* Open a cursor to index, or restore an open cursor position */
  1138. mtr_start(&mtr);
  1139. if (consistent_read && plan->unique_search && !plan->pcur_is_open
  1140. && !plan->must_get_clust
  1141. && !plan->table->big_rows) {
  1142. if (!search_latch_locked) {
  1143. rw_lock_s_lock(btr_search_get_latch(index));
  1144. search_latch_locked = TRUE;
  1145. } else if (rw_lock_get_writer(btr_search_get_latch(index))
  1146. == RW_LOCK_WAIT_EX) {
  1147. /* There is an x-latch request waiting: release the
  1148. s-latch for a moment; as an s-latch here is often
  1149. kept for some 10 searches before being released,
  1150. a waiting x-latch request would block other threads
  1151. from acquiring an s-latch for a long time, lowering
  1152. performance significantly in multiprocessors. */
  1153. rw_lock_s_unlock(btr_search_get_latch(index));
  1154. rw_lock_s_lock(btr_search_get_latch(index));
  1155. }
  1156. found_flag = row_sel_try_search_shortcut(node, plan,
  1157. search_latch_locked,
  1158. &mtr);
  1159. if (found_flag == SEL_FOUND) {
  1160. goto next_table;
  1161. } else if (found_flag == SEL_EXHAUSTED) {
  1162. goto table_exhausted;
  1163. }
  1164. ut_ad(found_flag == SEL_RETRY);
  1165. plan_reset_cursor(plan);
  1166. mtr_commit(&mtr);
  1167. mtr_start(&mtr);
  1168. }
  1169. if (search_latch_locked) {
  1170. rw_lock_s_unlock(btr_search_get_latch(index));
  1171. search_latch_locked = FALSE;
  1172. }
  1173. if (!plan->pcur_is_open) {
  1174. /* Evaluate the expressions to build the search tuple and
  1175. open the cursor */
  1176. row_sel_open_pcur(plan, search_latch_locked, &mtr);
  1177. cursor_just_opened = TRUE;
  1178. /* A new search was made: increment the cost counter */
  1179. cost_counter++;
  1180. } else {
  1181. /* Restore pcur position to the index */
  1182. must_go_to_next = row_sel_restore_pcur_pos(plan, &mtr);
  1183. cursor_just_opened = FALSE;
  1184. if (must_go_to_next) {
  1185. /* We have already processed the cursor record: move
  1186. to the next */
  1187. goto next_rec;
  1188. }
  1189. }
  1190. rec_loop:
  1191. /* RECORD LOOP
  1192. -----------
  1193. In this loop we use pcur and try to fetch a qualifying row, and
  1194. also fill the prefetch buffer for this table if n_rows_fetched has
  1195. exceeded a threshold. While we are inside this loop, the following
  1196. holds:
  1197. (1) &mtr is started,
  1198. (2) pcur is positioned and open.
  1199. NOTE that if cursor_just_opened is TRUE here, it means that we came
  1200. to this point right after row_sel_open_pcur. */
  1201. ut_ad(mtr_has_extra_clust_latch == FALSE);
  1202. rec = btr_pcur_get_rec(&(plan->pcur));
  1203. /* PHASE 1: Set a lock if specified */
  1204. if (!node->asc && cursor_just_opened
  1205. && !page_rec_is_supremum(rec)) {
  1206. /* When we open a cursor for a descending search, we must set
  1207. a next-key lock on the successor record: otherwise it would
  1208. be possible to insert new records next to the cursor position,
  1209. and it might be that these new records should appear in the
  1210. search result set, resulting in the phantom problem. */
  1211. if (!consistent_read) {
  1212. rec_t* next_rec = page_rec_get_next(rec);
  1213. ulint lock_type;
  1214. trx_t* trx;
  1215. trx = thr_get_trx(thr);
  1216. offsets = rec_get_offsets(next_rec, index, offsets,
  1217. ULINT_UNDEFINED, &heap);
  1218. /* If innodb_locks_unsafe_for_binlog option is used
  1219. or this session is using READ COMMITTED or lower isolation
  1220. level, we lock only the record, i.e., next-key
  1221. locking is not used. */
  1222. if (srv_locks_unsafe_for_binlog
  1223. || trx->isolation_level
  1224. <= TRX_ISO_READ_COMMITTED) {
  1225. if (page_rec_is_supremum(next_rec)) {
  1226. goto skip_lock;
  1227. }
  1228. lock_type = LOCK_REC_NOT_GAP;
  1229. } else {
  1230. lock_type = LOCK_ORDINARY;
  1231. }
  1232. err = sel_set_rec_lock(btr_pcur_get_block(&plan->pcur),
  1233. next_rec, index, offsets,
  1234. node->row_lock_mode,
  1235. lock_type, thr);
  1236. switch (err) {
  1237. case DB_SUCCESS_LOCKED_REC:
  1238. err = DB_SUCCESS;
  1239. case DB_SUCCESS:
  1240. break;
  1241. default:
  1242. /* Note that in this case we will store in pcur
  1243. the PREDECESSOR of the record we are waiting
  1244. the lock for */
  1245. goto lock_wait_or_error;
  1246. }
  1247. }
  1248. }
  1249. skip_lock:
  1250. if (page_rec_is_infimum(rec)) {
  1251. /* The infimum record on a page cannot be in the result set,
  1252. and neither can a record lock be placed on it: we skip such
  1253. a record. We also increment the cost counter as we may have
  1254. processed yet another page of index. */
  1255. cost_counter++;
  1256. goto next_rec;
  1257. }
  1258. if (!consistent_read) {
  1259. /* Try to place a lock on the index record */
  1260. ulint lock_type;
  1261. trx_t* trx;
  1262. offsets = rec_get_offsets(rec, index, offsets,
  1263. ULINT_UNDEFINED, &heap);
  1264. trx = thr_get_trx(thr);
  1265. /* If innodb_locks_unsafe_for_binlog option is used
  1266. or this session is using READ COMMITTED or lower isolation level,
  1267. we lock only the record, i.e., next-key locking is
  1268. not used. */
  1269. if (srv_locks_unsafe_for_binlog
  1270. || trx->isolation_level <= TRX_ISO_READ_COMMITTED) {
  1271. if (page_rec_is_supremum(rec)) {
  1272. goto next_rec;
  1273. }
  1274. lock_type = LOCK_REC_NOT_GAP;
  1275. } else {
  1276. lock_type = LOCK_ORDINARY;
  1277. }
  1278. err = sel_set_rec_lock(btr_pcur_get_block(&plan->pcur),
  1279. rec, index, offsets,
  1280. node->row_lock_mode, lock_type, thr);
  1281. switch (err) {
  1282. case DB_SUCCESS_LOCKED_REC:
  1283. err = DB_SUCCESS;
  1284. case DB_SUCCESS:
  1285. break;
  1286. default:
  1287. goto lock_wait_or_error;
  1288. }
  1289. }
  1290. if (page_rec_is_supremum(rec)) {
  1291. /* A page supremum record cannot be in the result set: skip
  1292. it now when we have placed a possible lock on it */
  1293. goto next_rec;
  1294. }
  1295. ut_ad(page_rec_is_user_rec(rec));
  1296. if (cost_counter > SEL_COST_LIMIT) {
  1297. /* Now that we have placed the necessary locks, we can stop
  1298. for a while and store the cursor position; NOTE that if we
  1299. would store the cursor position BEFORE placing a record lock,
  1300. it might happen that the cursor would jump over some records
  1301. that another transaction could meanwhile insert adjacent to
  1302. the cursor: this would result in the phantom problem. */
  1303. goto stop_for_a_while;
  1304. }
  1305. /* PHASE 2: Check a mixed index mix id if needed */
  1306. if (plan->unique_search && cursor_just_opened) {
  1307. ut_ad(plan->mode == PAGE_CUR_GE);
  1308. /* As the cursor is now placed on a user record after a search
  1309. with the mode PAGE_CUR_GE, the up_match field in the cursor
  1310. tells how many fields in the user record matched to the search
  1311. tuple */
  1312. if (btr_pcur_get_up_match(&(plan->pcur))
  1313. < plan->n_exact_match) {
  1314. goto table_exhausted;
  1315. }
  1316. /* Ok, no need to test end_conds or mix id */
  1317. }
  1318. /* We are ready to look at a possible new index entry in the result
  1319. set: the cursor is now placed on a user record */
  1320. /* PHASE 3: Get previous version in a consistent read */
  1321. cons_read_requires_clust_rec = FALSE;
  1322. offsets = rec_get_offsets(rec, index, offsets, ULINT_UNDEFINED, &heap);
  1323. if (consistent_read) {
  1324. /* This is a non-locking consistent read: if necessary, fetch
  1325. a previous version of the record */
  1326. if (dict_index_is_clust(index)) {
  1327. if (!lock_clust_rec_cons_read_sees(rec, index, offsets,
  1328. node->read_view)) {
  1329. err = row_sel_build_prev_vers(
  1330. node->read_view, index, rec,
  1331. &offsets, &heap, &plan->old_vers_heap,
  1332. &old_vers, &mtr);
  1333. if (err != DB_SUCCESS) {
  1334. goto lock_wait_or_error;
  1335. }
  1336. if (old_vers == NULL) {
  1337. /* The record does not exist
  1338. in our read view. Skip it, but
  1339. first attempt to determine
  1340. whether the index segment we
  1341. are searching through has been
  1342. exhausted. */
  1343. offsets = rec_get_offsets(
  1344. rec, index, offsets,
  1345. ULINT_UNDEFINED, &heap);
  1346. /* Fetch the columns needed in
  1347. test conditions. The clustered
  1348. index record is protected by a
  1349. page latch that was acquired
  1350. by row_sel_open_pcur() or
  1351. row_sel_restore_pcur_pos().
  1352. The latch will not be released
  1353. until mtr_commit(mtr). */
  1354. row_sel_fetch_columns(
  1355. index, rec, offsets,
  1356. UT_LIST_GET_FIRST(
  1357. plan->columns));
  1358. if (!row_sel_test_end_conds(plan)) {
  1359. goto table_exhausted;
  1360. }
  1361. goto next_rec;
  1362. }
  1363. rec = old_vers;
  1364. }
  1365. } else if (!lock_sec_rec_cons_read_sees(rec,
  1366. node->read_view)) {
  1367. cons_read_requires_clust_rec = TRUE;
  1368. }
  1369. }
  1370. /* PHASE 4: Test search end conditions and deleted flag */
  1371. /* Fetch the columns needed in test conditions. The record is
  1372. protected by a page latch that was acquired by
  1373. row_sel_open_pcur() or row_sel_restore_pcur_pos(). The latch
  1374. will not be released until mtr_commit(mtr). */
  1375. row_sel_fetch_columns(index, rec, offsets,
  1376. UT_LIST_GET_FIRST(plan->columns));
  1377. /* Test the selection end conditions: these can only contain columns
  1378. which already are found in the index, even though the index might be
  1379. non-clustered */
  1380. if (plan->unique_search && cursor_just_opened) {
  1381. /* No test necessary: the test was already made above */
  1382. } else if (!row_sel_test_end_conds(plan)) {
  1383. goto table_exhausted;
  1384. }
  1385. if (rec_get_deleted_flag(rec, dict_table_is_comp(plan->table))
  1386. && !cons_read_requires_clust_rec) {
  1387. /* The record is delete marked: we can skip it if this is
  1388. not a consistent read which might see an earlier version
  1389. of a non-clustered index record */
  1390. if (plan->unique_search) {
  1391. goto table_exhausted;
  1392. }
  1393. goto next_rec;
  1394. }
  1395. /* PHASE 5: Get the clustered index record, if needed and if we did
  1396. not do the search using the clustered index */
  1397. if (plan->must_get_clust || cons_read_requires_clust_rec) {
  1398. /* It was a non-clustered index and we must fetch also the
  1399. clustered index record */
  1400. err = row_sel_get_clust_rec(node, plan, rec, thr, &clust_rec,
  1401. &mtr);
  1402. mtr_has_extra_clust_latch = TRUE;
  1403. if (err != DB_SUCCESS) {
  1404. goto lock_wait_or_error;
  1405. }
  1406. /* Retrieving the clustered record required a search:
  1407. increment the cost counter */
  1408. cost_counter++;
  1409. if (clust_rec == NULL) {
  1410. /* The record did not exist in the read view */
  1411. ut_ad(consistent_read);
  1412. goto next_rec;
  1413. }
  1414. if (rec_get_deleted_flag(clust_rec,
  1415. dict_table_is_comp(plan->table))) {
  1416. /* The record is delete marked: we can skip it */
  1417. goto next_rec;
  1418. }
  1419. if (node->can_get_updated) {
  1420. btr_pcur_store_position(&(plan->clust_pcur), &mtr);
  1421. }
  1422. }
  1423. /* PHASE 6: Test the rest of search conditions */
  1424. if (!row_sel_test_other_conds(plan)) {
  1425. if (plan->unique_search) {
  1426. goto table_exhausted;
  1427. }
  1428. goto next_rec;
  1429. }
  1430. /* PHASE 7: We found a new qualifying row for the current table; push
  1431. the row if prefetch is on, or move to the next table in the join */
  1432. plan->n_rows_fetched++;
  1433. ut_ad(plan->pcur.latch_mode == BTR_SEARCH_LEAF);
  1434. if ((plan->n_rows_fetched <= SEL_PREFETCH_LIMIT)
  1435. || plan->unique_search || plan->no_prefetch
  1436. || plan->table->big_rows) {
  1437. /* No prefetch in operation: go to the next table */
  1438. goto next_table;
  1439. }
  1440. sel_enqueue_prefetched_row(plan);
  1441. if (plan->n_rows_prefetched == SEL_MAX_N_PREFETCH) {
  1442. /* The prefetch buffer is now full */
  1443. sel_dequeue_prefetched_row(plan);
  1444. goto next_table;
  1445. }
  1446. next_rec:
  1447. ut_ad(!search_latch_locked);
  1448. if (mtr_has_extra_clust_latch) {
  1449. /* We must commit &mtr if we are moving to the next
  1450. non-clustered index record, because we could break the
  1451. latching order if we would access a different clustered
  1452. index page right away without releasing the previous. */
  1453. goto commit_mtr_for_a_while;
  1454. }
  1455. if (node->asc) {
  1456. moved = btr_pcur_move_to_next(&(plan->pcur), &mtr);
  1457. } else {
  1458. moved = btr_pcur_move_to_prev(&(plan->pcur), &mtr);
  1459. }
  1460. if (!moved) {
  1461. goto table_exhausted;
  1462. }
  1463. cursor_just_opened = FALSE;
  1464. /* END OF RECORD LOOP
  1465. ------------------ */
  1466. goto rec_loop;
  1467. next_table:
  1468. /* We found a record which satisfies the conditions: we can move to
  1469. the next table or return a row in the result set */
  1470. ut_ad(btr_pcur_is_on_user_rec(&plan->pcur));
  1471. if (plan->unique_search && !node->can_get_updated) {
  1472. plan->cursor_at_end = TRUE;
  1473. } else {
  1474. ut_ad(!search_latch_locked);
  1475. plan->stored_cursor_rec_processed = TRUE;
  1476. btr_pcur_store_position(&(plan->pcur), &mtr);
  1477. }
  1478. mtr_commit(&mtr);
  1479. mtr_has_extra_clust_latch = FALSE;
  1480. next_table_no_mtr:
  1481. /* If we use 'goto' to this label, it means that the row was popped
  1482. from the prefetched rows stack, and &mtr is already committed */
  1483. if (node->fetch_table + 1 == node->n_tables) {
  1484. sel_eval_select_list(node);
  1485. if (node->is_aggregate) {
  1486. goto table_loop;
  1487. }
  1488. sel_assign_into_var_values(node->into_list, node);
  1489. thr->run_node = que_node_get_parent(node);
  1490. err = DB_SUCCESS;
  1491. goto func_exit;
  1492. }
  1493. node->fetch_table++;
  1494. /* When we move to the next table, we first reset the plan cursor:
  1495. we do not care about resetting it when we backtrack from a table */
  1496. plan_reset_cursor(sel_node_get_nth_plan(node, node->fetch_table));
  1497. goto table_loop;
  1498. table_exhausted:
  1499. /* The table cursor pcur reached the result set end: backtrack to the
  1500. previous table in the join if we do not have cached prefetched rows */
  1501. plan->cursor_at_end = TRUE;
  1502. mtr_commit(&mtr);
  1503. mtr_has_extra_clust_latch = FALSE;
  1504. if (plan->n_rows_prefetched > 0) {
  1505. /* The table became exhausted during a prefetch */
  1506. sel_dequeue_prefetched_row(plan);
  1507. goto next_table_no_mtr;
  1508. }
  1509. table_exhausted_no_mtr:
  1510. if (node->fetch_table == 0) {
  1511. err = DB_SUCCESS;
  1512. if (node->is_aggregate && !node->aggregate_already_fetched) {
  1513. node->aggregate_already_fetched = TRUE;
  1514. sel_assign_into_var_values(node->into_list, node);
  1515. thr->run_node = que_node_get_parent(node);
  1516. } else {
  1517. node->state = SEL_NODE_NO_MORE_ROWS;
  1518. thr->run_node = que_node_get_parent(node);
  1519. }
  1520. goto func_exit;
  1521. }
  1522. node->fetch_table--;
  1523. goto table_loop;
  1524. stop_for_a_while:
  1525. /* Return control for a while to que_run_threads, so that runaway
  1526. queries can be canceled. NOTE that when we come here, we must, in a
  1527. locking read, have placed the necessary (possibly waiting request)
  1528. record lock on the cursor record or its successor: when we reposition
  1529. the cursor, this record lock guarantees that nobody can meanwhile have
  1530. inserted new records which should have appeared in the result set,
  1531. which would result in the phantom problem. */
  1532. ut_ad(!search_latch_locked);
  1533. plan->stored_cursor_rec_processed = FALSE;
  1534. btr_pcur_store_position(&(plan->pcur), &mtr);
  1535. mtr_commit(&mtr);
  1536. #ifdef UNIV_SYNC_DEBUG
  1537. ut_ad(sync_thread_levels_empty_except_dict());
  1538. #endif /* UNIV_SYNC_DEBUG */
  1539. err = DB_SUCCESS;
  1540. goto func_exit;
  1541. commit_mtr_for_a_while:
  1542. /* Stores the cursor position and commits &mtr; this is used if
  1543. &mtr may contain latches which would break the latching order if
  1544. &mtr would not be committed and the latches released. */
  1545. plan->stored_cursor_rec_processed = TRUE;
  1546. ut_ad(!search_latch_locked);
  1547. btr_pcur_store_position(&(plan->pcur), &mtr);
  1548. mtr_commit(&mtr);
  1549. mtr_has_extra_clust_latch = FALSE;
  1550. #ifdef UNIV_SYNC_DEBUG
  1551. ut_ad(sync_thread_levels_empty_except_dict());
  1552. #endif /* UNIV_SYNC_DEBUG */
  1553. goto table_loop;
  1554. lock_wait_or_error:
  1555. /* See the note at stop_for_a_while: the same holds for this case */
  1556. ut_ad(!btr_pcur_is_before_first_on_page(&plan->pcur) || !node->asc);
  1557. ut_ad(!search_latch_locked);
  1558. plan->stored_cursor_rec_processed = FALSE;
  1559. btr_pcur_store_position(&(plan->pcur), &mtr);
  1560. mtr_commit(&mtr);
  1561. #ifdef UNIV_SYNC_DEBUG
  1562. ut_ad(sync_thread_levels_empty_except_dict());
  1563. #endif /* UNIV_SYNC_DEBUG */
  1564. func_exit:
  1565. if (search_latch_locked) {
  1566. rw_lock_s_unlock(btr_search_get_latch(index));
  1567. }
  1568. if (UNIV_LIKELY_NULL(heap)) {
  1569. mem_heap_free(heap);
  1570. }
  1571. return(err);
  1572. }
  1573. /**********************************************************************//**
  1574. Performs a select step. This is a high-level function used in SQL execution
  1575. graphs.
  1576. @return query thread to run next or NULL */
  1577. UNIV_INTERN
  1578. que_thr_t*
  1579. row_sel_step(
  1580. /*=========*/
  1581. que_thr_t* thr) /*!< in: query thread */
  1582. {
  1583. sel_node_t* node;
  1584. ut_ad(thr);
  1585. node = static_cast<sel_node_t*>(thr->run_node);
  1586. ut_ad(que_node_get_type(node) == QUE_NODE_SELECT);
  1587. /* If this is a new time this node is executed (or when execution
  1588. resumes after wait for a table intention lock), set intention locks
  1589. on the tables, or assign a read view */
  1590. if (node->into_list && (thr->prev_node == que_node_get_parent(node))) {
  1591. node->state = SEL_NODE_OPEN;
  1592. }
  1593. if (node->state == SEL_NODE_OPEN) {
  1594. /* It may be that the current session has not yet started
  1595. its transaction, or it has been committed: */
  1596. trx_start_if_not_started_xa(thr_get_trx(thr));
  1597. plan_reset_cursor(sel_node_get_nth_plan(node, 0));
  1598. if (node->consistent_read) {
  1599. /* Assign a read view for the query */
  1600. node->read_view = trx_assign_read_view(
  1601. thr_get_trx(thr));
  1602. } else {
  1603. sym_node_t* table_node;
  1604. enum lock_mode i_lock_mode;
  1605. if (node->set_x_locks) {
  1606. i_lock_mode = LOCK_IX;
  1607. } else {
  1608. i_lock_mode = LOCK_IS;
  1609. }
  1610. for (table_node = node->table_list;
  1611. table_node != 0;
  1612. table_node = static_cast<sym_node_t*>(
  1613. que_node_get_next(table_node))) {
  1614. dberr_t err = lock_table(
  1615. 0, table_node->table, i_lock_mode,
  1616. thr);
  1617. if (err != DB_SUCCESS) {
  1618. trx_t* trx;
  1619. trx = thr_get_trx(thr);
  1620. trx->error_state = err;
  1621. return(NULL);
  1622. }
  1623. }
  1624. }
  1625. /* If this is an explicit cursor, copy stored procedure
  1626. variable values, so that the values cannot change between
  1627. fetches (currently, we copy them also for non-explicit
  1628. cursors) */
  1629. if (node->explicit_cursor
  1630. && UT_LIST_GET_FIRST(node->copy_variables)) {
  1631. row_sel_copy_input_variable_vals(node);
  1632. }
  1633. node->state = SEL_NODE_FETCH;
  1634. node->fetch_table = 0;
  1635. if (node->is_aggregate) {
  1636. /* Reset the aggregate total values */
  1637. sel_reset_aggregate_vals(node);
  1638. }
  1639. }
  1640. dberr_t err = row_sel(node, thr);
  1641. /* NOTE! if queries are parallelized, the following assignment may
  1642. have problems; the assignment should be made only if thr is the
  1643. only top-level thr in the graph: */
  1644. thr->graph->last_sel_node = node;
  1645. if (err != DB_SUCCESS) {
  1646. thr_get_trx(thr)->error_state = err;
  1647. return(NULL);
  1648. }
  1649. return(thr);
  1650. }
  1651. /**********************************************************************//**
  1652. Performs a fetch for a cursor.
  1653. @return query thread to run next or NULL */
  1654. UNIV_INTERN
  1655. que_thr_t*
  1656. fetch_step(
  1657. /*=======*/
  1658. que_thr_t* thr) /*!< in: query thread */
  1659. {
  1660. sel_node_t* sel_node;
  1661. fetch_node_t* node;
  1662. ut_ad(thr);
  1663. node = static_cast<fetch_node_t*>(thr->run_node);
  1664. sel_node = node->cursor_def;
  1665. ut_ad(que_node_get_type(node) == QUE_NODE_FETCH);
  1666. if (thr->prev_node != que_node_get_parent(node)) {
  1667. if (sel_node->state != SEL_NODE_NO_MORE_ROWS) {
  1668. if (node->into_list) {
  1669. sel_assign_into_var_values(node->into_list,
  1670. sel_node);
  1671. } else {
  1672. ibool ret = (*node->func->func)(
  1673. sel_node, node->func->arg);
  1674. if (!ret) {
  1675. sel_node->state
  1676. = SEL_NODE_NO_MORE_ROWS;
  1677. }
  1678. }
  1679. }
  1680. thr->run_node = que_node_get_parent(node);
  1681. return(thr);
  1682. }
  1683. /* Make the fetch node the parent of the cursor definition for
  1684. the time of the fetch, so that execution knows to return to this
  1685. fetch node after a row has been selected or we know that there is
  1686. no row left */
  1687. sel_node->common.parent = node;
  1688. if (sel_node->state == SEL_NODE_CLOSED) {
  1689. fprintf(stderr,
  1690. "InnoDB: Error: fetch called on a closed cursor\n");
  1691. thr_get_trx(thr)->error_state = DB_ERROR;
  1692. return(NULL);
  1693. }
  1694. thr->run_node = sel_node;
  1695. return(thr);
  1696. }
  1697. /****************************************************************//**
  1698. Sample callback function for fetch that prints each row.
  1699. @return always returns non-NULL */
  1700. UNIV_INTERN
  1701. void*
  1702. row_fetch_print(
  1703. /*============*/
  1704. void* row, /*!< in: sel_node_t* */
  1705. void* user_arg) /*!< in: not used */
  1706. {
  1707. que_node_t* exp;
  1708. ulint i = 0;
  1709. sel_node_t* node = static_cast<sel_node_t*>(row);
  1710. UT_NOT_USED(user_arg);
  1711. fprintf(stderr, "row_fetch_print: row %p\n", row);
  1712. for (exp = node->select_list;
  1713. exp != 0;
  1714. exp = que_node_get_next(exp), i++) {
  1715. dfield_t* dfield = que_node_get_val(exp);
  1716. const dtype_t* type = dfield_get_type(dfield);
  1717. fprintf(stderr, " column %lu:\n", (ulong) i);
  1718. dtype_print(type);
  1719. putc('\n', stderr);
  1720. if (dfield_get_len(dfield) != UNIV_SQL_NULL) {
  1721. ut_print_buf(stderr, dfield_get_data(dfield),
  1722. dfield_get_len(dfield));
  1723. putc('\n', stderr);
  1724. } else {
  1725. fputs(" <NULL>;\n", stderr);
  1726. }
  1727. }
  1728. return((void*)42);
  1729. }
  1730. /***********************************************************//**
  1731. Prints a row in a select result.
  1732. @return query thread to run next or NULL */
  1733. UNIV_INTERN
  1734. que_thr_t*
  1735. row_printf_step(
  1736. /*============*/
  1737. que_thr_t* thr) /*!< in: query thread */
  1738. {
  1739. row_printf_node_t* node;
  1740. sel_node_t* sel_node;
  1741. que_node_t* arg;
  1742. ut_ad(thr);
  1743. node = static_cast<row_printf_node_t*>(thr->run_node);
  1744. sel_node = node->sel_node;
  1745. ut_ad(que_node_get_type(node) == QUE_NODE_ROW_PRINTF);
  1746. if (thr->prev_node == que_node_get_parent(node)) {
  1747. /* Reset the cursor */
  1748. sel_node->state = SEL_NODE_OPEN;
  1749. /* Fetch next row to print */
  1750. thr->run_node = sel_node;
  1751. return(thr);
  1752. }
  1753. if (sel_node->state != SEL_NODE_FETCH) {
  1754. ut_ad(sel_node->state == SEL_NODE_NO_MORE_ROWS);
  1755. /* No more rows to print */
  1756. thr->run_node = que_node_get_parent(node);
  1757. return(thr);
  1758. }
  1759. arg = sel_node->select_list;
  1760. while (arg) {
  1761. dfield_print_also_hex(que_node_get_val(arg));
  1762. fputs(" ::: ", stderr);
  1763. arg = que_node_get_next(arg);
  1764. }
  1765. putc('\n', stderr);
  1766. /* Fetch next row to print */
  1767. thr->run_node = sel_node;
  1768. return(thr);
  1769. }
  1770. /****************************************************************//**
  1771. Converts a key value stored in MySQL format to an Innobase dtuple. The last
  1772. field of the key value may be just a prefix of a fixed length field: hence
  1773. the parameter key_len. But currently we do not allow search keys where the
  1774. last field is only a prefix of the full key field len and print a warning if
  1775. such appears. A counterpart of this function is
  1776. ha_innobase::store_key_val_for_row() in ha_innodb.cc. */
  1777. UNIV_INTERN
  1778. void
  1779. row_sel_convert_mysql_key_to_innobase(
  1780. /*==================================*/
  1781. dtuple_t* tuple, /*!< in/out: tuple where to build;
  1782. NOTE: we assume that the type info
  1783. in the tuple is already according
  1784. to index! */
  1785. byte* buf, /*!< in: buffer to use in field
  1786. conversions; NOTE that dtuple->data
  1787. may end up pointing inside buf so
  1788. do not discard that buffer while
  1789. the tuple is being used. See
  1790. row_mysql_store_col_in_innobase_format()
  1791. in the case of DATA_INT */
  1792. ulint buf_len, /*!< in: buffer length */
  1793. dict_index_t* index, /*!< in: index of the key value */
  1794. const byte* key_ptr, /*!< in: MySQL key value */
  1795. ulint key_len, /*!< in: MySQL key value length */
  1796. trx_t* trx) /*!< in: transaction */
  1797. {
  1798. byte* original_buf = buf;
  1799. const byte* original_key_ptr = key_ptr;
  1800. dict_field_t* field;
  1801. dfield_t* dfield;
  1802. ulint data_offset;
  1803. ulint data_len;
  1804. ulint data_field_len;
  1805. ibool is_null;
  1806. const byte* key_end;
  1807. ulint n_fields = 0;
  1808. /* For documentation of the key value storage format in MySQL, see
  1809. ha_innobase::store_key_val_for_row() in ha_innodb.cc. */
  1810. key_end = key_ptr + key_len;
  1811. /* Permit us to access any field in the tuple (ULINT_MAX): */
  1812. dtuple_set_n_fields(tuple, ULINT_MAX);
  1813. dfield = dtuple_get_nth_field(tuple, 0);
  1814. field = dict_index_get_nth_field(index, 0);
  1815. if (UNIV_UNLIKELY(dfield_get_type(dfield)->mtype == DATA_SYS)) {
  1816. /* A special case: we are looking for a position in the
  1817. generated clustered index which InnoDB automatically added
  1818. to a table with no primary key: the first and the only
  1819. ordering column is ROW_ID which InnoDB stored to the key_ptr
  1820. buffer. */
  1821. ut_a(key_len == DATA_ROW_ID_LEN);
  1822. dfield_set_data(dfield, key_ptr, DATA_ROW_ID_LEN);
  1823. dtuple_set_n_fields(tuple, 1);
  1824. return;
  1825. }
  1826. while (key_ptr < key_end) {
  1827. ulint type = dfield_get_type(dfield)->mtype;
  1828. ut_a(field->col->mtype == type);
  1829. data_offset = 0;
  1830. is_null = FALSE;
  1831. if (!(dfield_get_type(dfield)->prtype & DATA_NOT_NULL)) {
  1832. /* The first byte in the field tells if this is
  1833. an SQL NULL value */
  1834. data_offset = 1;
  1835. if (*key_ptr != 0) {
  1836. dfield_set_null(dfield);
  1837. is_null = TRUE;
  1838. }
  1839. }
  1840. /* Calculate data length and data field total length */
  1841. if (type == DATA_BLOB) {
  1842. /* The key field is a column prefix of a BLOB or
  1843. TEXT */
  1844. ut_a(field->prefix_len > 0);
  1845. /* MySQL stores the actual data length to the first 2
  1846. bytes after the optional SQL NULL marker byte. The
  1847. storage format is little-endian, that is, the most
  1848. significant byte at a higher address. In UTF-8, MySQL
  1849. seems to reserve field->prefix_len bytes for
  1850. storing this field in the key value buffer, even
  1851. though the actual value only takes data_len bytes
  1852. from the start. */
  1853. data_len = key_ptr[data_offset]
  1854. + 256 * key_ptr[data_offset + 1];
  1855. data_field_len = data_offset + 2 + field->prefix_len;
  1856. data_offset += 2;
  1857. /* Now that we know the length, we store the column
  1858. value like it would be a fixed char field */
  1859. } else if (field->prefix_len > 0) {
  1860. /* Looks like MySQL pads unused end bytes in the
  1861. prefix with space. Therefore, also in UTF-8, it is ok
  1862. to compare with a prefix containing full prefix_len
  1863. bytes, and no need to take at most prefix_len / 3
  1864. UTF-8 characters from the start.
  1865. If the prefix is used as the upper end of a LIKE
  1866. 'abc%' query, then MySQL pads the end with chars
  1867. 0xff. TODO: in that case does it any harm to compare
  1868. with the full prefix_len bytes. How do characters
  1869. 0xff in UTF-8 behave? */
  1870. data_len = field->prefix_len;
  1871. data_field_len = data_offset + data_len;
  1872. } else {
  1873. data_len = dfield_get_type(dfield)->len;
  1874. data_field_len = data_offset + data_len;
  1875. }
  1876. if (UNIV_UNLIKELY
  1877. (dtype_get_mysql_type(dfield_get_type(dfield))
  1878. == DATA_MYSQL_TRUE_VARCHAR)
  1879. && UNIV_LIKELY(type != DATA_INT)) {
  1880. /* In a MySQL key value format, a true VARCHAR is
  1881. always preceded by 2 bytes of a length field.
  1882. dfield_get_type(dfield)->len returns the maximum
  1883. 'payload' len in bytes. That does not include the
  1884. 2 bytes that tell the actual data length.
  1885. We added the check != DATA_INT to make sure we do
  1886. not treat MySQL ENUM or SET as a true VARCHAR! */
  1887. data_len += 2;
  1888. data_field_len += 2;
  1889. }
  1890. /* Storing may use at most data_len bytes of buf */
  1891. if (UNIV_LIKELY(!is_null)) {
  1892. ut_a(buf + data_len <= original_buf + buf_len);
  1893. row_mysql_store_col_in_innobase_format(
  1894. dfield, buf,
  1895. FALSE, /* MySQL key value format col */
  1896. key_ptr + data_offset, data_len,
  1897. dict_table_is_comp(index->table));
  1898. buf += data_len;
  1899. }
  1900. key_ptr += data_field_len;
  1901. if (UNIV_UNLIKELY(key_ptr > key_end)) {
  1902. /* The last field in key was not a complete key field
  1903. but a prefix of it.
  1904. Print a warning about this! HA_READ_PREFIX_LAST does
  1905. not currently work in InnoDB with partial-field key
  1906. value prefixes. Since MySQL currently uses a padding
  1907. trick to calculate LIKE 'abc%' type queries there
  1908. should never be partial-field prefixes in searches. */
  1909. ut_print_timestamp(stderr);
  1910. fputs(" InnoDB: Warning: using a partial-field"
  1911. " key prefix in search.\n"
  1912. "InnoDB: ", stderr);
  1913. dict_index_name_print(stderr, trx, index);
  1914. fprintf(stderr, ". Last data field length %lu bytes,\n"
  1915. "InnoDB: key ptr now exceeds"
  1916. " key end by %lu bytes.\n"
  1917. "InnoDB: Key value in the MySQL format:\n",
  1918. (ulong) data_field_len,
  1919. (ulong) (key_ptr - key_end));
  1920. fflush(stderr);
  1921. ut_print_buf(stderr, original_key_ptr, key_len);
  1922. putc('\n', stderr);
  1923. if (!is_null) {
  1924. ulint len = dfield_get_len(dfield);
  1925. dfield_set_len(dfield, len
  1926. - (ulint) (key_ptr - key_end));
  1927. }
  1928. ut_ad(0);
  1929. }
  1930. n_fields++;
  1931. field++;
  1932. dfield++;
  1933. }
  1934. DBUG_EXECUTE_IF("innodb_srch_key_buffer_full",
  1935. ut_a(buf == (original_buf + buf_len)););
  1936. ut_a(buf <= original_buf + buf_len);
  1937. /* We set the length of tuple to n_fields: we assume that the memory
  1938. area allocated for it is big enough (usually bigger than n_fields). */
  1939. dtuple_set_n_fields(tuple, n_fields);
  1940. }
  1941. /**************************************************************//**
  1942. Stores the row id to the prebuilt struct. */
  1943. static
  1944. void
  1945. row_sel_store_row_id_to_prebuilt(
  1946. /*=============================*/
  1947. row_prebuilt_t* prebuilt, /*!< in/out: prebuilt */
  1948. const rec_t* index_rec, /*!< in: record */
  1949. const dict_index_t* index, /*!< in: index of the record */
  1950. const ulint* offsets) /*!< in: rec_get_offsets
  1951. (index_rec, index) */
  1952. {
  1953. const byte* data;
  1954. ulint len;
  1955. ut_ad(rec_offs_validate(index_rec, index, offsets));
  1956. data = rec_get_nth_field(
  1957. index_rec, offsets,
  1958. dict_index_get_sys_col_pos(index, DATA_ROW_ID), &len);
  1959. if (UNIV_UNLIKELY(len != DATA_ROW_ID_LEN)) {
  1960. fprintf(stderr,
  1961. "InnoDB: Error: Row id field is"
  1962. " wrong length %lu in ", (ulong) len);
  1963. dict_index_name_print(stderr, prebuilt->trx, index);
  1964. fprintf(stderr, "\n"
  1965. "InnoDB: Field number %lu, record:\n",
  1966. (ulong) dict_index_get_sys_col_pos(index,
  1967. DATA_ROW_ID));
  1968. rec_print_new(stderr, index_rec, offsets);
  1969. putc('\n', stderr);
  1970. ut_error;
  1971. }
  1972. ut_memcpy(prebuilt->row_id, data, len);
  1973. }
  1974. #ifdef UNIV_DEBUG
  1975. /** Convert a non-SQL-NULL field from Innobase format to MySQL format. */
  1976. # define row_sel_field_store_in_mysql_format(dest,templ,idx,field,src,len) \
  1977. row_sel_field_store_in_mysql_format_func(dest,templ,idx,field,src,len)
  1978. #else /* UNIV_DEBUG */
  1979. /** Convert a non-SQL-NULL field from Innobase format to MySQL format. */
  1980. # define row_sel_field_store_in_mysql_format(dest,templ,idx,field,src,len) \
  1981. row_sel_field_store_in_mysql_format_func(dest,templ,src,len)
  1982. #endif /* UNIV_DEBUG */
  1983. /**************************************************************//**
  1984. Stores a non-SQL-NULL field in the MySQL format. The counterpart of this
  1985. function is row_mysql_store_col_in_innobase_format() in row0mysql.cc. */
  1986. static __attribute__((nonnull))
  1987. void
  1988. row_sel_field_store_in_mysql_format_func(
  1989. /*=====================================*/
  1990. byte* dest, /*!< in/out: buffer where to store; NOTE
  1991. that BLOBs are not in themselves
  1992. stored here: the caller must allocate
  1993. and copy the BLOB into buffer before,
  1994. and pass the pointer to the BLOB in
  1995. 'data' */
  1996. const mysql_row_templ_t* templ,
  1997. /*!< in: MySQL column template.
  1998. Its following fields are referenced:
  1999. type, is_unsigned, mysql_col_len,
  2000. mbminlen, mbmaxlen */
  2001. #ifdef UNIV_DEBUG
  2002. const dict_index_t* index,
  2003. /*!< in: InnoDB index */
  2004. ulint field_no,
  2005. /*!< in: templ->rec_field_no or
  2006. templ->clust_rec_field_no or
  2007. templ->icp_rec_field_no */
  2008. #endif /* UNIV_DEBUG */
  2009. const byte* data, /*!< in: data to store */
  2010. ulint len) /*!< in: length of the data */
  2011. {
  2012. byte* ptr;
  2013. #ifdef UNIV_DEBUG
  2014. const dict_field_t* field
  2015. = dict_index_get_nth_field(index, field_no);
  2016. #endif /* UNIV_DEBUG */
  2017. ut_ad(len != UNIV_SQL_NULL);
  2018. UNIV_MEM_ASSERT_RW(data, len);
  2019. UNIV_MEM_ASSERT_W(dest, templ->mysql_col_len);
  2020. UNIV_MEM_INVALID(dest, templ->mysql_col_len);
  2021. switch (templ->type) {
  2022. const byte* field_end;
  2023. byte* pad;
  2024. case DATA_INT:
  2025. /* Convert integer data from Innobase to a little-endian
  2026. format, sign bit restored to normal */
  2027. ptr = dest + len;
  2028. for (;;) {
  2029. ptr--;
  2030. *ptr = *data;
  2031. if (ptr == dest) {
  2032. break;
  2033. }
  2034. data++;
  2035. }
  2036. if (!templ->is_unsigned) {
  2037. dest[len - 1] = (byte) (dest[len - 1] ^ 128);
  2038. }
  2039. ut_ad(templ->mysql_col_len == len);
  2040. break;
  2041. case DATA_VARCHAR:
  2042. case DATA_VARMYSQL:
  2043. case DATA_BINARY:
  2044. field_end = dest + templ->mysql_col_len;
  2045. if (templ->mysql_type == DATA_MYSQL_TRUE_VARCHAR) {
  2046. /* This is a >= 5.0.3 type true VARCHAR. Store the
  2047. length of the data to the first byte or the first
  2048. two bytes of dest. */
  2049. dest = row_mysql_store_true_var_len(
  2050. dest, len, templ->mysql_length_bytes);
  2051. /* Copy the actual data. Leave the rest of the
  2052. buffer uninitialized. */
  2053. memcpy(dest, data, len);
  2054. break;
  2055. }
  2056. /* Copy the actual data */
  2057. ut_memcpy(dest, data, len);
  2058. /* Pad with trailing spaces. */
  2059. pad = dest + len;
  2060. ut_ad(templ->mbminlen <= templ->mbmaxlen);
  2061. /* We treat some Unicode charset strings specially. */
  2062. switch (templ->mbminlen) {
  2063. case 4:
  2064. /* InnoDB should never have stripped partial
  2065. UTF-32 characters. */
  2066. ut_a(!(len & 3));
  2067. break;
  2068. case 2:
  2069. /* A space char is two bytes,
  2070. 0x0020 in UCS2 and UTF-16 */
  2071. if (UNIV_UNLIKELY(len & 1)) {
  2072. /* A 0x20 has been stripped from the column.
  2073. Pad it back. */
  2074. if (pad < field_end) {
  2075. *pad++ = 0x20;
  2076. }
  2077. }
  2078. }
  2079. row_mysql_pad_col(templ->mbminlen, pad, field_end - pad);
  2080. break;
  2081. case DATA_BLOB:
  2082. /* Store a pointer to the BLOB buffer to dest: the BLOB was
  2083. already copied to the buffer in row_sel_store_mysql_rec */
  2084. row_mysql_store_blob_ref(dest, templ->mysql_col_len, data,
  2085. len);
  2086. break;
  2087. case DATA_MYSQL:
  2088. memcpy(dest, data, len);
  2089. ut_ad(templ->mysql_col_len >= len);
  2090. ut_ad(templ->mbmaxlen >= templ->mbminlen);
  2091. /* If field_no equals to templ->icp_rec_field_no,
  2092. we are examining a row pointed by "icp_rec_field_no".
  2093. There is possibility that icp_rec_field_no refers to
  2094. a field in a secondary index while templ->rec_field_no
  2095. points to field in a primary index. The length
  2096. should still be equal, unless the field pointed
  2097. by icp_rec_field_no has a prefix */
  2098. ut_ad(templ->mbmaxlen > templ->mbminlen
  2099. || templ->mysql_col_len == len
  2100. || (field_no == templ->icp_rec_field_no
  2101. && field->prefix_len > 0));
  2102. /* The following assertion would fail for old tables
  2103. containing UTF-8 ENUM columns due to Bug #9526. */
  2104. ut_ad(!templ->mbmaxlen
  2105. || !(templ->mysql_col_len % templ->mbmaxlen));
  2106. ut_ad(len * templ->mbmaxlen >= templ->mysql_col_len
  2107. || (field_no == templ->icp_rec_field_no
  2108. && field->prefix_len > 0));
  2109. ut_ad(!(field->prefix_len % templ->mbmaxlen));
  2110. if (templ->mbminlen == 1 && templ->mbmaxlen != 1) {
  2111. /* Pad with spaces. This undoes the stripping
  2112. done in row0mysql.cc, function
  2113. row_mysql_store_col_in_innobase_format(). */
  2114. memset(dest + len, 0x20, templ->mysql_col_len - len);
  2115. }
  2116. break;
  2117. default:
  2118. #ifdef UNIV_DEBUG
  2119. case DATA_SYS_CHILD:
  2120. case DATA_SYS:
  2121. /* These column types should never be shipped to MySQL. */
  2122. ut_ad(0);
  2123. case DATA_CHAR:
  2124. case DATA_FIXBINARY:
  2125. case DATA_FLOAT:
  2126. case DATA_DOUBLE:
  2127. case DATA_DECIMAL:
  2128. /* Above are the valid column types for MySQL data. */
  2129. #endif /* UNIV_DEBUG */
  2130. ut_ad(field->prefix_len
  2131. ? field->prefix_len == len
  2132. : templ->mysql_col_len == len);
  2133. memcpy(dest, data, len);
  2134. }
  2135. }
  2136. #ifdef UNIV_DEBUG
  2137. /** Convert a field from Innobase format to MySQL format. */
  2138. # define row_sel_store_mysql_field(m,p,r,i,o,f,t) \
  2139. row_sel_store_mysql_field_func(m,p,r,i,o,f,t)
  2140. #else /* UNIV_DEBUG */
  2141. /** Convert a field from Innobase format to MySQL format. */
  2142. # define row_sel_store_mysql_field(m,p,r,i,o,f,t) \
  2143. row_sel_store_mysql_field_func(m,p,r,o,f,t)
  2144. #endif /* UNIV_DEBUG */
  2145. /**************************************************************//**
  2146. Convert a field in the Innobase format to a field in the MySQL format. */
  2147. static __attribute__((warn_unused_result))
  2148. ibool
  2149. row_sel_store_mysql_field_func(
  2150. /*===========================*/
  2151. byte* mysql_rec, /*!< out: record in the
  2152. MySQL format */
  2153. row_prebuilt_t* prebuilt, /*!< in/out: prebuilt struct */
  2154. const rec_t* rec, /*!< in: InnoDB record;
  2155. must be protected by
  2156. a page latch */
  2157. #ifdef UNIV_DEBUG
  2158. const dict_index_t* index, /*!< in: index of rec */
  2159. #endif
  2160. const ulint* offsets, /*!< in: array returned by
  2161. rec_get_offsets() */
  2162. ulint field_no, /*!< in: templ->rec_field_no or
  2163. templ->clust_rec_field_no or
  2164. templ->icp_rec_field_no */
  2165. const mysql_row_templ_t*templ) /*!< in: row template */
  2166. {
  2167. const byte* data;
  2168. ulint len;
  2169. ut_ad(prebuilt->default_rec);
  2170. ut_ad(templ);
  2171. ut_ad(templ >= prebuilt->mysql_template);
  2172. ut_ad(templ < &prebuilt->mysql_template[prebuilt->n_template]);
  2173. ut_ad(field_no == templ->clust_rec_field_no
  2174. || field_no == templ->rec_field_no
  2175. || field_no == templ->icp_rec_field_no);
  2176. ut_ad(rec_offs_validate(rec, index, offsets));
  2177. if (UNIV_UNLIKELY(rec_offs_nth_extern(offsets, field_no))) {
  2178. mem_heap_t* heap;
  2179. /* Copy an externally stored field to a temporary heap */
  2180. ut_a(!prebuilt->trx->has_search_latch);
  2181. #ifdef UNIV_SYNC_DEBUG
  2182. ut_ad(!btr_search_own_any());
  2183. #endif
  2184. ut_ad(field_no == templ->clust_rec_field_no);
  2185. if (UNIV_UNLIKELY(templ->type == DATA_BLOB)) {
  2186. if (prebuilt->blob_heap == NULL) {
  2187. prebuilt->blob_heap = mem_heap_create(
  2188. UNIV_PAGE_SIZE);
  2189. }
  2190. heap = prebuilt->blob_heap;
  2191. } else {
  2192. heap = mem_heap_create(UNIV_PAGE_SIZE);
  2193. }
  2194. /* NOTE: if we are retrieving a big BLOB, we may
  2195. already run out of memory in the next call, which
  2196. causes an assert */
  2197. data = btr_rec_copy_externally_stored_field(
  2198. rec, offsets,
  2199. dict_table_zip_size(prebuilt->table),
  2200. field_no, &len, heap);
  2201. if (UNIV_UNLIKELY(!data)) {
  2202. /* The externally stored field was not written
  2203. yet. This record should only be seen by
  2204. recv_recovery_rollback_active() or any
  2205. TRX_ISO_READ_UNCOMMITTED transactions. */
  2206. if (heap != prebuilt->blob_heap) {
  2207. mem_heap_free(heap);
  2208. }
  2209. ut_a(prebuilt->trx->isolation_level
  2210. == TRX_ISO_READ_UNCOMMITTED);
  2211. return(FALSE);
  2212. }
  2213. ut_a(len != UNIV_SQL_NULL);
  2214. row_sel_field_store_in_mysql_format(
  2215. mysql_rec + templ->mysql_col_offset,
  2216. templ, index, field_no, data, len);
  2217. if (heap != prebuilt->blob_heap) {
  2218. mem_heap_free(heap);
  2219. }
  2220. } else {
  2221. /* Field is stored in the row. */
  2222. data = rec_get_nth_field(rec, offsets, field_no, &len);
  2223. if (len == UNIV_SQL_NULL) {
  2224. /* MySQL assumes that the field for an SQL
  2225. NULL value is set to the default value. */
  2226. ut_ad(templ->mysql_null_bit_mask);
  2227. UNIV_MEM_ASSERT_RW(prebuilt->default_rec
  2228. + templ->mysql_col_offset,
  2229. templ->mysql_col_len);
  2230. mysql_rec[templ->mysql_null_byte_offset]
  2231. |= (byte) templ->mysql_null_bit_mask;
  2232. memcpy(mysql_rec + templ->mysql_col_offset,
  2233. (const byte*) prebuilt->default_rec
  2234. + templ->mysql_col_offset,
  2235. templ->mysql_col_len);
  2236. return(TRUE);
  2237. }
  2238. if (UNIV_UNLIKELY(templ->type == DATA_BLOB)) {
  2239. /* It is a BLOB field locally stored in the
  2240. InnoDB record: we MUST copy its contents to
  2241. prebuilt->blob_heap here because
  2242. row_sel_field_store_in_mysql_format() stores a
  2243. pointer to the data, and the data passed to us
  2244. will be invalid as soon as the
  2245. mini-transaction is committed and the page
  2246. latch on the clustered index page is
  2247. released. */
  2248. if (prebuilt->blob_heap == NULL) {
  2249. prebuilt->blob_heap = mem_heap_create(
  2250. UNIV_PAGE_SIZE);
  2251. }
  2252. data = static_cast<byte*>(
  2253. mem_heap_dup(prebuilt->blob_heap, data, len));
  2254. }
  2255. row_sel_field_store_in_mysql_format(
  2256. mysql_rec + templ->mysql_col_offset,
  2257. templ, index, field_no, data, len);
  2258. }
  2259. ut_ad(len != UNIV_SQL_NULL);
  2260. if (templ->mysql_null_bit_mask) {
  2261. /* It is a nullable column with a non-NULL
  2262. value */
  2263. mysql_rec[templ->mysql_null_byte_offset]
  2264. &= ~(byte) templ->mysql_null_bit_mask;
  2265. }
  2266. return(TRUE);
  2267. }
  2268. /**************************************************************//**
  2269. Convert a row in the Innobase format to a row in the MySQL format.
  2270. Note that the template in prebuilt may advise us to copy only a few
  2271. columns to mysql_rec, other columns are left blank. All columns may not
  2272. be needed in the query.
  2273. @return TRUE on success, FALSE if not all columns could be retrieved */
  2274. static __attribute__((warn_unused_result))
  2275. ibool
  2276. row_sel_store_mysql_rec(
  2277. /*====================*/
  2278. byte* mysql_rec, /*!< out: row in the MySQL format */
  2279. row_prebuilt_t* prebuilt, /*!< in: prebuilt struct */
  2280. const rec_t* rec, /*!< in: Innobase record in the index
  2281. which was described in prebuilt's
  2282. template, or in the clustered index;
  2283. must be protected by a page latch */
  2284. ibool rec_clust, /*!< in: TRUE if rec is in the
  2285. clustered index instead of
  2286. prebuilt->index */
  2287. const dict_index_t* index, /*!< in: index of rec */
  2288. const ulint* offsets) /*!< in: array returned by
  2289. rec_get_offsets(rec) */
  2290. {
  2291. ulint i;
  2292. ut_ad(rec_clust || index == prebuilt->index);
  2293. ut_ad(!rec_clust || dict_index_is_clust(index));
  2294. if (UNIV_LIKELY_NULL(prebuilt->blob_heap)) {
  2295. mem_heap_free(prebuilt->blob_heap);
  2296. prebuilt->blob_heap = NULL;
  2297. }
  2298. for (i = 0; i < prebuilt->n_template; i++) {
  2299. const mysql_row_templ_t*templ = &prebuilt->mysql_template[i];
  2300. const ulint field_no
  2301. = rec_clust
  2302. ? templ->clust_rec_field_no
  2303. : templ->rec_field_no;
  2304. /* We should never deliver column prefixes to MySQL,
  2305. except for evaluating innobase_index_cond(). */
  2306. /* ...actually, we do want to do this in order to
  2307. support the prefix query optimization.
  2308. ut_ad(dict_index_get_nth_field(index, field_no)->prefix_len
  2309. == 0);
  2310. ...so we disable this assert. */
  2311. if (!row_sel_store_mysql_field(mysql_rec, prebuilt,
  2312. rec, index, offsets,
  2313. field_no, templ)) {
  2314. return(FALSE);
  2315. }
  2316. }
  2317. /* FIXME: We only need to read the doc_id if an FTS indexed
  2318. column is being updated.
  2319. NOTE, the record must be cluster index record. Secondary index
  2320. might not have the Doc ID */
  2321. if (dict_table_has_fts_index(prebuilt->table)
  2322. && dict_index_is_clust(index)) {
  2323. prebuilt->fts_doc_id = fts_get_doc_id_from_rec(
  2324. prebuilt->table, rec, NULL);
  2325. }
  2326. return(TRUE);
  2327. }
  2328. /*********************************************************************//**
  2329. Builds a previous version of a clustered index record for a consistent read
  2330. @return DB_SUCCESS or error code */
  2331. static __attribute__((nonnull, warn_unused_result))
  2332. dberr_t
  2333. row_sel_build_prev_vers_for_mysql(
  2334. /*==============================*/
  2335. read_view_t* read_view, /*!< in: read view */
  2336. dict_index_t* clust_index, /*!< in: clustered index */
  2337. row_prebuilt_t* prebuilt, /*!< in: prebuilt struct */
  2338. const rec_t* rec, /*!< in: record in a clustered index */
  2339. ulint** offsets, /*!< in/out: offsets returned by
  2340. rec_get_offsets(rec, clust_index) */
  2341. mem_heap_t** offset_heap, /*!< in/out: memory heap from which
  2342. the offsets are allocated */
  2343. rec_t** old_vers, /*!< out: old version, or NULL if the
  2344. record does not exist in the view:
  2345. i.e., it was freshly inserted
  2346. afterwards */
  2347. mtr_t* mtr) /*!< in: mtr */
  2348. {
  2349. dberr_t err;
  2350. if (prebuilt->old_vers_heap) {
  2351. mem_heap_empty(prebuilt->old_vers_heap);
  2352. } else {
  2353. prebuilt->old_vers_heap = mem_heap_create(200);
  2354. }
  2355. err = row_vers_build_for_consistent_read(
  2356. rec, mtr, clust_index, offsets, read_view, offset_heap,
  2357. prebuilt->old_vers_heap, old_vers);
  2358. return(err);
  2359. }
  2360. /*********************************************************************//**
  2361. Retrieves the clustered index record corresponding to a record in a
  2362. non-clustered index. Does the necessary locking. Used in the MySQL
  2363. interface.
  2364. @return DB_SUCCESS, DB_SUCCESS_LOCKED_REC, or error code */
  2365. static __attribute__((nonnull, warn_unused_result))
  2366. dberr_t
  2367. row_sel_get_clust_rec_for_mysql(
  2368. /*============================*/
  2369. row_prebuilt_t* prebuilt,/*!< in: prebuilt struct in the handle */
  2370. dict_index_t* sec_index,/*!< in: secondary index where rec resides */
  2371. const rec_t* rec, /*!< in: record in a non-clustered index; if
  2372. this is a locking read, then rec is not
  2373. allowed to be delete-marked, and that would
  2374. not make sense either */
  2375. que_thr_t* thr, /*!< in: query thread */
  2376. const rec_t** out_rec,/*!< out: clustered record or an old version of
  2377. it, NULL if the old version did not exist
  2378. in the read view, i.e., it was a fresh
  2379. inserted version */
  2380. ulint** offsets,/*!< in: offsets returned by
  2381. rec_get_offsets(rec, sec_index);
  2382. out: offsets returned by
  2383. rec_get_offsets(out_rec, clust_index) */
  2384. mem_heap_t** offset_heap,/*!< in/out: memory heap from which
  2385. the offsets are allocated */
  2386. mtr_t* mtr) /*!< in: mtr used to get access to the
  2387. non-clustered record; the same mtr is used to
  2388. access the clustered index */
  2389. {
  2390. dict_index_t* clust_index;
  2391. const rec_t* clust_rec;
  2392. rec_t* old_vers;
  2393. dberr_t err;
  2394. trx_t* trx;
  2395. srv_stats.n_sec_rec_cluster_reads.inc();
  2396. *out_rec = NULL;
  2397. trx = thr_get_trx(thr);
  2398. row_build_row_ref_in_tuple(prebuilt->clust_ref, rec,
  2399. sec_index, *offsets, trx);
  2400. clust_index = dict_table_get_first_index(sec_index->table);
  2401. btr_pcur_open_with_no_init(clust_index, prebuilt->clust_ref,
  2402. PAGE_CUR_LE, BTR_SEARCH_LEAF,
  2403. &prebuilt->clust_pcur, 0, mtr);
  2404. clust_rec = btr_pcur_get_rec(&prebuilt->clust_pcur);
  2405. prebuilt->clust_pcur.trx_if_known = trx;
  2406. /* Note: only if the search ends up on a non-infimum record is the
  2407. low_match value the real match to the search tuple */
  2408. if (!page_rec_is_user_rec(clust_rec)
  2409. || btr_pcur_get_low_match(&prebuilt->clust_pcur)
  2410. < dict_index_get_n_unique(clust_index)) {
  2411. /* In a rare case it is possible that no clust rec is found
  2412. for a delete-marked secondary index record: if in row0umod.cc
  2413. in row_undo_mod_remove_clust_low() we have already removed
  2414. the clust rec, while purge is still cleaning and removing
  2415. secondary index records associated with earlier versions of
  2416. the clustered index record. In that case we know that the
  2417. clustered index record did not exist in the read view of
  2418. trx. */
  2419. if (!rec_get_deleted_flag(rec,
  2420. dict_table_is_comp(sec_index->table))
  2421. || prebuilt->select_lock_type != LOCK_NONE) {
  2422. ut_print_timestamp(stderr);
  2423. fputs(" InnoDB: error clustered record"
  2424. " for sec rec not found\n"
  2425. "InnoDB: ", stderr);
  2426. dict_index_name_print(stderr, trx, sec_index);
  2427. fputs("\n"
  2428. "InnoDB: sec index record ", stderr);
  2429. rec_print(stderr, rec, sec_index);
  2430. fputs("\n"
  2431. "InnoDB: clust index record ", stderr);
  2432. rec_print(stderr, clust_rec, clust_index);
  2433. putc('\n', stderr);
  2434. trx_print(stderr, trx, 600);
  2435. fputs("\n"
  2436. "InnoDB: Submit a detailed bug report"
  2437. " to http://bugs.mysql.com\n", stderr);
  2438. ut_ad(0);
  2439. }
  2440. clust_rec = NULL;
  2441. err = DB_SUCCESS;
  2442. goto func_exit;
  2443. }
  2444. *offsets = rec_get_offsets(clust_rec, clust_index, *offsets,
  2445. ULINT_UNDEFINED, offset_heap);
  2446. if (prebuilt->select_lock_type != LOCK_NONE) {
  2447. /* Try to place a lock on the index record; we are searching
  2448. the clust rec with a unique condition, hence
  2449. we set a LOCK_REC_NOT_GAP type lock */
  2450. err = lock_clust_rec_read_check_and_lock(
  2451. 0, btr_pcur_get_block(&prebuilt->clust_pcur),
  2452. clust_rec, clust_index, *offsets,
  2453. static_cast<enum lock_mode>(prebuilt->select_lock_type),
  2454. LOCK_REC_NOT_GAP,
  2455. thr);
  2456. switch (err) {
  2457. case DB_SUCCESS:
  2458. case DB_SUCCESS_LOCKED_REC:
  2459. break;
  2460. default:
  2461. goto err_exit;
  2462. }
  2463. } else {
  2464. /* This is a non-locking consistent read: if necessary, fetch
  2465. a previous version of the record */
  2466. old_vers = NULL;
  2467. /* If the isolation level allows reading of uncommitted data,
  2468. then we never look for an earlier version */
  2469. if (trx->isolation_level > TRX_ISO_READ_UNCOMMITTED
  2470. && !lock_clust_rec_cons_read_sees(
  2471. clust_rec, clust_index, *offsets,
  2472. trx->read_view)) {
  2473. /* The following call returns 'offsets' associated with
  2474. 'old_vers' */
  2475. err = row_sel_build_prev_vers_for_mysql(
  2476. trx->read_view, clust_index, prebuilt,
  2477. clust_rec, offsets, offset_heap, &old_vers,
  2478. mtr);
  2479. if (err != DB_SUCCESS || old_vers == NULL) {
  2480. goto err_exit;
  2481. }
  2482. clust_rec = old_vers;
  2483. }
  2484. /* If we had to go to an earlier version of row or the
  2485. secondary index record is delete marked, then it may be that
  2486. the secondary index record corresponding to clust_rec
  2487. (or old_vers) is not rec; in that case we must ignore
  2488. such row because in our snapshot rec would not have existed.
  2489. Remember that from rec we cannot see directly which transaction
  2490. id corresponds to it: we have to go to the clustered index
  2491. record. A query where we want to fetch all rows where
  2492. the secondary index value is in some interval would return
  2493. a wrong result if we would not drop rows which we come to
  2494. visit through secondary index records that would not really
  2495. exist in our snapshot. */
  2496. if (clust_rec
  2497. && (old_vers
  2498. || trx->isolation_level <= TRX_ISO_READ_UNCOMMITTED
  2499. || rec_get_deleted_flag(rec, dict_table_is_comp(
  2500. sec_index->table)))
  2501. && !row_sel_sec_rec_is_for_clust_rec(
  2502. rec, sec_index, clust_rec, clust_index)) {
  2503. clust_rec = NULL;
  2504. #ifdef UNIV_SEARCH_DEBUG
  2505. } else {
  2506. ut_a(clust_rec == NULL
  2507. || row_sel_sec_rec_is_for_clust_rec(
  2508. rec, sec_index, clust_rec, clust_index));
  2509. #endif
  2510. }
  2511. err = DB_SUCCESS;
  2512. }
  2513. func_exit:
  2514. *out_rec = clust_rec;
  2515. /* Store the current position if select_lock_type is not
  2516. LOCK_NONE or if we are scanning using InnoDB APIs */
  2517. if (prebuilt->select_lock_type != LOCK_NONE
  2518. || prebuilt->innodb_api) {
  2519. /* We may use the cursor in update or in unlock_row():
  2520. store its position */
  2521. btr_pcur_store_position(&prebuilt->clust_pcur, mtr);
  2522. }
  2523. err_exit:
  2524. return(err);
  2525. }
  2526. /********************************************************************//**
  2527. Restores cursor position after it has been stored. We have to take into
  2528. account that the record cursor was positioned on may have been deleted.
  2529. Then we may have to move the cursor one step up or down.
  2530. @return TRUE if we may need to process the record the cursor is now
  2531. positioned on (i.e. we should not go to the next record yet) */
  2532. static
  2533. ibool
  2534. sel_restore_position_for_mysql(
  2535. /*===========================*/
  2536. ibool* same_user_rec, /*!< out: TRUE if we were able to restore
  2537. the cursor on a user record with the
  2538. same ordering prefix in in the
  2539. B-tree index */
  2540. ulint latch_mode, /*!< in: latch mode wished in
  2541. restoration */
  2542. btr_pcur_t* pcur, /*!< in: cursor whose position
  2543. has been stored */
  2544. ibool moves_up, /*!< in: TRUE if the cursor moves up
  2545. in the index */
  2546. mtr_t* mtr) /*!< in: mtr; CAUTION: may commit
  2547. mtr temporarily! */
  2548. {
  2549. ibool success;
  2550. success = btr_pcur_restore_position(latch_mode, pcur, mtr);
  2551. *same_user_rec = success;
  2552. ut_ad(!success || pcur->rel_pos == BTR_PCUR_ON);
  2553. #ifdef UNIV_DEBUG
  2554. if (pcur->pos_state == BTR_PCUR_IS_POSITIONED_OPTIMISTIC) {
  2555. ut_ad(pcur->rel_pos == BTR_PCUR_BEFORE
  2556. || pcur->rel_pos == BTR_PCUR_AFTER);
  2557. } else {
  2558. ut_ad(pcur->pos_state == BTR_PCUR_IS_POSITIONED);
  2559. ut_ad((pcur->rel_pos == BTR_PCUR_ON)
  2560. == btr_pcur_is_on_user_rec(pcur));
  2561. }
  2562. #endif
  2563. /* The position may need be adjusted for rel_pos and moves_up. */
  2564. switch (pcur->rel_pos) {
  2565. case BTR_PCUR_ON:
  2566. if (!success && moves_up) {
  2567. next:
  2568. btr_pcur_move_to_next(pcur, mtr);
  2569. return(TRUE);
  2570. }
  2571. return(!success);
  2572. case BTR_PCUR_AFTER_LAST_IN_TREE:
  2573. case BTR_PCUR_BEFORE_FIRST_IN_TREE:
  2574. return(TRUE);
  2575. case BTR_PCUR_AFTER:
  2576. /* positioned to record after pcur->old_rec. */
  2577. pcur->pos_state = BTR_PCUR_IS_POSITIONED;
  2578. prev:
  2579. if (btr_pcur_is_on_user_rec(pcur) && !moves_up) {
  2580. btr_pcur_move_to_prev(pcur, mtr);
  2581. }
  2582. return(TRUE);
  2583. case BTR_PCUR_BEFORE:
  2584. /* For non optimistic restoration:
  2585. The position is now set to the record before pcur->old_rec.
  2586. For optimistic restoration:
  2587. The position also needs to take the previous search_mode into
  2588. consideration. */
  2589. switch (pcur->pos_state) {
  2590. case BTR_PCUR_IS_POSITIONED_OPTIMISTIC:
  2591. pcur->pos_state = BTR_PCUR_IS_POSITIONED;
  2592. if (pcur->search_mode == PAGE_CUR_GE) {
  2593. /* Positioned during Greater or Equal search
  2594. with BTR_PCUR_BEFORE. Optimistic restore to
  2595. the same record. If scanning for lower then
  2596. we must move to previous record.
  2597. This can happen with:
  2598. HANDLER READ idx a = (const);
  2599. HANDLER READ idx PREV; */
  2600. goto prev;
  2601. }
  2602. return(TRUE);
  2603. case BTR_PCUR_IS_POSITIONED:
  2604. if (moves_up && btr_pcur_is_on_user_rec(pcur)) {
  2605. goto next;
  2606. }
  2607. return(TRUE);
  2608. case BTR_PCUR_WAS_POSITIONED:
  2609. case BTR_PCUR_NOT_POSITIONED:
  2610. break;
  2611. }
  2612. }
  2613. ut_ad(0);
  2614. return(TRUE);
  2615. }
  2616. /********************************************************************//**
  2617. Copies a cached field for MySQL from the fetch cache. */
  2618. static
  2619. void
  2620. row_sel_copy_cached_field_for_mysql(
  2621. /*================================*/
  2622. byte* buf, /*!< in/out: row buffer */
  2623. const byte* cache, /*!< in: cached row */
  2624. const mysql_row_templ_t*templ) /*!< in: column template */
  2625. {
  2626. ulint len;
  2627. buf += templ->mysql_col_offset;
  2628. cache += templ->mysql_col_offset;
  2629. UNIV_MEM_ASSERT_W(buf, templ->mysql_col_len);
  2630. if (templ->mysql_type == DATA_MYSQL_TRUE_VARCHAR
  2631. && templ->type != DATA_INT) {
  2632. /* Check for != DATA_INT to make sure we do
  2633. not treat MySQL ENUM or SET as a true VARCHAR!
  2634. Find the actual length of the true VARCHAR field. */
  2635. row_mysql_read_true_varchar(
  2636. &len, cache, templ->mysql_length_bytes);
  2637. len += templ->mysql_length_bytes;
  2638. UNIV_MEM_INVALID(buf, templ->mysql_col_len);
  2639. } else {
  2640. len = templ->mysql_col_len;
  2641. }
  2642. ut_memcpy(buf, cache, len);
  2643. }
  2644. /********************************************************************//**
  2645. Pops a cached row for MySQL from the fetch cache. */
  2646. UNIV_INLINE
  2647. void
  2648. row_sel_dequeue_cached_row_for_mysql(
  2649. /*=================================*/
  2650. byte* buf, /*!< in/out: buffer where to copy the
  2651. row */
  2652. row_prebuilt_t* prebuilt) /*!< in: prebuilt struct */
  2653. {
  2654. ulint i;
  2655. const mysql_row_templ_t*templ;
  2656. const byte* cached_rec;
  2657. ut_ad(prebuilt->n_fetch_cached > 0);
  2658. ut_ad(prebuilt->mysql_prefix_len <= prebuilt->mysql_row_len);
  2659. UNIV_MEM_ASSERT_W(buf, prebuilt->mysql_row_len);
  2660. cached_rec = prebuilt->fetch_cache[prebuilt->fetch_cache_first];
  2661. if (UNIV_UNLIKELY(prebuilt->keep_other_fields_on_keyread)) {
  2662. /* Copy cache record field by field, don't touch fields that
  2663. are not covered by current key */
  2664. for (i = 0; i < prebuilt->n_template; i++) {
  2665. templ = prebuilt->mysql_template + i;
  2666. row_sel_copy_cached_field_for_mysql(
  2667. buf, cached_rec, templ);
  2668. /* Copy NULL bit of the current field from cached_rec
  2669. to buf */
  2670. if (templ->mysql_null_bit_mask) {
  2671. buf[templ->mysql_null_byte_offset]
  2672. ^= (buf[templ->mysql_null_byte_offset]
  2673. ^ cached_rec[templ->mysql_null_byte_offset])
  2674. & (byte) templ->mysql_null_bit_mask;
  2675. }
  2676. }
  2677. } else if (prebuilt->mysql_prefix_len > 63) {
  2678. /* The record is long. Copy it field by field, in case
  2679. there are some long VARCHAR column of which only a
  2680. small length is being used. */
  2681. UNIV_MEM_INVALID(buf, prebuilt->mysql_prefix_len);
  2682. /* First copy the NULL bits. */
  2683. ut_memcpy(buf, cached_rec, prebuilt->null_bitmap_len);
  2684. /* Then copy the requested fields. */
  2685. for (i = 0; i < prebuilt->n_template; i++) {
  2686. row_sel_copy_cached_field_for_mysql(
  2687. buf, cached_rec, prebuilt->mysql_template + i);
  2688. }
  2689. } else {
  2690. ut_memcpy(buf, cached_rec, prebuilt->mysql_prefix_len);
  2691. }
  2692. prebuilt->n_fetch_cached--;
  2693. prebuilt->fetch_cache_first++;
  2694. if (prebuilt->n_fetch_cached == 0) {
  2695. prebuilt->fetch_cache_first = 0;
  2696. }
  2697. }
  2698. /********************************************************************//**
  2699. Initialise the prefetch cache. */
  2700. UNIV_INLINE
  2701. void
  2702. row_sel_prefetch_cache_init(
  2703. /*========================*/
  2704. row_prebuilt_t* prebuilt) /*!< in/out: prebuilt struct */
  2705. {
  2706. ulint i;
  2707. ulint sz;
  2708. byte* ptr;
  2709. /* Reserve space for the magic number. */
  2710. sz = UT_ARR_SIZE(prebuilt->fetch_cache) * (prebuilt->mysql_row_len + 8);
  2711. ptr = static_cast<byte*>(mem_alloc(sz));
  2712. for (i = 0; i < UT_ARR_SIZE(prebuilt->fetch_cache); i++) {
  2713. /* A user has reported memory corruption in these
  2714. buffers in Linux. Put magic numbers there to help
  2715. to track a possible bug. */
  2716. mach_write_to_4(ptr, ROW_PREBUILT_FETCH_MAGIC_N);
  2717. ptr += 4;
  2718. prebuilt->fetch_cache[i] = ptr;
  2719. ptr += prebuilt->mysql_row_len;
  2720. mach_write_to_4(ptr, ROW_PREBUILT_FETCH_MAGIC_N);
  2721. ptr += 4;
  2722. }
  2723. }
  2724. /********************************************************************//**
  2725. Get the last fetch cache buffer from the queue.
  2726. @return pointer to buffer. */
  2727. UNIV_INLINE
  2728. byte*
  2729. row_sel_fetch_last_buf(
  2730. /*===================*/
  2731. row_prebuilt_t* prebuilt) /*!< in/out: prebuilt struct */
  2732. {
  2733. ut_ad(!prebuilt->templ_contains_blob);
  2734. ut_ad(prebuilt->n_fetch_cached < MYSQL_FETCH_CACHE_SIZE);
  2735. if (prebuilt->fetch_cache[0] == NULL) {
  2736. /* Allocate memory for the fetch cache */
  2737. ut_ad(prebuilt->n_fetch_cached == 0);
  2738. row_sel_prefetch_cache_init(prebuilt);
  2739. }
  2740. ut_ad(prebuilt->fetch_cache_first == 0);
  2741. UNIV_MEM_INVALID(prebuilt->fetch_cache[prebuilt->n_fetch_cached],
  2742. prebuilt->mysql_row_len);
  2743. return(prebuilt->fetch_cache[prebuilt->n_fetch_cached]);
  2744. }
  2745. /********************************************************************//**
  2746. Pushes a row for MySQL to the fetch cache. */
  2747. UNIV_INLINE
  2748. void
  2749. row_sel_enqueue_cache_row_for_mysql(
  2750. /*================================*/
  2751. byte* mysql_rec, /*!< in/out: MySQL record */
  2752. row_prebuilt_t* prebuilt) /*!< in/out: prebuilt struct */
  2753. {
  2754. /* For non ICP code path the row should already exist in the
  2755. next fetch cache slot. */
  2756. if (prebuilt->idx_cond != NULL) {
  2757. byte* dest = row_sel_fetch_last_buf(prebuilt);
  2758. ut_memcpy(dest, mysql_rec, prebuilt->mysql_row_len);
  2759. }
  2760. ++prebuilt->n_fetch_cached;
  2761. }
  2762. /*********************************************************************//**
  2763. Tries to do a shortcut to fetch a clustered index record with a unique key,
  2764. using the hash index if possible (not always). We assume that the search
  2765. mode is PAGE_CUR_GE, it is a consistent read, there is a read view in trx,
  2766. btr search latch has been locked in S-mode if AHI is enabled.
  2767. @return SEL_FOUND, SEL_EXHAUSTED, SEL_RETRY */
  2768. static
  2769. ulint
  2770. row_sel_try_search_shortcut_for_mysql(
  2771. /*==================================*/
  2772. const rec_t** out_rec,/*!< out: record if found */
  2773. row_prebuilt_t* prebuilt,/*!< in: prebuilt struct */
  2774. ulint** offsets,/*!< in/out: for rec_get_offsets(*out_rec) */
  2775. mem_heap_t** heap, /*!< in/out: heap for rec_get_offsets() */
  2776. mtr_t* mtr) /*!< in: started mtr */
  2777. {
  2778. dict_index_t* index = prebuilt->index;
  2779. const dtuple_t* search_tuple = prebuilt->search_tuple;
  2780. btr_pcur_t* pcur = &prebuilt->pcur;
  2781. trx_t* trx = prebuilt->trx;
  2782. const rec_t* rec;
  2783. ut_ad(dict_index_is_clust(index));
  2784. ut_ad(!prebuilt->templ_contains_blob);
  2785. #ifndef UNIV_SEARCH_DEBUG
  2786. ut_ad(trx->has_search_latch);
  2787. btr_pcur_open_with_no_init(index, search_tuple, PAGE_CUR_GE,
  2788. BTR_SEARCH_LEAF, pcur,
  2789. RW_S_LATCH,
  2790. mtr);
  2791. #else /* UNIV_SEARCH_DEBUG */
  2792. btr_pcur_open_with_no_init(index, search_tuple, PAGE_CUR_GE,
  2793. BTR_SEARCH_LEAF, pcur,
  2794. 0,
  2795. mtr);
  2796. #endif /* UNIV_SEARCH_DEBUG */
  2797. rec = btr_pcur_get_rec(pcur);
  2798. if (!page_rec_is_user_rec(rec)) {
  2799. return(SEL_RETRY);
  2800. }
  2801. /* As the cursor is now placed on a user record after a search with
  2802. the mode PAGE_CUR_GE, the up_match field in the cursor tells how many
  2803. fields in the user record matched to the search tuple */
  2804. if (btr_pcur_get_up_match(pcur) < dtuple_get_n_fields(search_tuple)) {
  2805. return(SEL_EXHAUSTED);
  2806. }
  2807. /* This is a non-locking consistent read: if necessary, fetch
  2808. a previous version of the record */
  2809. *offsets = rec_get_offsets(rec, index, *offsets,
  2810. ULINT_UNDEFINED, heap);
  2811. if (!lock_clust_rec_cons_read_sees(rec, index,
  2812. *offsets, trx->read_view)) {
  2813. return(SEL_RETRY);
  2814. }
  2815. if (rec_get_deleted_flag(rec, dict_table_is_comp(index->table))) {
  2816. return(SEL_EXHAUSTED);
  2817. }
  2818. *out_rec = rec;
  2819. return(SEL_FOUND);
  2820. }
  2821. /*********************************************************************//**
  2822. Check a pushed-down index condition.
  2823. @return ICP_NO_MATCH, ICP_MATCH, or ICP_OUT_OF_RANGE */
  2824. static
  2825. enum icp_result
  2826. row_search_idx_cond_check(
  2827. /*======================*/
  2828. byte* mysql_rec, /*!< out: record
  2829. in MySQL format (invalid unless
  2830. prebuilt->idx_cond!=NULL and
  2831. we return ICP_MATCH) */
  2832. row_prebuilt_t* prebuilt, /*!< in/out: prebuilt struct
  2833. for the table handle */
  2834. const rec_t* rec, /*!< in: InnoDB record */
  2835. const ulint* offsets) /*!< in: rec_get_offsets() */
  2836. {
  2837. enum icp_result result;
  2838. ulint i;
  2839. ut_ad(rec_offs_validate(rec, prebuilt->index, offsets));
  2840. if (!prebuilt->idx_cond) {
  2841. return(ICP_MATCH);
  2842. }
  2843. MONITOR_INC(MONITOR_ICP_ATTEMPTS);
  2844. /* Convert to MySQL format those fields that are needed for
  2845. evaluating the index condition. */
  2846. if (UNIV_LIKELY_NULL(prebuilt->blob_heap)) {
  2847. mem_heap_empty(prebuilt->blob_heap);
  2848. }
  2849. for (i = 0; i < prebuilt->idx_cond_n_cols; i++) {
  2850. const mysql_row_templ_t*templ = &prebuilt->mysql_template[i];
  2851. if (!row_sel_store_mysql_field(mysql_rec, prebuilt,
  2852. rec, prebuilt->index, offsets,
  2853. templ->icp_rec_field_no,
  2854. templ)) {
  2855. return(ICP_NO_MATCH);
  2856. }
  2857. }
  2858. /* We assume that the index conditions on
  2859. case-insensitive columns are case-insensitive. The
  2860. case of such columns may be wrong in a secondary
  2861. index, if the case of the column has been updated in
  2862. the past, or a record has been deleted and a record
  2863. inserted in a different case. */
  2864. result = innobase_index_cond(prebuilt->idx_cond);
  2865. switch (result) {
  2866. case ICP_MATCH:
  2867. /* Convert the remaining fields to MySQL format.
  2868. If this is a secondary index record, we must defer
  2869. this until we have fetched the clustered index record. */
  2870. if (!prebuilt->need_to_access_clustered
  2871. || dict_index_is_clust(prebuilt->index)) {
  2872. if (!row_sel_store_mysql_rec(
  2873. mysql_rec, prebuilt, rec, FALSE,
  2874. prebuilt->index, offsets)) {
  2875. ut_ad(dict_index_is_clust(prebuilt->index));
  2876. return(ICP_NO_MATCH);
  2877. }
  2878. }
  2879. MONITOR_INC(MONITOR_ICP_MATCH);
  2880. return(result);
  2881. case ICP_NO_MATCH:
  2882. MONITOR_INC(MONITOR_ICP_NO_MATCH);
  2883. return(result);
  2884. case ICP_OUT_OF_RANGE:
  2885. MONITOR_INC(MONITOR_ICP_OUT_OF_RANGE);
  2886. return(result);
  2887. case ICP_ERROR:
  2888. case ICP_ABORTED_BY_USER:
  2889. return(result);
  2890. }
  2891. ut_error;
  2892. return(result);
  2893. }
  2894. /********************************************************************//**
  2895. Searches for rows in the database. This is used in the interface to
  2896. MySQL. This function opens a cursor, and also implements fetch next
  2897. and fetch prev. NOTE that if we do a search with a full key value
  2898. from a unique index (ROW_SEL_EXACT), then we will not store the cursor
  2899. position and fetch next or fetch prev must not be tried to the cursor!
  2900. @return DB_SUCCESS, DB_RECORD_NOT_FOUND, DB_END_OF_INDEX, DB_DEADLOCK,
  2901. DB_LOCK_TABLE_FULL, DB_CORRUPTION, DB_SEARCH_ABORTED_BY_USER or
  2902. DB_TOO_BIG_RECORD */
  2903. UNIV_INTERN
  2904. dberr_t
  2905. row_search_for_mysql(
  2906. /*=================*/
  2907. byte* buf, /*!< in/out: buffer for the fetched
  2908. row in the MySQL format */
  2909. ulint mode, /*!< in: search mode PAGE_CUR_L, ... */
  2910. row_prebuilt_t* prebuilt, /*!< in: prebuilt struct for the
  2911. table handle; this contains the info
  2912. of search_tuple, index; if search
  2913. tuple contains 0 fields then we
  2914. position the cursor at the start or
  2915. the end of the index, depending on
  2916. 'mode' */
  2917. ulint match_mode, /*!< in: 0 or ROW_SEL_EXACT or
  2918. ROW_SEL_EXACT_PREFIX */
  2919. ulint direction) /*!< in: 0 or ROW_SEL_NEXT or
  2920. ROW_SEL_PREV; NOTE: if this is != 0,
  2921. then prebuilt must have a pcur
  2922. with stored position! In opening of a
  2923. cursor 'direction' should be 0. */
  2924. {
  2925. dict_index_t* index = prebuilt->index;
  2926. ibool comp = dict_table_is_comp(index->table);
  2927. const dtuple_t* search_tuple = prebuilt->search_tuple;
  2928. btr_pcur_t* pcur = &prebuilt->pcur;
  2929. trx_t* trx = prebuilt->trx;
  2930. dict_index_t* clust_index;
  2931. que_thr_t* thr;
  2932. const rec_t* rec;
  2933. const rec_t* result_rec = NULL;
  2934. const rec_t* clust_rec;
  2935. dberr_t err = DB_SUCCESS;
  2936. ibool unique_search = FALSE;
  2937. ibool mtr_has_extra_clust_latch = FALSE;
  2938. ibool moves_up = FALSE;
  2939. ibool set_also_gap_locks = TRUE;
  2940. /* if the query is a plain locking SELECT, and the isolation level
  2941. is <= TRX_ISO_READ_COMMITTED, then this is set to FALSE */
  2942. ibool did_semi_consistent_read = FALSE;
  2943. /* if the returned record was locked and we did a semi-consistent
  2944. read (fetch the newest committed version), then this is set to
  2945. TRUE */
  2946. #ifdef UNIV_SEARCH_DEBUG
  2947. ulint cnt = 0;
  2948. #endif /* UNIV_SEARCH_DEBUG */
  2949. ulint next_offs;
  2950. ibool same_user_rec;
  2951. mtr_t mtr;
  2952. mem_heap_t* heap = NULL;
  2953. ulint offsets_[REC_OFFS_NORMAL_SIZE];
  2954. ulint* offsets = offsets_;
  2955. ibool table_lock_waited = FALSE;
  2956. byte* next_buf = 0;
  2957. ibool use_clustered_index = FALSE;
  2958. rec_offs_init(offsets_);
  2959. ut_ad(index && pcur && search_tuple);
  2960. /* We don't support FTS queries from the HANDLER interfaces, because
  2961. we implemented FTS as reversed inverted index with auxiliary tables.
  2962. So anything related to traditional index query would not apply to
  2963. it. */
  2964. if (index->type & DICT_FTS) {
  2965. return(DB_END_OF_INDEX);
  2966. }
  2967. ut_ad(!trx->has_search_latch);
  2968. #ifdef UNIV_SYNC_DEBUG
  2969. ut_ad(!btr_search_own_any());
  2970. ut_ad(!sync_thread_levels_nonempty_trx(trx->has_search_latch));
  2971. #endif /* UNIV_SYNC_DEBUG */
  2972. if (dict_table_is_discarded(prebuilt->table)) {
  2973. return(DB_TABLESPACE_DELETED);
  2974. } else if (prebuilt->table->ibd_file_missing) {
  2975. return(DB_TABLESPACE_NOT_FOUND);
  2976. } else if (!prebuilt->index_usable) {
  2977. return(DB_MISSING_HISTORY);
  2978. } else if (dict_index_is_corrupted(index)) {
  2979. return(DB_CORRUPTION);
  2980. } else if (prebuilt->magic_n != ROW_PREBUILT_ALLOCATED) {
  2981. fprintf(stderr,
  2982. "InnoDB: Error: trying to free a corrupt\n"
  2983. "InnoDB: table handle. Magic n %lu, table name ",
  2984. (ulong) prebuilt->magic_n);
  2985. ut_print_name(stderr, trx, TRUE, prebuilt->table->name);
  2986. putc('\n', stderr);
  2987. mem_analyze_corruption(prebuilt);
  2988. ut_error;
  2989. }
  2990. /* init null bytes with default values as they might be
  2991. left uninitialized in some cases and these uninited bytes
  2992. might be copied into mysql record buffer that leads to
  2993. valgrind warnings */
  2994. memcpy(buf, prebuilt->default_rec, prebuilt->null_bitmap_len);
  2995. #if 0
  2996. /* August 19, 2005 by Heikki: temporarily disable this error
  2997. print until the cursor lock count is done correctly.
  2998. See bugs #12263 and #12456!*/
  2999. if (trx->n_mysql_tables_in_use == 0
  3000. && UNIV_UNLIKELY(prebuilt->select_lock_type == LOCK_NONE)) {
  3001. /* Note that if MySQL uses an InnoDB temp table that it
  3002. created inside LOCK TABLES, then n_mysql_tables_in_use can
  3003. be zero; in that case select_lock_type is set to LOCK_X in
  3004. ::start_stmt. */
  3005. fputs("InnoDB: Error: MySQL is trying to perform a SELECT\n"
  3006. "InnoDB: but it has not locked"
  3007. " any tables in ::external_lock()!\n",
  3008. stderr);
  3009. trx_print(stderr, trx, 600);
  3010. fputc('\n', stderr);
  3011. }
  3012. #endif
  3013. #if 0
  3014. fprintf(stderr, "Match mode %lu\n search tuple ",
  3015. (ulong) match_mode);
  3016. dtuple_print(search_tuple);
  3017. fprintf(stderr, "N tables locked %lu\n",
  3018. (ulong) trx->mysql_n_tables_locked);
  3019. #endif
  3020. /* Reset the new record lock info if srv_locks_unsafe_for_binlog
  3021. is set or session is using a READ COMMITED isolation level. Then
  3022. we are able to remove the record locks set here on an individual
  3023. row. */
  3024. prebuilt->new_rec_locks = 0;
  3025. /*-------------------------------------------------------------*/
  3026. /* PHASE 1: Try to pop the row from the prefetch cache */
  3027. if (UNIV_UNLIKELY(direction == 0)) {
  3028. trx->op_info = "starting index read";
  3029. prebuilt->n_rows_fetched = 0;
  3030. prebuilt->n_fetch_cached = 0;
  3031. prebuilt->fetch_cache_first = 0;
  3032. if (prebuilt->sel_graph == NULL) {
  3033. /* Build a dummy select query graph */
  3034. row_prebuild_sel_graph(prebuilt);
  3035. }
  3036. } else {
  3037. trx->op_info = "fetching rows";
  3038. if (prebuilt->n_rows_fetched == 0) {
  3039. prebuilt->fetch_direction = direction;
  3040. }
  3041. if (UNIV_UNLIKELY(direction != prebuilt->fetch_direction)) {
  3042. if (UNIV_UNLIKELY(prebuilt->n_fetch_cached > 0)) {
  3043. ut_error;
  3044. /* TODO: scrollable cursor: restore cursor to
  3045. the place of the latest returned row,
  3046. or better: prevent caching for a scroll
  3047. cursor! */
  3048. }
  3049. prebuilt->n_rows_fetched = 0;
  3050. prebuilt->n_fetch_cached = 0;
  3051. prebuilt->fetch_cache_first = 0;
  3052. } else if (UNIV_LIKELY(prebuilt->n_fetch_cached > 0)) {
  3053. row_sel_dequeue_cached_row_for_mysql(buf, prebuilt);
  3054. prebuilt->n_rows_fetched++;
  3055. err = DB_SUCCESS;
  3056. goto func_exit;
  3057. }
  3058. if (prebuilt->fetch_cache_first > 0
  3059. && prebuilt->fetch_cache_first < MYSQL_FETCH_CACHE_SIZE) {
  3060. /* The previous returned row was popped from the fetch
  3061. cache, but the cache was not full at the time of the
  3062. popping: no more rows can exist in the result set */
  3063. err = DB_RECORD_NOT_FOUND;
  3064. goto func_exit;
  3065. }
  3066. prebuilt->n_rows_fetched++;
  3067. if (prebuilt->n_rows_fetched > 1000000000) {
  3068. /* Prevent wrap-over */
  3069. prebuilt->n_rows_fetched = 500000000;
  3070. }
  3071. mode = pcur->search_mode;
  3072. }
  3073. /* In a search where at most one record in the index may match, we
  3074. can use a LOCK_REC_NOT_GAP type record lock when locking a
  3075. non-delete-marked matching record.
  3076. Note that in a unique secondary index there may be different
  3077. delete-marked versions of a record where only the primary key
  3078. values differ: thus in a secondary index we must use next-key
  3079. locks when locking delete-marked records. */
  3080. if (match_mode == ROW_SEL_EXACT
  3081. && dict_index_is_unique(index)
  3082. && dtuple_get_n_fields(search_tuple)
  3083. == dict_index_get_n_unique(index)
  3084. && (dict_index_is_clust(index)
  3085. || !dtuple_contains_null(search_tuple))) {
  3086. /* Note above that a UNIQUE secondary index can contain many
  3087. rows with the same key value if one of the columns is the SQL
  3088. null. A clustered index under MySQL can never contain null
  3089. columns because we demand that all the columns in primary key
  3090. are non-null. */
  3091. unique_search = TRUE;
  3092. /* Even if the condition is unique, MySQL seems to try to
  3093. retrieve also a second row if a primary key contains more than
  3094. 1 column. Return immediately if this is not a HANDLER
  3095. command. */
  3096. if (UNIV_UNLIKELY(direction != 0
  3097. && !prebuilt->used_in_HANDLER)) {
  3098. err = DB_RECORD_NOT_FOUND;
  3099. goto func_exit;
  3100. }
  3101. }
  3102. mtr_start(&mtr);
  3103. /*-------------------------------------------------------------*/
  3104. /* PHASE 2: Try fast adaptive hash index search if possible */
  3105. /* Next test if this is the special case where we can use the fast
  3106. adaptive hash index to try the search. Since we must release the
  3107. search system latch when we retrieve an externally stored field, we
  3108. cannot use the adaptive hash index in a search in the case the row
  3109. may be long and there may be externally stored fields */
  3110. if (UNIV_UNLIKELY(direction == 0)
  3111. && unique_search
  3112. && dict_index_is_clust(index)
  3113. && !prebuilt->templ_contains_blob
  3114. && !prebuilt->used_in_HANDLER
  3115. && (prebuilt->mysql_row_len < UNIV_PAGE_SIZE / 8)
  3116. && !prebuilt->innodb_api) {
  3117. mode = PAGE_CUR_GE;
  3118. if (trx->mysql_n_tables_locked == 0
  3119. && prebuilt->select_lock_type == LOCK_NONE
  3120. && trx->isolation_level > TRX_ISO_READ_UNCOMMITTED
  3121. && trx->read_view) {
  3122. /* This is a SELECT query done as a consistent read,
  3123. and the read view has already been allocated:
  3124. let us try a search shortcut through the hash
  3125. index.
  3126. NOTE that we must also test that
  3127. mysql_n_tables_locked == 0, because this might
  3128. also be INSERT INTO ... SELECT ... or
  3129. CREATE TABLE ... SELECT ... . Our algorithm is
  3130. NOT prepared to inserts interleaved with the SELECT,
  3131. and if we try that, we can deadlock on the adaptive
  3132. hash index semaphore! */
  3133. #ifndef UNIV_SEARCH_DEBUG
  3134. ut_ad(!trx->has_search_latch);
  3135. rw_lock_s_lock(btr_search_get_latch(index));
  3136. trx->has_search_latch = TRUE;
  3137. #endif
  3138. switch (row_sel_try_search_shortcut_for_mysql(
  3139. &rec, prebuilt, &offsets, &heap,
  3140. &mtr)) {
  3141. case SEL_FOUND:
  3142. #ifdef UNIV_SEARCH_DEBUG
  3143. ut_a(0 == cmp_dtuple_rec(search_tuple,
  3144. rec, offsets));
  3145. #endif
  3146. /* At this point, rec is protected by
  3147. a page latch that was acquired by
  3148. row_sel_try_search_shortcut_for_mysql().
  3149. The latch will not be released until
  3150. mtr_commit(&mtr). */
  3151. ut_ad(!rec_get_deleted_flag(rec, comp));
  3152. if (prebuilt->idx_cond) {
  3153. switch (row_search_idx_cond_check(
  3154. buf, prebuilt,
  3155. rec, offsets)) {
  3156. case ICP_NO_MATCH:
  3157. case ICP_OUT_OF_RANGE:
  3158. case ICP_ABORTED_BY_USER:
  3159. case ICP_ERROR:
  3160. goto shortcut_mismatch;
  3161. case ICP_MATCH:
  3162. goto shortcut_match;
  3163. }
  3164. }
  3165. if (!row_sel_store_mysql_rec(
  3166. buf, prebuilt,
  3167. rec, FALSE, index, offsets)) {
  3168. /* Only fresh inserts may contain
  3169. incomplete externally stored
  3170. columns. Pretend that such
  3171. records do not exist. Such
  3172. records may only be accessed
  3173. at the READ UNCOMMITTED
  3174. isolation level or when
  3175. rolling back a recovered
  3176. transaction. Rollback happens
  3177. at a lower level, not here. */
  3178. /* Proceed as in case SEL_RETRY. */
  3179. break;
  3180. }
  3181. shortcut_match:
  3182. mtr_commit(&mtr);
  3183. /* ut_print_name(stderr, index->name);
  3184. fputs(" shortcut\n", stderr); */
  3185. err = DB_SUCCESS;
  3186. goto release_search_latch;
  3187. case SEL_EXHAUSTED:
  3188. shortcut_mismatch:
  3189. mtr_commit(&mtr);
  3190. /* ut_print_name(stderr, index->name);
  3191. fputs(" record not found 2\n", stderr); */
  3192. err = DB_RECORD_NOT_FOUND;
  3193. release_search_latch:
  3194. rw_lock_s_unlock(
  3195. btr_search_get_latch(index));
  3196. trx->has_search_latch = FALSE;
  3197. /* NOTE that we do NOT store the cursor
  3198. position */
  3199. goto func_exit;
  3200. case SEL_RETRY:
  3201. break;
  3202. default:
  3203. ut_ad(0);
  3204. }
  3205. mtr_commit(&mtr);
  3206. mtr_start(&mtr);
  3207. rw_lock_s_unlock(btr_search_get_latch(index));
  3208. trx->has_search_latch = FALSE;
  3209. }
  3210. }
  3211. /*-------------------------------------------------------------*/
  3212. /* PHASE 3: Open or restore index cursor position */
  3213. ut_ad(!trx->has_search_latch);
  3214. #ifdef UNIV_SYNC_DEBUG
  3215. ut_ad(!btr_search_own_any());
  3216. #endif
  3217. /* The state of a running trx can only be changed by the
  3218. thread that is currently serving the transaction. Because we
  3219. are that thread, we can read trx->state without holding any
  3220. mutex. */
  3221. ut_ad(prebuilt->sql_stat_start || trx->state == TRX_STATE_ACTIVE);
  3222. ut_ad(trx->state == TRX_STATE_NOT_STARTED
  3223. || trx->state == TRX_STATE_ACTIVE);
  3224. ut_ad(prebuilt->sql_stat_start
  3225. || prebuilt->select_lock_type != LOCK_NONE
  3226. || trx->read_view);
  3227. trx_start_if_not_started(trx);
  3228. if (trx->isolation_level <= TRX_ISO_READ_COMMITTED
  3229. && prebuilt->select_lock_type != LOCK_NONE
  3230. && trx->mysql_thd != NULL
  3231. && thd_is_select(trx->mysql_thd)) {
  3232. /* It is a plain locking SELECT and the isolation
  3233. level is low: do not lock gaps */
  3234. set_also_gap_locks = FALSE;
  3235. }
  3236. /* Note that if the search mode was GE or G, then the cursor
  3237. naturally moves upward (in fetch next) in alphabetical order,
  3238. otherwise downward */
  3239. if (UNIV_UNLIKELY(direction == 0)) {
  3240. if (mode == PAGE_CUR_GE || mode == PAGE_CUR_G) {
  3241. moves_up = TRUE;
  3242. }
  3243. } else if (direction == ROW_SEL_NEXT) {
  3244. moves_up = TRUE;
  3245. }
  3246. thr = que_fork_get_first_thr(prebuilt->sel_graph);
  3247. que_thr_move_to_run_state_for_mysql(thr, trx);
  3248. clust_index = dict_table_get_first_index(index->table);
  3249. /* Do some start-of-statement preparations */
  3250. if (!prebuilt->sql_stat_start) {
  3251. /* No need to set an intention lock or assign a read view */
  3252. if (UNIV_UNLIKELY
  3253. (trx->read_view == NULL
  3254. && prebuilt->select_lock_type == LOCK_NONE)) {
  3255. fputs("InnoDB: Error: MySQL is trying to"
  3256. " perform a consistent read\n"
  3257. "InnoDB: but the read view is not assigned!\n",
  3258. stderr);
  3259. trx_print(stderr, trx, 600);
  3260. fputc('\n', stderr);
  3261. ut_error;
  3262. }
  3263. } else if (prebuilt->select_lock_type == LOCK_NONE) {
  3264. /* This is a consistent read */
  3265. /* Assign a read view for the query */
  3266. trx_assign_read_view(trx);
  3267. prebuilt->sql_stat_start = FALSE;
  3268. } else {
  3269. wait_table_again:
  3270. err = lock_table(0, index->table,
  3271. prebuilt->select_lock_type == LOCK_S
  3272. ? LOCK_IS : LOCK_IX, thr);
  3273. if (err != DB_SUCCESS) {
  3274. table_lock_waited = TRUE;
  3275. goto lock_table_wait;
  3276. }
  3277. prebuilt->sql_stat_start = FALSE;
  3278. }
  3279. /* Open or restore index cursor position */
  3280. if (UNIV_LIKELY(direction != 0)) {
  3281. ibool need_to_process = sel_restore_position_for_mysql(
  3282. &same_user_rec, BTR_SEARCH_LEAF,
  3283. pcur, moves_up, &mtr);
  3284. if (UNIV_UNLIKELY(need_to_process)) {
  3285. if (UNIV_UNLIKELY(prebuilt->row_read_type
  3286. == ROW_READ_DID_SEMI_CONSISTENT)) {
  3287. /* We did a semi-consistent read,
  3288. but the record was removed in
  3289. the meantime. */
  3290. prebuilt->row_read_type
  3291. = ROW_READ_TRY_SEMI_CONSISTENT;
  3292. }
  3293. } else if (UNIV_LIKELY(prebuilt->row_read_type
  3294. != ROW_READ_DID_SEMI_CONSISTENT)) {
  3295. /* The cursor was positioned on the record
  3296. that we returned previously. If we need
  3297. to repeat a semi-consistent read as a
  3298. pessimistic locking read, the record
  3299. cannot be skipped. */
  3300. goto next_rec;
  3301. }
  3302. } else if (dtuple_get_n_fields(search_tuple) > 0) {
  3303. btr_pcur_open_with_no_init(index, search_tuple, mode,
  3304. BTR_SEARCH_LEAF,
  3305. pcur, 0, &mtr);
  3306. pcur->trx_if_known = trx;
  3307. rec = btr_pcur_get_rec(pcur);
  3308. if (!moves_up
  3309. && !page_rec_is_supremum(rec)
  3310. && set_also_gap_locks
  3311. && !(srv_locks_unsafe_for_binlog
  3312. || trx->isolation_level <= TRX_ISO_READ_COMMITTED)
  3313. && prebuilt->select_lock_type != LOCK_NONE) {
  3314. /* Try to place a gap lock on the next index record
  3315. to prevent phantoms in ORDER BY ... DESC queries */
  3316. const rec_t* next_rec = page_rec_get_next_const(rec);
  3317. offsets = rec_get_offsets(next_rec, index, offsets,
  3318. ULINT_UNDEFINED, &heap);
  3319. err = sel_set_rec_lock(btr_pcur_get_block(pcur),
  3320. next_rec, index, offsets,
  3321. prebuilt->select_lock_type,
  3322. LOCK_GAP, thr);
  3323. switch (err) {
  3324. case DB_SUCCESS_LOCKED_REC:
  3325. err = DB_SUCCESS;
  3326. case DB_SUCCESS:
  3327. break;
  3328. default:
  3329. goto lock_wait_or_error;
  3330. }
  3331. }
  3332. } else if (mode == PAGE_CUR_G || mode == PAGE_CUR_L) {
  3333. btr_pcur_open_at_index_side(
  3334. mode == PAGE_CUR_G, index, BTR_SEARCH_LEAF,
  3335. pcur, false, 0, &mtr);
  3336. }
  3337. rec_loop:
  3338. DEBUG_SYNC_C("row_search_rec_loop");
  3339. if (trx_is_interrupted(trx)) {
  3340. btr_pcur_store_position(pcur, &mtr);
  3341. err = DB_INTERRUPTED;
  3342. goto normal_return;
  3343. }
  3344. /*-------------------------------------------------------------*/
  3345. /* PHASE 4: Look for matching records in a loop */
  3346. rec = btr_pcur_get_rec(pcur);
  3347. SRV_CORRUPT_TABLE_CHECK(rec,
  3348. {
  3349. err = DB_CORRUPTION;
  3350. goto lock_wait_or_error;
  3351. });
  3352. ut_ad(!!page_rec_is_comp(rec) == comp);
  3353. #ifdef UNIV_SEARCH_DEBUG
  3354. /*
  3355. fputs("Using ", stderr);
  3356. dict_index_name_print(stderr, trx, index);
  3357. fprintf(stderr, " cnt %lu ; Page no %lu\n", cnt,
  3358. page_get_page_no(page_align(rec)));
  3359. rec_print(stderr, rec, index);
  3360. printf("delete-mark: %lu\n",
  3361. rec_get_deleted_flag(rec, page_rec_is_comp(rec)));
  3362. */
  3363. #endif /* UNIV_SEARCH_DEBUG */
  3364. if (page_rec_is_infimum(rec)) {
  3365. /* The infimum record on a page cannot be in the result set,
  3366. and neither can a record lock be placed on it: we skip such
  3367. a record. */
  3368. goto next_rec;
  3369. }
  3370. if (page_rec_is_supremum(rec)) {
  3371. if (set_also_gap_locks
  3372. && !(srv_locks_unsafe_for_binlog
  3373. || trx->isolation_level <= TRX_ISO_READ_COMMITTED)
  3374. && prebuilt->select_lock_type != LOCK_NONE) {
  3375. /* Try to place a lock on the index record */
  3376. /* If innodb_locks_unsafe_for_binlog option is used
  3377. or this session is using a READ COMMITTED or lower isolation
  3378. level we do not lock gaps. Supremum record is really
  3379. a gap and therefore we do not set locks there. */
  3380. offsets = rec_get_offsets(rec, index, offsets,
  3381. ULINT_UNDEFINED, &heap);
  3382. err = sel_set_rec_lock(btr_pcur_get_block(pcur),
  3383. rec, index, offsets,
  3384. prebuilt->select_lock_type,
  3385. LOCK_ORDINARY, thr);
  3386. switch (err) {
  3387. case DB_SUCCESS_LOCKED_REC:
  3388. err = DB_SUCCESS;
  3389. case DB_SUCCESS:
  3390. break;
  3391. default:
  3392. goto lock_wait_or_error;
  3393. }
  3394. }
  3395. /* A page supremum record cannot be in the result set: skip
  3396. it now that we have placed a possible lock on it */
  3397. goto next_rec;
  3398. }
  3399. /*-------------------------------------------------------------*/
  3400. /* Do sanity checks in case our cursor has bumped into page
  3401. corruption */
  3402. if (comp) {
  3403. next_offs = rec_get_next_offs(rec, TRUE);
  3404. if (UNIV_UNLIKELY(next_offs < PAGE_NEW_SUPREMUM)) {
  3405. goto wrong_offs;
  3406. }
  3407. } else {
  3408. next_offs = rec_get_next_offs(rec, FALSE);
  3409. if (UNIV_UNLIKELY(next_offs < PAGE_OLD_SUPREMUM)) {
  3410. goto wrong_offs;
  3411. }
  3412. }
  3413. if (UNIV_UNLIKELY(next_offs >= UNIV_PAGE_SIZE - PAGE_DIR)) {
  3414. wrong_offs:
  3415. if (srv_pass_corrupt_table && index->table->space != 0 &&
  3416. index->table->space < SRV_LOG_SPACE_FIRST_ID) {
  3417. index->table->is_corrupt = TRUE;
  3418. fil_space_set_corrupt(index->table->space);
  3419. }
  3420. if ((srv_force_recovery == 0 || moves_up == FALSE)
  3421. && srv_pass_corrupt_table <= 1) {
  3422. ut_print_timestamp(stderr);
  3423. buf_page_print(page_align(rec), 0,
  3424. BUF_PAGE_PRINT_NO_CRASH);
  3425. fprintf(stderr,
  3426. "\nInnoDB: rec address %p,"
  3427. " buf block fix count %lu\n",
  3428. (void*) rec, (ulong)
  3429. btr_cur_get_block(btr_pcur_get_btr_cur(pcur))
  3430. ->page.buf_fix_count);
  3431. fprintf(stderr,
  3432. "InnoDB: Index corruption: rec offs %lu"
  3433. " next offs %lu, page no %lu,\n"
  3434. "InnoDB: ",
  3435. (ulong) page_offset(rec),
  3436. (ulong) next_offs,
  3437. (ulong) page_get_page_no(page_align(rec)));
  3438. dict_index_name_print(stderr, trx, index);
  3439. fputs(". Run CHECK TABLE. You may need to\n"
  3440. "InnoDB: restore from a backup, or"
  3441. " dump + drop + reimport the table.\n",
  3442. stderr);
  3443. ut_ad(0);
  3444. err = DB_CORRUPTION;
  3445. goto lock_wait_or_error;
  3446. } else {
  3447. /* The user may be dumping a corrupt table. Jump
  3448. over the corruption to recover as much as possible. */
  3449. fprintf(stderr,
  3450. "InnoDB: Index corruption: rec offs %lu"
  3451. " next offs %lu, page no %lu,\n"
  3452. "InnoDB: ",
  3453. (ulong) page_offset(rec),
  3454. (ulong) next_offs,
  3455. (ulong) page_get_page_no(page_align(rec)));
  3456. dict_index_name_print(stderr, trx, index);
  3457. fputs(". We try to skip the rest of the page.\n",
  3458. stderr);
  3459. btr_pcur_move_to_last_on_page(pcur, &mtr);
  3460. goto next_rec;
  3461. }
  3462. }
  3463. /*-------------------------------------------------------------*/
  3464. /* Calculate the 'offsets' associated with 'rec' */
  3465. ut_ad(fil_page_get_type(btr_pcur_get_page(pcur)) == FIL_PAGE_INDEX);
  3466. ut_ad(btr_page_get_index_id(btr_pcur_get_page(pcur)) == index->id);
  3467. offsets = rec_get_offsets(rec, index, offsets, ULINT_UNDEFINED, &heap);
  3468. if (UNIV_UNLIKELY(srv_force_recovery > 0
  3469. || (index->table->is_corrupt &&
  3470. srv_pass_corrupt_table == 2))) {
  3471. if (!rec_validate(rec, offsets)
  3472. || !btr_index_rec_validate(rec, index, FALSE)) {
  3473. fprintf(stderr,
  3474. "InnoDB: Index corruption: rec offs %lu"
  3475. " next offs %lu, page no %lu,\n"
  3476. "InnoDB: ",
  3477. (ulong) page_offset(rec),
  3478. (ulong) next_offs,
  3479. (ulong) page_get_page_no(page_align(rec)));
  3480. dict_index_name_print(stderr, trx, index);
  3481. fputs(". We try to skip the record.\n",
  3482. stderr);
  3483. goto next_rec;
  3484. }
  3485. }
  3486. /* Note that we cannot trust the up_match value in the cursor at this
  3487. place because we can arrive here after moving the cursor! Thus
  3488. we have to recompare rec and search_tuple to determine if they
  3489. match enough. */
  3490. if (match_mode == ROW_SEL_EXACT) {
  3491. /* Test if the index record matches completely to search_tuple
  3492. in prebuilt: if not, then we return with DB_RECORD_NOT_FOUND */
  3493. /* fputs("Comparing rec and search tuple\n", stderr); */
  3494. if (0 != cmp_dtuple_rec(search_tuple, rec, offsets)) {
  3495. if (set_also_gap_locks
  3496. && !(srv_locks_unsafe_for_binlog
  3497. || trx->isolation_level
  3498. <= TRX_ISO_READ_COMMITTED)
  3499. && prebuilt->select_lock_type != LOCK_NONE) {
  3500. /* Try to place a gap lock on the index
  3501. record only if innodb_locks_unsafe_for_binlog
  3502. option is not set or this session is not
  3503. using a READ COMMITTED or lower isolation level. */
  3504. err = sel_set_rec_lock(
  3505. btr_pcur_get_block(pcur),
  3506. rec, index, offsets,
  3507. prebuilt->select_lock_type, LOCK_GAP,
  3508. thr);
  3509. switch (err) {
  3510. case DB_SUCCESS_LOCKED_REC:
  3511. case DB_SUCCESS:
  3512. break;
  3513. default:
  3514. goto lock_wait_or_error;
  3515. }
  3516. }
  3517. btr_pcur_store_position(pcur, &mtr);
  3518. /* The found record was not a match, but may be used
  3519. as NEXT record (index_next). Set the relative position
  3520. to BTR_PCUR_BEFORE, to reflect that the position of
  3521. the persistent cursor is before the found/stored row
  3522. (pcur->old_rec). */
  3523. ut_ad(pcur->rel_pos == BTR_PCUR_ON);
  3524. pcur->rel_pos = BTR_PCUR_BEFORE;
  3525. err = DB_RECORD_NOT_FOUND;
  3526. #if 0
  3527. ut_print_name(stderr, trx, FALSE, index->name);
  3528. fputs(" record not found 3\n", stderr);
  3529. #endif
  3530. goto normal_return;
  3531. }
  3532. } else if (match_mode == ROW_SEL_EXACT_PREFIX) {
  3533. if (!cmp_dtuple_is_prefix_of_rec(search_tuple, rec, offsets)) {
  3534. if (set_also_gap_locks
  3535. && !(srv_locks_unsafe_for_binlog
  3536. || trx->isolation_level
  3537. <= TRX_ISO_READ_COMMITTED)
  3538. && prebuilt->select_lock_type != LOCK_NONE) {
  3539. /* Try to place a gap lock on the index
  3540. record only if innodb_locks_unsafe_for_binlog
  3541. option is not set or this session is not
  3542. using a READ COMMITTED or lower isolation level. */
  3543. err = sel_set_rec_lock(
  3544. btr_pcur_get_block(pcur),
  3545. rec, index, offsets,
  3546. prebuilt->select_lock_type, LOCK_GAP,
  3547. thr);
  3548. switch (err) {
  3549. case DB_SUCCESS_LOCKED_REC:
  3550. case DB_SUCCESS:
  3551. break;
  3552. default:
  3553. goto lock_wait_or_error;
  3554. }
  3555. }
  3556. btr_pcur_store_position(pcur, &mtr);
  3557. /* The found record was not a match, but may be used
  3558. as NEXT record (index_next). Set the relative position
  3559. to BTR_PCUR_BEFORE, to reflect that the position of
  3560. the persistent cursor is before the found/stored row
  3561. (pcur->old_rec). */
  3562. ut_ad(pcur->rel_pos == BTR_PCUR_ON);
  3563. pcur->rel_pos = BTR_PCUR_BEFORE;
  3564. err = DB_RECORD_NOT_FOUND;
  3565. #if 0
  3566. ut_print_name(stderr, trx, FALSE, index->name);
  3567. fputs(" record not found 4\n", stderr);
  3568. #endif
  3569. goto normal_return;
  3570. }
  3571. }
  3572. /* We are ready to look at a possible new index entry in the result
  3573. set: the cursor is now placed on a user record */
  3574. if (prebuilt->select_lock_type != LOCK_NONE) {
  3575. /* Try to place a lock on the index record; note that delete
  3576. marked records are a special case in a unique search. If there
  3577. is a non-delete marked record, then it is enough to lock its
  3578. existence with LOCK_REC_NOT_GAP. */
  3579. /* If innodb_locks_unsafe_for_binlog option is used
  3580. or this session is using a READ COMMITED isolation
  3581. level we lock only the record, i.e., next-key locking is
  3582. not used. */
  3583. ulint lock_type;
  3584. if (!set_also_gap_locks
  3585. || srv_locks_unsafe_for_binlog
  3586. || trx->isolation_level <= TRX_ISO_READ_COMMITTED
  3587. || (unique_search && !rec_get_deleted_flag(rec, comp))) {
  3588. goto no_gap_lock;
  3589. } else {
  3590. lock_type = LOCK_ORDINARY;
  3591. }
  3592. /* If we are doing a 'greater or equal than a primary key
  3593. value' search from a clustered index, and we find a record
  3594. that has that exact primary key value, then there is no need
  3595. to lock the gap before the record, because no insert in the
  3596. gap can be in our search range. That is, no phantom row can
  3597. appear that way.
  3598. An example: if col1 is the primary key, the search is WHERE
  3599. col1 >= 100, and we find a record where col1 = 100, then no
  3600. need to lock the gap before that record. */
  3601. if (index == clust_index
  3602. && mode == PAGE_CUR_GE
  3603. && direction == 0
  3604. && dtuple_get_n_fields_cmp(search_tuple)
  3605. == dict_index_get_n_unique(index)
  3606. && 0 == cmp_dtuple_rec(search_tuple, rec, offsets)) {
  3607. no_gap_lock:
  3608. lock_type = LOCK_REC_NOT_GAP;
  3609. }
  3610. err = sel_set_rec_lock(btr_pcur_get_block(pcur),
  3611. rec, index, offsets,
  3612. prebuilt->select_lock_type,
  3613. lock_type, thr);
  3614. switch (err) {
  3615. const rec_t* old_vers;
  3616. case DB_SUCCESS_LOCKED_REC:
  3617. if (srv_locks_unsafe_for_binlog
  3618. || trx->isolation_level
  3619. <= TRX_ISO_READ_COMMITTED) {
  3620. /* Note that a record of
  3621. prebuilt->index was locked. */
  3622. prebuilt->new_rec_locks = 1;
  3623. }
  3624. err = DB_SUCCESS;
  3625. case DB_SUCCESS:
  3626. break;
  3627. case DB_LOCK_WAIT:
  3628. /* Never unlock rows that were part of a conflict. */
  3629. prebuilt->new_rec_locks = 0;
  3630. if (UNIV_LIKELY(prebuilt->row_read_type
  3631. != ROW_READ_TRY_SEMI_CONSISTENT)
  3632. || unique_search
  3633. || index != clust_index) {
  3634. goto lock_wait_or_error;
  3635. }
  3636. /* The following call returns 'offsets'
  3637. associated with 'old_vers' */
  3638. row_sel_build_committed_vers_for_mysql(
  3639. clust_index, prebuilt, rec,
  3640. &offsets, &heap, &old_vers, &mtr);
  3641. /* Check whether it was a deadlock or not, if not
  3642. a deadlock and the transaction had to wait then
  3643. release the lock it is waiting on. */
  3644. err = lock_trx_handle_wait(trx);
  3645. switch (err) {
  3646. case DB_SUCCESS:
  3647. /* The lock was granted while we were
  3648. searching for the last committed version.
  3649. Do a normal locking read. */
  3650. offsets = rec_get_offsets(
  3651. rec, index, offsets, ULINT_UNDEFINED,
  3652. &heap);
  3653. goto locks_ok;
  3654. case DB_DEADLOCK:
  3655. goto lock_wait_or_error;
  3656. case DB_LOCK_WAIT:
  3657. err = DB_SUCCESS;
  3658. break;
  3659. default:
  3660. ut_error;
  3661. }
  3662. if (old_vers == NULL) {
  3663. /* The row was not yet committed */
  3664. goto next_rec;
  3665. }
  3666. did_semi_consistent_read = TRUE;
  3667. rec = old_vers;
  3668. break;
  3669. default:
  3670. goto lock_wait_or_error;
  3671. }
  3672. } else {
  3673. /* This is a non-locking consistent read: if necessary, fetch
  3674. a previous version of the record */
  3675. if (trx->isolation_level == TRX_ISO_READ_UNCOMMITTED) {
  3676. /* Do nothing: we let a non-locking SELECT read the
  3677. latest version of the record */
  3678. } else if (index == clust_index) {
  3679. /* Fetch a previous version of the row if the current
  3680. one is not visible in the snapshot; if we have a very
  3681. high force recovery level set, we try to avoid crashes
  3682. by skipping this lookup */
  3683. if (UNIV_LIKELY(srv_force_recovery < 5)
  3684. && !lock_clust_rec_cons_read_sees(
  3685. rec, index, offsets, trx->read_view)) {
  3686. rec_t* old_vers;
  3687. /* The following call returns 'offsets'
  3688. associated with 'old_vers' */
  3689. err = row_sel_build_prev_vers_for_mysql(
  3690. trx->read_view, clust_index,
  3691. prebuilt, rec, &offsets, &heap,
  3692. &old_vers, &mtr);
  3693. if (err != DB_SUCCESS) {
  3694. goto lock_wait_or_error;
  3695. }
  3696. if (old_vers == NULL) {
  3697. /* The row did not exist yet in
  3698. the read view */
  3699. goto next_rec;
  3700. }
  3701. rec = old_vers;
  3702. }
  3703. } else {
  3704. /* We are looking into a non-clustered index,
  3705. and to get the right version of the record we
  3706. have to look also into the clustered index: this
  3707. is necessary, because we can only get the undo
  3708. information via the clustered index record. */
  3709. ut_ad(!dict_index_is_clust(index));
  3710. if (!lock_sec_rec_cons_read_sees(
  3711. rec, trx->read_view)) {
  3712. /* We should look at the clustered index.
  3713. However, as this is a non-locking read,
  3714. we can skip the clustered index lookup if
  3715. the condition does not match the secondary
  3716. index entry. */
  3717. switch (row_search_idx_cond_check(
  3718. buf, prebuilt, rec, offsets)) {
  3719. case ICP_NO_MATCH:
  3720. goto next_rec;
  3721. case ICP_OUT_OF_RANGE:
  3722. err = DB_RECORD_NOT_FOUND;
  3723. goto idx_cond_failed;
  3724. case ICP_ABORTED_BY_USER:
  3725. err = DB_SEARCH_ABORTED_BY_USER;
  3726. goto idx_cond_failed;
  3727. case ICP_ERROR:
  3728. err = DB_ERROR;
  3729. goto idx_cond_failed;
  3730. case ICP_MATCH:
  3731. goto requires_clust_rec;
  3732. }
  3733. ut_error;
  3734. }
  3735. }
  3736. }
  3737. locks_ok:
  3738. /* NOTE that at this point rec can be an old version of a clustered
  3739. index record built for a consistent read. We cannot assume after this
  3740. point that rec is on a buffer pool page. Functions like
  3741. page_rec_is_comp() cannot be used! */
  3742. if (rec_get_deleted_flag(rec, comp)) {
  3743. /* The record is delete-marked: we can skip it */
  3744. if ((srv_locks_unsafe_for_binlog
  3745. || trx->isolation_level <= TRX_ISO_READ_COMMITTED)
  3746. && prebuilt->select_lock_type != LOCK_NONE
  3747. && !did_semi_consistent_read) {
  3748. /* No need to keep a lock on a delete-marked record
  3749. if we do not want to use next-key locking. */
  3750. row_unlock_for_mysql(prebuilt, TRUE);
  3751. }
  3752. /* This is an optimization to skip setting the next key lock
  3753. on the record that follows this delete-marked record. This
  3754. optimization works because of the unique search criteria
  3755. which precludes the presence of a range lock between this
  3756. delete marked record and the record following it.
  3757. For now this is applicable only to clustered indexes while
  3758. doing a unique search except for HANDLER queries because
  3759. HANDLER allows NEXT and PREV even in unique search on
  3760. clustered index. There is scope for further optimization
  3761. applicable to unique secondary indexes. Current behaviour is
  3762. to widen the scope of a lock on an already delete marked record
  3763. if the same record is deleted twice by the same transaction */
  3764. if (index == clust_index && unique_search
  3765. && !prebuilt->used_in_HANDLER) {
  3766. err = DB_RECORD_NOT_FOUND;
  3767. goto normal_return;
  3768. }
  3769. goto next_rec;
  3770. }
  3771. /* Check if the record matches the index condition. */
  3772. switch (row_search_idx_cond_check(buf, prebuilt, rec, offsets)) {
  3773. case ICP_NO_MATCH:
  3774. if (did_semi_consistent_read) {
  3775. row_unlock_for_mysql(prebuilt, TRUE);
  3776. }
  3777. goto next_rec;
  3778. case ICP_ABORTED_BY_USER:
  3779. err = DB_SEARCH_ABORTED_BY_USER;
  3780. goto idx_cond_failed;
  3781. case ICP_ERROR:
  3782. err = DB_ERROR;
  3783. goto idx_cond_failed;
  3784. case ICP_OUT_OF_RANGE:
  3785. err = DB_RECORD_NOT_FOUND;
  3786. goto idx_cond_failed;
  3787. case ICP_MATCH:
  3788. break;
  3789. }
  3790. /* Get the clustered index record if needed, if we did not do the
  3791. search using the clustered index... */
  3792. use_clustered_index =
  3793. (index != clust_index && prebuilt->need_to_access_clustered);
  3794. if (use_clustered_index && srv_prefix_index_cluster_optimization
  3795. && prebuilt->n_template <= index->n_fields) {
  3796. /* ...but, perhaps avoid the clustered index lookup if
  3797. all of the following are true:
  3798. 1) all columns are in the secondary index
  3799. 2) all values for columns that are prefix-only
  3800. indexes are shorter than the prefix size
  3801. This optimization can avoid many IOs for certain schemas.
  3802. */
  3803. ibool row_contains_all_values = TRUE;
  3804. int i;
  3805. for (i = 0; i < prebuilt->n_template; i++) {
  3806. /* Condition (1) from above: is the field in the
  3807. index (prefix or not)? */
  3808. mysql_row_templ_t* templ =
  3809. prebuilt->mysql_template + i;
  3810. ulint secondary_index_field_no =
  3811. templ->rec_prefix_field_no;
  3812. if (secondary_index_field_no == ULINT_UNDEFINED) {
  3813. row_contains_all_values = FALSE;
  3814. break;
  3815. }
  3816. /* Condition (2) from above: if this is a
  3817. prefix, is this row's value size shorter
  3818. than the prefix? */
  3819. if (templ->rec_field_is_prefix) {
  3820. ulint record_size = rec_offs_nth_size(
  3821. offsets,
  3822. secondary_index_field_no);
  3823. const dict_field_t *field =
  3824. dict_index_get_nth_field(
  3825. index,
  3826. secondary_index_field_no);
  3827. ut_a(field->prefix_len > 0);
  3828. if (record_size >= field->prefix_len) {
  3829. row_contains_all_values = FALSE;
  3830. break;
  3831. }
  3832. }
  3833. }
  3834. /* If (1) and (2) were true for all columns above, use
  3835. rec_prefix_field_no instead of rec_field_no, and skip
  3836. the clustered lookup below. */
  3837. if (row_contains_all_values) {
  3838. for (i = 0; i < prebuilt->n_template; i++) {
  3839. mysql_row_templ_t* templ =
  3840. prebuilt->mysql_template + i;
  3841. templ->rec_field_no =
  3842. templ->rec_prefix_field_no;
  3843. ut_a(templ->rec_field_no != ULINT_UNDEFINED);
  3844. }
  3845. use_clustered_index = FALSE;
  3846. srv_stats.n_sec_rec_cluster_reads_avoided.inc();
  3847. }
  3848. }
  3849. if (use_clustered_index) {
  3850. requires_clust_rec:
  3851. ut_ad(index != clust_index);
  3852. /* We use a 'goto' to the preceding label if a consistent
  3853. read of a secondary index record requires us to look up old
  3854. versions of the associated clustered index record. */
  3855. ut_ad(rec_offs_validate(rec, index, offsets));
  3856. /* It was a non-clustered index and we must fetch also the
  3857. clustered index record */
  3858. mtr_has_extra_clust_latch = TRUE;
  3859. /* The following call returns 'offsets' associated with
  3860. 'clust_rec'. Note that 'clust_rec' can be an old version
  3861. built for a consistent read. */
  3862. err = row_sel_get_clust_rec_for_mysql(prebuilt, index, rec,
  3863. thr, &clust_rec,
  3864. &offsets, &heap, &mtr);
  3865. switch (err) {
  3866. case DB_SUCCESS:
  3867. if (clust_rec == NULL) {
  3868. /* The record did not exist in the read view */
  3869. ut_ad(prebuilt->select_lock_type == LOCK_NONE);
  3870. goto next_rec;
  3871. }
  3872. break;
  3873. case DB_SUCCESS_LOCKED_REC:
  3874. ut_a(clust_rec != NULL);
  3875. if (srv_locks_unsafe_for_binlog
  3876. || trx->isolation_level
  3877. <= TRX_ISO_READ_COMMITTED) {
  3878. /* Note that the clustered index record
  3879. was locked. */
  3880. prebuilt->new_rec_locks = 2;
  3881. }
  3882. err = DB_SUCCESS;
  3883. break;
  3884. default:
  3885. goto lock_wait_or_error;
  3886. }
  3887. if (rec_get_deleted_flag(clust_rec, comp)) {
  3888. /* The record is delete marked: we can skip it */
  3889. if ((srv_locks_unsafe_for_binlog
  3890. || trx->isolation_level <= TRX_ISO_READ_COMMITTED)
  3891. && prebuilt->select_lock_type != LOCK_NONE) {
  3892. /* No need to keep a lock on a delete-marked
  3893. record if we do not want to use next-key
  3894. locking. */
  3895. row_unlock_for_mysql(prebuilt, TRUE);
  3896. }
  3897. goto next_rec;
  3898. }
  3899. result_rec = clust_rec;
  3900. ut_ad(rec_offs_validate(result_rec, clust_index, offsets));
  3901. if (prebuilt->idx_cond) {
  3902. /* Convert the record to MySQL format. We were
  3903. unable to do this in row_search_idx_cond_check(),
  3904. because the condition is on the secondary index
  3905. and the requested column is in the clustered index.
  3906. We convert all fields, including those that
  3907. may have been used in ICP, because the
  3908. secondary index may contain a column prefix
  3909. rather than the full column. Also, as noted
  3910. in Bug #56680, the column in the secondary
  3911. index may be in the wrong case, and the
  3912. authoritative case is in result_rec, the
  3913. appropriate version of the clustered index record. */
  3914. if (!row_sel_store_mysql_rec(
  3915. buf, prebuilt, result_rec,
  3916. TRUE, clust_index, offsets)) {
  3917. goto next_rec;
  3918. }
  3919. }
  3920. } else {
  3921. result_rec = rec;
  3922. }
  3923. /* We found a qualifying record 'result_rec'. At this point,
  3924. 'offsets' are associated with 'result_rec'. */
  3925. ut_ad(rec_offs_validate(result_rec,
  3926. result_rec != rec ? clust_index : index,
  3927. offsets));
  3928. ut_ad(!rec_get_deleted_flag(result_rec, comp));
  3929. /* At this point, the clustered index record is protected
  3930. by a page latch that was acquired when pcur was positioned.
  3931. The latch will not be released until mtr_commit(&mtr). */
  3932. if ((match_mode == ROW_SEL_EXACT
  3933. || prebuilt->n_rows_fetched >= MYSQL_FETCH_CACHE_THRESHOLD)
  3934. && prebuilt->select_lock_type == LOCK_NONE
  3935. && !prebuilt->templ_contains_blob
  3936. && !prebuilt->clust_index_was_generated
  3937. && !prebuilt->used_in_HANDLER
  3938. && !prebuilt->innodb_api
  3939. && prebuilt->template_type
  3940. != ROW_MYSQL_DUMMY_TEMPLATE
  3941. && !prebuilt->in_fts_query) {
  3942. /* Inside an update, for example, we do not cache rows,
  3943. since we may use the cursor position to do the actual
  3944. update, that is why we require ...lock_type == LOCK_NONE.
  3945. Since we keep space in prebuilt only for the BLOBs of
  3946. a single row, we cannot cache rows in the case there
  3947. are BLOBs in the fields to be fetched. In HANDLER we do
  3948. not cache rows because there the cursor is a scrollable
  3949. cursor. */
  3950. ut_a(prebuilt->n_fetch_cached < MYSQL_FETCH_CACHE_SIZE);
  3951. /* We only convert from InnoDB row format to MySQL row
  3952. format when ICP is disabled. */
  3953. if (!prebuilt->idx_cond) {
  3954. /* We use next_buf to track the allocation of buffers
  3955. where we store and enqueue the buffers for our
  3956. pre-fetch optimisation.
  3957. If next_buf == 0 then we store the converted record
  3958. directly into the MySQL record buffer (buf). If it is
  3959. != 0 then we allocate a pre-fetch buffer and store the
  3960. converted record there.
  3961. If the conversion fails and the MySQL record buffer
  3962. was not written to then we reset next_buf so that
  3963. we can re-use the MySQL record buffer in the next
  3964. iteration. */
  3965. next_buf = next_buf
  3966. ? row_sel_fetch_last_buf(prebuilt) : buf;
  3967. if (!row_sel_store_mysql_rec(
  3968. next_buf, prebuilt, result_rec,
  3969. result_rec != rec,
  3970. result_rec != rec ? clust_index : index,
  3971. offsets)) {
  3972. if (next_buf == buf) {
  3973. ut_a(prebuilt->n_fetch_cached == 0);
  3974. next_buf = 0;
  3975. }
  3976. /* Only fresh inserts may contain incomplete
  3977. externally stored columns. Pretend that such
  3978. records do not exist. Such records may only be
  3979. accessed at the READ UNCOMMITTED isolation
  3980. level or when rolling back a recovered
  3981. transaction. Rollback happens at a lower
  3982. level, not here. */
  3983. goto next_rec;
  3984. }
  3985. if (next_buf != buf) {
  3986. row_sel_enqueue_cache_row_for_mysql(
  3987. next_buf, prebuilt);
  3988. }
  3989. } else {
  3990. row_sel_enqueue_cache_row_for_mysql(buf, prebuilt);
  3991. }
  3992. if (prebuilt->n_fetch_cached < MYSQL_FETCH_CACHE_SIZE) {
  3993. goto next_rec;
  3994. }
  3995. } else {
  3996. if (UNIV_UNLIKELY
  3997. (prebuilt->template_type == ROW_MYSQL_DUMMY_TEMPLATE)) {
  3998. /* CHECK TABLE: fetch the row */
  3999. if (result_rec != rec
  4000. && !prebuilt->need_to_access_clustered) {
  4001. /* We used 'offsets' for the clust
  4002. rec, recalculate them for 'rec' */
  4003. offsets = rec_get_offsets(rec, index, offsets,
  4004. ULINT_UNDEFINED,
  4005. &heap);
  4006. result_rec = rec;
  4007. }
  4008. memcpy(buf + 4, result_rec
  4009. - rec_offs_extra_size(offsets),
  4010. rec_offs_size(offsets));
  4011. mach_write_to_4(buf,
  4012. rec_offs_extra_size(offsets) + 4);
  4013. } else if (!prebuilt->idx_cond && !prebuilt->innodb_api) {
  4014. /* The record was not yet converted to MySQL format. */
  4015. if (!row_sel_store_mysql_rec(
  4016. buf, prebuilt, result_rec,
  4017. result_rec != rec,
  4018. result_rec != rec ? clust_index : index,
  4019. offsets)) {
  4020. /* Only fresh inserts may contain
  4021. incomplete externally stored
  4022. columns. Pretend that such records do
  4023. not exist. Such records may only be
  4024. accessed at the READ UNCOMMITTED
  4025. isolation level or when rolling back a
  4026. recovered transaction. Rollback
  4027. happens at a lower level, not here. */
  4028. goto next_rec;
  4029. }
  4030. }
  4031. if (prebuilt->clust_index_was_generated) {
  4032. row_sel_store_row_id_to_prebuilt(
  4033. prebuilt, result_rec,
  4034. result_rec == rec ? index : clust_index,
  4035. offsets);
  4036. }
  4037. }
  4038. /* From this point on, 'offsets' are invalid. */
  4039. /* We have an optimization to save CPU time: if this is a consistent
  4040. read on a unique condition on the clustered index, then we do not
  4041. store the pcur position, because any fetch next or prev will anyway
  4042. return 'end of file'. Exceptions are locking reads and the MySQL
  4043. HANDLER command where the user can move the cursor with PREV or NEXT
  4044. even after a unique search. */
  4045. err = DB_SUCCESS;
  4046. idx_cond_failed:
  4047. if (!unique_search
  4048. || !dict_index_is_clust(index)
  4049. || direction != 0
  4050. || prebuilt->select_lock_type != LOCK_NONE
  4051. || prebuilt->used_in_HANDLER
  4052. || prebuilt->innodb_api) {
  4053. /* Inside an update always store the cursor position */
  4054. btr_pcur_store_position(pcur, &mtr);
  4055. if (prebuilt->innodb_api) {
  4056. prebuilt->innodb_api_rec = result_rec;
  4057. }
  4058. }
  4059. goto normal_return;
  4060. next_rec:
  4061. /* Reset the old and new "did semi-consistent read" flags. */
  4062. if (UNIV_UNLIKELY(prebuilt->row_read_type
  4063. == ROW_READ_DID_SEMI_CONSISTENT)) {
  4064. prebuilt->row_read_type = ROW_READ_TRY_SEMI_CONSISTENT;
  4065. }
  4066. did_semi_consistent_read = FALSE;
  4067. prebuilt->new_rec_locks = 0;
  4068. /*-------------------------------------------------------------*/
  4069. /* PHASE 5: Move the cursor to the next index record */
  4070. /* NOTE: For moves_up==FALSE, the mini-transaction will be
  4071. committed and restarted every time when switching b-tree
  4072. pages. For moves_up==TRUE in index condition pushdown, we can
  4073. scan an entire secondary index tree within a single
  4074. mini-transaction. As long as the prebuilt->idx_cond does not
  4075. match, we do not need to consult the clustered index or
  4076. return records to MySQL, and thus we can avoid repositioning
  4077. the cursor. What prevents us from buffer-fixing all leaf pages
  4078. within the mini-transaction is the btr_leaf_page_release()
  4079. call in btr_pcur_move_to_next_page(). Only the leaf page where
  4080. the cursor is positioned will remain buffer-fixed. */
  4081. if (UNIV_UNLIKELY(mtr_has_extra_clust_latch)) {
  4082. /* We must commit mtr if we are moving to the next
  4083. non-clustered index record, because we could break the
  4084. latching order if we would access a different clustered
  4085. index page right away without releasing the previous. */
  4086. btr_pcur_store_position(pcur, &mtr);
  4087. mtr_commit(&mtr);
  4088. mtr_has_extra_clust_latch = FALSE;
  4089. mtr_start(&mtr);
  4090. if (sel_restore_position_for_mysql(&same_user_rec,
  4091. BTR_SEARCH_LEAF,
  4092. pcur, moves_up, &mtr)) {
  4093. #ifdef UNIV_SEARCH_DEBUG
  4094. cnt++;
  4095. #endif /* UNIV_SEARCH_DEBUG */
  4096. goto rec_loop;
  4097. }
  4098. }
  4099. if (moves_up) {
  4100. if (UNIV_UNLIKELY(!btr_pcur_move_to_next(pcur, &mtr))) {
  4101. not_moved:
  4102. btr_pcur_store_position(pcur, &mtr);
  4103. if (match_mode != 0) {
  4104. err = DB_RECORD_NOT_FOUND;
  4105. } else {
  4106. err = DB_END_OF_INDEX;
  4107. }
  4108. goto normal_return;
  4109. }
  4110. } else {
  4111. if (UNIV_UNLIKELY(!btr_pcur_move_to_prev(pcur, &mtr))) {
  4112. goto not_moved;
  4113. }
  4114. }
  4115. #ifdef UNIV_SEARCH_DEBUG
  4116. cnt++;
  4117. #endif /* UNIV_SEARCH_DEBUG */
  4118. goto rec_loop;
  4119. lock_wait_or_error:
  4120. /* Reset the old and new "did semi-consistent read" flags. */
  4121. if (UNIV_UNLIKELY(prebuilt->row_read_type
  4122. == ROW_READ_DID_SEMI_CONSISTENT)) {
  4123. prebuilt->row_read_type = ROW_READ_TRY_SEMI_CONSISTENT;
  4124. }
  4125. did_semi_consistent_read = FALSE;
  4126. /*-------------------------------------------------------------*/
  4127. btr_pcur_store_position(pcur, &mtr);
  4128. lock_table_wait:
  4129. mtr_commit(&mtr);
  4130. mtr_has_extra_clust_latch = FALSE;
  4131. trx->error_state = err;
  4132. /* The following is a patch for MySQL */
  4133. que_thr_stop_for_mysql(thr);
  4134. thr->lock_state = QUE_THR_LOCK_ROW;
  4135. if (row_mysql_handle_errors(&err, trx, thr, NULL)) {
  4136. /* It was a lock wait, and it ended */
  4137. thr->lock_state = QUE_THR_LOCK_NOLOCK;
  4138. mtr_start(&mtr);
  4139. /* Table lock waited, go try to obtain table lock
  4140. again */
  4141. if (table_lock_waited) {
  4142. table_lock_waited = FALSE;
  4143. goto wait_table_again;
  4144. }
  4145. sel_restore_position_for_mysql(&same_user_rec,
  4146. BTR_SEARCH_LEAF, pcur,
  4147. moves_up, &mtr);
  4148. if ((srv_locks_unsafe_for_binlog
  4149. || trx->isolation_level <= TRX_ISO_READ_COMMITTED)
  4150. && !same_user_rec) {
  4151. /* Since we were not able to restore the cursor
  4152. on the same user record, we cannot use
  4153. row_unlock_for_mysql() to unlock any records, and
  4154. we must thus reset the new rec lock info. Since
  4155. in lock0lock.cc we have blocked the inheriting of gap
  4156. X-locks, we actually do not have any new record locks
  4157. set in this case.
  4158. Note that if we were able to restore on the 'same'
  4159. user record, it is still possible that we were actually
  4160. waiting on a delete-marked record, and meanwhile
  4161. it was removed by purge and inserted again by some
  4162. other user. But that is no problem, because in
  4163. rec_loop we will again try to set a lock, and
  4164. new_rec_lock_info in trx will be right at the end. */
  4165. prebuilt->new_rec_locks = 0;
  4166. }
  4167. mode = pcur->search_mode;
  4168. goto rec_loop;
  4169. }
  4170. thr->lock_state = QUE_THR_LOCK_NOLOCK;
  4171. #ifdef UNIV_SEARCH_DEBUG
  4172. /* fputs("Using ", stderr);
  4173. dict_index_name_print(stderr, index);
  4174. fprintf(stderr, " cnt %lu ret value %lu err\n", cnt, err); */
  4175. #endif /* UNIV_SEARCH_DEBUG */
  4176. goto func_exit;
  4177. normal_return:
  4178. /*-------------------------------------------------------------*/
  4179. que_thr_stop_for_mysql_no_error(thr, trx);
  4180. mtr_commit(&mtr);
  4181. if (prebuilt->idx_cond != 0) {
  4182. /* When ICP is active we don't write to the MySQL buffer
  4183. directly, only to buffers that are enqueued in the pre-fetch
  4184. queue. We need to dequeue the first buffer and copy the contents
  4185. to the record buffer that was passed in by MySQL. */
  4186. if (prebuilt->n_fetch_cached > 0) {
  4187. row_sel_dequeue_cached_row_for_mysql(buf, prebuilt);
  4188. err = DB_SUCCESS;
  4189. }
  4190. } else if (next_buf != 0) {
  4191. /* We may or may not have enqueued some buffers to the
  4192. pre-fetch queue, but we definitely wrote to the record
  4193. buffer passed to use by MySQL. */
  4194. DEBUG_SYNC_C("row_search_cached_row");
  4195. err = DB_SUCCESS;
  4196. }
  4197. #ifdef UNIV_SEARCH_DEBUG
  4198. /* fputs("Using ", stderr);
  4199. dict_index_name_print(stderr, index);
  4200. fprintf(stderr, " cnt %lu ret value %lu err\n", cnt, err); */
  4201. #endif /* UNIV_SEARCH_DEBUG */
  4202. func_exit:
  4203. trx->op_info = "";
  4204. if (UNIV_LIKELY_NULL(heap)) {
  4205. mem_heap_free(heap);
  4206. }
  4207. /* Set or reset the "did semi-consistent read" flag on return.
  4208. The flag did_semi_consistent_read is set if and only if
  4209. the record being returned was fetched with a semi-consistent read. */
  4210. ut_ad(prebuilt->row_read_type != ROW_READ_WITH_LOCKS
  4211. || !did_semi_consistent_read);
  4212. if (UNIV_UNLIKELY(prebuilt->row_read_type != ROW_READ_WITH_LOCKS)) {
  4213. if (UNIV_UNLIKELY(did_semi_consistent_read)) {
  4214. prebuilt->row_read_type = ROW_READ_DID_SEMI_CONSISTENT;
  4215. } else {
  4216. prebuilt->row_read_type = ROW_READ_TRY_SEMI_CONSISTENT;
  4217. }
  4218. }
  4219. ut_ad(!trx->has_search_latch);
  4220. #ifdef UNIV_SYNC_DEBUG
  4221. ut_ad(!btr_search_own_any());
  4222. ut_ad(!sync_thread_levels_nonempty_trx(trx->has_search_latch));
  4223. #endif /* UNIV_SYNC_DEBUG */
  4224. DEBUG_SYNC_C("innodb_row_search_for_mysql_exit");
  4225. return(err);
  4226. }
  4227. /*******************************************************************//**
  4228. Checks if MySQL at the moment is allowed for this table to retrieve a
  4229. consistent read result, or store it to the query cache.
  4230. @return TRUE if storing or retrieving from the query cache is permitted */
  4231. UNIV_INTERN
  4232. ibool
  4233. row_search_check_if_query_cache_permitted(
  4234. /*======================================*/
  4235. trx_t* trx, /*!< in: transaction object */
  4236. const char* norm_name) /*!< in: concatenation of database name,
  4237. '/' char, table name */
  4238. {
  4239. dict_table_t* table;
  4240. ibool ret = FALSE;
  4241. /* Disable query cache altogether for all tables if recovered XA
  4242. transactions in prepared state exist. This is because we do not
  4243. restore the table locks for those transactions and we may wrongly
  4244. set ret=TRUE above if "lock_table_get_n_locks(table) == 0". See
  4245. "Bug#14658648 XA ROLLBACK (DISTRIBUTED DATABASE) NOT WORKING WITH
  4246. QUERY CACHE ENABLED".
  4247. Read trx_sys->n_prepared_recovered_trx without mutex protection,
  4248. not possible to end up with a torn read since n_prepared_recovered_trx
  4249. is word size. */
  4250. if (trx_sys->n_prepared_recovered_trx > 0) {
  4251. return(FALSE);
  4252. }
  4253. table = dict_table_open_on_name(norm_name, FALSE, FALSE,
  4254. DICT_ERR_IGNORE_NONE);
  4255. if (table == NULL) {
  4256. return(FALSE);
  4257. }
  4258. /* Start the transaction if it is not started yet */
  4259. trx_start_if_not_started(trx);
  4260. /* If there are locks on the table or some trx has invalidated the
  4261. cache up to our trx id, then ret = FALSE.
  4262. We do not check what type locks there are on the table, though only
  4263. IX type locks actually would require ret = FALSE. */
  4264. if (lock_table_get_n_locks(table) == 0
  4265. && trx->id >= table->query_cache_inv_trx_id) {
  4266. ret = TRUE;
  4267. /* If the isolation level is high, assign a read view for the
  4268. transaction if it does not yet have one */
  4269. if (trx->isolation_level >= TRX_ISO_REPEATABLE_READ
  4270. && !trx->read_view) {
  4271. trx->read_view =
  4272. read_view_open_now(trx->id,
  4273. trx->prebuilt_view);
  4274. trx->global_read_view = trx->read_view;
  4275. }
  4276. }
  4277. dict_table_close(table, FALSE, FALSE);
  4278. return(ret);
  4279. }
  4280. /*******************************************************************//**
  4281. Read the AUTOINC column from the current row. If the value is less than
  4282. 0 and the type is not unsigned then we reset the value to 0.
  4283. @return value read from the column */
  4284. static
  4285. ib_uint64_t
  4286. row_search_autoinc_read_column(
  4287. /*===========================*/
  4288. dict_index_t* index, /*!< in: index to read from */
  4289. const rec_t* rec, /*!< in: current rec */
  4290. ulint col_no, /*!< in: column number */
  4291. ulint mtype, /*!< in: column main type */
  4292. ibool unsigned_type) /*!< in: signed or unsigned flag */
  4293. {
  4294. ulint len;
  4295. const byte* data;
  4296. ib_uint64_t value;
  4297. mem_heap_t* heap = NULL;
  4298. ulint offsets_[REC_OFFS_NORMAL_SIZE];
  4299. ulint* offsets = offsets_;
  4300. rec_offs_init(offsets_);
  4301. offsets = rec_get_offsets(rec, index, offsets, col_no + 1, &heap);
  4302. if (rec_offs_nth_sql_null(offsets, col_no)) {
  4303. /* There is no non-NULL value in the auto-increment column. */
  4304. value = 0;
  4305. goto func_exit;
  4306. }
  4307. data = rec_get_nth_field(rec, offsets, col_no, &len);
  4308. switch (mtype) {
  4309. case DATA_INT:
  4310. ut_a(len <= sizeof value);
  4311. value = mach_read_int_type(data, len, unsigned_type);
  4312. break;
  4313. case DATA_FLOAT:
  4314. ut_a(len == sizeof(float));
  4315. value = (ib_uint64_t) mach_float_read(data);
  4316. break;
  4317. case DATA_DOUBLE:
  4318. ut_a(len == sizeof(double));
  4319. value = (ib_uint64_t) mach_double_read(data);
  4320. break;
  4321. default:
  4322. ut_error;
  4323. }
  4324. if (!unsigned_type && (ib_int64_t) value < 0) {
  4325. value = 0;
  4326. }
  4327. func_exit:
  4328. if (UNIV_LIKELY_NULL(heap)) {
  4329. mem_heap_free(heap);
  4330. }
  4331. return(value);
  4332. }
  4333. /** Get the maximum and non-delete-marked record in an index.
  4334. @param[in] index index tree
  4335. @param[in,out] mtr mini-transaction (may be committed and restarted)
  4336. @return maximum record, page s-latched in mtr
  4337. @retval NULL if there are no records, or if all of them are delete-marked */
  4338. static
  4339. const rec_t*
  4340. row_search_get_max_rec(
  4341. dict_index_t* index,
  4342. mtr_t* mtr)
  4343. {
  4344. btr_pcur_t pcur;
  4345. const rec_t* rec;
  4346. /* Open at the high/right end (false), and init cursor */
  4347. btr_pcur_open_at_index_side(
  4348. false, index, BTR_SEARCH_LEAF, &pcur, true, 0, mtr);
  4349. do {
  4350. const page_t* page;
  4351. page = btr_pcur_get_page(&pcur);
  4352. rec = page_find_rec_max_not_deleted(page);
  4353. if (page_rec_is_user_rec(rec)) {
  4354. break;
  4355. } else {
  4356. rec = NULL;
  4357. }
  4358. btr_pcur_move_before_first_on_page(&pcur);
  4359. } while (btr_pcur_move_to_prev(&pcur, mtr));
  4360. btr_pcur_close(&pcur);
  4361. return(rec);
  4362. }
  4363. /*******************************************************************//**
  4364. Read the max AUTOINC value from an index.
  4365. @return DB_SUCCESS if all OK else error code, DB_RECORD_NOT_FOUND if
  4366. column name can't be found in index */
  4367. UNIV_INTERN
  4368. dberr_t
  4369. row_search_max_autoinc(
  4370. /*===================*/
  4371. dict_index_t* index, /*!< in: index to search */
  4372. const char* col_name, /*!< in: name of autoinc column */
  4373. ib_uint64_t* value) /*!< out: AUTOINC value read */
  4374. {
  4375. dict_field_t* dfield = dict_index_get_nth_field(index, 0);
  4376. dberr_t error = DB_SUCCESS;
  4377. *value = 0;
  4378. if (strcmp(col_name, dfield->name) != 0) {
  4379. error = DB_RECORD_NOT_FOUND;
  4380. } else {
  4381. mtr_t mtr;
  4382. const rec_t* rec;
  4383. mtr_start(&mtr);
  4384. rec = row_search_get_max_rec(index, &mtr);
  4385. if (rec != NULL) {
  4386. ibool unsigned_type = (
  4387. dfield->col->prtype & DATA_UNSIGNED);
  4388. *value = row_search_autoinc_read_column(
  4389. index, rec, 0,
  4390. dfield->col->mtype, unsigned_type);
  4391. }
  4392. mtr_commit(&mtr);
  4393. }
  4394. return(error);
  4395. }