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.

4980 lines
132 KiB

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