dberr_t row_search_mvcc()

in storage/innobase/row/row0sel.cc [4423:6069]


dberr_t row_search_mvcc(byte *buf, page_cur_mode_t mode,
                        row_prebuilt_t *prebuilt, ulint match_mode,
                        const ulint direction) {
  DBUG_TRACE;

  dict_index_t *index = prebuilt->index;
  bool comp = dict_table_is_comp(index->table);
  const dtuple_t *search_tuple = prebuilt->search_tuple;
  btr_pcur_t *pcur = prebuilt->pcur;
  trx_t *trx = prebuilt->trx;
  dict_index_t *clust_index;
  /* True if we are scanning a secondary index, but the template is based
  on the primary index. */
  bool clust_templ_for_sec;
  que_thr_t *thr;
  const rec_t *prev_rec = nullptr;
#ifdef UNIV_DEBUG
  const rec_t *prev_rec_debug = nullptr;
  ulint prev_rec_debug_n_fields = 0;
  byte *prev_rec_debug_buf = nullptr;
  size_t prev_rec_debug_buf_size = 0;
#endif /* UNIV_DEBUG */
  const rec_t *rec = nullptr;
  byte *end_range_cache = nullptr;
  const dtuple_t *vrow = nullptr;
  const rec_t *result_rec = nullptr;
  const rec_t *clust_rec;
  Row_sel_get_clust_rec_for_mysql row_sel_get_clust_rec_for_mysql;
  dberr_t err = DB_SUCCESS;
  bool unique_search = false;
  bool mtr_has_extra_clust_latch = false;
  bool moves_up = false;
  bool set_also_gap_locks = true;
  /* if the query is a plain locking SELECT, and the isolation level
  is <= TRX_ISO_READ_COMMITTED, then this is set to false */
  bool did_semi_consistent_read = false;
  /* if the returned record was locked and we did a semi-consistent
  read (fetch the newest committed version), then this is set to
  true */
  ulint next_offs;
  bool same_user_rec = false;
  mtr_t mtr;
  mem_heap_t *heap = nullptr;
  ulint offsets_[REC_OFFS_NORMAL_SIZE];
  ulint *offsets = offsets_;
  ulint sec_offsets_[REC_OFFS_NORMAL_SIZE];
  ulint *sec_offsets = nullptr;
  bool table_lock_waited = false;
  byte *next_buf = nullptr;
  bool spatial_search = false;

  rec_offs_init(offsets_);

  ut_ad(index && pcur && search_tuple);
  ut_a(prebuilt->magic_n == ROW_PREBUILT_ALLOCATED);
  ut_a(prebuilt->magic_n2 == ROW_PREBUILT_ALLOCATED);
  ut_a(!trx->has_search_latch);

  /* We don't support FTS queries from the HANDLER interfaces, because
  we implemented FTS as reversed inverted index with auxiliary tables.
  So anything related to traditional index query would not apply to
  it. */
  if (prebuilt->index->type & DICT_FTS) {
    return DB_END_OF_INDEX;
  }

#ifdef UNIV_DEBUG
  {
    btrsea_sync_check check(trx->has_search_latch);
    ut_ad(!sync_check_iterate(check));
  }
#endif /* UNIV_DEBUG */

  if (dict_table_is_discarded(prebuilt->table)) {
    return DB_TABLESPACE_DELETED;

  } else if (prebuilt->table->ibd_file_missing) {
    return DB_TABLESPACE_NOT_FOUND;

  } else if (!prebuilt->index_usable) {
    return DB_MISSING_HISTORY;

  } else if (prebuilt->index->is_corrupted()) {
    return DB_CORRUPTION;
  }

  /* We need to get the virtual column values stored in secondary
  index key, if this is covered index scan or virtual key read is
  requested. */
  bool need_vrow = dict_index_has_virtual(prebuilt->index) &&
                   (prebuilt->read_just_key || prebuilt->m_read_virtual_key);

  /* Reset the new record lock info.
  Then we are able to remove the record locks set here on an
  individual row. */
  prebuilt->new_rec_lock.reset();
  /*-------------------------------------------------------------*/
  /* PHASE 1: Try to pop the row from the record buffer or from
  the prefetch cache */

  const auto record_buffer = row_sel_get_record_buffer(prebuilt);

  if (UNIV_UNLIKELY(direction == 0)) {
    trx->op_info = "starting index read";

    prebuilt->n_rows_fetched = 0;
    prebuilt->n_fetch_cached = 0;
    prebuilt->fetch_cache_first = 0;
    prebuilt->m_end_range = false;
    if (record_buffer != nullptr) {
      record_buffer->reset();
    }

    if (prebuilt->sel_graph == nullptr) {
      /* Build a dummy select query graph */
      row_prebuild_sel_graph(prebuilt);
    }
  } else {
    trx->op_info = "fetching rows";

    if (prebuilt->n_rows_fetched == 0) {
      prebuilt->fetch_direction = direction;
    }

    if (UNIV_UNLIKELY(direction != prebuilt->fetch_direction)) {
      if (UNIV_UNLIKELY(prebuilt->n_fetch_cached > 0)) {
        ut_error;
        /* TODO: scrollable cursor: restore cursor to
        the place of the latest returned row,
        or better: prevent caching for a scroll
        cursor! */
      }

      prebuilt->n_rows_fetched = 0;
      prebuilt->n_fetch_cached = 0;
      prebuilt->fetch_cache_first = 0;
      prebuilt->m_end_range = false;

      /* A record buffer is not used for scroll cursors.
      Otherwise, it would have to be reset here too. */
      ut_ad(record_buffer == nullptr);

    } else if (UNIV_LIKELY(prebuilt->n_fetch_cached > 0)) {
      row_sel_dequeue_cached_row_for_mysql(buf, prebuilt);

      prebuilt->n_rows_fetched++;

      err = DB_SUCCESS;
      goto func_exit;
    } else if (prebuilt->m_end_range) {
      err = DB_RECORD_NOT_FOUND;
      goto func_exit;
    }

    /* The prefetch cache is exhausted, so fetch_cache_first
    should point to the beginning of the cache. */
    ut_ad(prebuilt->fetch_cache_first == 0);

    if (record_buffer != nullptr && record_buffer->is_out_of_range()) {
      /* The previous returned row was popped from
      the fetch cache, but the end of the range was
      reached while filling the cache, so there are
      no more rows to put into the cache. */

      err = DB_RECORD_NOT_FOUND;
      goto func_exit;
    }

    prebuilt->n_rows_fetched++;

    if (prebuilt->n_rows_fetched > 1000000000) {
      /* Prevent wrap-over */
      prebuilt->n_rows_fetched = 500000000;
    }

    mode = pcur->m_search_mode;
  }

  /* In a search where at most one record in the index may match, we
  can use a LOCK_REC_NOT_GAP type record lock when locking a
  non-delete-marked matching record.

  Note that in a unique secondary index there may be different
  delete-marked versions of a record where only the primary key
  values differ: thus in a secondary index we must use next-key
  locks when locking delete-marked records. */

  if (match_mode == ROW_SEL_EXACT && dict_index_is_unique(index) &&
      dtuple_get_n_fields(search_tuple) == dict_index_get_n_unique(index) &&
      (index->is_clustered() || !dtuple_contains_null(search_tuple))) {
    /* Note above that a UNIQUE secondary index can contain many
    rows with the same key value if one of the columns is the SQL
    null. A clustered index under MySQL can never contain null
    columns because we demand that all the columns in primary key
    are non-null. */

    unique_search = true;

    /* Even if the condition is unique, MySQL seems to try to
    retrieve also a second row if a primary key contains more than
    1 column. Return immediately if this is not a HANDLER
    command. */

    if (UNIV_UNLIKELY(direction != 0 && !prebuilt->used_in_HANDLER)) {
      err = DB_RECORD_NOT_FOUND;
      goto func_exit;
    }
  }

  /* We don't support sequential scan for Rtree index, because it
  is no meaning to do so. */
  if (dict_index_is_spatial(index) && !RTREE_SEARCH_MODE(mode)) {
    err = DB_END_OF_INDEX;
    goto func_exit;
  }

  mtr_start(&mtr);

  /*-------------------------------------------------------------*/
  /* PHASE 2: Try fast adaptive hash index search if possible */

  /* Next test if this is the special case where we can use the fast
  adaptive hash index to try the search. Since we must release the
  search system latch when we retrieve an externally stored field, we
  cannot use the adaptive hash index in a search in the case the row
  may be long and there may be externally stored fields */

  if (UNIV_UNLIKELY(direction == 0) && unique_search && btr_search_enabled &&
      index->is_clustered() && !prebuilt->templ_contains_blob &&
      !prebuilt->used_in_HANDLER &&
      (prebuilt->mysql_row_len < UNIV_PAGE_SIZE / 8) && !prebuilt->innodb_api) {
    mode = PAGE_CUR_GE;

    if (trx->mysql_n_tables_locked == 0 && !prebuilt->ins_sel_stmt &&
        prebuilt->select_lock_type == LOCK_NONE &&
        trx->isolation_level > TRX_ISO_READ_UNCOMMITTED &&
        MVCC::is_view_active(trx->read_view)) {
      /* This is a SELECT query done as a consistent read,
      and the read view has already been allocated:
      let us try a search shortcut through the hash
      index.
      NOTE that we must also test that
      mysql_n_tables_locked == 0, because this might
      also be INSERT INTO ... SELECT ... or
      CREATE TABLE ... SELECT ... . Our algorithm is
      NOT prepared to inserts interleaved with the SELECT,
      and if we try that, we can deadlock on the adaptive
      hash index semaphore! */

      ut_a(!trx->has_search_latch);
      rw_lock_s_lock(btr_get_search_latch(index), UT_LOCATION_HERE);
      trx->has_search_latch = true;

      switch (row_sel_try_search_shortcut_for_mysql(&rec, prebuilt, &offsets,
                                                    &heap, &mtr)) {
        case SEL_FOUND:
          /* At this point, rec is protected by
          a page latch that was acquired by
          row_sel_try_search_shortcut_for_mysql().
          The latch will not be released until
          mtr_commit(&mtr). */
          ut_ad(!rec_get_deleted_flag(rec, comp));

          if (prebuilt->idx_cond) {
            switch (row_search_idx_cond_check(buf, prebuilt, rec, offsets)) {
              case ICP_NO_MATCH:
              case ICP_OUT_OF_RANGE:
                goto shortcut_mismatch;
              case ICP_MATCH:
                goto shortcut_match;
            }
          }

          if (!row_sel_store_mysql_rec(buf, prebuilt, rec, nullptr, false,
                                       index, prebuilt->index, offsets, false,
                                       nullptr, prebuilt->blob_heap)) {
            /* Only fresh inserts may contain
            incomplete externally stored
            columns. Pretend that such
            records do not exist. Such
            records may only be accessed
            at the READ UNCOMMITTED
            isolation level or when
            rolling back a recovered
            transaction. Rollback happens
            at a lower level, not here. */

            /* Proceed as in case SEL_RETRY. */
            break;
          }

        shortcut_match:
          mtr_commit(&mtr);

          /* NOTE that we do NOT store the cursor
          position */

          err = DB_SUCCESS;

          rw_lock_s_unlock(btr_get_search_latch(index));
          trx->has_search_latch = false;

          goto func_exit;

        case SEL_EXHAUSTED:
        shortcut_mismatch:
          mtr_commit(&mtr);

          err = DB_RECORD_NOT_FOUND;

          rw_lock_s_unlock(btr_get_search_latch(index));
          trx->has_search_latch = false;

          /* NOTE that we do NOT store the cursor
          position */

          goto func_exit;

        case SEL_RETRY:
          break;

        default:
          ut_d(ut_error);
      }

      mtr_commit(&mtr);
      mtr_start(&mtr);

      rw_lock_s_unlock(btr_get_search_latch(index));
      trx->has_search_latch = false;
    }
  }

  /*-------------------------------------------------------------*/
  /* PHASE 3: Open or restore index cursor position */

  spatial_search = dict_index_is_spatial(index) && mode >= PAGE_CUR_CONTAIN;

  /* The state of a running trx can only be changed by the
  thread that is currently serving the transaction. Because we
  are that thread, we can read trx->state without holding any
  mutex. */

  ut_ad(prebuilt->sql_stat_start ||
        trx->state.load(std::memory_order_relaxed) == TRX_STATE_ACTIVE);

  ut_ad(!trx_is_started(trx) ||
        trx->state.load(std::memory_order_relaxed) == TRX_STATE_ACTIVE);

  ut_ad(prebuilt->sql_stat_start || prebuilt->select_lock_type != LOCK_NONE ||
        MVCC::is_view_active(trx->read_view) || srv_read_only_mode);

  trx_start_if_not_started(trx, false, UT_LOCATION_HERE);

  if (prebuilt->table->skip_gap_locks() ||
      (trx->skip_gap_locks() && prebuilt->select_lock_type != LOCK_NONE &&
       trx->mysql_thd != nullptr && thd_is_query_block(trx->mysql_thd))) {
    /* It is a plain locking SELECT and the isolation
    level is low: do not lock gaps */

    /* Reads on DD tables dont require gap-locks as serializability
    between different DDL statements is achieved using
    metadata locks */
    set_also_gap_locks = false;
  }

  /* Note that if the search mode was GE or G, then the cursor
  naturally moves upward (in fetch next) in alphabetical order,
  otherwise downward */

  if (direction == 0) {
    if (mode == PAGE_CUR_GE || mode == PAGE_CUR_G || mode >= PAGE_CUR_CONTAIN) {
      moves_up = true;
    }

  } else if (direction == ROW_SEL_NEXT) {
    moves_up = true;
  }

  thr = que_fork_get_first_thr(prebuilt->sel_graph);

  que_thr_move_to_run_state_for_mysql(thr, trx);

  clust_index = index->table->first_index();

  clust_templ_for_sec =
      index != clust_index && prebuilt->need_to_access_clustered;

  /* Do some start-of-statement preparations */

  if (!prebuilt->sql_stat_start) {
    /* No need to set an intention lock or assign a read view */

    if (!MVCC::is_view_active(trx->read_view) && !srv_read_only_mode &&
        prebuilt->select_lock_type == LOCK_NONE) {
      ib::error(ER_IB_MSG_1031) << "MySQL is trying to perform a"
                                   " consistent read but the read view is not"
                                   " assigned!";
      trx_print(stderr, trx, 600);
      fputc('\n', stderr);
      ut_error;
    }
  } else if (prebuilt->select_lock_type == LOCK_NONE) {
    /* This is a consistent read */
    /* Assign a read view for the query */

    if (!srv_read_only_mode) {
      trx_assign_read_view(trx);
      DEBUG_SYNC_C("after_mvcc_assign_read_view");
    }

    prebuilt->sql_stat_start = false;
  } else {
  wait_table_again:
    err = lock_table(0, index->table,
                     prebuilt->select_lock_type == LOCK_S ? LOCK_IS : LOCK_IX,
                     thr);

    if (err != DB_SUCCESS) {
      table_lock_waited = true;
      goto lock_table_wait;
    }
    prebuilt->sql_stat_start = false;
  }

  /* Open or restore index cursor position */

  if (UNIV_LIKELY(direction != 0)) {
    if (spatial_search) {
      /* R-Tree access does not need to do
      cursor position and resposition */
      goto next_rec;
    }

    auto need_to_process = sel_restore_position_for_mysql(
        &same_user_rec, BTR_SEARCH_LEAF, pcur, moves_up, &mtr);

    ut_ad(prev_rec == nullptr);

    if (UNIV_UNLIKELY(need_to_process)) {
      if (UNIV_UNLIKELY(prebuilt->row_read_type ==
                        ROW_READ_DID_SEMI_CONSISTENT)) {
        /* We did a semi-consistent read,
        but the record was removed in
        the meantime. */
        prebuilt->row_read_type = ROW_READ_TRY_SEMI_CONSISTENT;
      }
    } else if (UNIV_LIKELY(prebuilt->row_read_type !=
                           ROW_READ_DID_SEMI_CONSISTENT)) {
      /* The cursor was positioned on the record
      that we returned previously.  If we need
      to repeat a semi-consistent read as a
      pessimistic locking read, the record
      cannot be skipped. */

      goto next_rec;
    }

  } else if (dtuple_get_n_fields(search_tuple) > 0) {
    pcur->m_btr_cur.thr = thr;

    if (dict_index_is_spatial(index)) {
      bool need_pred_lock = set_also_gap_locks && !trx->skip_gap_locks() &&
                            prebuilt->select_lock_type != LOCK_NONE;

      if (!prebuilt->rtr_info) {
        prebuilt->rtr_info = rtr_create_rtr_info(need_pred_lock, true,
                                                 pcur->get_btr_cur(), index);
        prebuilt->rtr_info->search_tuple = search_tuple;
        prebuilt->rtr_info->search_mode = mode;
        rtr_info_update_btr(pcur->get_btr_cur(), prebuilt->rtr_info);
      } else {
        rtr_info_reinit_in_cursor(pcur->get_btr_cur(), index, need_pred_lock);
        prebuilt->rtr_info->search_tuple = search_tuple;
        prebuilt->rtr_info->search_mode = mode;
      }
    }

    pcur->open_no_init(index, search_tuple, mode, BTR_SEARCH_LEAF, 0, &mtr,
                       UT_LOCATION_HERE);

    pcur->m_trx_if_known = trx;

    rec = pcur->get_rec();

    if (!moves_up && !page_rec_is_supremum(rec) && set_also_gap_locks &&
        !trx->skip_gap_locks() && prebuilt->select_lock_type != LOCK_NONE &&
        !dict_index_is_spatial(index)) {
      /* Try to place a gap lock on the next index record
      to prevent phantoms in ORDER BY ... DESC queries */
      const rec_t *next_rec = page_rec_get_next_const(rec);

      offsets = rec_get_offsets(next_rec, index, offsets, ULINT_UNDEFINED,
                                UT_LOCATION_HERE, &heap);
      err = sel_set_rec_lock(pcur, next_rec, index, offsets,
                             prebuilt->select_mode, prebuilt->select_lock_type,
                             LOCK_GAP, thr, &mtr);

      switch (err) {
        case DB_SUCCESS_LOCKED_REC:
          err = DB_SUCCESS;
        case DB_SUCCESS:
          break;
        case DB_SKIP_LOCKED:
        case DB_LOCK_NOWAIT:
          ut_d(ut_error);
          ut_o(goto next_rec);
        default:
          goto lock_wait_or_error;
      }
    }
  } else if (mode == PAGE_CUR_G || mode == PAGE_CUR_L) {
    pcur->open_at_side(mode == PAGE_CUR_G, index, BTR_SEARCH_LEAF, false, 0,
                       &mtr);
  }

rec_loop:
  ut_ad(trx_can_be_handled_by_current_thread(trx));
  DEBUG_SYNC_C("row_search_rec_loop");

  prebuilt->lob_undo_reset();

  if (trx_is_interrupted(trx)) {
    if (!spatial_search) {
      pcur->store_position(&mtr);
    }
    err = DB_INTERRUPTED;
    goto normal_return;
  }

  /*-------------------------------------------------------------*/
  /* PHASE 4: Look for matching records in a loop */

  rec = pcur->get_rec();

  ut_ad(page_rec_is_comp(rec) == comp);

  if (page_rec_is_infimum(rec)) {
    /* The infimum record on a page cannot be in the result set,
    and neither can a record lock be placed on it: we skip such
    a record. */

    prev_rec = nullptr;
    goto next_rec;
  }

  if (page_rec_is_supremum(rec)) {
    /* Compare the last record of the page with end range
    passed to InnoDB when there is no ICP and number of
    loops in row_search_mvcc for rows found but not
    reporting due to search views etc.
    When scanning a multi-value index, we don't perform the
    check because we cannot convert the indexed value
    (single scalar element) into the primary index (virtual)
    column type (array of values).  */
    if (prev_rec != nullptr && !prebuilt->innodb_api &&
        prebuilt->m_mysql_handler->end_range != nullptr &&
        prebuilt->idx_cond == false &&
        !(clust_templ_for_sec && index->is_multi_value())) {
      /* Create offsets based on prebuilt index. */
      offsets = rec_get_offsets(prev_rec, prebuilt->index, offsets,
                                ULINT_UNDEFINED, UT_LOCATION_HERE, &heap);

      ut_a(prebuilt->m_stop_tuple);

      const auto stop_len = dtuple_get_n_fields_cmp(prebuilt->m_stop_tuple);

      /* If we have prebuilt->m_mysql_handler->end_range we should also
      have a (populated) stop tuple. */
      ut_ad_ne(stop_len, 0);

      if (stop_len > 0) {
        const auto index_len = dict_index_get_n_unique(index);
        ut_a_le(stop_len, index_len);

        /* we can only reach supremum after having scanned another record
          (prev_rec != nullptr) if we are "moving up". The end range check
          optimization does not apply to reverse scans. */
        ut_ad(moves_up);
        const auto cmp =
            cmp_dtuple_rec(prebuilt->m_stop_tuple, prev_rec, index, offsets);

        if (cmp < 0 ||
            (cmp == 0 && prebuilt->m_mysql_handler->end_range->flag ==
                             HA_READ_BEFORE_KEY)) {
          /* Set flag to remeber that the scan reached end of range, so that,
          on subsequent calls to row_search_mvcc(), prebuilt->fetch_cache is
          not filled and DB_RECORD_NOT_FOUND is returned when
          prebuilt->n_fetch_cached is 0, rather than refilling it.
          In case next_buf == nullptr, DB_RECORD_NOT_FOUND is returned
          immediately, otherwise DB_SUCCESS is returned with data row stored
          in next_buf. */
          if (next_buf != nullptr) {
            prebuilt->m_end_range = true;
          }

          err = DB_RECORD_NOT_FOUND;
          goto normal_return;
        }
      }
    }

    if (set_also_gap_locks && !trx->skip_gap_locks() &&
        prebuilt->select_lock_type != LOCK_NONE &&
        !dict_index_is_spatial(index)) {
      /* Try to place a lock on the index record */

      offsets = rec_get_offsets(rec, index, offsets, ULINT_UNDEFINED,
                                UT_LOCATION_HERE, &heap);
      err = sel_set_rec_lock(pcur, rec, index, offsets, prebuilt->select_mode,
                             prebuilt->select_lock_type, LOCK_ORDINARY, thr,
                             &mtr);

      switch (err) {
        case DB_SUCCESS_LOCKED_REC:
          err = DB_SUCCESS;
        case DB_SUCCESS:
          break;
        case DB_SKIP_LOCKED:
        case DB_LOCK_NOWAIT:
          ut_d(ut_error);
        default:
          goto lock_wait_or_error;
      }
    }

    /* A page supremum record cannot be in the result set: skip
    it now that we have placed a possible lock on it */

    prev_rec = nullptr;
    goto next_rec;
  }

  /*-------------------------------------------------------------*/
  /* Do sanity checks in case our cursor has bumped into page
  corruption */

  if (comp) {
    next_offs = rec_get_next_offs(rec, true);
    if (UNIV_UNLIKELY(next_offs < PAGE_NEW_SUPREMUM)) {
      goto wrong_offs;
    }
  } else {
    next_offs = rec_get_next_offs(rec, false);
    if (UNIV_UNLIKELY(next_offs < PAGE_OLD_SUPREMUM)) {
      goto wrong_offs;
    }
  }

  if (UNIV_UNLIKELY(next_offs >= UNIV_PAGE_SIZE - PAGE_DIR)) {
  wrong_offs:
    if (srv_force_recovery == 0 || moves_up == false) {
      ib::error(ER_IB_MSG_1032)
          << "Rec address " << static_cast<const void *>(rec)
          << ", buf block fix count "
          << btr_cur_get_block(pcur->get_btr_cur())->page.buf_fix_count;

      ib::error(ER_IB_MSG_1033)
          << "Index corruption: rec offs " << page_offset(rec) << " next offs "
          << next_offs << ", page no " << page_get_page_no(page_align(rec))
          << ", index " << index->name << " of table " << index->table->name
          << ". Run CHECK TABLE. You may need to"
             " restore from a backup, or dump + drop +"
             " reimport the table.";
      err = DB_CORRUPTION;

      ut_d(ut_error);
      ut_o(goto lock_wait_or_error);
    } else {
      /* The user may be dumping a corrupt table. Jump
      over the corruption to recover as much as possible. */

      ib::info(ER_IB_MSG_1034)
          << "Index corruption: rec offs " << page_offset(rec) << " next offs "
          << next_offs << ", page no " << page_get_page_no(page_align(rec))
          << ", index " << index->name << " of table " << index->table->name
          << ". We try to skip the rest of the page.";

      pcur->move_to_last_on_page(&mtr);

      prev_rec = nullptr;
      goto next_rec;
    }
  }
  /*-------------------------------------------------------------*/

  /* Calculate the 'offsets' associated with 'rec' */

  ut_ad(fil_page_index_page_check(pcur->get_page()));
  ut_ad(btr_page_get_index_id(pcur->get_page()) == index->id);

  offsets = rec_get_offsets(rec, index, offsets, ULINT_UNDEFINED,
                            UT_LOCATION_HERE, &heap);

  if (UNIV_UNLIKELY(srv_force_recovery > 0)) {
    if (!rec_validate(rec, offsets) ||
        !btr_index_rec_validate(rec, index, false)) {
      ib::info(ER_IB_MSG_1035)
          << "Index corruption: rec offs " << page_offset(rec) << " next offs "
          << next_offs << ", page no " << page_get_page_no(page_align(rec))
          << ", index " << index->name << " of table " << index->table->name
          << ". We try to skip the record.";

      prev_rec = nullptr;
      goto next_rec;
    }
  }

  prev_rec = rec;
  ut_d(prev_rec_debug = row_search_debug_copy_rec_order_prefix(
           pcur, index, prev_rec, &prev_rec_debug_n_fields, &prev_rec_debug_buf,
           &prev_rec_debug_buf_size));

  /* Note that we cannot trust the up_match value in the cursor at this
  place because we can arrive here after moving the cursor! Thus
  we have to recompare rec and search_tuple to determine if they
  match enough. */

  if (match_mode == ROW_SEL_EXACT) {
    /* Test if the index record matches completely to search_tuple
    in prebuilt: if not, then we return with DB_RECORD_NOT_FOUND */

    /* fputs("Comparing rec and search tuple\n", stderr); */

    if (0 != cmp_dtuple_rec(search_tuple, rec, index, offsets)) {
      if (set_also_gap_locks && !trx->skip_gap_locks() &&
          prebuilt->select_lock_type != LOCK_NONE &&
          !dict_index_is_spatial(index)) {
        err = sel_set_rec_lock(pcur, rec, index, offsets, prebuilt->select_mode,
                               prebuilt->select_lock_type, LOCK_GAP, thr, &mtr);

        switch (err) {
          case DB_SUCCESS_LOCKED_REC:
          case DB_SUCCESS:
            break;
          case DB_SKIP_LOCKED:
          case DB_LOCK_NOWAIT:
            ut_d(ut_error);
          default:
            goto lock_wait_or_error;
        }
      }

      pcur->store_position(&mtr);

      /* The found record was not a match, but may be used
      as NEXT record (index_next). Set the relative position
      to BTR_PCUR_BEFORE, to reflect that the position of
      the persistent cursor is before the found/stored row
      (pcur->m_old_rec). */
      ut_ad(pcur->m_rel_pos == BTR_PCUR_ON);
      pcur->m_rel_pos = BTR_PCUR_BEFORE;

      err = DB_RECORD_NOT_FOUND;
      goto normal_return;
    }

  } else if (match_mode == ROW_SEL_EXACT_PREFIX) {
    if (!cmp_dtuple_is_prefix_of_rec(search_tuple, rec, index, offsets)) {
      if (set_also_gap_locks && !trx->skip_gap_locks() &&
          prebuilt->select_lock_type != LOCK_NONE &&
          !dict_index_is_spatial(index)) {
        err = sel_set_rec_lock(pcur, rec, index, offsets, prebuilt->select_mode,
                               prebuilt->select_lock_type, LOCK_GAP, thr, &mtr);

        switch (err) {
          case DB_SUCCESS_LOCKED_REC:
          case DB_SUCCESS:
            break;
          case DB_SKIP_LOCKED:
          case DB_LOCK_NOWAIT:
            ut_d(ut_error);
          default:
            goto lock_wait_or_error;
        }
      }

      pcur->store_position(&mtr);

      /* The found record was not a match, but may be used
      as NEXT record (index_next). Set the relative position
      to BTR_PCUR_BEFORE, to reflect that the position of
      the persistent cursor is before the found/stored row
      (pcur->old_rec). */
      ut_ad(pcur->m_rel_pos == BTR_PCUR_ON);
      pcur->m_rel_pos = BTR_PCUR_BEFORE;

      err = DB_RECORD_NOT_FOUND;
      goto normal_return;
    }
  }

  /* We are ready to look at a possible new index entry in the result
  set: the cursor is now placed on a user record */

  if (prebuilt->select_lock_type != LOCK_NONE) {
    auto row_to_range_relation = row_compare_row_to_range(
        set_also_gap_locks, trx, unique_search, index, clust_index, rec, comp,
        mode, direction, search_tuple, offsets, moves_up, prebuilt);

    ulint lock_type;
    if (row_to_range_relation.row_can_be_in_range) {
      if (row_to_range_relation.gap_can_intersect_range) {
        lock_type = LOCK_ORDINARY;
      } else {
        lock_type = LOCK_REC_NOT_GAP;
      }
    } else {
      if (row_to_range_relation.gap_can_intersect_range) {
        lock_type = LOCK_GAP;
      } else {
        err = DB_RECORD_NOT_FOUND;
        goto normal_return;
      }
    }
    /* in case of semi-consistent read, we use SELECT_SKIP_LOCKED, so we don't
    waste time on creating a WAITING lock, as we won't wait on it anyway */
    const bool use_semi_consistent =
        prebuilt->row_read_type == ROW_READ_TRY_SEMI_CONSISTENT &&
        !unique_search && index == clust_index && !trx_is_high_priority(trx);
    err = sel_set_rec_lock(
        pcur, rec, index, offsets,
        use_semi_consistent ? SELECT_SKIP_LOCKED : prebuilt->select_mode,
        prebuilt->select_lock_type, lock_type, thr, &mtr);

    switch (err) {
      const rec_t *old_vers;
      case DB_SUCCESS_LOCKED_REC:
        if (trx->releases_non_matching_rows()) {
          /* Note that a record of
          prebuilt->index was locked. */
          ut_ad(!prebuilt->new_rec_lock[row_prebuilt_t::LOCK_PCUR]);
          prebuilt->new_rec_lock[row_prebuilt_t::LOCK_PCUR] = true;
        }
        err = DB_SUCCESS;
        [[fallthrough]];
      case DB_SUCCESS:
        if (row_to_range_relation.row_must_be_at_end) {
          prebuilt->m_stop_tuple_found = true;
        }
        break;
      case DB_SKIP_LOCKED:
        if (prebuilt->select_mode == SELECT_SKIP_LOCKED) {
          goto next_rec;
        }
        DEBUG_SYNC_C("semi_consistent_read_would_wait");
        ut_a(use_semi_consistent);
        ut_a(trx->allow_semi_consistent());
        /* The following call returns 'offsets' associated with 'old_vers' */
        row_sel_build_committed_vers_for_mysql(
            clust_index, prebuilt, rec, &offsets, &heap, &old_vers,
            need_vrow ? &vrow : nullptr, &mtr);

        ut_ad(!dict_index_is_spatial(index));
        err = DB_SUCCESS;

        if (old_vers == nullptr) {
          /* The row was not yet committed */
          goto next_rec;
        }

        did_semi_consistent_read = true;
        rec = old_vers;
        prev_rec = rec;
        ut_d(prev_rec_debug = row_search_debug_copy_rec_order_prefix(
                 pcur, index, prev_rec, &prev_rec_debug_n_fields,
                 &prev_rec_debug_buf, &prev_rec_debug_buf_size));
        break;
      case DB_LOCK_WAIT:
        /* Lock wait for R-tree should already
        be handled in sel_set_rtr_rec_lock() */
        ut_ad(!dict_index_is_spatial(index));
        /* Never unlock rows that were part of a conflict. */
        prebuilt->new_rec_lock.reset();
        ut_a(!use_semi_consistent);
        goto lock_wait_or_error;
      case DB_RECORD_NOT_FOUND:
        if (dict_index_is_spatial(index)) {
          goto next_rec;
        } else {
          goto lock_wait_or_error;
        }

      default:
        ut_a(!use_semi_consistent);
        goto lock_wait_or_error;
    }
    if (err == DB_SUCCESS && !row_to_range_relation.row_can_be_in_range) {
      err = DB_RECORD_NOT_FOUND;
      goto normal_return;
    }
  } else {
    /* This is a non-locking consistent read: if necessary, fetch
    a previous version of the record */

    if (trx->isolation_level == TRX_ISO_READ_UNCOMMITTED) {
      /* Do nothing: we let a non-locking SELECT read the
      latest version of the record */

    } else if (index == clust_index) {
      /* Fetch a previous version of the row if the current
      one is not visible in the snapshot; if we have a very
      high force recovery level set, we try to avoid crashes
      by skipping this lookup */

      if (srv_force_recovery < 5 &&
          !lock_clust_rec_cons_read_sees(rec, index, offsets,
                                         trx_get_read_view(trx))) {
        rec_t *old_vers;
        /* The following call returns 'offsets' associated with 'old_vers' */
        err = row_sel_build_prev_vers_for_mysql(
            trx->read_view, clust_index, prebuilt, rec, &offsets, &heap,
            &old_vers, need_vrow ? &vrow : nullptr, &mtr,
            prebuilt->get_lob_undo());

        if (err != DB_SUCCESS) {
          goto lock_wait_or_error;
        }

        if (old_vers == nullptr) {
          /* The row did not exist yet in
          the read view */

          goto next_rec;
        }

        rec = old_vers;
        prev_rec = rec;
        ut_d(prev_rec_debug = row_search_debug_copy_rec_order_prefix(
                 pcur, index, prev_rec, &prev_rec_debug_n_fields,
                 &prev_rec_debug_buf, &prev_rec_debug_buf_size));
      }
    } else {
      /* We are looking into a non-clustered index,
      and to get the right version of the record we
      have to look also into the clustered index: this
      is necessary, because we can only get the undo
      information via the clustered index record. */

      ut_ad(!index->is_clustered());

      if (!srv_read_only_mode &&
          !lock_sec_rec_cons_read_sees(rec, index, trx->read_view)) {
        /* We should look at the clustered index.
        However, as this is a non-locking read,
        we can skip the clustered index lookup if
        the condition does not match the secondary
        index entry. */
        switch (row_search_idx_cond_check(buf, prebuilt, rec, offsets)) {
          case ICP_NO_MATCH:
            goto next_rec;
          case ICP_OUT_OF_RANGE:
            err = DB_RECORD_NOT_FOUND;
            goto idx_cond_failed;
          case ICP_MATCH:
            goto requires_clust_rec;
        }

        ut_error;
      }
    }
  }

#ifdef UNIV_DEBUG
  if (did_semi_consistent_read) {
    ut_a(prebuilt->select_lock_type != LOCK_NONE);
    ut_a(!prebuilt->table->is_intrinsic());
    ut_a(prebuilt->row_read_type == ROW_READ_TRY_SEMI_CONSISTENT);
    ut_a(prebuilt->trx->allow_semi_consistent());
    ut_a(prebuilt->new_rec_locks_count() == 0);
  }
#endif /* UNIV_DEBUG */

  /* NOTE that at this point rec can be an old version of a clustered
  index record built for a consistent read. We cannot assume after this
  point that rec is on a buffer pool page. Functions like
  page_rec_is_comp() cannot be used! */

  if (rec_get_deleted_flag(rec, comp)) {
    /* The record is delete-marked: we can skip it */

    /* No need to keep a lock on a delete-marked record in lower isolation
    levels - it's similar to when Server sees the WHERE condition doesn't match
    and calls unlock_row(). */
    prebuilt->try_unlock(true);

    /* This is an optimization to skip setting the next key lock
    on the record that follows this delete-marked record. This
    optimization works because of the unique search criteria
    which precludes the presence of a range lock between this
    delete marked record and the record following it.

    For now this is applicable only to clustered indexes while
    doing a unique search except for HANDLER queries because
    HANDLER allows NEXT and PREV even in unique search on
    clustered index. There is scope for further optimization
    applicable to unique secondary indexes. Current behaviour is
    to widen the scope of a lock on an already delete marked record
    if the same record is deleted twice by the same transaction */
    if (index == clust_index && unique_search && !prebuilt->used_in_HANDLER) {
      err = DB_RECORD_NOT_FOUND;

      goto normal_return;
    }

    goto next_rec;
  }

  /* Check if the record matches the index condition. */
  switch (row_search_idx_cond_check(buf, prebuilt, rec, offsets)) {
    case ICP_NO_MATCH:
      prebuilt->try_unlock(true);
      goto next_rec;
    case ICP_OUT_OF_RANGE:
      err = DB_RECORD_NOT_FOUND;
      prebuilt->try_unlock(true);
      goto idx_cond_failed;
    case ICP_MATCH:
      break;
  }

  /* Get the clustered index record if needed, if we did not do the
  search using the clustered index. */

  if (index != clust_index && prebuilt->need_to_access_clustered) {
  requires_clust_rec:
    ut_ad(index != clust_index);
    /* We use a 'goto' to the preceding label if a consistent
    read of a secondary index record requires us to look up old
    versions of the associated clustered index record. */

    ut_ad(rec_offs_validate(rec, index, offsets));

    /* It was a non-clustered index and we must fetch also the
    clustered index record */

    mtr_has_extra_clust_latch = true;

    ut_ad(!vrow);

    /* The following call returns 'offsets' associated with
    'clust_rec'. Note that 'clust_rec' can be an old version
    built for a consistent read. */
    err = row_sel_get_clust_rec_for_mysql(
        prebuilt, index, rec, thr, &clust_rec, &offsets, &heap,
        need_vrow ? &vrow : nullptr, &mtr, prebuilt->get_lob_undo());
    switch (err) {
      case DB_SUCCESS:
        if (clust_rec == nullptr) {
          /* The record did not exist in the read view */
          ut_ad(prebuilt->select_lock_type == LOCK_NONE ||
                dict_index_is_spatial(index));

          goto next_rec;
        }
        break;
      case DB_SKIP_LOCKED:
        goto next_rec;
      case DB_SUCCESS_LOCKED_REC:
        ut_a(clust_rec != nullptr);
        if (trx->releases_non_matching_rows()) {
          /* Note that the clustered index record
          was locked. */
          ut_ad(!prebuilt->new_rec_lock[row_prebuilt_t::LOCK_CLUST_PCUR]);
          prebuilt->new_rec_lock[row_prebuilt_t::LOCK_CLUST_PCUR] = true;
        }
        err = DB_SUCCESS;
        break;
      default:
        vrow = nullptr;
        goto lock_wait_or_error;
    }

    if (rec_get_deleted_flag(clust_rec, comp)) {
      /* The record is delete marked: we can skip it */

      /* No need to keep a lock on a delete-marked record in lower isolation
      levels - it's similar to when Server sees the WHERE condition doesn't
      match and calls unlock_row(). */
      prebuilt->try_unlock(true);

      goto next_rec;
    }

    if (need_vrow && !vrow) {
      if (!heap) {
        heap = mem_heap_create(100, UT_LOCATION_HERE);
      }
      row_sel_fill_vrow(rec, index, &vrow, heap);
    }

    result_rec = clust_rec;
    ut_ad(rec_offs_validate(result_rec, clust_index, offsets));

    if (prebuilt->idx_cond) {
      /* Convert the record to MySQL format. We were
      unable to do this in row_search_idx_cond_check(),
      because the condition is on the secondary index
      and the requested column is in the clustered index.
      We convert all fields, including those that
      may have been used in ICP, because the
      secondary index may contain a column prefix
      rather than the full column. Also, as noted
      in Bug #56680, the column in the secondary
      index may be in the wrong case, and the
      authoritative case is in result_rec, the
      appropriate version of the clustered index record. */
      if (!row_sel_store_mysql_rec(buf, prebuilt, result_rec, vrow, true,
                                   clust_index, prebuilt->index, offsets, false,
                                   nullptr, prebuilt->blob_heap)) {
        goto next_rec;
      }
    }

    /* TODO: This is for a temporary fix, will be removed later */
    /* Check duplicate rec for spatial index. */
    if (dict_index_is_spatial(index) && rec_get_deleted_flag(rec, comp) &&
        prebuilt->rtr_info->is_dup) {
      dtuple_t *clust_row;
      row_ext_t *ext = nullptr;
      rtr_mbr_t clust_mbr;
      rtr_mbr_t index_mbr;
      ulint *index_offsets;
      const dtuple_t *index_entry;
      bool *is_dup_rec = prebuilt->rtr_info->is_dup;

      *is_dup_rec = false;

      if (!heap) {
        heap = mem_heap_create(100, UT_LOCATION_HERE);
      }

      clust_row = row_build(ROW_COPY_DATA, clust_index, clust_rec, offsets,
                            nullptr, nullptr, nullptr, &ext, heap);
      index_entry = row_build_index_entry(clust_row, ext, index, heap);
      rtr_get_mbr_from_tuple(index_entry, &clust_mbr);

      index_offsets = rec_get_offsets(rec, index, nullptr, ULINT_UNDEFINED,
                                      UT_LOCATION_HERE, &heap);
      rtr_get_mbr_from_rec(rec, index_offsets, &index_mbr);

      /* We use mbr_equal_physically() because we are comparing
      MBR between Clustured Index & Spatial Index to identify duplicates.
      As during UPDATE we check for MBR being physically equal, check
      for duplicate should also happen physically.*/
      if (mbr_equal_physically(&clust_mbr, &index_mbr)) {
        ut_ad(!rec_get_deleted_flag(clust_rec, comp));
        /* Duplicate because it has the same MBR as the record in PK,
        but the record in PK is not delete marked, while ours is. */
        *is_dup_rec = true;
      }
    }
  } else {
    result_rec = rec;
  }

  /* We found a qualifying record 'result_rec'. At this point,
  'offsets' are associated with 'result_rec'. */

  ut_ad(rec_offs_validate(result_rec, result_rec != rec ? clust_index : index,
                          offsets));
  ut_ad(!rec_get_deleted_flag(result_rec, comp));

  /* If we cannot prefetch records, we should not have a record buffer.
  See ha_innobase::ha_is_record_buffer_wanted(). */
  ut_ad(prebuilt->can_prefetch_records() || record_buffer == nullptr);

  /* Decide whether to prefetch extra rows.
  At this point, the clustered index record is protected
  by a page latch that was acquired when pcur was positioned.
  The latch will not be released until mtr_commit(&mtr). */

  if (record_buffer != nullptr ||
      ((match_mode == ROW_SEL_EXACT ||
        prebuilt->n_rows_fetched >= MYSQL_FETCH_CACHE_THRESHOLD) &&
       prebuilt->can_prefetch_records())) {
    /* Inside an update, for example, we do not cache rows,
    since we may use the cursor position to do the actual
    update, that is why we require ...lock_type == LOCK_NONE.
    Since we keep space in prebuilt only for the BLOBs of
    a single row, we cannot cache rows in the case there
    are BLOBs in the fields to be fetched. In HANDLER (note:
    the HANDLER statement, not the handler class) we do
    not cache rows because there the cursor is a scrollable
    cursor. */

    const auto max_rows_to_cache =
        record_buffer ? record_buffer->max_records() : MYSQL_FETCH_CACHE_SIZE;
    ut_a(prebuilt->n_fetch_cached < max_rows_to_cache);

    /* We only convert from InnoDB row format to MySQL row
    format when ICP is disabled. */

    if (!prebuilt->idx_cond) {
      /* We use next_buf to track the allocation of buffers
      where we store and enqueue the buffers for our
      pre-fetch optimisation.

      If next_buf == 0 then we store the converted record
      directly into the MySQL record buffer (buf). If it is
      != 0 then we allocate a pre-fetch buffer and store the
      converted record there.

      If the conversion fails and the MySQL record buffer
      was not written to then we reset next_buf so that
      we can re-use the MySQL record buffer in the next
      iteration. */
      byte *prev_buf = next_buf;

      next_buf = next_buf ? row_sel_fetch_last_buf(prebuilt) : buf;

      if (!row_sel_store_mysql_rec(
              next_buf, prebuilt, result_rec, vrow, result_rec != rec,
              result_rec != rec ? clust_index : index, prebuilt->index, offsets,
              false, nullptr, prebuilt->blob_heap)) {
        if (next_buf == buf) {
          ut_a(prebuilt->n_fetch_cached == 0);
          next_buf = nullptr;
        }

        /* Only fresh inserts may contain incomplete
        externally stored columns. Pretend that such
        records do not exist. Such records may only be
        accessed at the READ UNCOMMITTED isolation
        level or when rolling back a recovered
        transaction. Rollback happens at a lower
        level, not here. */
        goto next_rec;
      }

      /* If we are filling a server-provided buffer, and the
      server has pushed down an end range condition, evaluate
      the condition to prevent that we read too many rows.
      When scanning a multi-value index, we don't perform the
      check because we cannot convert the indexed value
      (single scalar element) into the primary index (virtual)
      column type (array of values). */
      if (record_buffer != nullptr &&
          prebuilt->m_mysql_handler->end_range != nullptr &&
          !(clust_templ_for_sec && index->is_multi_value())) {
        /* If the end-range condition refers to a
        virtual column and we are reading from the
        clustered index, next_buf does not have the
        value of the virtual column. Get the offsets in
        the secondary index so that we can read the
        virtual column from the index. */
        if (clust_templ_for_sec &&
            prebuilt->m_mysql_handler->m_virt_gcol_in_end_range) {
          if (sec_offsets == nullptr) {
            rec_offs_init(sec_offsets_);
            sec_offsets = sec_offsets_;
          }
          sec_offsets =
              rec_get_offsets(rec, index, sec_offsets, ULINT_UNDEFINED,
                              UT_LOCATION_HERE, &heap);
        }

        if (row_search_end_range_check(next_buf, rec, prebuilt,
                                       clust_templ_for_sec, sec_offsets,
                                       record_buffer)) {
          if (next_buf != buf) {
            record_buffer->remove_last();
          }
          next_buf = prev_buf;
          err = DB_RECORD_NOT_FOUND;
          goto normal_return;
        }
      }

      if (next_buf != buf) {
        row_sel_enqueue_cache_row_for_mysql(next_buf, prebuilt);
      }
    } else {
      row_sel_enqueue_cache_row_for_mysql(buf, prebuilt);
    }

    if (prebuilt->n_fetch_cached < max_rows_to_cache) {
      goto next_rec;
    }

  } else {
    /* We cannot use a record buffer for this scan, so assert that
    we don't have one. If we have a record buffer here,
    ha_innobase::is_record_buffer_wanted() should be updated so
    that a buffer is not allocated unnecessarily. */
    ut_ad(record_buffer == nullptr);

    if (UNIV_UNLIKELY(prebuilt->template_type == ROW_MYSQL_DUMMY_TEMPLATE)) {
      /* CHECK TABLE: fetch the row */

      if (result_rec != rec && !prebuilt->need_to_access_clustered) {
        /* We used 'offsets' for the clust
        rec, recalculate them for 'rec' */
        offsets = rec_get_offsets(rec, index, offsets, ULINT_UNDEFINED,
                                  UT_LOCATION_HERE, &heap);
        result_rec = rec;
      }

      memcpy(buf + 4, result_rec - rec_offs_extra_size(offsets),
             rec_offs_size(offsets));
      mach_write_to_4(buf, rec_offs_extra_size(offsets) + 4);
    } else if (!prebuilt->idx_cond && !prebuilt->innodb_api) {
      /* The record was not yet converted to MySQL format. */
      if (!row_sel_store_mysql_rec(
              buf, prebuilt, result_rec, vrow, result_rec != rec,
              result_rec != rec ? clust_index : index, prebuilt->index, offsets,
              false, prebuilt->get_lob_undo(), prebuilt->blob_heap)) {
        /* Only fresh inserts may contain
        incomplete externally stored
        columns. Pretend that such records do
        not exist. Such records may only be
        accessed at the READ UNCOMMITTED
        isolation level or when rolling back a
        recovered transaction. Rollback
        happens at a lower level, not here. */
        goto next_rec;
      }
    }

    if (prebuilt->clust_index_was_generated) {
      row_sel_store_row_id_to_prebuilt(prebuilt, result_rec,
                                       result_rec == rec ? index : clust_index,
                                       offsets);
    }
  }

  /* From this point on, 'offsets' are invalid. */

  /* We have an optimization to save CPU time: if this is a consistent
  read on a unique condition on the clustered index, then we do not
  store the pcur position, because any fetch next or prev will anyway
  return 'end of file'. Exceptions are locking reads and the MySQL
  HANDLER command where the user can move the cursor with PREV or NEXT
  even after a unique search. */

  err = DB_SUCCESS;

idx_cond_failed:
  if (!unique_search || !index->is_clustered() || direction != 0 ||
      prebuilt->select_lock_type != LOCK_NONE || prebuilt->used_in_HANDLER ||
      prebuilt->innodb_api) {
    /* Inside an update always store the cursor position */

    if (!spatial_search) {
      pcur->store_position(&mtr);
    }

    if (prebuilt->innodb_api && (pcur->get_rec() != result_rec)) {
      ulint rec_size = rec_offs_size(offsets);
      if (!prebuilt->innodb_api_rec_size ||
          (prebuilt->innodb_api_rec_size < rec_size)) {
        prebuilt->innodb_api_buf = static_cast<byte *>(
            mem_heap_alloc(prebuilt->cursor_heap, rec_size));
        prebuilt->innodb_api_rec_size = rec_size;
      }
      prebuilt->innodb_api_rec =
          rec_copy(prebuilt->innodb_api_buf, result_rec, offsets);
    }
  }

  goto normal_return;

next_rec:

  /* Reset the old and new "did semi-consistent read" flags. */
  if (UNIV_UNLIKELY(prebuilt->row_read_type == ROW_READ_DID_SEMI_CONSISTENT)) {
    prebuilt->row_read_type = ROW_READ_TRY_SEMI_CONSISTENT;
  }
  did_semi_consistent_read = false;
  prebuilt->new_rec_lock.reset();

  vrow = nullptr;

  /*-------------------------------------------------------------*/
  /* PHASE 5: Move the cursor to the next index record */

  /* NOTE: For moves_up==false, the mini-transaction will be
  committed and restarted every time when switching b-tree
  pages. For moves_up==true in index condition pushdown, we can
  scan an entire secondary index tree within a single
  mini-transaction. As long as the prebuilt->idx_cond does not
  match, we do not need to consult the clustered index or
  return records to MySQL, and thus we can avoid repositioning
  the cursor. What prevents us from buffer-fixing all leaf pages
  within the mini-transaction is the btr_leaf_page_release()
  call in btr_pcur::move_to_next_page(). Only the leaf page where
  the cursor is positioned will remain buffer-fixed.
  For R-tree spatial search, we also commit the mini-transaction
  each time  */

  if (mtr_has_extra_clust_latch || spatial_search) {
    /* If we have extra cluster latch, we must commit
    mtr if we are moving to the next non-clustered
    index record, because we could break the latching
    order if we would access a different clustered
    index page right away without releasing the previous. */

    bool is_pcur_rec = (pcur->get_rec() == prev_rec);

    /* No need to do store restore for R-tree */
    if (!spatial_search) {
      pcur->store_position(&mtr);
    }

    mtr_commit(&mtr);
    mtr_has_extra_clust_latch = false;

    DEBUG_SYNC_C("row_search_before_mtr_restart_for_extra_clust");

    mtr_start(&mtr);

    if (!spatial_search) {
      const auto result = sel_restore_position_for_mysql(
          &same_user_rec, BTR_SEARCH_LEAF, pcur, moves_up, &mtr);

      if (result) {
        prev_rec = nullptr;
        goto rec_loop;
      }

      ut_ad(same_user_rec);

      if (is_pcur_rec && pcur->get_rec() != prev_rec) {
        /* prev_rec is invalid. */
        prev_rec = nullptr;
      }

#ifdef UNIV_DEBUG
      if (prev_rec != nullptr && prev_rec_debug != nullptr) {
        const ulint *offsets1;
        const ulint *offsets2;

        auto heap_tmp = mem_heap_create(256, UT_LOCATION_HERE);

        offsets1 = rec_get_offsets(prev_rec_debug, index, nullptr,
                                   prev_rec_debug_n_fields, UT_LOCATION_HERE,
                                   &heap_tmp);

        offsets2 =
            rec_get_offsets(prev_rec, index, nullptr, prev_rec_debug_n_fields,
                            UT_LOCATION_HERE, &heap_tmp);

        ut_ad(!cmp_rec_rec(prev_rec_debug, prev_rec, offsets1, offsets2, index,
                           page_is_spatial_non_leaf(prev_rec, index), nullptr,
                           false));
        mem_heap_free(heap_tmp);
      }
#endif /* UNIV_DEBUG */
    }
  }

  if (moves_up) {
    bool move;

    if (spatial_search) {
      move = rtr_pcur_move_to_next(search_tuple, mode, prebuilt->select_mode,
                                   pcur, 0, &mtr);
    } else {
      move = pcur->move_to_next(&mtr);
    }

    if (!move) {
    not_moved:
      if (!spatial_search) {
        pcur->store_position(&mtr);
      }

      if (match_mode != 0) {
        err = DB_RECORD_NOT_FOUND;
      } else {
        err = DB_END_OF_INDEX;
      }

      goto normal_return;
    }
  } else {
    if (UNIV_UNLIKELY(!pcur->move_to_prev(&mtr))) {
      goto not_moved;
    }
  }

  goto rec_loop;

lock_wait_or_error:
  /* Reset the old and new "did semi-consistent read" flags. */
  if (UNIV_UNLIKELY(prebuilt->row_read_type == ROW_READ_DID_SEMI_CONSISTENT)) {
    prebuilt->row_read_type = ROW_READ_TRY_SEMI_CONSISTENT;
  }
  did_semi_consistent_read = false;

  /*-------------------------------------------------------------*/
  if (!dict_index_is_spatial(index)) {
    pcur->store_position(&mtr);
  }

lock_table_wait:
  mtr_commit(&mtr);
  mtr_has_extra_clust_latch = false;

  trx->error_state = err;

  /* The following is a patch for MySQL */

  if (thr->is_active) {
    que_thr_stop_for_mysql(thr);
  }

  thr->lock_state = QUE_THR_LOCK_ROW;

  if (row_mysql_handle_errors(&err, trx, thr, nullptr)) {
    /* It was a lock wait, and it ended */

    thr->lock_state = QUE_THR_LOCK_NOLOCK;
    mtr_start(&mtr);

    /* Table lock waited, go try to obtain table lock
    again */
    if (table_lock_waited) {
      table_lock_waited = false;

      goto wait_table_again;
    }

    if (!dict_index_is_spatial(index)) {
      sel_restore_position_for_mysql(&same_user_rec, BTR_SEARCH_LEAF, pcur,
                                     moves_up, &mtr);
      prev_rec = nullptr;
    }

    if (!same_user_rec && trx->releases_non_matching_rows()) {
      /* Since we were not able to restore the cursor
      on the same user record, we cannot use
      row_prebuilt_t::try_unlock() to unlock any records, and
      we must thus reset the new rec lock info. Since
      in lock0lock.cc we have blocked the inheriting of gap
      X-locks, we actually do not have any new record locks
      set in this case.

      Note that if we were able to restore on the 'same'
      user record, it is still possible that we were actually
      waiting on a delete-marked record, and meanwhile
      it was removed by purge and inserted again by some
      other user. But that is no problem, because in
      rec_loop we will again try to set a lock, and
      new_rec_lock_info in trx will be right at the end. */

      prebuilt->new_rec_lock.reset();
    }

    mode = pcur->m_search_mode;

    goto rec_loop;
  }

  thr->lock_state = QUE_THR_LOCK_NOLOCK;

  goto func_exit;

normal_return:
  /*-------------------------------------------------------------*/
  que_thr_stop_for_mysql_no_error(thr, trx);

  mtr_commit(&mtr);

  /* Rollback blocking transactions from hit list for high priority
  transaction, if any. We should not be holding latches here as
  we are going to rollback the blocking transactions. */
  trx_kill_blocking(trx);

  DEBUG_SYNC_C("row_search_for_mysql_before_return");

  if (prebuilt->idx_cond != 0) {
    /* When ICP is active we don't write to the MySQL buffer
    directly, only to buffers that are enqueued in the pre-fetch
    queue. We need to dequeue the first buffer and copy the contents
    to the record buffer that was passed in by MySQL. */

    if (prebuilt->n_fetch_cached > 0) {
      row_sel_dequeue_cached_row_for_mysql(buf, prebuilt);
      err = DB_SUCCESS;
    }

  } else if (next_buf != nullptr) {
    /* We may or may not have enqueued some buffers to the
    pre-fetch queue, but we definitely wrote to the record
    buffer passed to use by MySQL. */

    DEBUG_SYNC_C("row_search_cached_row");
    err = DB_SUCCESS;
  }

#ifdef UNIV_DEBUG
  if (dict_index_is_spatial(index) && err != DB_SUCCESS &&
      err != DB_END_OF_INDEX && err != DB_INTERRUPTED) {
    rtr_node_path_t *path = pcur->m_btr_cur.rtr_info->path;

    ut_ad(path->empty());
  }
#endif

func_exit:
  trx->op_info = "";

  if (end_range_cache != nullptr) {
    ut::free(end_range_cache);
  }

  if (heap != nullptr) {
    mem_heap_free(heap);
  }

#ifdef UNIV_DEBUG
  if (prev_rec_debug_buf != nullptr) {
    ut::free(prev_rec_debug_buf);
  }
#endif /* UNIV_DEBUG */

  /* Set or reset the "did semi-consistent read" flag on return.
  The flag did_semi_consistent_read is set if and only if
  the record being returned was fetched with a semi-consistent read. */
  ut_ad(prebuilt->row_read_type != ROW_READ_WITH_LOCKS ||
        !did_semi_consistent_read);

  if (prebuilt->row_read_type != ROW_READ_WITH_LOCKS) {
    if (did_semi_consistent_read) {
      prebuilt->row_read_type = ROW_READ_DID_SEMI_CONSISTENT;
    } else {
      prebuilt->row_read_type = ROW_READ_TRY_SEMI_CONSISTENT;
    }
  }

#ifdef UNIV_DEBUG
  {
    btrsea_sync_check check(trx->has_search_latch);

    ut_ad(!sync_check_iterate(check));
  }
#endif /* UNIV_DEBUG */

  DEBUG_SYNC_C("innodb_row_search_for_mysql_exit");

  prebuilt->lob_undo_reset();

  ut_a(!trx->has_search_latch);

  return err;
}