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.

4784 lines
125 KiB

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