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.

5055 lines
135 KiB

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