row0sel.c 125 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
/*****************************************************************************

Copyright (c) 1997, 2009, Innobase Oy. All Rights Reserved.
Copyright (c) 2008, Google Inc.

Portions of this file contain modifications contributed and copyrighted by
Google, Inc. Those modifications are gratefully acknowledged and are described
briefly in the InnoDB documentation. The contributions by Google are
incorporated with their permission, and subject to the conditions contained in
the file COPYING.Google.

This program is free software; you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free Software
Foundation; version 2 of the License.

This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.

You should have received a copy of the GNU General Public License along with
this program; if not, write to the Free Software Foundation, Inc., 59 Temple
Place, Suite 330, Boston, MA 02111-1307 USA

*****************************************************************************/

26 27
/***************************************************//**
@file row/row0sel.c
osku's avatar
osku committed
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
Select

Created 12/19/1997 Heikki Tuuri
*******************************************************/

#include "row0sel.h"

#ifdef UNIV_NONINL
#include "row0sel.ic"
#endif

#include "dict0dict.h"
#include "dict0boot.h"
#include "trx0undo.h"
#include "trx0trx.h"
#include "btr0btr.h"
#include "btr0cur.h"
#include "btr0sea.h"
#include "mach0data.h"
#include "que0que.h"
#include "row0upd.h"
#include "row0row.h"
#include "row0vers.h"
#include "rem0cmp.h"
#include "lock0lock.h"
#include "eval0eval.h"
#include "pars0sym.h"
#include "pars0pars.h"
#include "row0mysql.h"
#include "read0read.h"
#include "buf0lru.h"
59
#include "ha_prototypes.h"
osku's avatar
osku committed
60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77

/* Maximum number of rows to prefetch; MySQL interface has another parameter */
#define SEL_MAX_N_PREFETCH	16

/* Number of rows fetched, after which to start prefetching; MySQL interface
has another parameter */
#define SEL_PREFETCH_LIMIT	1

/* When a select has accessed about this many pages, it returns control back
to que_run_threads: this is to allow canceling runaway queries */

#define SEL_COST_LIMIT	100

/* Flags for search shortcut */
#define SEL_FOUND	0
#define	SEL_EXHAUSTED	1
#define SEL_RETRY	2

78
/********************************************************************//**
79 80 81 82
Returns TRUE if the user-defined column in a secondary index record
is alphabetically the same as the corresponding BLOB column in the clustered
index record.
NOTE: the comparison is NOT done as a binary comparison, but character
83 84
fields are compared with collation!
@return	TRUE if the columns are equal */
85 86 87 88
static
ibool
row_sel_sec_rec_is_for_blob(
/*========================*/
89 90 91
	ulint		mtype,		/*!< in: main type */
	ulint		prtype,		/*!< in: precise type */
	ulint		mbminlen,	/*!< in: minimum length of a
marko's avatar
marko committed
92
					multi-byte character */
93
	ulint		mbmaxlen,	/*!< in: maximum length of a
94
					multi-byte character */
95
	const byte*	clust_field,	/*!< in: the locally stored part of
96 97 98 99 100
					the clustered index column, including
					the BLOB pointer; the clustered
					index record must be covered by
					a lock or a page latch to protect it
					against deletion (rollback or purge) */
101 102 103 104
	ulint		clust_len,	/*!< in: length of clust_field */
	const byte*	sec_field,	/*!< in: column in secondary index */
	ulint		sec_len,	/*!< in: length of sec_field */
	ulint		zip_size)	/*!< in: compressed page size, or 0 */
105 106 107 108 109 110 111
{
	ulint	len;
	byte	buf[DICT_MAX_INDEX_COL_LEN];

	len = btr_copy_externally_stored_field_prefix(buf, sizeof buf,
						      zip_size,
						      clust_field, clust_len);
112 113 114 115 116 117 118 119 120 121

	if (UNIV_UNLIKELY(len == 0)) {
		/* The BLOB was being deleted as the server crashed.
		There should not be any secondary index records
		referring to this clustered index record, because
		btr_free_externally_stored_field() is called after all
		secondary index entries of the row have been purged. */
		return(FALSE);
	}

122
	len = dtype_get_at_most_n_mbchars(prtype, mbminlen, mbmaxlen,
123
					  sec_len, len, (const char*) buf);
124 125 126 127

	return(!cmp_data_data(mtype, prtype, buf, len, sec_field, sec_len));
}

128
/********************************************************************//**
osku's avatar
osku committed
129 130 131 132
Returns TRUE if the user-defined column values in a secondary index record
are alphabetically the same as the corresponding columns in the clustered
index record.
NOTE: the comparison is NOT done as a binary comparison, but character
133
fields are compared with collation!
134
@return TRUE if the secondary record is equal to the corresponding
135 136
fields in the clustered record, when compared with collation;
FALSE if not equal or if the clustered record has been marked for deletion */
osku's avatar
osku committed
137 138 139 140
static
ibool
row_sel_sec_rec_is_for_clust_rec(
/*=============================*/
141 142 143
	const rec_t*	sec_rec,	/*!< in: secondary index record */
	dict_index_t*	sec_index,	/*!< in: secondary index */
	const rec_t*	clust_rec,	/*!< in: clustered index record;
144 145 146
					must be protected by a lock or
					a page latch against deletion
					in rollback or purge */
147
	dict_index_t*	clust_index)	/*!< in: clustered index */
osku's avatar
osku committed
148
{
marko's avatar
marko committed
149
	const byte*	sec_field;
150
	ulint		sec_len;
marko's avatar
marko committed
151
	const byte*	clust_field;
152 153
	ulint		n;
	ulint		i;
osku's avatar
osku committed
154 155 156 157 158 159 160
	mem_heap_t*	heap		= NULL;
	ulint		clust_offsets_[REC_OFFS_NORMAL_SIZE];
	ulint		sec_offsets_[REC_OFFS_SMALL_SIZE];
	ulint*		clust_offs	= clust_offsets_;
	ulint*		sec_offs	= sec_offsets_;
	ibool		is_equal	= TRUE;

161 162
	rec_offs_init(clust_offsets_);
	rec_offs_init(sec_offsets_);
osku's avatar
osku committed
163

164 165 166 167 168 169 170 171 172 173
	if (rec_get_deleted_flag(clust_rec,
				 dict_table_is_comp(clust_index->table))) {

		/* The clustered index record is delete-marked;
		it is not visible in the read view.  Besides,
		if there are any externally stored columns,
		some of them may have already been purged. */
		return(FALSE);
	}

osku's avatar
osku committed
174
	clust_offs = rec_get_offsets(clust_rec, clust_index, clust_offs,
175
				     ULINT_UNDEFINED, &heap);
osku's avatar
osku committed
176
	sec_offs = rec_get_offsets(sec_rec, sec_index, sec_offs,
177
				   ULINT_UNDEFINED, &heap);
osku's avatar
osku committed
178

179
	n = dict_index_get_n_ordering_defined_by_user(sec_index);
osku's avatar
osku committed
180

181
	for (i = 0; i < n; i++) {
182 183
		const dict_field_t*	ifield;
		const dict_col_t*	col;
184 185 186
		ulint			clust_pos;
		ulint			clust_len;
		ulint			len;
187

osku's avatar
osku committed
188
		ifield = dict_index_get_nth_field(sec_index, i);
189
		col = dict_field_get_col(ifield);
190
		clust_pos = dict_col_get_clust_pos(col, clust_index);
191

192
		clust_field = rec_get_nth_field(
193
			clust_rec, clust_offs, clust_pos, &clust_len);
osku's avatar
osku committed
194 195
		sec_field = rec_get_nth_field(sec_rec, sec_offs, i, &sec_len);

196 197 198 199 200 201 202
		len = clust_len;

		if (ifield->prefix_len > 0 && len != UNIV_SQL_NULL) {

			if (rec_offs_nth_extern(clust_offs, clust_pos)) {
				len -= BTR_EXTERN_FIELD_REF_SIZE;
			}
osku's avatar
osku committed
203

204
			len = dtype_get_at_most_n_mbchars(
205
				col->prtype, col->mbminlen, col->mbmaxlen,
206 207 208 209 210 211
				ifield->prefix_len, len, (char*) clust_field);

			if (rec_offs_nth_extern(clust_offs, clust_pos)
			    && len < sec_len) {
				if (!row_sel_sec_rec_is_for_blob(
					    col->mtype, col->prtype,
212
					    col->mbminlen, col->mbmaxlen,
213 214 215 216 217 218
					    clust_field, clust_len,
					    sec_field, sec_len,
					    dict_table_zip_size(
						    clust_index->table))) {
					goto inequal;
				}
219 220

				continue;
221
			}
osku's avatar
osku committed
222 223
		}

224
		if (0 != cmp_data_data(col->mtype, col->prtype,
225
				       clust_field, len,
226
				       sec_field, sec_len)) {
227
inequal:
osku's avatar
osku committed
228 229
			is_equal = FALSE;
			goto func_exit;
230 231
		}
	}
osku's avatar
osku committed
232 233 234 235 236 237 238 239

func_exit:
	if (UNIV_LIKELY_NULL(heap)) {
		mem_heap_free(heap);
	}
	return(is_equal);
}

240
/*********************************************************************//**
241 242
Creates a select node struct.
@return	own: select node struct */
243
UNIV_INTERN
osku's avatar
osku committed
244 245 246
sel_node_t*
sel_node_create(
/*============*/
247
	mem_heap_t*	heap)	/*!< in: memory heap where created */
osku's avatar
osku committed
248 249 250 251 252 253 254 255
{
	sel_node_t*	node;

	node = mem_heap_alloc(heap, sizeof(sel_node_t));
	node->common.type = QUE_NODE_SELECT;
	node->state = SEL_NODE_OPEN;

	node->plans = NULL;
256

osku's avatar
osku committed
257 258 259
	return(node);
}

260
/*********************************************************************//**
osku's avatar
osku committed
261 262
Frees the memory private to a select node when a query graph is freed,
does not free the heap where the node was originally created. */
263
UNIV_INTERN
osku's avatar
osku committed
264 265 266
void
sel_node_free_private(
/*==================*/
267
	sel_node_t*	node)	/*!< in: select node struct */
osku's avatar
osku committed
268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285
{
	ulint	i;
	plan_t*	plan;

	if (node->plans != NULL) {
		for (i = 0; i < node->n_tables; i++) {
			plan = sel_node_get_nth_plan(node, i);

			btr_pcur_close(&(plan->pcur));
			btr_pcur_close(&(plan->clust_pcur));

			if (plan->old_vers_heap) {
				mem_heap_free(plan->old_vers_heap);
			}
		}
	}
}

286
/*********************************************************************//**
osku's avatar
osku committed
287 288 289 290 291 292
Evaluates the values in a select list. If there are aggregate functions,
their argument value is added to the aggregate total. */
UNIV_INLINE
void
sel_eval_select_list(
/*=================*/
293
	sel_node_t*	node)	/*!< in: select node */
osku's avatar
osku committed
294 295 296 297 298 299 300 301 302 303 304 305
{
	que_node_t*	exp;

	exp = node->select_list;

	while (exp) {
		eval_exp(exp);

		exp = que_node_get_next(exp);
	}
}

306
/*********************************************************************//**
osku's avatar
osku committed
307 308 309 310 311 312
Assigns the values in the select list to the possible into-variables in
SELECT ... INTO ... */
UNIV_INLINE
void
sel_assign_into_var_values(
/*=======================*/
313 314
	sym_node_t*	var,	/*!< in: first variable in a list of variables */
	sel_node_t*	node)	/*!< in: select node */
osku's avatar
osku committed
315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334
{
	que_node_t*	exp;

	if (var == NULL) {

		return;
	}

	exp = node->select_list;

	while (var) {
		ut_ad(exp);

		eval_node_copy_val(var->alias, exp);

		exp = que_node_get_next(exp);
		var = que_node_get_next(var);
	}
}

335
/*********************************************************************//**
osku's avatar
osku committed
336 337 338 339 340 341
Resets the aggregate value totals in the select list of an aggregate type
query. */
UNIV_INLINE
void
sel_reset_aggregate_vals(
/*=====================*/
342
	sel_node_t*	node)	/*!< in: select node */
osku's avatar
osku committed
343 344 345 346 347 348 349 350 351 352 353
{
	func_node_t*	func_node;

	ut_ad(node->is_aggregate);

	func_node = node->select_list;

	while (func_node) {
		eval_node_set_int_val(func_node, 0);

		func_node = que_node_get_next(func_node);
354
	}
osku's avatar
osku committed
355 356 357 358

	node->aggregate_already_fetched = FALSE;
}

359
/*********************************************************************//**
osku's avatar
osku committed
360 361 362 363 364
Copies the input variable values when an explicit cursor is opened. */
UNIV_INLINE
void
row_sel_copy_input_variable_vals(
/*=============================*/
365
	sel_node_t*	node)	/*!< in: select node */
osku's avatar
osku committed
366 367 368 369 370 371 372 373 374 375 376 377 378 379
{
	sym_node_t*	var;

	var = UT_LIST_GET_FIRST(node->copy_variables);

	while (var) {
		eval_node_copy_val(var, var->alias);

		var->indirection = NULL;

		var = UT_LIST_GET_NEXT(col_var_list, var);
	}
}

380
/*********************************************************************//**
osku's avatar
osku committed
381 382 383 384 385
Fetches the column values from a record. */
static
void
row_sel_fetch_columns(
/*==================*/
386 387
	dict_index_t*	index,	/*!< in: record index */
	const rec_t*	rec,	/*!< in: record in a clustered or non-clustered
388
				index; must be protected by a page latch */
389 390
	const ulint*	offsets,/*!< in: rec_get_offsets(rec, index) */
	sym_node_t*	column)	/*!< in: first column in a column list, or
osku's avatar
osku committed
391 392 393 394 395
				NULL */
{
	dfield_t*	val;
	ulint		index_type;
	ulint		field_no;
396
	const byte*	data;
osku's avatar
osku committed
397
	ulint		len;
398

osku's avatar
osku committed
399 400
	ut_ad(rec_offs_validate(rec, index, offsets));

401
	if (dict_index_is_clust(index)) {
osku's avatar
osku committed
402 403 404 405 406 407
		index_type = SYM_CLUST_FIELD_NO;
	} else {
		index_type = SYM_SEC_FIELD_NO;
	}

	while (column) {
408 409 410
		mem_heap_t*	heap = NULL;
		ibool		needs_copy;

osku's avatar
osku committed
411 412 413
		field_no = column->field_nos[index_type];

		if (field_no != ULINT_UNDEFINED) {
414

415
			if (UNIV_UNLIKELY(rec_offs_nth_extern(offsets,
416
							      field_no))) {
417 418 419 420 421 422

				/* Copy an externally stored field to the
				temporary heap */

				heap = mem_heap_create(1);

423 424 425 426
				data = btr_rec_copy_externally_stored_field(
					rec, offsets,
					dict_table_zip_size(index->table),
					field_no, &len, heap);
427 428

				ut_a(len != UNIV_SQL_NULL);
429

430 431 432
				needs_copy = TRUE;
			} else {
				data = rec_get_nth_field(rec, offsets,
433
							 field_no, &len);
434 435 436 437 438

				needs_copy = column->copy_val;
			}

			if (needs_copy) {
osku's avatar
osku committed
439
				eval_node_copy_and_alloc_val(column, data,
440
							     len);
osku's avatar
osku committed
441 442 443 444
			} else {
				val = que_node_get_val(column);
				dfield_set_data(val, data, len);
			}
445 446 447 448

			if (UNIV_LIKELY_NULL(heap)) {
				mem_heap_free(heap);
			}
osku's avatar
osku committed
449 450 451 452 453 454
		}

		column = UT_LIST_GET_NEXT(col_var_list, column);
	}
}

455
/*********************************************************************//**
osku's avatar
osku committed
456 457 458 459 460
Allocates a prefetch buffer for a column when prefetch is first time done. */
static
void
sel_col_prefetch_buf_alloc(
/*=======================*/
461
	sym_node_t*	column)	/*!< in: symbol table node for a column */
osku's avatar
osku committed
462 463 464 465 466
{
	sel_buf_t*	sel_buf;
	ulint		i;

	ut_ad(que_node_get_type(column) == QUE_NODE_SYMBOL);
467

osku's avatar
osku committed
468
	column->prefetch_buf = mem_alloc(SEL_MAX_N_PREFETCH
469
					 * sizeof(sel_buf_t));
osku's avatar
osku committed
470 471 472 473 474 475 476 477 478
	for (i = 0; i < SEL_MAX_N_PREFETCH; i++) {
		sel_buf = column->prefetch_buf + i;

		sel_buf->data = NULL;

		sel_buf->val_buf_size = 0;
	}
}

479
/*********************************************************************//**
osku's avatar
osku committed
480 481
Frees a prefetch buffer for a column, including the dynamically allocated
memory for data stored there. */
482
UNIV_INTERN
osku's avatar
osku committed
483 484 485
void
sel_col_prefetch_buf_free(
/*======================*/
486
	sel_buf_t*	prefetch_buf)	/*!< in, own: prefetch buffer */
osku's avatar
osku committed
487 488 489 490 491 492 493 494 495 496 497 498 499 500
{
	sel_buf_t*	sel_buf;
	ulint		i;

	for (i = 0; i < SEL_MAX_N_PREFETCH; i++) {
		sel_buf = prefetch_buf + i;

		if (sel_buf->val_buf_size > 0) {

			mem_free(sel_buf->data);
		}
	}
}

501
/*********************************************************************//**
osku's avatar
osku committed
502 503 504 505 506 507
Pops the column values for a prefetched, cached row from the column prefetch
buffers and places them to the val fields in the column nodes. */
static
void
sel_pop_prefetched_row(
/*===================*/
508
	plan_t*	plan)	/*!< in: plan node for a table */
osku's avatar
osku committed
509 510 511 512 513 514 515
{
	sym_node_t*	column;
	sel_buf_t*	sel_buf;
	dfield_t*	val;
	byte*		data;
	ulint		len;
	ulint		val_buf_size;
516

osku's avatar
osku committed
517 518 519 520 521 522 523 524 525 526 527 528 529
	ut_ad(plan->n_rows_prefetched > 0);

	column = UT_LIST_GET_FIRST(plan->columns);

	while (column) {
		val = que_node_get_val(column);

		if (!column->copy_val) {
			/* We did not really push any value for the
			column */

			ut_ad(!column->prefetch_buf);
			ut_ad(que_node_get_val_buf_size(column) == 0);
530 531
			ut_d(dfield_set_null(val));

osku's avatar
osku committed
532 533 534 535
			goto next_col;
		}

		ut_ad(column->prefetch_buf);
536
		ut_ad(!dfield_is_ext(val));
osku's avatar
osku committed
537 538 539 540 541 542 543 544 545 546 547 548 549 550

		sel_buf = column->prefetch_buf + plan->first_prefetched;

		data = sel_buf->data;
		len = sel_buf->len;
		val_buf_size = sel_buf->val_buf_size;

		/* We must keep track of the allocated memory for
		column values to be able to free it later: therefore
		we swap the values for sel_buf and val */

		sel_buf->data = dfield_get_data(val);
		sel_buf->len = dfield_get_len(val);
		sel_buf->val_buf_size = que_node_get_val_buf_size(column);
551

osku's avatar
osku committed
552 553 554 555 556 557 558 559 560 561 562
		dfield_set_data(val, data, len);
		que_node_set_val_buf_size(column, val_buf_size);
next_col:
		column = UT_LIST_GET_NEXT(col_var_list, column);
	}

	plan->n_rows_prefetched--;

	plan->first_prefetched++;
}

563
/*********************************************************************//**
osku's avatar
osku committed
564 565 566 567 568 569
Pushes the column values for a prefetched, cached row to the column prefetch
buffers from the val fields in the column nodes. */
UNIV_INLINE
void
sel_push_prefetched_row(
/*====================*/
570
	plan_t*	plan)	/*!< in: plan node for a table */
osku's avatar
osku committed
571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587
{
	sym_node_t*	column;
	sel_buf_t*	sel_buf;
	dfield_t*	val;
	byte*		data;
	ulint		len;
	ulint		pos;
	ulint		val_buf_size;

	if (plan->n_rows_prefetched == 0) {
		pos = 0;
		plan->first_prefetched = 0;
	} else {
		pos = plan->n_rows_prefetched;

		/* We have the convention that pushing new rows starts only
		after the prefetch stack has been emptied: */
588

osku's avatar
osku committed
589 590 591 592
		ut_ad(plan->first_prefetched == 0);
	}

	plan->n_rows_prefetched++;
593

osku's avatar
osku committed
594
	ut_ad(pos < SEL_MAX_N_PREFETCH);
595

osku's avatar
osku committed
596 597 598 599 600 601 602 603 604
	column = UT_LIST_GET_FIRST(plan->columns);

	while (column) {
		if (!column->copy_val) {
			/* There is no sense to push pointers to database
			page fields when we do not keep latch on the page! */

			goto next_col;
		}
605

osku's avatar
osku committed
606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625
		if (!column->prefetch_buf) {
			/* Allocate a new prefetch buffer */

			sel_col_prefetch_buf_alloc(column);
		}

		sel_buf = column->prefetch_buf + pos;

		val = que_node_get_val(column);

		data = dfield_get_data(val);
		len = dfield_get_len(val);
		val_buf_size = que_node_get_val_buf_size(column);

		/* We must keep track of the allocated memory for
		column values to be able to free it later: therefore
		we swap the values for sel_buf and val */

		dfield_set_data(val, sel_buf->data, sel_buf->len);
		que_node_set_val_buf_size(column, sel_buf->val_buf_size);
626

osku's avatar
osku committed
627 628 629
		sel_buf->data = data;
		sel_buf->len = len;
		sel_buf->val_buf_size = val_buf_size;
630
next_col:
osku's avatar
osku committed
631 632 633 634
		column = UT_LIST_GET_NEXT(col_var_list, column);
	}
}

635
/*********************************************************************//**
636 637
Builds a previous version of a clustered index record for a consistent read
@return	DB_SUCCESS or error code */
osku's avatar
osku committed
638 639 640 641
static
ulint
row_sel_build_prev_vers(
/*====================*/
642 643 644 645
	read_view_t*	read_view,	/*!< in: read view */
	dict_index_t*	index,		/*!< in: plan node for table */
	rec_t*		rec,		/*!< in: record in a clustered index */
	ulint**		offsets,	/*!< in/out: offsets returned by
osku's avatar
osku committed
646
					rec_get_offsets(rec, plan->index) */
647
	mem_heap_t**	offset_heap,	/*!< in/out: memory heap from which
osku's avatar
osku committed
648
					the offsets are allocated */
649 650
	mem_heap_t**    old_vers_heap,  /*!< out: old version heap to use */
	rec_t**		old_vers,	/*!< out: old version, or NULL if the
osku's avatar
osku committed
651 652 653
					record does not exist in the view:
					i.e., it was freshly inserted
					afterwards */
654
	mtr_t*		mtr)		/*!< in: mtr */
osku's avatar
osku committed
655 656 657
{
	ulint	err;

658 659
	if (*old_vers_heap) {
		mem_heap_empty(*old_vers_heap);
osku's avatar
osku committed
660
	} else {
661
		*old_vers_heap = mem_heap_create(512);
osku's avatar
osku committed
662
	}
663

664
	err = row_vers_build_for_consistent_read(
665 666
		rec, mtr, index, offsets, read_view, offset_heap,
		*old_vers_heap, old_vers);
osku's avatar
osku committed
667 668 669
	return(err);
}

670
/*********************************************************************//**
671
Builds the last committed version of a clustered index record for a
672 673
semi-consistent read.
@return	DB_SUCCESS or error code */
674 675 676 677
static
ulint
row_sel_build_committed_vers_for_mysql(
/*===================================*/
678 679 680 681
	dict_index_t*	clust_index,	/*!< in: clustered index */
	row_prebuilt_t*	prebuilt,	/*!< in: prebuilt struct */
	const rec_t*	rec,		/*!< in: record in a clustered index */
	ulint**		offsets,	/*!< in/out: offsets returned by
682
					rec_get_offsets(rec, clust_index) */
683
	mem_heap_t**	offset_heap,	/*!< in/out: memory heap from which
684
					the offsets are allocated */
685
	const rec_t**	old_vers,	/*!< out: old version, or NULL if the
686 687 688
					record does not exist in the view:
					i.e., it was freshly inserted
					afterwards */
689
	mtr_t*		mtr)		/*!< in: mtr */
690 691 692 693 694 695 696 697
{
	ulint	err;

	if (prebuilt->old_vers_heap) {
		mem_heap_empty(prebuilt->old_vers_heap);
	} else {
		prebuilt->old_vers_heap = mem_heap_create(200);
	}
698

699 700 701
	err = row_vers_build_for_semi_consistent_read(
		rec, mtr, clust_index, offsets, offset_heap,
		prebuilt->old_vers_heap, old_vers);
702 703 704
	return(err);
}

705
/*********************************************************************//**
osku's avatar
osku committed
706
Tests the conditions which determine when the index segment we are searching
707 708
through has been exhausted.
@return	TRUE if row passed the tests */
osku's avatar
osku committed
709 710 711 712
UNIV_INLINE
ibool
row_sel_test_end_conds(
/*===================*/
713
	plan_t*	plan)	/*!< in: plan for the table; the column values must
osku's avatar
osku committed
714 715 716 717 718 719 720
			already have been retrieved and the right sides of
			comparisons evaluated */
{
	func_node_t*	cond;

	/* All conditions in end_conds are comparisons of a column to an
	expression */
721

osku's avatar
osku committed
722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742
	cond = UT_LIST_GET_FIRST(plan->end_conds);

	while (cond) {
		/* Evaluate the left side of the comparison, i.e., get the
		column value if there is an indirection */

		eval_sym(cond->args);

		/* Do the comparison */

		if (!eval_cmp(cond)) {

			return(FALSE);
		}

		cond = UT_LIST_GET_NEXT(cond_list, cond);
	}

	return(TRUE);
}

743
/*********************************************************************//**
744 745
Tests the other conditions.
@return	TRUE if row passed the tests */
osku's avatar
osku committed
746 747 748 749
UNIV_INLINE
ibool
row_sel_test_other_conds(
/*=====================*/
750
	plan_t*	plan)	/*!< in: plan for the table; the column values must
osku's avatar
osku committed
751 752 753
			already have been retrieved */
{
	func_node_t*	cond;
754

osku's avatar
osku committed
755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770
	cond = UT_LIST_GET_FIRST(plan->other_conds);

	while (cond) {
		eval_exp(cond);

		if (!eval_node_get_ibool_val(cond)) {

			return(FALSE);
		}

		cond = UT_LIST_GET_NEXT(cond_list, cond);
	}

	return(TRUE);
}

771
/*********************************************************************//**
osku's avatar
osku committed
772
Retrieves the clustered index record corresponding to a record in a
773 774
non-clustered index. Does the necessary locking.
@return	DB_SUCCESS or error code */
osku's avatar
osku committed
775 776 777 778
static
ulint
row_sel_get_clust_rec(
/*==================*/
779 780 781 782 783
	sel_node_t*	node,	/*!< in: select_node */
	plan_t*		plan,	/*!< in: plan node for table */
	rec_t*		rec,	/*!< in: record in a non-clustered index */
	que_thr_t*	thr,	/*!< in: query thread */
	rec_t**		out_rec,/*!< out: clustered record or an old version of
osku's avatar
osku committed
784 785 786
				it, NULL if the old version did not exist
				in the read view, i.e., it was a fresh
				inserted version */
787
	mtr_t*		mtr)	/*!< in: mtr used to get access to the
osku's avatar
osku committed
788 789 790 791 792 793 794 795 796 797
				non-clustered record; the same mtr is used to
				access the clustered index */
{
	dict_index_t*	index;
	rec_t*		clust_rec;
	rec_t*		old_vers;
	ulint		err;
	mem_heap_t*	heap		= NULL;
	ulint		offsets_[REC_OFFS_NORMAL_SIZE];
	ulint*		offsets		= offsets_;
798
	rec_offs_init(offsets_);
osku's avatar
osku committed
799 800 801 802

	*out_rec = NULL;

	offsets = rec_get_offsets(rec,
803 804
				  btr_pcur_get_btr_cur(&plan->pcur)->index,
				  offsets, ULINT_UNDEFINED, &heap);
805

osku's avatar
osku committed
806 807 808
	row_build_row_ref_fast(plan->clust_ref, plan->clust_map, rec, offsets);

	index = dict_table_get_first_index(plan->table);
809

osku's avatar
osku committed
810
	btr_pcur_open_with_no_init(index, plan->clust_ref, PAGE_CUR_LE,
811
				   BTR_SEARCH_LEAF, &plan->clust_pcur,
812
				   0, mtr);
osku's avatar
osku committed
813 814 815 816 817 818 819

	clust_rec = btr_pcur_get_rec(&(plan->clust_pcur));

	/* Note: only if the search ends up on a non-infimum record is the
	low_match value the real match to the search tuple */

	if (!page_rec_is_user_rec(clust_rec)
820 821
	    || btr_pcur_get_low_match(&(plan->clust_pcur))
	    < dict_index_get_n_unique(index)) {
822

823
		ut_a(rec_get_deleted_flag(rec,
824
					  dict_table_is_comp(plan->table)));
osku's avatar
osku committed
825 826 827 828 829 830 831 832 833 834 835 836 837 838 839
		ut_a(node->read_view);

		/* In a rare case it is possible that no clust rec is found
		for a delete-marked secondary index record: if in row0umod.c
		in row_undo_mod_remove_clust_low() we have already removed
		the clust rec, while purge is still cleaning and removing
		secondary index records associated with earlier versions of
		the clustered index record. In that case we know that the
		clustered index record did not exist in the read view of
		trx. */

		goto func_exit;
	}

	offsets = rec_get_offsets(clust_rec, index, offsets,
840
				  ULINT_UNDEFINED, &heap);
osku's avatar
osku committed
841 842 843

	if (!node->read_view) {
		/* Try to place a lock on the index record */
844

845 846
		/* If innodb_locks_unsafe_for_binlog option is used
		or this session is using READ COMMITTED isolation level
osku's avatar
osku committed
847 848 849
		we lock only the record, i.e., next-key locking is
		not used. */
		ulint	lock_type;
850
		trx_t*	trx;
osku's avatar
osku committed
851

852 853 854
		trx = thr_get_trx(thr);

		if (srv_locks_unsafe_for_binlog
855
		    || trx->isolation_level == TRX_ISO_READ_COMMITTED) {
osku's avatar
osku committed
856 857 858 859 860
			lock_type = LOCK_REC_NOT_GAP;
		} else {
			lock_type = LOCK_ORDINARY;
		}

861
		err = lock_clust_rec_read_check_and_lock(
862 863
			0, btr_pcur_get_block(&plan->clust_pcur),
			clust_rec, index, offsets,
864
			node->row_lock_mode, lock_type, thr);
osku's avatar
osku committed
865 866 867 868 869 870 871 872 873 874 875 876

		if (err != DB_SUCCESS) {

			goto err_exit;
		}
	} else {
		/* This is a non-locking consistent read: if necessary, fetch
		a previous version of the record */

		old_vers = NULL;

		if (!lock_clust_rec_cons_read_sees(clust_rec, index, offsets,
877
						   node->read_view)) {
osku's avatar
osku committed
878

879 880 881 882 883
			err = row_sel_build_prev_vers(
				node->read_view, index, clust_rec,
				&offsets, &heap, &plan->old_vers_heap,
				&old_vers, mtr);

osku's avatar
osku committed
884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907
			if (err != DB_SUCCESS) {

				goto err_exit;
			}

			clust_rec = old_vers;

			if (clust_rec == NULL) {
				goto func_exit;
			}
		}

		/* If we had to go to an earlier version of row or the
		secondary index record is delete marked, then it may be that
		the secondary index record corresponding to clust_rec
		(or old_vers) is not rec; in that case we must ignore
		such row because in our snapshot rec would not have existed.
		Remember that from rec we cannot see directly which transaction
		id corresponds to it: we have to go to the clustered index
		record. A query where we want to fetch all rows where
		the secondary index value is in some interval would return
		a wrong result if we would not drop rows which we come to
		visit through secondary index records that would not really
		exist in our snapshot. */
908

909
		if ((old_vers
910 911
		     || rec_get_deleted_flag(rec, dict_table_is_comp(
						     plan->table)))
912 913
		    && !row_sel_sec_rec_is_for_clust_rec(rec, plan->index,
							 clust_rec, index)) {
osku's avatar
osku committed
914 915 916 917
			goto func_exit;
		}
	}

918 919 920 921
	/* Fetch the columns needed in test conditions.  The clustered
	index record is protected by a page latch that was acquired
	when plan->clust_pcur was positioned.  The latch will not be
	released until mtr_commit(mtr). */
osku's avatar
osku committed
922 923

	row_sel_fetch_columns(index, clust_rec, offsets,
924
			      UT_LIST_GET_FIRST(plan->columns));
osku's avatar
osku committed
925 926 927 928 929 930 931 932 933 934
	*out_rec = clust_rec;
func_exit:
	err = DB_SUCCESS;
err_exit:
	if (UNIV_LIKELY_NULL(heap)) {
		mem_heap_free(heap);
	}
	return(err);
}

935
/*********************************************************************//**
936 937
Sets a lock on a record.
@return	DB_SUCCESS or error code */
osku's avatar
osku committed
938 939 940 941
UNIV_INLINE
ulint
sel_set_rec_lock(
/*=============*/
942 943 944 945 946 947
	const buf_block_t*	block,	/*!< in: buffer block of rec */
	const rec_t*		rec,	/*!< in: record */
	dict_index_t*		index,	/*!< in: index */
	const ulint*		offsets,/*!< in: rec_get_offsets(rec, index) */
	ulint			mode,	/*!< in: lock mode */
	ulint			type,	/*!< in: LOCK_ORDINARY, LOCK_GAP, or
948
					LOC_REC_NOT_GAP */
949
	que_thr_t*		thr)	/*!< in: query thread */
osku's avatar
osku committed
950 951 952 953
{
	trx_t*	trx;
	ulint	err;

954
	trx = thr_get_trx(thr);
osku's avatar
osku committed
955 956 957

	if (UT_LIST_GET_LEN(trx->trx_locks) > 10000) {
		if (buf_LRU_buf_pool_running_out()) {
958

osku's avatar
osku committed
959 960 961 962
			return(DB_LOCK_TABLE_FULL);
		}
	}

963
	if (dict_index_is_clust(index)) {
964
		err = lock_clust_rec_read_check_and_lock(
965
			0, block, rec, index, offsets, mode, type, thr);
osku's avatar
osku committed
966
	} else {
967
		err = lock_sec_rec_read_check_and_lock(
968
			0, block, rec, index, offsets, mode, type, thr);
osku's avatar
osku committed
969 970 971 972 973
	}

	return(err);
}

974
/*********************************************************************//**
osku's avatar
osku committed
975 976 977 978 979
Opens a pcur to a table index. */
static
void
row_sel_open_pcur(
/*==============*/
980
	plan_t*		plan,		/*!< in: table plan */
osku's avatar
osku committed
981
	ibool		search_latch_locked,
982
					/*!< in: TRUE if the thread currently
osku's avatar
osku committed
983 984
					has the search latch locked in
					s-mode */
985
	mtr_t*		mtr)		/*!< in: mtr */
osku's avatar
osku committed
986 987 988 989 990
{
	dict_index_t*	index;
	func_node_t*	cond;
	que_node_t*	exp;
	ulint		n_fields;
991
	ulint		has_search_latch = 0;	/* RW_S_LATCH or 0 */
osku's avatar
osku committed
992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007
	ulint		i;

	if (search_latch_locked) {
		has_search_latch = RW_S_LATCH;
	}

	index = plan->index;

	/* Calculate the value of the search tuple: the exact match columns
	get their expressions evaluated when we evaluate the right sides of
	end_conds */

	cond = UT_LIST_GET_FIRST(plan->end_conds);

	while (cond) {
		eval_exp(que_node_get_next(cond->args));
1008

osku's avatar
osku committed
1009 1010
		cond = UT_LIST_GET_NEXT(cond_list, cond);
	}
1011

osku's avatar
osku committed
1012 1013
	if (plan->tuple) {
		n_fields = dtuple_get_n_fields(plan->tuple);
1014

osku's avatar
osku committed
1015 1016 1017
		if (plan->n_exact_match < n_fields) {
			/* There is a non-exact match field which must be
			evaluated separately */
1018

osku's avatar
osku committed
1019 1020
			eval_exp(plan->tuple_exps[n_fields - 1]);
		}
1021

osku's avatar
osku committed
1022 1023
		for (i = 0; i < n_fields; i++) {
			exp = plan->tuple_exps[i];
1024

1025
			dfield_copy_data(dtuple_get_nth_field(plan->tuple, i),
1026
					 que_node_get_val(exp));
osku's avatar
osku committed
1027
		}
1028

osku's avatar
osku committed
1029
		/* Open pcur to the index */
1030

osku's avatar
osku committed
1031
		btr_pcur_open_with_no_init(index, plan->tuple, plan->mode,
1032
					   BTR_SEARCH_LEAF, &plan->pcur,
1033
					   has_search_latch, mtr);
osku's avatar
osku committed
1034 1035 1036 1037
	} else {
		/* Open the cursor to the start or the end of the index
		(FALSE: no init) */

1038
		btr_pcur_open_at_index_side(plan->asc, index, BTR_SEARCH_LEAF,
1039
					    &(plan->pcur), FALSE, mtr);
osku's avatar
osku committed
1040 1041 1042 1043 1044
	}

	ut_ad(plan->n_rows_prefetched == 0);
	ut_ad(plan->n_rows_fetched == 0);
	ut_ad(plan->cursor_at_end == FALSE);
1045

osku's avatar
osku committed
1046 1047 1048
	plan->pcur_is_open = TRUE;
}

1049
/*********************************************************************//**
1050
Restores a stored pcur position to a table index.
1051 1052 1053 1054
@return TRUE if the cursor should be moved to the next record after we
return from this function (moved to the previous, in the case of a
descending cursor) without processing again the current cursor
record */
osku's avatar
osku committed
1055 1056 1057 1058
static
ibool
row_sel_restore_pcur_pos(
/*=====================*/
1059 1060
	plan_t*		plan,	/*!< in: table plan */
	mtr_t*		mtr)	/*!< in: mtr */
osku's avatar
osku committed
1061 1062 1063 1064 1065
{
	ibool	equal_position;
	ulint	relative_position;

	ut_ad(!plan->cursor_at_end);
1066

osku's avatar
osku committed
1067 1068
	relative_position = btr_pcur_get_rel_pos(&(plan->pcur));

1069
	equal_position = btr_pcur_restore_position(BTR_SEARCH_LEAF,
1070
						   &(plan->pcur), mtr);
osku's avatar
osku committed
1071 1072

	/* If the cursor is traveling upwards, and relative_position is
1073

osku's avatar
osku committed
1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099
	(1) BTR_PCUR_BEFORE: this is not allowed, as we did not have a lock
	yet on the successor of the page infimum;
	(2) BTR_PCUR_AFTER: btr_pcur_restore_position placed the cursor on the
	first record GREATER than the predecessor of a page supremum; we have
	not yet processed the cursor record: no need to move the cursor to the
	next record;
	(3) BTR_PCUR_ON: btr_pcur_restore_position placed the cursor on the
	last record LESS or EQUAL to the old stored user record; (a) if
	equal_position is FALSE, this means that the cursor is now on a record
	less than the old user record, and we must move to the next record;
	(b) if equal_position is TRUE, then if
	plan->stored_cursor_rec_processed is TRUE, we must move to the next
	record, else there is no need to move the cursor. */

	if (plan->asc) {
		if (relative_position == BTR_PCUR_ON) {

			if (equal_position) {

				return(plan->stored_cursor_rec_processed);
			}

			return(TRUE);
		}

		ut_ad(relative_position == BTR_PCUR_AFTER
1100
		      || relative_position == BTR_PCUR_AFTER_LAST_IN_TREE);
osku's avatar
osku committed
1101 1102 1103 1104 1105

		return(FALSE);
	}

	/* If the cursor is traveling downwards, and relative_position is
1106

osku's avatar
osku committed
1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122
	(1) BTR_PCUR_BEFORE: btr_pcur_restore_position placed the cursor on
	the last record LESS than the successor of a page infimum; we have not
	processed the cursor record: no need to move the cursor;
	(2) BTR_PCUR_AFTER: btr_pcur_restore_position placed the cursor on the
	first record GREATER than the predecessor of a page supremum; we have
	processed the cursor record: we should move the cursor to the previous
	record;
	(3) BTR_PCUR_ON: btr_pcur_restore_position placed the cursor on the
	last record LESS or EQUAL to the old stored user record; (a) if
	equal_position is FALSE, this means that the cursor is now on a record
	less than the old user record, and we need not move to the previous
	record; (b) if equal_position is TRUE, then if
	plan->stored_cursor_rec_processed is TRUE, we must move to the previous
	record, else there is no need to move the cursor. */

	if (relative_position == BTR_PCUR_BEFORE
1123
	    || relative_position == BTR_PCUR_BEFORE_FIRST_IN_TREE) {
osku's avatar
osku committed
1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138

		return(FALSE);
	}

	if (relative_position == BTR_PCUR_ON) {

		if (equal_position) {

			return(plan->stored_cursor_rec_processed);
		}

		return(FALSE);
	}

	ut_ad(relative_position == BTR_PCUR_AFTER
1139
	      || relative_position == BTR_PCUR_AFTER_LAST_IN_TREE);
osku's avatar
osku committed
1140 1141 1142 1143

	return(TRUE);
}

1144
/*********************************************************************//**
osku's avatar
osku committed
1145 1146 1147 1148 1149
Resets a plan cursor to a closed state. */
UNIV_INLINE
void
plan_reset_cursor(
/*==============*/
1150
	plan_t*	plan)	/*!< in: plan */
1151
{
osku's avatar
osku committed
1152
	plan->pcur_is_open = FALSE;
1153
	plan->cursor_at_end = FALSE;
osku's avatar
osku committed
1154 1155 1156
	plan->n_rows_fetched = 0;
	plan->n_rows_prefetched = 0;
}
1157

1158
/*********************************************************************//**
osku's avatar
osku committed
1159
Tries to do a shortcut to fetch a clustered index record with a unique key,
1160 1161
using the hash index if possible (not always).
@return	SEL_FOUND, SEL_EXHAUSTED, SEL_RETRY */
osku's avatar
osku committed
1162 1163 1164 1165
static
ulint
row_sel_try_search_shortcut(
/*========================*/
1166 1167
	sel_node_t*	node,	/*!< in: select node for a consistent read */
	plan_t*		plan,	/*!< in: plan for a unique search in clustered
osku's avatar
osku committed
1168
				index */
1169
	mtr_t*		mtr)	/*!< in: mtr */
osku's avatar
osku committed
1170 1171 1172 1173 1174 1175 1176
{
	dict_index_t*	index;
	rec_t*		rec;
	mem_heap_t*	heap		= NULL;
	ulint		offsets_[REC_OFFS_NORMAL_SIZE];
	ulint*		offsets		= offsets_;
	ulint		ret;
1177
	rec_offs_init(offsets_);
osku's avatar
osku committed
1178 1179 1180 1181 1182 1183 1184 1185 1186

	index = plan->index;

	ut_ad(node->read_view);
	ut_ad(plan->unique_search);
	ut_ad(!plan->must_get_clust);
#ifdef UNIV_SYNC_DEBUG
	ut_ad(rw_lock_own(&btr_search_latch, RW_LOCK_SHARED));
#endif /* UNIV_SYNC_DEBUG */
1187

1188
	row_sel_open_pcur(plan, TRUE, mtr);
osku's avatar
osku committed
1189 1190

	rec = btr_pcur_get_rec(&(plan->pcur));
1191

osku's avatar
osku committed
1192 1193 1194 1195 1196 1197
	if (!page_rec_is_user_rec(rec)) {

		return(SEL_RETRY);
	}

	ut_ad(plan->mode == PAGE_CUR_GE);
1198

osku's avatar
osku committed
1199 1200
	/* As the cursor is now placed on a user record after a search with
	the mode PAGE_CUR_GE, the up_match field in the cursor tells how many
1201
	fields in the user record matched to the search tuple */
osku's avatar
osku committed
1202 1203 1204 1205 1206 1207 1208 1209

	if (btr_pcur_get_up_match(&(plan->pcur)) < plan->n_exact_match) {

		return(SEL_EXHAUSTED);
	}

	/* This is a non-locking consistent read: if necessary, fetch
	a previous version of the record */
1210

osku's avatar
osku committed
1211 1212
	offsets = rec_get_offsets(rec, index, offsets, ULINT_UNDEFINED, &heap);

1213
	if (dict_index_is_clust(index)) {
osku's avatar
osku committed
1214
		if (!lock_clust_rec_cons_read_sees(rec, index, offsets,
1215
						   node->read_view)) {
osku's avatar
osku committed
1216 1217 1218
			ret = SEL_RETRY;
			goto func_exit;
		}
1219
	} else if (!lock_sec_rec_cons_read_sees(rec, node->read_view)) {
osku's avatar
osku committed
1220 1221 1222 1223 1224

		ret = SEL_RETRY;
		goto func_exit;
	}

1225
	/* Test the deleted flag. */
osku's avatar
osku committed
1226

1227
	if (rec_get_deleted_flag(rec, dict_table_is_comp(plan->table))) {
osku's avatar
osku committed
1228 1229 1230 1231 1232

		ret = SEL_EXHAUSTED;
		goto func_exit;
	}

1233 1234 1235 1236 1237 1238 1239 1240
	/* Fetch the columns needed in test conditions.  The index
	record is protected by a page latch that was acquired when
	plan->pcur was positioned.  The latch will not be released
	until mtr_commit(mtr). */

	row_sel_fetch_columns(index, rec, offsets,
			      UT_LIST_GET_FIRST(plan->columns));

osku's avatar
osku committed
1241
	/* Test the rest of search conditions */
1242

osku's avatar
osku committed
1243 1244 1245 1246 1247 1248
	if (!row_sel_test_other_conds(plan)) {

		ret = SEL_EXHAUSTED;
		goto func_exit;
	}

1249
	ut_ad(plan->pcur.latch_mode == BTR_SEARCH_LEAF);
osku's avatar
osku committed
1250 1251

	plan->n_rows_fetched++;
1252
	ret = SEL_FOUND;
osku's avatar
osku committed
1253 1254 1255 1256
func_exit:
	if (UNIV_LIKELY_NULL(heap)) {
		mem_heap_free(heap);
	}
1257
	return(ret);
osku's avatar
osku committed
1258 1259
}

1260
/*********************************************************************//**
1261 1262
Performs a select step.
@return	DB_SUCCESS or error code */
osku's avatar
osku committed
1263 1264 1265 1266
static
ulint
row_sel(
/*====*/
1267 1268
	sel_node_t*	node,	/*!< in: select node */
	que_thr_t*	thr)	/*!< in: query thread */
osku's avatar
osku committed
1269 1270 1271 1272 1273 1274 1275 1276 1277 1278
{
	dict_index_t*	index;
	plan_t*		plan;
	mtr_t		mtr;
	ibool		moved;
	rec_t*		rec;
	rec_t*		old_vers;
	rec_t*		clust_rec;
	ibool		search_latch_locked;
	ibool		consistent_read;
1279

1280 1281 1282 1283
	/* The following flag becomes TRUE when we are doing a
	consistent read from a non-clustered index and we must look
	at the clustered index to find out the previous delete mark
	state of the non-clustered record: */
osku's avatar
osku committed
1284 1285 1286 1287 1288

	ibool		cons_read_requires_clust_rec	= FALSE;
	ulint		cost_counter			= 0;
	ibool		cursor_just_opened;
	ibool		must_go_to_next;
1289
	ibool		mtr_has_extra_clust_latch	= FALSE;
1290 1291 1292 1293 1294 1295
	/* TRUE if the search was made using
	a non-clustered index, and we had to
	access the clustered record: now &mtr
	contains a clustered index latch, and
	&mtr must be committed before we move
	to the next non-clustered record */
osku's avatar
osku committed
1296 1297 1298 1299 1300
	ulint		found_flag;
	ulint		err;
	mem_heap_t*	heap				= NULL;
	ulint		offsets_[REC_OFFS_NORMAL_SIZE];
	ulint*		offsets				= offsets_;
1301
	rec_offs_init(offsets_);
osku's avatar
osku committed
1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321

	ut_ad(thr->run_node == node);

	search_latch_locked = FALSE;

	if (node->read_view) {
		/* In consistent reads, we try to do with the hash index and
		not to use the buffer page get. This is to reduce memory bus
		load resulting from semaphore operations. The search latch
		will be s-locked when we access an index with a unique search
		condition, but not locked when we access an index with a
		less selective search condition. */

		consistent_read = TRUE;
	} else {
		consistent_read = FALSE;
	}

table_loop:
	/* TABLE LOOP
1322
	----------
osku's avatar
osku committed
1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348
	This is the outer major loop in calculating a join. We come here when
	node->fetch_table changes, and after adding a row to aggregate totals
	and, of course, when this function is called. */

	ut_ad(mtr_has_extra_clust_latch == FALSE);

	plan = sel_node_get_nth_plan(node, node->fetch_table);
	index = plan->index;

	if (plan->n_rows_prefetched > 0) {
		sel_pop_prefetched_row(plan);

		goto next_table_no_mtr;
	}

	if (plan->cursor_at_end) {
		/* The cursor has already reached the result set end: no more
		rows to process for this table cursor, as also the prefetch
		stack was empty */

		ut_ad(plan->pcur_is_open);

		goto table_exhausted_no_mtr;
	}

	/* Open a cursor to index, or restore an open cursor position */
1349

osku's avatar
osku committed
1350 1351 1352
	mtr_start(&mtr);

	if (consistent_read && plan->unique_search && !plan->pcur_is_open
1353
	    && !plan->must_get_clust
1354
	    && !plan->table->big_rows) {
osku's avatar
osku committed
1355 1356 1357 1358
		if (!search_latch_locked) {
			rw_lock_s_lock(&btr_search_latch);

			search_latch_locked = TRUE;
1359
		} else if (rw_lock_get_writer(&btr_search_latch) == RW_LOCK_WAIT_EX) {
osku's avatar
osku committed
1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381

			/* There is an x-latch request waiting: release the
			s-latch for a moment; as an s-latch here is often
			kept for some 10 searches before being released,
			a waiting x-latch request would block other threads
			from acquiring an s-latch for a long time, lowering
			performance significantly in multiprocessors. */

			rw_lock_s_unlock(&btr_search_latch);
			rw_lock_s_lock(&btr_search_latch);
		}

		found_flag = row_sel_try_search_shortcut(node, plan, &mtr);

		if (found_flag == SEL_FOUND) {

			goto next_table;

		} else if (found_flag == SEL_EXHAUSTED) {

			goto table_exhausted;
		}
1382

osku's avatar
osku committed
1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400
		ut_ad(found_flag == SEL_RETRY);

		plan_reset_cursor(plan);

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

	if (search_latch_locked) {
		rw_lock_s_unlock(&btr_search_latch);

		search_latch_locked = FALSE;
	}

	if (!plan->pcur_is_open) {
		/* Evaluate the expressions to build the search tuple and
		open the cursor */

1401
		row_sel_open_pcur(plan, search_latch_locked, &mtr);
osku's avatar
osku committed
1402 1403 1404 1405 1406 1407 1408 1409

		cursor_just_opened = TRUE;

		/* A new search was made: increment the cost counter */
		cost_counter++;
	} else {
		/* Restore pcur position to the index */

1410
		must_go_to_next = row_sel_restore_pcur_pos(plan, &mtr);
osku's avatar
osku committed
1411 1412 1413 1414 1415 1416

		cursor_just_opened = FALSE;

		if (must_go_to_next) {
			/* We have already processed the cursor record: move
			to the next */
1417

osku's avatar
osku committed
1418 1419 1420
			goto next_rec;
		}
	}
1421

osku's avatar
osku committed
1422 1423
rec_loop:
	/* RECORD LOOP
1424
	-----------
osku's avatar
osku committed
1425 1426 1427 1428 1429 1430 1431 1432 1433
	In this loop we use pcur and try to fetch a qualifying row, and
	also fill the prefetch buffer for this table if n_rows_fetched has
	exceeded a threshold. While we are inside this loop, the following
	holds:
	(1) &mtr is started,
	(2) pcur is positioned and open.

	NOTE that if cursor_just_opened is TRUE here, it means that we came
	to this point right after row_sel_open_pcur. */
1434

osku's avatar
osku committed
1435 1436 1437
	ut_ad(mtr_has_extra_clust_latch == FALSE);

	rec = btr_pcur_get_rec(&(plan->pcur));
1438

osku's avatar
osku committed
1439 1440 1441
	/* PHASE 1: Set a lock if specified */

	if (!node->asc && cursor_just_opened
1442
	    && !page_rec_is_supremum(rec)) {
osku's avatar
osku committed
1443 1444 1445 1446 1447 1448

		/* When we open a cursor for a descending search, we must set
		a next-key lock on the successor record: otherwise it would
		be possible to insert new records next to the cursor position,
		and it might be that these new records should appear in the
		search result set, resulting in the phantom problem. */
1449

osku's avatar
osku committed
1450 1451
		if (!consistent_read) {

1452 1453 1454 1455
			/* If innodb_locks_unsafe_for_binlog option is used
			or this session is using READ COMMITTED isolation
			level, we lock only the record, i.e., next-key
			locking is not used. */
osku's avatar
osku committed
1456 1457 1458

			rec_t*	next_rec = page_rec_get_next(rec);
			ulint	lock_type;
1459 1460 1461 1462
			trx_t*	trx;

			trx = thr_get_trx(thr);

osku's avatar
osku committed
1463
			offsets = rec_get_offsets(next_rec, index, offsets,
1464
						  ULINT_UNDEFINED, &heap);
osku's avatar
osku committed
1465

1466
			if (srv_locks_unsafe_for_binlog
1467 1468
			    || trx->isolation_level
			    == TRX_ISO_READ_COMMITTED) {
1469 1470 1471 1472 1473 1474

				if (page_rec_is_supremum(next_rec)) {

					goto skip_lock;
				}

osku's avatar
osku committed
1475 1476 1477 1478 1479
				lock_type = LOCK_REC_NOT_GAP;
			} else {
				lock_type = LOCK_ORDINARY;
			}

1480 1481
			err = sel_set_rec_lock(btr_pcur_get_block(&plan->pcur),
					       next_rec, index, offsets,
1482 1483
					       node->row_lock_mode,
					       lock_type, thr);
osku's avatar
osku committed
1484 1485 1486 1487 1488

			if (err != DB_SUCCESS) {
				/* Note that in this case we will store in pcur
				the PREDECESSOR of the record we are waiting
				the lock for */
1489

osku's avatar
osku committed
1490 1491 1492 1493 1494
				goto lock_wait_or_error;
			}
		}
	}

1495
skip_lock:
osku's avatar
osku committed
1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508
	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. We also increment the cost counter as we may have
		processed yet another page of index. */

		cost_counter++;

		goto next_rec;
	}

	if (!consistent_read) {
1509
		/* Try to place a lock on the index record */
osku's avatar
osku committed
1510

1511 1512
		/* If innodb_locks_unsafe_for_binlog option is used
		or this session is using READ COMMITTED isolation level,
osku's avatar
osku committed
1513 1514 1515 1516
		we lock only the record, i.e., next-key locking is
		not used. */

		ulint	lock_type;
1517 1518
		trx_t*	trx;

osku's avatar
osku committed
1519
		offsets = rec_get_offsets(rec, index, offsets,
1520
					  ULINT_UNDEFINED, &heap);
osku's avatar
osku committed
1521

1522 1523 1524
		trx = thr_get_trx(thr);

		if (srv_locks_unsafe_for_binlog
1525
		    || trx->isolation_level == TRX_ISO_READ_COMMITTED) {
1526 1527 1528 1529 1530 1531

			if (page_rec_is_supremum(rec)) {

				goto next_rec;
			}

osku's avatar
osku committed
1532 1533 1534 1535 1536
			lock_type = LOCK_REC_NOT_GAP;
		} else {
			lock_type = LOCK_ORDINARY;
		}

1537 1538
		err = sel_set_rec_lock(btr_pcur_get_block(&plan->pcur),
				       rec, index, offsets,
1539
				       node->row_lock_mode, lock_type, thr);
osku's avatar
osku committed
1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557

		if (err != DB_SUCCESS) {

			goto lock_wait_or_error;
		}
	}

	if (page_rec_is_supremum(rec)) {

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

		goto next_rec;
	}

	ut_ad(page_rec_is_user_rec(rec));

	if (cost_counter > SEL_COST_LIMIT) {
1558

osku's avatar
osku committed
1559 1560 1561 1562 1563 1564 1565 1566 1567
		/* Now that we have placed the necessary locks, we can stop
		for a while and store the cursor position; NOTE that if we
		would store the cursor position BEFORE placing a record lock,
		it might happen that the cursor would jump over some records
		that another transaction could meanwhile insert adjacent to
		the cursor: this would result in the phantom problem. */

		goto stop_for_a_while;
	}
1568

osku's avatar
osku committed
1569 1570 1571 1572 1573
	/* PHASE 2: Check a mixed index mix id if needed */

	if (plan->unique_search && cursor_just_opened) {

		ut_ad(plan->mode == PAGE_CUR_GE);
1574

osku's avatar
osku committed
1575 1576 1577
		/* As the cursor is now placed on a user record after a search
		with the mode PAGE_CUR_GE, the up_match field in the cursor
		tells how many fields in the user record matched to the search
1578
		tuple */
osku's avatar
osku committed
1579 1580

		if (btr_pcur_get_up_match(&(plan->pcur))
1581
		    < plan->n_exact_match) {
osku's avatar
osku committed
1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600
			goto table_exhausted;
		}

		/* Ok, no need to test end_conds or mix id */

	}

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

	/* PHASE 3: Get previous version in a consistent read */

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

	if (consistent_read) {
		/* This is a non-locking consistent read: if necessary, fetch
		a previous version of the record */

1601
		if (dict_index_is_clust(index)) {
1602

osku's avatar
osku committed
1603
			if (!lock_clust_rec_cons_read_sees(rec, index, offsets,
1604
							   node->read_view)) {
osku's avatar
osku committed
1605

1606 1607 1608 1609 1610
				err = row_sel_build_prev_vers(
					node->read_view, index, rec,
					&offsets, &heap, &plan->old_vers_heap,
					&old_vers, &mtr);

osku's avatar
osku committed
1611 1612 1613 1614 1615 1616
				if (err != DB_SUCCESS) {

					goto lock_wait_or_error;
				}

				if (old_vers == NULL) {
1617 1618 1619
					offsets = rec_get_offsets(
						rec, index, offsets,
						ULINT_UNDEFINED, &heap);
1620 1621 1622 1623 1624 1625 1626 1627 1628 1629

					/* Fetch the columns needed in
					test conditions. The clustered
					index record is protected by a
					page latch that was acquired
					by row_sel_open_pcur() or
					row_sel_restore_pcur_pos().
					The latch will not be released
					until mtr_commit(mtr). */

1630 1631 1632 1633
					row_sel_fetch_columns(
						index, rec, offsets,
						UT_LIST_GET_FIRST(
							plan->columns));
osku's avatar
osku committed
1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644

					if (!row_sel_test_end_conds(plan)) {

						goto table_exhausted;
					}

					goto next_rec;
				}

				rec = old_vers;
			}
1645
		} else if (!lock_sec_rec_cons_read_sees(rec,
osku's avatar
osku committed
1646 1647 1648 1649 1650 1651 1652
							node->read_view)) {
			cons_read_requires_clust_rec = TRUE;
		}
	}

	/* PHASE 4: Test search end conditions and deleted flag */

1653 1654 1655 1656
	/* Fetch the columns needed in test conditions.  The record is
	protected by a page latch that was acquired by
	row_sel_open_pcur() or row_sel_restore_pcur_pos().  The latch
	will not be released until mtr_commit(mtr). */
1657

osku's avatar
osku committed
1658
	row_sel_fetch_columns(index, rec, offsets,
1659
			      UT_LIST_GET_FIRST(plan->columns));
osku's avatar
osku committed
1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673

	/* Test the selection end conditions: these can only contain columns
	which already are found in the index, even though the index might be
	non-clustered */

	if (plan->unique_search && cursor_just_opened) {

		/* No test necessary: the test was already made above */

	} else if (!row_sel_test_end_conds(plan)) {

		goto table_exhausted;
	}

1674
	if (rec_get_deleted_flag(rec, dict_table_is_comp(plan->table))
1675
	    && !cons_read_requires_clust_rec) {
osku's avatar
osku committed
1676 1677 1678 1679 1680 1681

		/* The record is delete marked: we can skip it if this is
		not a consistent read which might see an earlier version
		of a non-clustered index record */

		if (plan->unique_search) {
1682

osku's avatar
osku committed
1683 1684
			goto table_exhausted;
		}
1685

osku's avatar
osku committed
1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697
		goto next_rec;
	}

	/* PHASE 5: Get the clustered index record, if needed and if we did
	not do the search using the clustered index */

	if (plan->must_get_clust || cons_read_requires_clust_rec) {

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

		err = row_sel_get_clust_rec(node, plan, rec, thr, &clust_rec,
1698
					    &mtr);
osku's avatar
osku committed
1699
		mtr_has_extra_clust_latch = TRUE;
1700

osku's avatar
osku committed
1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717
		if (err != DB_SUCCESS) {

			goto lock_wait_or_error;
		}

		/* Retrieving the clustered record required a search:
		increment the cost counter */

		cost_counter++;

		if (clust_rec == NULL) {
			/* The record did not exist in the read view */
			ut_ad(consistent_read);

			goto next_rec;
		}

1718
		if (rec_get_deleted_flag(clust_rec,
1719
					 dict_table_is_comp(plan->table))) {
osku's avatar
osku committed
1720 1721 1722 1723 1724 1725 1726 1727 1728 1729

			/* The record is delete marked: we can skip it */

			goto next_rec;
		}

		if (node->can_get_updated) {

			btr_pcur_store_position(&(plan->clust_pcur), &mtr);
		}
1730
	}
osku's avatar
osku committed
1731 1732

	/* PHASE 6: Test the rest of search conditions */
1733

osku's avatar
osku committed
1734 1735 1736
	if (!row_sel_test_other_conds(plan)) {

		if (plan->unique_search) {
1737

osku's avatar
osku committed
1738 1739 1740 1741 1742 1743 1744 1745
			goto table_exhausted;
		}

		goto next_rec;
	}

	/* PHASE 7: We found a new qualifying row for the current table; push
	the row if prefetch is on, or move to the next table in the join */
1746

osku's avatar
osku committed
1747 1748
	plan->n_rows_fetched++;

1749
	ut_ad(plan->pcur.latch_mode == BTR_SEARCH_LEAF);
osku's avatar
osku committed
1750 1751

	if ((plan->n_rows_fetched <= SEL_PREFETCH_LIMIT)
1752
	    || plan->unique_search || plan->no_prefetch
1753
	    || plan->table->big_rows) {
osku's avatar
osku committed
1754 1755

		/* No prefetch in operation: go to the next table */
1756

osku's avatar
osku committed
1757 1758 1759 1760 1761 1762 1763 1764
		goto next_table;
	}

	sel_push_prefetched_row(plan);

	if (plan->n_rows_prefetched == SEL_MAX_N_PREFETCH) {

		/* The prefetch buffer is now full */
1765

osku's avatar
osku committed
1766 1767 1768 1769 1770
		sel_pop_prefetched_row(plan);

		goto next_table;
	}

1771
next_rec:
osku's avatar
osku committed
1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782
	ut_ad(!search_latch_locked);

	if (mtr_has_extra_clust_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. */

		goto commit_mtr_for_a_while;
	}
1783

osku's avatar
osku committed
1784 1785 1786 1787 1788 1789 1790
	if (node->asc) {
		moved = btr_pcur_move_to_next(&(plan->pcur), &mtr);
	} else {
		moved = btr_pcur_move_to_prev(&(plan->pcur), &mtr);
	}

	if (!moved) {
1791

osku's avatar
osku committed
1792 1793 1794 1795 1796 1797
		goto table_exhausted;
	}

	cursor_just_opened = FALSE;

	/* END OF RECORD LOOP
1798
	------------------ */
osku's avatar
osku committed
1799 1800 1801 1802 1803 1804
	goto rec_loop;

next_table:
	/* We found a record which satisfies the conditions: we can move to
	the next table or return a row in the result set */

1805
	ut_ad(btr_pcur_is_on_user_rec(&plan->pcur));
1806

osku's avatar
osku committed
1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824
	if (plan->unique_search && !node->can_get_updated) {

		plan->cursor_at_end = TRUE;
	} else {
		ut_ad(!search_latch_locked);

		plan->stored_cursor_rec_processed = TRUE;

		btr_pcur_store_position(&(plan->pcur), &mtr);
	}

	mtr_commit(&mtr);

	mtr_has_extra_clust_latch = FALSE;

next_table_no_mtr:
	/* If we use 'goto' to this label, it means that the row was popped
	from the prefetched rows stack, and &mtr is already committed */
1825

osku's avatar
osku committed
1826 1827 1828 1829 1830 1831
	if (node->fetch_table + 1 == node->n_tables) {

		sel_eval_select_list(node);

		if (node->is_aggregate) {

1832
			goto table_loop;
osku's avatar
osku committed
1833 1834 1835
		}

		sel_assign_into_var_values(node->into_list, node);
1836

osku's avatar
osku committed
1837 1838 1839 1840 1841 1842 1843 1844 1845 1846
		thr->run_node = que_node_get_parent(node);

		err = DB_SUCCESS;
		goto func_exit;
	}

	node->fetch_table++;

	/* When we move to the next table, we first reset the plan cursor:
	we do not care about resetting it when we backtrack from a table */
1847

osku's avatar
osku committed
1848
	plan_reset_cursor(sel_node_get_nth_plan(node, node->fetch_table));
1849

osku's avatar
osku committed
1850 1851 1852 1853
	goto table_loop;

table_exhausted:
	/* The table cursor pcur reached the result set end: backtrack to the
1854
	previous table in the join if we do not have cached prefetched rows */
osku's avatar
osku committed
1855 1856 1857 1858 1859 1860

	plan->cursor_at_end = TRUE;

	mtr_commit(&mtr);

	mtr_has_extra_clust_latch = FALSE;
1861

osku's avatar
osku committed
1862 1863
	if (plan->n_rows_prefetched > 0) {
		/* The table became exhausted during a prefetch */
1864

osku's avatar
osku committed
1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880
		sel_pop_prefetched_row(plan);

		goto next_table_no_mtr;
	}

table_exhausted_no_mtr:
	if (node->fetch_table == 0) {
		err = DB_SUCCESS;

		if (node->is_aggregate && !node->aggregate_already_fetched) {

			node->aggregate_already_fetched = TRUE;

			sel_assign_into_var_values(node->into_list, node);

			thr->run_node = que_node_get_parent(node);
1881 1882
		} else {
			node->state = SEL_NODE_NO_MORE_ROWS;
osku's avatar
osku committed
1883

1884
			thr->run_node = que_node_get_parent(node);
osku's avatar
osku committed
1885
		}
1886

osku's avatar
osku committed
1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900
		goto func_exit;
	}

	node->fetch_table--;

	goto table_loop;

stop_for_a_while:
	/* Return control for a while to que_run_threads, so that runaway
	queries can be canceled. NOTE that when we come here, we must, in a
	locking read, have placed the necessary (possibly waiting request)
	record lock on the cursor record or its successor: when we reposition
	the cursor, this record lock guarantees that nobody can meanwhile have
	inserted new records which should have appeared in the result set,
1901
	which would result in the phantom problem. */
osku's avatar
osku committed
1902 1903 1904 1905 1906 1907 1908

	ut_ad(!search_latch_locked);

	plan->stored_cursor_rec_processed = FALSE;
	btr_pcur_store_position(&(plan->pcur), &mtr);

	mtr_commit(&mtr);
1909

1910
#ifdef UNIV_SYNC_DEBUG
osku's avatar
osku committed
1911
	ut_ad(sync_thread_levels_empty_gen(TRUE));
1912
#endif /* UNIV_SYNC_DEBUG */
osku's avatar
osku committed
1913 1914 1915 1916 1917 1918
	err = DB_SUCCESS;
	goto func_exit;

commit_mtr_for_a_while:
	/* Stores the cursor position and commits &mtr; this is used if
	&mtr may contain latches which would break the latching order if
1919
	&mtr would not be committed and the latches released. */
osku's avatar
osku committed
1920 1921 1922 1923 1924 1925 1926 1927 1928

	plan->stored_cursor_rec_processed = TRUE;

	ut_ad(!search_latch_locked);
	btr_pcur_store_position(&(plan->pcur), &mtr);

	mtr_commit(&mtr);

	mtr_has_extra_clust_latch = FALSE;
1929

1930
#ifdef UNIV_SYNC_DEBUG
osku's avatar
osku committed
1931
	ut_ad(sync_thread_levels_empty_gen(TRUE));
1932
#endif /* UNIV_SYNC_DEBUG */
osku's avatar
osku committed
1933 1934 1935 1936 1937 1938

	goto table_loop;

lock_wait_or_error:
	/* See the note at stop_for_a_while: the same holds for this case */

1939
	ut_ad(!btr_pcur_is_before_first_on_page(&plan->pcur) || !node->asc);
osku's avatar
osku committed
1940 1941 1942 1943
	ut_ad(!search_latch_locked);

	plan->stored_cursor_rec_processed = FALSE;
	btr_pcur_store_position(&(plan->pcur), &mtr);
1944

osku's avatar
osku committed
1945
	mtr_commit(&mtr);
1946

1947
#ifdef UNIV_SYNC_DEBUG
osku's avatar
osku committed
1948
	ut_ad(sync_thread_levels_empty_gen(TRUE));
1949
#endif /* UNIV_SYNC_DEBUG */
osku's avatar
osku committed
1950 1951

func_exit:
1952 1953 1954
	if (search_latch_locked) {
		rw_lock_s_unlock(&btr_search_latch);
	}
osku's avatar
osku committed
1955 1956 1957 1958 1959 1960
	if (UNIV_LIKELY_NULL(heap)) {
		mem_heap_free(heap);
	}
	return(err);
}

1961
/**********************************************************************//**
osku's avatar
osku committed
1962
Performs a select step. This is a high-level function used in SQL execution
1963 1964
graphs.
@return	query thread to run next or NULL */
1965
UNIV_INTERN
osku's avatar
osku committed
1966 1967 1968
que_thr_t*
row_sel_step(
/*=========*/
1969
	que_thr_t*	thr)	/*!< in: query thread */
osku's avatar
osku committed
1970 1971 1972 1973 1974 1975 1976
{
	ulint		i_lock_mode;
	sym_node_t*	table_node;
	sel_node_t*	node;
	ulint		err;

	ut_ad(thr);
1977

osku's avatar
osku committed
1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001
	node = thr->run_node;

	ut_ad(que_node_get_type(node) == QUE_NODE_SELECT);

	/* If this is a new time this node is executed (or when execution
	resumes after wait for a table intention lock), set intention locks
	on the tables, or assign a read view */

	if (node->into_list && (thr->prev_node == que_node_get_parent(node))) {

		node->state = SEL_NODE_OPEN;
	}

	if (node->state == SEL_NODE_OPEN) {

		/* It may be that the current session has not yet started
		its transaction, or it has been committed: */

		trx_start_if_not_started(thr_get_trx(thr));

		plan_reset_cursor(sel_node_get_nth_plan(node, 0));

		if (node->consistent_read) {
			/* Assign a read view for the query */
2002 2003
			node->read_view = trx_assign_read_view(
				thr_get_trx(thr));
osku's avatar
osku committed
2004 2005 2006 2007 2008 2009
		} else {
			if (node->set_x_locks) {
				i_lock_mode = LOCK_IX;
			} else {
				i_lock_mode = LOCK_IS;
			}
2010

osku's avatar
osku committed
2011
			table_node = node->table_list;
2012

osku's avatar
osku committed
2013 2014
			while (table_node) {
				err = lock_table(0, table_node->table,
2015
						 i_lock_mode, thr);
osku's avatar
osku committed
2016
				if (err != DB_SUCCESS) {
2017
					thr_get_trx(thr)->error_state = err;
2018

osku's avatar
osku committed
2019 2020
					return(NULL);
				}
2021

osku's avatar
osku committed
2022 2023 2024
				table_node = que_node_get_next(table_node);
			}
		}
2025

osku's avatar
osku committed
2026 2027 2028 2029 2030
		/* If this is an explicit cursor, copy stored procedure
		variable values, so that the values cannot change between
		fetches (currently, we copy them also for non-explicit
		cursors) */

2031 2032
		if (node->explicit_cursor
		    && UT_LIST_GET_FIRST(node->copy_variables)) {
osku's avatar
osku committed
2033 2034 2035

			row_sel_copy_input_variable_vals(node);
		}
2036

osku's avatar
osku committed
2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050
		node->state = SEL_NODE_FETCH;
		node->fetch_table = 0;

		if (node->is_aggregate) {
			/* Reset the aggregate total values */
			sel_reset_aggregate_vals(node);
		}
	}

	err = row_sel(node, thr);

	/* NOTE! if queries are parallelized, the following assignment may
	have problems; the assignment should be made only if thr is the
	only top-level thr in the graph: */
2051

osku's avatar
osku committed
2052 2053
	thr->graph->last_sel_node = node;

2054 2055
	if (err != DB_SUCCESS) {
		thr_get_trx(thr)->error_state = err;
osku's avatar
osku committed
2056 2057 2058 2059 2060

		return(NULL);
	}

	return(thr);
2061
}
osku's avatar
osku committed
2062

2063
/**********************************************************************//**
2064 2065
Performs a fetch for a cursor.
@return	query thread to run next or NULL */
2066
UNIV_INTERN
osku's avatar
osku committed
2067 2068 2069
que_thr_t*
fetch_step(
/*=======*/
2070
	que_thr_t*	thr)	/*!< in: query thread */
osku's avatar
osku committed
2071 2072 2073 2074 2075
{
	sel_node_t*	sel_node;
	fetch_node_t*	node;

	ut_ad(thr);
2076

osku's avatar
osku committed
2077 2078
	node = thr->run_node;
	sel_node = node->cursor_def;
2079

osku's avatar
osku committed
2080 2081 2082 2083 2084
	ut_ad(que_node_get_type(node) == QUE_NODE_FETCH);

	if (thr->prev_node != que_node_get_parent(node)) {

		if (sel_node->state != SEL_NODE_NO_MORE_ROWS) {
2085

2086 2087
			if (node->into_list) {
				sel_assign_into_var_values(node->into_list,
2088
							   sel_node);
2089
			} else {
2090 2091
				void* ret = (*node->func->func)(
					sel_node, node->func->arg);
2092 2093

				if (!ret) {
2094 2095
					sel_node->state
						= SEL_NODE_NO_MORE_ROWS;
2096 2097
				}
			}
osku's avatar
osku committed
2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108
		}

		thr->run_node = que_node_get_parent(node);

		return(thr);
	}

	/* Make the fetch node the parent of the cursor definition for
	the time of the fetch, so that execution knows to return to this
	fetch node after a row has been selected or we know that there is
	no row left */
2109

osku's avatar
osku committed
2110
	sel_node->common.parent = node;
2111

osku's avatar
osku committed
2112
	if (sel_node->state == SEL_NODE_CLOSED) {
2113 2114
		fprintf(stderr,
			"InnoDB: Error: fetch called on a closed cursor\n");
osku's avatar
osku committed
2115

2116
		thr_get_trx(thr)->error_state = DB_ERROR;
osku's avatar
osku committed
2117 2118 2119 2120 2121 2122 2123

		return(NULL);
	}

	thr->run_node = sel_node;

	return(thr);
2124
}
osku's avatar
osku committed
2125

2126
/****************************************************************//**
2127 2128
Sample callback function for fetch that prints each row.
@return	always returns non-NULL */
2129
UNIV_INTERN
2130 2131 2132
void*
row_fetch_print(
/*============*/
2133 2134
	void*	row,		/*!< in:  sel_node_t* */
	void*	user_arg)	/*!< in:  not used */
2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147
{
	sel_node_t*	node = row;
	que_node_t*	exp;
	ulint		i = 0;

	UT_NOT_USED(user_arg);

	fprintf(stderr, "row_fetch_print: row %p\n", row);

	exp = node->select_list;

	while (exp) {
		dfield_t*	dfield = que_node_get_val(exp);
2148
		const dtype_t*	type = dfield_get_type(dfield);
2149 2150 2151 2152

		fprintf(stderr, " column %lu:\n", (ulong)i);

		dtype_print(type);
2153
		putc('\n', stderr);
2154

2155 2156
		if (dfield_get_len(dfield) != UNIV_SQL_NULL) {
			ut_print_buf(stderr, dfield_get_data(dfield),
2157
				     dfield_get_len(dfield));
2158
			putc('\n', stderr);
2159
		} else {
2160
			fputs(" <NULL>;\n", stderr);
2161 2162
		}

2163 2164 2165 2166 2167 2168 2169
		exp = que_node_get_next(exp);
		i++;
	}

	return((void*)42);
}

2170
/****************************************************************//**
2171 2172
Callback function for fetch that stores an unsigned 4 byte integer to the
location pointed. The column's type must be DATA_INT, DATA_UNSIGNED, length
2173 2174
= 4.
@return	always returns NULL */
2175
UNIV_INTERN
2176 2177 2178
void*
row_fetch_store_uint4(
/*==================*/
2179 2180
	void*	row,		/*!< in:  sel_node_t* */
	void*	user_arg)	/*!< in:  data pointer */
2181 2182 2183 2184 2185 2186
{
	sel_node_t*	node = row;
	ib_uint32_t*	val = user_arg;
	ulint		tmp;

	dfield_t*	dfield = que_node_get_val(node->select_list);
2187
	const dtype_t*	type = dfield_get_type(dfield);
2188 2189 2190 2191 2192 2193 2194
	ulint		len = dfield_get_len(dfield);

	ut_a(dtype_get_mtype(type) == DATA_INT);
	ut_a(dtype_get_prtype(type) & DATA_UNSIGNED);
	ut_a(len == 4);

	tmp = mach_read_from_4(dfield_get_data(dfield));
2195
	*val = (ib_uint32_t) tmp;
2196 2197 2198 2199

	return(NULL);
}

2200
/***********************************************************//**
2201 2202
Prints a row in a select result.
@return	query thread to run next or NULL */
2203
UNIV_INTERN
osku's avatar
osku committed
2204 2205 2206
que_thr_t*
row_printf_step(
/*============*/
2207
	que_thr_t*	thr)	/*!< in: query thread */
osku's avatar
osku committed
2208 2209 2210 2211 2212 2213
{
	row_printf_node_t*	node;
	sel_node_t*		sel_node;
	que_node_t*		arg;

	ut_ad(thr);
2214

osku's avatar
osku committed
2215
	node = thr->run_node;
2216

osku's avatar
osku committed
2217 2218 2219 2220 2221
	sel_node = node->sel_node;

	ut_ad(que_node_get_type(node) == QUE_NODE_ROW_PRINTF);

	if (thr->prev_node == que_node_get_parent(node)) {
2222

osku's avatar
osku committed
2223 2224 2225 2226 2227 2228
		/* Reset the cursor */
		sel_node->state = SEL_NODE_OPEN;

		/* Fetch next row to print */

		thr->run_node = sel_node;
2229

osku's avatar
osku committed
2230 2231 2232 2233 2234 2235 2236 2237 2238 2239
		return(thr);
	}

	if (sel_node->state != SEL_NODE_FETCH) {

		ut_ad(sel_node->state == SEL_NODE_NO_MORE_ROWS);

		/* No more rows to print */

		thr->run_node = que_node_get_parent(node);
2240

osku's avatar
osku committed
2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260
		return(thr);
	}

	arg = sel_node->select_list;

	while (arg) {
		dfield_print_also_hex(que_node_get_val(arg));

		fputs(" ::: ", stderr);

		arg = que_node_get_next(arg);
	}

	putc('\n', stderr);

	/* Fetch next row to print */

	thr->run_node = sel_node;

	return(thr);
2261
}
osku's avatar
osku committed
2262

2263
/****************************************************************//**
osku's avatar
osku committed
2264 2265 2266 2267 2268 2269
Converts a key value stored in MySQL format to an Innobase dtuple. The last
field of the key value may be just a prefix of a fixed length field: hence
the parameter key_len. But currently we do not allow search keys where the
last field is only a prefix of the full key field len and print a warning if
such appears. A counterpart of this function is
ha_innobase::store_key_val_for_row() in ha_innodb.cc. */
2270
UNIV_INTERN
osku's avatar
osku committed
2271 2272 2273
void
row_sel_convert_mysql_key_to_innobase(
/*==================================*/
2274
	dtuple_t*	tuple,		/*!< in/out: tuple where to build;
osku's avatar
osku committed
2275 2276 2277
					NOTE: we assume that the type info
					in the tuple is already according
					to index! */
2278
	byte*		buf,		/*!< in: buffer to use in field
osku's avatar
osku committed
2279
					conversions */
2280 2281 2282 2283 2284
	ulint		buf_len,	/*!< in: buffer length */
	dict_index_t*	index,		/*!< in: index of the key value */
	const byte*	key_ptr,	/*!< in: MySQL key value */
	ulint		key_len,	/*!< in: MySQL key value length */
	trx_t*		trx)		/*!< in: transaction */
osku's avatar
osku committed
2285 2286
{
	byte*		original_buf	= buf;
2287
	const byte*	original_key_ptr = key_ptr;
osku's avatar
osku committed
2288 2289 2290 2291 2292 2293
	dict_field_t*	field;
	dfield_t*	dfield;
	ulint		data_offset;
	ulint		data_len;
	ulint		data_field_len;
	ibool		is_null;
2294
	const byte*	key_end;
osku's avatar
osku committed
2295
	ulint		n_fields = 0;
2296

osku's avatar
osku committed
2297 2298 2299 2300 2301 2302
	/* For documentation of the key value storage format in MySQL, see
	ha_innobase::store_key_val_for_row() in ha_innodb.cc. */

	key_end = key_ptr + key_len;

	/* Permit us to access any field in the tuple (ULINT_MAX): */
2303

osku's avatar
osku committed
2304 2305
	dtuple_set_n_fields(tuple, ULINT_MAX);

2306
	dfield = dtuple_get_nth_field(tuple, 0);
osku's avatar
osku committed
2307 2308
	field = dict_index_get_nth_field(index, 0);

marko's avatar
marko committed
2309
	if (UNIV_UNLIKELY(dfield_get_type(dfield)->mtype == DATA_SYS)) {
osku's avatar
osku committed
2310 2311 2312 2313 2314 2315 2316 2317 2318
		/* A special case: we are looking for a position in the
		generated clustered index which InnoDB automatically added
		to a table with no primary key: the first and the only
		ordering column is ROW_ID which InnoDB stored to the key_ptr
		buffer. */

		ut_a(key_len == DATA_ROW_ID_LEN);

		dfield_set_data(dfield, key_ptr, DATA_ROW_ID_LEN);
2319

osku's avatar
osku committed
2320 2321 2322 2323 2324 2325 2326
		dtuple_set_n_fields(tuple, 1);

		return;
	}

	while (key_ptr < key_end) {

2327 2328
		ulint	type = dfield_get_type(dfield)->mtype;
		ut_a(field->col->mtype == type);
osku's avatar
osku committed
2329 2330 2331 2332

		data_offset = 0;
		is_null = FALSE;

2333 2334 2335 2336
		if (!(dfield_get_type(dfield)->prtype & DATA_NOT_NULL)) {
			/* The first byte in the field tells if this is
			an SQL NULL value */

osku's avatar
osku committed
2337 2338
			data_offset = 1;

2339
			if (*key_ptr != 0) {
2340
				dfield_set_null(dfield);
osku's avatar
osku committed
2341 2342

				is_null = TRUE;
2343 2344
			}
		}
osku's avatar
osku committed
2345 2346

		/* Calculate data length and data field total length */
2347

osku's avatar
osku committed
2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363
		if (type == DATA_BLOB) {
			/* The key field is a column prefix of a BLOB or
			TEXT */

			ut_a(field->prefix_len > 0);

			/* MySQL stores the actual data length to the first 2
			bytes after the optional SQL NULL marker byte. The
			storage format is little-endian, that is, the most
			significant byte at a higher address. In UTF-8, MySQL
			seems to reserve field->prefix_len bytes for
			storing this field in the key value buffer, even
			though the actual value only takes data_len bytes
			from the start. */

			data_len = key_ptr[data_offset]
2364
				+ 256 * key_ptr[data_offset + 1];
osku's avatar
osku committed
2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383
			data_field_len = data_offset + 2 + field->prefix_len;

			data_offset += 2;

			/* Now that we know the length, we store the column
			value like it would be a fixed char field */

		} else if (field->prefix_len > 0) {
			/* Looks like MySQL pads unused end bytes in the
			prefix with space. Therefore, also in UTF-8, it is ok
			to compare with a prefix containing full prefix_len
			bytes, and no need to take at most prefix_len / 3
			UTF-8 characters from the start.
			If the prefix is used as the upper end of a LIKE
			'abc%' query, then MySQL pads the end with chars
			0xff. TODO: in that case does it any harm to compare
			with the full prefix_len bytes. How do characters
			0xff in UTF-8 behave? */

2384
			data_len = field->prefix_len;
osku's avatar
osku committed
2385 2386 2387 2388 2389 2390
			data_field_len = data_offset + data_len;
		} else {
			data_len = dfield_get_type(dfield)->len;
			data_field_len = data_offset + data_len;
		}

2391 2392 2393 2394
		if (UNIV_UNLIKELY
		    (dtype_get_mysql_type(dfield_get_type(dfield))
		     == DATA_MYSQL_TRUE_VARCHAR)
		    && UNIV_LIKELY(type != DATA_INT)) {
osku's avatar
osku committed
2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408
			/* In a MySQL key value format, a true VARCHAR is
			always preceded by 2 bytes of a length field.
			dfield_get_type(dfield)->len returns the maximum
			'payload' len in bytes. That does not include the
			2 bytes that tell the actual data length.

			We added the check != DATA_INT to make sure we do
			not treat MySQL ENUM or SET as a true VARCHAR! */

			data_len += 2;
			data_field_len += 2;
		}

		/* Storing may use at most data_len bytes of buf */
2409

marko's avatar
marko committed
2410
		if (UNIV_LIKELY(!is_null)) {
2411 2412 2413 2414 2415
			row_mysql_store_col_in_innobase_format(
				dfield, buf,
				FALSE, /* MySQL key value format col */
				key_ptr + data_offset, data_len,
				dict_table_is_comp(index->table));
osku's avatar
osku committed
2416 2417 2418
			buf += data_len;
		}

2419
		key_ptr += data_field_len;
osku's avatar
osku committed
2420

marko's avatar
marko committed
2421
		if (UNIV_UNLIKELY(key_ptr > key_end)) {
osku's avatar
osku committed
2422 2423 2424
			/* The last field in key was not a complete key field
			but a prefix of it.

2425
			Print a warning about this! HA_READ_PREFIX_LAST does
osku's avatar
osku committed
2426 2427 2428 2429 2430
			not currently work in InnoDB with partial-field key
			value prefixes. Since MySQL currently uses a padding
			trick to calculate LIKE 'abc%' type queries there
			should never be partial-field prefixes in searches. */

2431 2432
			ut_print_timestamp(stderr);

2433 2434 2435
			fputs("  InnoDB: Warning: using a partial-field"
			      " key prefix in search.\n"
			      "InnoDB: ", stderr);
osku's avatar
osku committed
2436 2437
			dict_index_name_print(stderr, trx, index);
			fprintf(stderr, ". Last data field length %lu bytes,\n"
2438 2439 2440 2441 2442
				"InnoDB: key ptr now exceeds"
				" key end by %lu bytes.\n"
				"InnoDB: Key value in the MySQL format:\n",
				(ulong) data_field_len,
				(ulong) (key_ptr - key_end));
osku's avatar
osku committed
2443 2444
			fflush(stderr);
			ut_print_buf(stderr, original_key_ptr, key_len);
2445
			putc('\n', stderr);
osku's avatar
osku committed
2446 2447

			if (!is_null) {
2448 2449 2450
				ulint	len = dfield_get_len(dfield);
				dfield_set_len(dfield, len
					       - (ulint) (key_ptr - key_end));
osku's avatar
osku committed
2451 2452 2453
			}
		}

2454 2455
		n_fields++;
		field++;
osku's avatar
osku committed
2456
		dfield++;
2457
	}
osku's avatar
osku committed
2458 2459 2460

	ut_a(buf <= original_buf + buf_len);

2461
	/* We set the length of tuple to n_fields: we assume that the memory
osku's avatar
osku committed
2462
	area allocated for it is big enough (usually bigger than n_fields). */
2463 2464

	dtuple_set_n_fields(tuple, n_fields);
osku's avatar
osku committed
2465 2466
}

2467
/**************************************************************//**
osku's avatar
osku committed
2468 2469 2470 2471 2472
Stores the row id to the prebuilt struct. */
static
void
row_sel_store_row_id_to_prebuilt(
/*=============================*/
2473 2474 2475 2476
	row_prebuilt_t*		prebuilt,	/*!< in/out: prebuilt */
	const rec_t*		index_rec,	/*!< in: record */
	const dict_index_t*	index,		/*!< in: index of the record */
	const ulint*		offsets)	/*!< in: rec_get_offsets
2477
						(index_rec, index) */
osku's avatar
osku committed
2478
{
2479 2480
	const byte*	data;
	ulint		len;
osku's avatar
osku committed
2481 2482 2483

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

2484 2485 2486
	data = rec_get_nth_field(
		index_rec, offsets,
		dict_index_get_sys_col_pos(index, DATA_ROW_ID), &len);
osku's avatar
osku committed
2487

2488
	if (UNIV_UNLIKELY(len != DATA_ROW_ID_LEN)) {
2489
		fprintf(stderr,
2490 2491
			"InnoDB: Error: Row id field is"
			" wrong length %lu in ", (ulong) len);
osku's avatar
osku committed
2492 2493
		dict_index_name_print(stderr, prebuilt->trx, index);
		fprintf(stderr, "\n"
2494
			"InnoDB: Field number %lu, record:\n",
2495
			(ulong) dict_index_get_sys_col_pos(index,
2496
							   DATA_ROW_ID));
osku's avatar
osku committed
2497 2498 2499 2500 2501 2502 2503 2504
		rec_print_new(stderr, index_rec, offsets);
		putc('\n', stderr);
		ut_error;
	}

	ut_memcpy(prebuilt->row_id, data, len);
}

2505
/**************************************************************//**
osku's avatar
osku committed
2506 2507 2508 2509 2510 2511
Stores a non-SQL-NULL field in the MySQL format. The counterpart of this
function is row_mysql_store_col_in_innobase_format() in row0mysql.c. */
static
void
row_sel_field_store_in_mysql_format(
/*================================*/
2512
	byte*		dest,	/*!< in/out: buffer where to store; NOTE
2513 2514 2515 2516 2517 2518
				that BLOBs are not in themselves
				stored here: the caller must allocate
				and copy the BLOB into buffer before,
				and pass the pointer to the BLOB in
				'data' */
	const mysql_row_templ_t* templ,
2519
				/*!< in: MySQL column template.
2520 2521 2522
				Its following fields are referenced:
				type, is_unsigned, mysql_col_len,
				mbminlen, mbmaxlen */
2523 2524
	const byte*	data,	/*!< in: data to store */
	ulint		len)	/*!< in: length of the data */
osku's avatar
osku committed
2525 2526 2527 2528 2529 2530 2531
{
	byte*	ptr;
	byte*	field_end;
	byte*	pad_ptr;

	ut_ad(len != UNIV_SQL_NULL);

2532 2533
	switch (templ->type) {
	case DATA_INT:
osku's avatar
osku committed
2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552
		/* Convert integer data from Innobase to a little-endian
		format, sign bit restored to normal */

		ptr = dest + len;

		for (;;) {
			ptr--;
			*ptr = *data;
			if (ptr == dest) {
				break;
			}
			data++;
		}

		if (!templ->is_unsigned) {
			dest[len - 1] = (byte) (dest[len - 1] ^ 128);
		}

		ut_ad(templ->mysql_col_len == len);
2553
		break;
osku's avatar
osku committed
2554

2555 2556 2557
	case DATA_VARCHAR:
	case DATA_VARMYSQL:
	case DATA_BINARY:
osku's avatar
osku committed
2558 2559 2560 2561 2562 2563
		field_end = dest + templ->mysql_col_len;

		if (templ->mysql_type == DATA_MYSQL_TRUE_VARCHAR) {
			/* This is a >= 5.0.3 type true VARCHAR. Store the
			length of the data to the first byte or the first
			two bytes of dest. */
2564

2565 2566
			dest = row_mysql_store_true_var_len(
				dest, len, templ->mysql_length_bytes);
osku's avatar
osku committed
2567 2568 2569 2570
		}

		/* Copy the actual data */
		ut_memcpy(dest, data, len);
2571

osku's avatar
osku committed
2572 2573 2574
		/* Pad with trailing spaces. We pad with spaces also the
		unused end of a >= 5.0.3 true VARCHAR column, just in case
		MySQL expects its contents to be deterministic. */
2575

osku's avatar
osku committed
2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586
		pad_ptr = dest + len;

		ut_ad(templ->mbminlen <= templ->mbmaxlen);

		/* We handle UCS2 charset strings differently. */
		if (templ->mbminlen == 2) {
			/* A space char is two bytes, 0x0020 in UCS2 */

			if (len & 1) {
				/* A 0x20 has been stripped from the column.
				Pad it back. */
2587

osku's avatar
osku committed
2588 2589 2590 2591 2592
				if (pad_ptr < field_end) {
					*pad_ptr = 0x20;
					pad_ptr++;
				}
			}
2593

osku's avatar
osku committed
2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607
			/* Pad the rest of the string with 0x0020 */

			while (pad_ptr < field_end) {
				*pad_ptr = 0x00;
				pad_ptr++;
				*pad_ptr = 0x20;
				pad_ptr++;
			}
		} else {
			ut_ad(templ->mbminlen == 1);
			/* space=0x20 */

			memset(pad_ptr, 0x20, field_end - pad_ptr);
		}
2608 2609 2610
		break;

	case DATA_BLOB:
osku's avatar
osku committed
2611 2612 2613 2614
		/* Store a pointer to the BLOB buffer to dest: the BLOB was
		already copied to the buffer in row_sel_store_mysql_rec */

		row_mysql_store_blob_ref(dest, templ->mysql_col_len, data,
2615
					 len);
2616 2617 2618
		break;

	case DATA_MYSQL:
osku's avatar
osku committed
2619 2620
		memcpy(dest, data, len);

2621 2622
		ut_ad(templ->mysql_col_len >= len);
		ut_ad(templ->mbmaxlen >= templ->mbminlen);
osku's avatar
osku committed
2623

2624
		ut_ad(templ->mbmaxlen > templ->mbminlen
2625
		      || templ->mysql_col_len == len);
osku's avatar
osku committed
2626 2627 2628
		/* The following assertion would fail for old tables
		containing UTF-8 ENUM columns due to Bug #9526. */
		ut_ad(!templ->mbmaxlen
2629
		      || !(templ->mysql_col_len % templ->mbmaxlen));
2630
		ut_ad(len * templ->mbmaxlen >= templ->mysql_col_len);
osku's avatar
osku committed
2631 2632 2633 2634 2635 2636 2637 2638

		if (templ->mbminlen != templ->mbmaxlen) {
			/* Pad with spaces. This undoes the stripping
			done in row0mysql.ic, function
			row_mysql_store_col_in_innobase_format(). */

			memset(dest + len, 0x20, templ->mysql_col_len - len);
		}
2639
		break;
osku's avatar
osku committed
2640

2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655
	default:
#ifdef UNIV_DEBUG
	case DATA_SYS_CHILD:
	case DATA_SYS:
		/* These column types should never be shipped to MySQL. */
		ut_ad(0);

	case DATA_CHAR:
	case DATA_FIXBINARY:
	case DATA_FLOAT:
	case DATA_DOUBLE:
	case DATA_DECIMAL:
		/* Above are the valid column types for MySQL data. */
#endif /* UNIV_DEBUG */
		ut_ad(templ->mysql_col_len == len);
osku's avatar
osku committed
2656 2657 2658 2659
		memcpy(dest, data, len);
	}
}

2660
/**************************************************************//**
osku's avatar
osku committed
2661 2662 2663
Convert a row in the Innobase format to a row in the MySQL format.
Note that the template in prebuilt may advise us to copy only a few
columns to mysql_rec, other columns are left blank. All columns may not
2664
be needed in the query.
2665 2666
@return TRUE if success, FALSE if could not allocate memory for a BLOB
(though we may also assert in that case) */
osku's avatar
osku committed
2667 2668 2669 2670
static
ibool
row_sel_store_mysql_rec(
/*====================*/
2671 2672 2673
	byte*		mysql_rec,	/*!< out: row in the MySQL format */
	row_prebuilt_t*	prebuilt,	/*!< in: prebuilt struct */
	const rec_t*	rec,		/*!< in: Innobase record in the index
osku's avatar
osku committed
2674
					which was described in prebuilt's
2675 2676
					template; must be protected by
					a page latch */
2677
	const ulint*	offsets)	/*!< in: array returned by
osku's avatar
osku committed
2678 2679 2680 2681
					rec_get_offsets() */
{
	mysql_row_templ_t*	templ;
	mem_heap_t*		extern_field_heap	= NULL;
2682
	mem_heap_t*		heap;
2683
	const byte*		data;
osku's avatar
osku committed
2684 2685
	ulint			len;
	ulint			i;
2686

osku's avatar
osku committed
2687
	ut_ad(prebuilt->mysql_template);
2688
	ut_ad(prebuilt->default_rec);
osku's avatar
osku committed
2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700
	ut_ad(rec_offs_validate(rec, NULL, offsets));

	if (UNIV_LIKELY_NULL(prebuilt->blob_heap)) {
		mem_heap_free(prebuilt->blob_heap);
		prebuilt->blob_heap = NULL;
	}

	for (i = 0; i < prebuilt->n_template; i++) {

		templ = prebuilt->mysql_template + i;

		if (UNIV_UNLIKELY(rec_offs_nth_extern(offsets,
2701
						      templ->rec_field_no))) {
osku's avatar
osku committed
2702 2703 2704 2705 2706 2707

			/* Copy an externally stored field to the temporary
			heap */

			ut_a(!prebuilt->trx->has_search_latch);

2708 2709
			if (UNIV_UNLIKELY(templ->type == DATA_BLOB)) {
				if (prebuilt->blob_heap == NULL) {
2710 2711
					prebuilt->blob_heap = mem_heap_create(
						UNIV_PAGE_SIZE);
2712 2713 2714 2715
				}

				heap = prebuilt->blob_heap;
			} else {
2716 2717
				extern_field_heap
					= mem_heap_create(UNIV_PAGE_SIZE);
2718 2719 2720

				heap = extern_field_heap;
			}
osku's avatar
osku committed
2721 2722 2723 2724 2725

			/* NOTE: if we are retrieving a big BLOB, we may
			already run out of memory in the next call, which
			causes an assert */

2726 2727 2728 2729
			data = btr_rec_copy_externally_stored_field(
				rec, offsets,
				dict_table_zip_size(prebuilt->table),
				templ->rec_field_no, &len, heap);
osku's avatar
osku committed
2730 2731

			ut_a(len != UNIV_SQL_NULL);
2732 2733 2734 2735
		} else {
			/* Field is stored in the row. */

			data = rec_get_nth_field(rec, offsets,
2736
						 templ->rec_field_no, &len);
2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755

			if (UNIV_UNLIKELY(templ->type == DATA_BLOB)
			    && len != UNIV_SQL_NULL) {

				/* It is a BLOB field locally stored in the
				InnoDB record: we MUST copy its contents to
				prebuilt->blob_heap here because later code
				assumes all BLOB values have been copied to a
				safe place. */

				if (prebuilt->blob_heap == NULL) {
					prebuilt->blob_heap = mem_heap_create(
						UNIV_PAGE_SIZE);
				}

				data = memcpy(mem_heap_alloc(
						prebuilt->blob_heap, len),
						data, len);
			}
osku's avatar
osku committed
2756 2757 2758
		}

		if (len != UNIV_SQL_NULL) {
2759 2760 2761
			row_sel_field_store_in_mysql_format(
				mysql_rec + templ->mysql_col_offset,
				templ, data, len);
osku's avatar
osku committed
2762 2763 2764

			/* Cleanup */
			if (extern_field_heap) {
2765
				mem_heap_free(extern_field_heap);
osku's avatar
osku committed
2766
				extern_field_heap = NULL;
2767 2768
			}

osku's avatar
osku committed
2769 2770 2771
			if (templ->mysql_null_bit_mask) {
				/* It is a nullable column with a non-NULL
				value */
2772 2773
				mysql_rec[templ->mysql_null_byte_offset]
					&= ~(byte) templ->mysql_null_bit_mask;
osku's avatar
osku committed
2774 2775
			}
		} else {
2776 2777
			/* MySQL assumes that the field for an SQL
			NULL value is set to the default value. */
osku's avatar
osku committed
2778

2779 2780
			mysql_rec[templ->mysql_null_byte_offset]
				|= (byte) templ->mysql_null_bit_mask;
2781
			memcpy(mysql_rec + templ->mysql_col_offset,
2782 2783
			       (const byte*) prebuilt->default_rec
			       + templ->mysql_col_offset,
2784
			       templ->mysql_col_len);
osku's avatar
osku committed
2785
		}
2786
	}
osku's avatar
osku committed
2787 2788 2789 2790

	return(TRUE);
}

2791
/*********************************************************************//**
2792 2793
Builds a previous version of a clustered index record for a consistent read
@return	DB_SUCCESS or error code */
osku's avatar
osku committed
2794 2795 2796 2797
static
ulint
row_sel_build_prev_vers_for_mysql(
/*==============================*/
2798 2799 2800 2801 2802
	read_view_t*	read_view,	/*!< in: read view */
	dict_index_t*	clust_index,	/*!< in: clustered index */
	row_prebuilt_t*	prebuilt,	/*!< in: prebuilt struct */
	const rec_t*	rec,		/*!< in: record in a clustered index */
	ulint**		offsets,	/*!< in/out: offsets returned by
osku's avatar
osku committed
2803
					rec_get_offsets(rec, clust_index) */
2804
	mem_heap_t**	offset_heap,	/*!< in/out: memory heap from which
osku's avatar
osku committed
2805
					the offsets are allocated */
2806
	rec_t**		old_vers,	/*!< out: old version, or NULL if the
osku's avatar
osku committed
2807 2808 2809
					record does not exist in the view:
					i.e., it was freshly inserted
					afterwards */
2810
	mtr_t*		mtr)		/*!< in: mtr */
osku's avatar
osku committed
2811 2812 2813 2814 2815 2816 2817 2818
{
	ulint	err;

	if (prebuilt->old_vers_heap) {
		mem_heap_empty(prebuilt->old_vers_heap);
	} else {
		prebuilt->old_vers_heap = mem_heap_create(200);
	}
2819

2820 2821 2822
	err = row_vers_build_for_consistent_read(
		rec, mtr, clust_index, offsets, read_view, offset_heap,
		prebuilt->old_vers_heap, old_vers);
osku's avatar
osku committed
2823 2824 2825
	return(err);
}

2826
/*********************************************************************//**
osku's avatar
osku committed
2827 2828
Retrieves the clustered index record corresponding to a record in a
non-clustered index. Does the necessary locking. Used in the MySQL
2829 2830
interface.
@return	DB_SUCCESS or error code */
osku's avatar
osku committed
2831 2832 2833 2834
static
ulint
row_sel_get_clust_rec_for_mysql(
/*============================*/
2835 2836 2837
	row_prebuilt_t*	prebuilt,/*!< in: prebuilt struct in the handle */
	dict_index_t*	sec_index,/*!< in: secondary index where rec resides */
	const rec_t*	rec,	/*!< in: record in a non-clustered index; if
osku's avatar
osku committed
2838 2839 2840
				this is a locking read, then rec is not
				allowed to be delete-marked, and that would
				not make sense either */
2841 2842
	que_thr_t*	thr,	/*!< in: query thread */
	const rec_t**	out_rec,/*!< out: clustered record or an old version of
osku's avatar
osku committed
2843 2844 2845
				it, NULL if the old version did not exist
				in the read view, i.e., it was a fresh
				inserted version */
2846
	ulint**		offsets,/*!< in: offsets returned by
2847 2848
				rec_get_offsets(rec, sec_index);
				out: offsets returned by
osku's avatar
osku committed
2849
				rec_get_offsets(out_rec, clust_index) */
2850
	mem_heap_t**	offset_heap,/*!< in/out: memory heap from which
osku's avatar
osku committed
2851
				the offsets are allocated */
2852
	mtr_t*		mtr)	/*!< in: mtr used to get access to the
osku's avatar
osku committed
2853 2854 2855 2856
				non-clustered record; the same mtr is used to
				access the clustered index */
{
	dict_index_t*	clust_index;
2857
	const rec_t*	clust_rec;
osku's avatar
osku committed
2858 2859 2860 2861 2862 2863
	rec_t*		old_vers;
	ulint		err;
	trx_t*		trx;

	*out_rec = NULL;
	trx = thr_get_trx(thr);
2864

2865 2866
	row_build_row_ref_in_tuple(prebuilt->clust_ref, rec,
				   sec_index, *offsets, trx);
osku's avatar
osku committed
2867 2868

	clust_index = dict_table_get_first_index(sec_index->table);
2869

osku's avatar
osku committed
2870
	btr_pcur_open_with_no_init(clust_index, prebuilt->clust_ref,
2871 2872
				   PAGE_CUR_LE, BTR_SEARCH_LEAF,
				   prebuilt->clust_pcur, 0, mtr);
osku's avatar
osku committed
2873 2874 2875 2876 2877 2878 2879 2880 2881

	clust_rec = btr_pcur_get_rec(prebuilt->clust_pcur);

	prebuilt->clust_pcur->trx_if_known = trx;

	/* Note: only if the search ends up on a non-infimum record is the
	low_match value the real match to the search tuple */

	if (!page_rec_is_user_rec(clust_rec)
2882 2883
	    || btr_pcur_get_low_match(prebuilt->clust_pcur)
	    < dict_index_get_n_unique(clust_index)) {
2884

osku's avatar
osku committed
2885 2886 2887 2888 2889 2890 2891 2892 2893
		/* In a rare case it is possible that no clust rec is found
		for a delete-marked secondary index record: if in row0umod.c
		in row_undo_mod_remove_clust_low() we have already removed
		the clust rec, while purge is still cleaning and removing
		secondary index records associated with earlier versions of
		the clustered index record. In that case we know that the
		clustered index record did not exist in the read view of
		trx. */

2894
		if (!rec_get_deleted_flag(rec,
2895 2896
					  dict_table_is_comp(sec_index->table))
		    || prebuilt->select_lock_type != LOCK_NONE) {
2897
			ut_print_timestamp(stderr);
2898
			fputs("  InnoDB: error clustered record"
2899 2900
			      " for sec rec not found\n"
			      "InnoDB: ", stderr);
osku's avatar
osku committed
2901 2902
			dict_index_name_print(stderr, trx, sec_index);
			fputs("\n"
2903
			      "InnoDB: sec index record ", stderr);
osku's avatar
osku committed
2904 2905
			rec_print(stderr, rec, sec_index);
			fputs("\n"
2906
			      "InnoDB: clust index record ", stderr);
osku's avatar
osku committed
2907 2908 2909 2910 2911
			rec_print(stderr, clust_rec, clust_index);
			putc('\n', stderr);
			trx_print(stderr, trx, 600);

			fputs("\n"
2912 2913
			      "InnoDB: Submit a detailed bug report"
			      " to http://bugs.mysql.com\n", stderr);
osku's avatar
osku committed
2914 2915 2916 2917 2918 2919 2920 2921
		}

		clust_rec = NULL;

		goto func_exit;
	}

	*offsets = rec_get_offsets(clust_rec, clust_index, *offsets,
2922
				   ULINT_UNDEFINED, offset_heap);
osku's avatar
osku committed
2923 2924 2925 2926 2927

	if (prebuilt->select_lock_type != LOCK_NONE) {
		/* Try to place a lock on the index record; we are searching
		the clust rec with a unique condition, hence
		we set a LOCK_REC_NOT_GAP type lock */
2928

2929
		err = lock_clust_rec_read_check_and_lock(
2930 2931
			0, btr_pcur_get_block(prebuilt->clust_pcur),
			clust_rec, clust_index, *offsets,
2932
			prebuilt->select_lock_type, LOCK_REC_NOT_GAP, thr);
osku's avatar
osku committed
2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946
		if (err != DB_SUCCESS) {

			goto err_exit;
		}
	} else {
		/* This is a non-locking consistent read: if necessary, fetch
		a previous version of the record */

		old_vers = NULL;

		/* If the isolation level allows reading of uncommitted data,
		then we never look for an earlier version */

		if (trx->isolation_level > TRX_ISO_READ_UNCOMMITTED
2947 2948 2949
		    && !lock_clust_rec_cons_read_sees(
			    clust_rec, clust_index, *offsets,
			    trx->read_view)) {
2950

osku's avatar
osku committed
2951 2952
			/* The following call returns 'offsets' associated with
			'old_vers' */
2953 2954 2955 2956
			err = row_sel_build_prev_vers_for_mysql(
				trx->read_view, clust_index, prebuilt,
				clust_rec, offsets, offset_heap, &old_vers,
				mtr);
2957

2958
			if (err != DB_SUCCESS || old_vers == NULL) {
osku's avatar
osku committed
2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977

				goto err_exit;
			}

			clust_rec = old_vers;
		}

		/* If we had to go to an earlier version of row or the
		secondary index record is delete marked, then it may be that
		the secondary index record corresponding to clust_rec
		(or old_vers) is not rec; in that case we must ignore
		such row because in our snapshot rec would not have existed.
		Remember that from rec we cannot see directly which transaction
		id corresponds to it: we have to go to the clustered index
		record. A query where we want to fetch all rows where
		the secondary index value is in some interval would return
		a wrong result if we would not drop rows which we come to
		visit through secondary index records that would not really
		exist in our snapshot. */
2978

2979 2980
		if (clust_rec
		    && (old_vers
2981
			|| trx->isolation_level <= TRX_ISO_READ_UNCOMMITTED
2982 2983
			|| rec_get_deleted_flag(rec, dict_table_is_comp(
							sec_index->table)))
2984 2985
		    && !row_sel_sec_rec_is_for_clust_rec(
			    rec, sec_index, clust_rec, clust_index)) {
osku's avatar
osku committed
2986 2987
			clust_rec = NULL;
#ifdef UNIV_SEARCH_DEBUG
2988
		} else {
2989
			ut_a(clust_rec == NULL
2990 2991
			     || row_sel_sec_rec_is_for_clust_rec(
				     rec, sec_index, clust_rec, clust_index));
2992
#endif
osku's avatar
osku committed
2993 2994 2995 2996 2997 2998
		}
	}

func_exit:
	*out_rec = clust_rec;

2999 3000 3001
	if (prebuilt->select_lock_type != LOCK_NONE) {
		/* We may use the cursor in update or in unlock_row():
		store its position */
3002

osku's avatar
osku committed
3003 3004 3005 3006 3007 3008 3009 3010
		btr_pcur_store_position(prebuilt->clust_pcur, mtr);
	}

	err = DB_SUCCESS;
err_exit:
	return(err);
}

3011
/********************************************************************//**
osku's avatar
osku committed
3012 3013
Restores cursor position after it has been stored. We have to take into
account that the record cursor was positioned on may have been deleted.
3014
Then we may have to move the cursor one step up or down.
3015 3016
@return TRUE if we may need to process the record the cursor is now
positioned on (i.e. we should not go to the next record yet) */
osku's avatar
osku committed
3017 3018 3019 3020
static
ibool
sel_restore_position_for_mysql(
/*===========================*/
3021
	ibool*		same_user_rec,	/*!< out: TRUE if we were able to restore
osku's avatar
osku committed
3022 3023 3024
					the cursor on a user record with the
					same ordering prefix in in the
					B-tree index */
3025
	ulint		latch_mode,	/*!< in: latch mode wished in
osku's avatar
osku committed
3026
					restoration */
3027
	btr_pcur_t*	pcur,		/*!< in: cursor whose position
osku's avatar
osku committed
3028
					has been stored */
3029
	ibool		moves_up,	/*!< in: TRUE if the cursor moves up
osku's avatar
osku committed
3030
					in the index */
3031
	mtr_t*		mtr)		/*!< in: mtr; CAUTION: may commit
osku's avatar
osku committed
3032 3033 3034 3035 3036 3037
					mtr temporarily! */
{
	ibool	success;
	ulint	relative_position;

	relative_position = pcur->rel_pos;
3038

osku's avatar
osku committed
3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055
	success = btr_pcur_restore_position(latch_mode, pcur, mtr);

	*same_user_rec = success;

	if (relative_position == BTR_PCUR_ON) {
		if (success) {
			return(FALSE);
		}

		if (moves_up) {
			btr_pcur_move_to_next(pcur, mtr);
		}

		return(TRUE);
	}

	if (relative_position == BTR_PCUR_AFTER
3056
	    || relative_position == BTR_PCUR_AFTER_LAST_IN_TREE) {
osku's avatar
osku committed
3057 3058 3059 3060

		if (moves_up) {
			return(TRUE);
		}
3061

3062
		if (btr_pcur_is_on_user_rec(pcur)) {
osku's avatar
osku committed
3063 3064 3065 3066 3067 3068 3069
			btr_pcur_move_to_prev(pcur, mtr);
		}

		return(TRUE);
	}

	ut_ad(relative_position == BTR_PCUR_BEFORE
3070
	      || relative_position == BTR_PCUR_BEFORE_FIRST_IN_TREE);
3071

3072
	if (moves_up && btr_pcur_is_on_user_rec(pcur)) {
osku's avatar
osku committed
3073 3074 3075 3076 3077 3078
		btr_pcur_move_to_next(pcur, mtr);
	}

	return(TRUE);
}

3079
/********************************************************************//**
osku's avatar
osku committed
3080 3081 3082 3083 3084
Pops a cached row for MySQL from the fetch cache. */
UNIV_INLINE
void
row_sel_pop_cached_row_for_mysql(
/*=============================*/
3085
	byte*		buf,		/*!< in/out: buffer where to copy the
osku's avatar
osku committed
3086
					row */
3087
	row_prebuilt_t*	prebuilt)	/*!< in: prebuilt struct */
osku's avatar
osku committed
3088 3089 3090 3091
{
	ulint			i;
	mysql_row_templ_t*	templ;
	byte*			cached_rec;
3092
	ut_ad(prebuilt->n_fetch_cached > 0);
osku's avatar
osku committed
3093
	ut_ad(prebuilt->mysql_prefix_len <= prebuilt->mysql_row_len);
3094

3095
	if (UNIV_UNLIKELY(prebuilt->keep_other_fields_on_keyread)) {
3096
		/* Copy cache record field by field, don't touch fields that
osku's avatar
osku committed
3097
		are not covered by current key */
3098 3099
		cached_rec = prebuilt->fetch_cache[
			prebuilt->fetch_cache_first];
osku's avatar
osku committed
3100 3101 3102

		for (i = 0; i < prebuilt->n_template; i++) {
			templ = prebuilt->mysql_template + i;
3103 3104 3105
			ut_memcpy(buf + templ->mysql_col_offset,
				  cached_rec + templ->mysql_col_offset,
				  templ->mysql_col_len);
3106
			/* Copy NULL bit of the current field from cached_rec
osku's avatar
osku committed
3107
			to buf */
3108
			if (templ->mysql_null_bit_mask) {
3109 3110
				buf[templ->mysql_null_byte_offset]
					^= (buf[templ->mysql_null_byte_offset]
3111
					    ^ cached_rec[templ->mysql_null_byte_offset])
3112
					& (byte)templ->mysql_null_bit_mask;
osku's avatar
osku committed
3113 3114 3115
			}
		}
	}
3116
	else {
3117 3118 3119
		ut_memcpy(buf,
			  prebuilt->fetch_cache[prebuilt->fetch_cache_first],
			  prebuilt->mysql_prefix_len);
osku's avatar
osku committed
3120 3121 3122 3123 3124 3125 3126 3127 3128
	}
	prebuilt->n_fetch_cached--;
	prebuilt->fetch_cache_first++;

	if (prebuilt->n_fetch_cached == 0) {
		prebuilt->fetch_cache_first = 0;
	}
}

3129
/********************************************************************//**
osku's avatar
osku committed
3130 3131 3132 3133 3134
Pushes a row for MySQL to the fetch cache. */
UNIV_INLINE
void
row_sel_push_cache_row_for_mysql(
/*=============================*/
3135 3136
	row_prebuilt_t*	prebuilt,	/*!< in: prebuilt struct */
	const rec_t*	rec,		/*!< in: record to push; must
3137
					be protected by a page latch */
3138
	const ulint*	offsets)	/*!< in: rec_get_offsets() */
osku's avatar
osku committed
3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154
{
	byte*	buf;
	ulint	i;

	ut_ad(prebuilt->n_fetch_cached < MYSQL_FETCH_CACHE_SIZE);
	ut_ad(rec_offs_validate(rec, NULL, offsets));
	ut_a(!prebuilt->templ_contains_blob);

	if (prebuilt->fetch_cache[0] == NULL) {
		/* Allocate memory for the fetch cache */

		for (i = 0; i < MYSQL_FETCH_CACHE_SIZE; i++) {

			/* A user has reported memory corruption in these
			buffers in Linux. Put magic numbers there to help
			to track a possible bug. */
3155

osku's avatar
osku committed
3156 3157 3158
			buf = mem_alloc(prebuilt->mysql_row_len + 8);

			prebuilt->fetch_cache[i] = buf + 4;
3159

osku's avatar
osku committed
3160 3161 3162 3163 3164 3165 3166 3167
			mach_write_to_4(buf, ROW_PREBUILT_FETCH_MAGIC_N);
			mach_write_to_4(buf + 4 + prebuilt->mysql_row_len,
					ROW_PREBUILT_FETCH_MAGIC_N);
		}
	}

	ut_ad(prebuilt->fetch_cache_first == 0);

3168 3169 3170 3171
	if (UNIV_UNLIKELY(!row_sel_store_mysql_rec(
				  prebuilt->fetch_cache[
					  prebuilt->n_fetch_cached],
				  prebuilt, rec, offsets))) {
osku's avatar
osku committed
3172 3173 3174 3175 3176 3177
		ut_error;
	}

	prebuilt->n_fetch_cached++;
}

3178
/*********************************************************************//**
osku's avatar
osku committed
3179 3180 3181
Tries to do a shortcut to fetch a clustered index record with a unique key,
using the hash index if possible (not always). We assume that the search
mode is PAGE_CUR_GE, it is a consistent read, there is a read view in trx,
3182 3183
btr search latch has been locked in S-mode.
@return	SEL_FOUND, SEL_EXHAUSTED, SEL_RETRY */
osku's avatar
osku committed
3184 3185 3186 3187
static
ulint
row_sel_try_search_shortcut_for_mysql(
/*==================================*/
3188 3189 3190 3191 3192
	const rec_t**	out_rec,/*!< out: record if found */
	row_prebuilt_t*	prebuilt,/*!< in: prebuilt struct */
	ulint**		offsets,/*!< in/out: for rec_get_offsets(*out_rec) */
	mem_heap_t**	heap,	/*!< in/out: heap for rec_get_offsets() */
	mtr_t*		mtr)	/*!< in: started mtr */
osku's avatar
osku committed
3193 3194
{
	dict_index_t*	index		= prebuilt->index;
marko's avatar
marko committed
3195
	const dtuple_t*	search_tuple	= prebuilt->search_tuple;
osku's avatar
osku committed
3196 3197
	btr_pcur_t*	pcur		= prebuilt->pcur;
	trx_t*		trx		= prebuilt->trx;
3198
	const rec_t*	rec;
3199

3200
	ut_ad(dict_index_is_clust(index));
osku's avatar
osku committed
3201
	ut_ad(!prebuilt->templ_contains_blob);
3202

osku's avatar
osku committed
3203
	btr_pcur_open_with_no_init(index, search_tuple, PAGE_CUR_GE,
3204
				   BTR_SEARCH_LEAF, pcur,
osku's avatar
osku committed
3205
#ifndef UNIV_SEARCH_DEBUG
3206
				   RW_S_LATCH,
osku's avatar
osku committed
3207
#else
3208
				   0,
osku's avatar
osku committed
3209
#endif
3210
				   mtr);
osku's avatar
osku committed
3211
	rec = btr_pcur_get_rec(pcur);
3212

osku's avatar
osku committed
3213 3214 3215 3216 3217 3218 3219
	if (!page_rec_is_user_rec(rec)) {

		return(SEL_RETRY);
	}

	/* As the cursor is now placed on a user record after a search with
	the mode PAGE_CUR_GE, the up_match field in the cursor tells how many
3220
	fields in the user record matched to the search tuple */
osku's avatar
osku committed
3221 3222 3223 3224 3225 3226 3227 3228 3229 3230

	if (btr_pcur_get_up_match(pcur) < dtuple_get_n_fields(search_tuple)) {

		return(SEL_EXHAUSTED);
	}

	/* This is a non-locking consistent read: if necessary, fetch
	a previous version of the record */

	*offsets = rec_get_offsets(rec, index, *offsets,
3231
				   ULINT_UNDEFINED, heap);
osku's avatar
osku committed
3232 3233

	if (!lock_clust_rec_cons_read_sees(rec, index,
3234
					   *offsets, trx->read_view)) {
osku's avatar
osku committed
3235 3236 3237 3238

		return(SEL_RETRY);
	}

3239
	if (rec_get_deleted_flag(rec, dict_table_is_comp(index->table))) {
osku's avatar
osku committed
3240 3241 3242 3243 3244

		return(SEL_EXHAUSTED);
	}

	*out_rec = rec;
3245

osku's avatar
osku committed
3246 3247 3248
	return(SEL_FOUND);
}

3249
/********************************************************************//**
osku's avatar
osku committed
3250 3251 3252 3253
Searches for rows in the database. This is used in the interface to
MySQL. This function opens a cursor, and also implements fetch next
and fetch prev. NOTE that if we do a search with a full key value
from a unique index (ROW_SEL_EXACT), then we will not store the cursor
3254
position and fetch next or fetch prev must not be tried to the cursor!
3255 3256
@return DB_SUCCESS, DB_RECORD_NOT_FOUND, DB_END_OF_INDEX, DB_DEADLOCK,
DB_LOCK_TABLE_FULL, DB_CORRUPTION, or DB_TOO_BIG_RECORD */
3257
UNIV_INTERN
osku's avatar
osku committed
3258 3259 3260
ulint
row_search_for_mysql(
/*=================*/
3261
	byte*		buf,		/*!< in/out: buffer for the fetched
osku's avatar
osku committed
3262
					row in the MySQL format */
3263 3264
	ulint		mode,		/*!< in: search mode PAGE_CUR_L, ... */
	row_prebuilt_t*	prebuilt,	/*!< in: prebuilt struct for the
osku's avatar
osku committed
3265 3266 3267 3268 3269 3270
					table handle; this contains the info
					of search_tuple, index; if search
					tuple contains 0 fields then we
					position the cursor at the start or
					the end of the index, depending on
					'mode' */
3271
	ulint		match_mode,	/*!< in: 0 or ROW_SEL_EXACT or
3272
					ROW_SEL_EXACT_PREFIX */
3273
	ulint		direction)	/*!< in: 0 or ROW_SEL_NEXT or
osku's avatar
osku committed
3274 3275 3276 3277 3278 3279
					ROW_SEL_PREV; NOTE: if this is != 0,
					then prebuilt must have a pcur
					with stored position! In opening of a
					cursor 'direction' should be 0. */
{
	dict_index_t*	index		= prebuilt->index;
3280
	ibool		comp		= dict_table_is_comp(index->table);
marko's avatar
marko committed
3281
	const dtuple_t*	search_tuple	= prebuilt->search_tuple;
osku's avatar
osku committed
3282 3283 3284 3285
	btr_pcur_t*	pcur		= prebuilt->pcur;
	trx_t*		trx		= prebuilt->trx;
	dict_index_t*	clust_index;
	que_thr_t*	thr;
3286 3287 3288
	const rec_t*	rec;
	const rec_t*	result_rec;
	const rec_t*	clust_rec;
osku's avatar
osku committed
3289 3290 3291
	ulint		err				= DB_SUCCESS;
	ibool		unique_search			= FALSE;
	ibool		unique_search_from_clust_index	= FALSE;
3292 3293
	ibool		mtr_has_extra_clust_latch	= FALSE;
	ibool		moves_up			= FALSE;
osku's avatar
osku committed
3294
	ibool		set_also_gap_locks		= TRUE;
3295 3296
	/* if the query is a plain locking SELECT, and the isolation level
	is <= TRX_ISO_READ_COMMITTED, then this is set to FALSE */
3297
	ibool		did_semi_consistent_read	= FALSE;
3298 3299 3300
	/* if the returned record was locked and we did a semi-consistent
	read (fetch the newest committed version), then this is set to
	TRUE */
osku's avatar
osku committed
3301 3302 3303 3304 3305 3306 3307 3308 3309 3310
#ifdef UNIV_SEARCH_DEBUG
	ulint		cnt				= 0;
#endif /* UNIV_SEARCH_DEBUG */
	ulint		next_offs;
	ibool		same_user_rec;
	mtr_t		mtr;
	mem_heap_t*	heap				= NULL;
	ulint		offsets_[REC_OFFS_NORMAL_SIZE];
	ulint*		offsets				= offsets_;

3311
	rec_offs_init(offsets_);
osku's avatar
osku committed
3312 3313 3314 3315 3316

	ut_ad(index && pcur && search_tuple);
	ut_ad(trx->mysql_thread_id == os_thread_get_curr_id());

	if (UNIV_UNLIKELY(prebuilt->table->ibd_file_missing)) {
3317 3318
		ut_print_timestamp(stderr);
		fprintf(stderr, "  InnoDB: Error:\n"
3319 3320 3321 3322 3323 3324 3325 3326
			"InnoDB: MySQL is trying to use a table handle"
			" but the .ibd file for\n"
			"InnoDB: table %s does not exist.\n"
			"InnoDB: Have you deleted the .ibd file"
			" from the database directory under\n"
			"InnoDB: the MySQL datadir, or have you used"
			" DISCARD TABLESPACE?\n"
			"InnoDB: Look from\n"
3327
			"InnoDB: " REFMAN "innodb-troubleshooting.html\n"
3328 3329
			"InnoDB: how you can resolve the problem.\n",
			prebuilt->table->name);
osku's avatar
osku committed
3330 3331 3332 3333

		return(DB_ERROR);
	}

3334 3335 3336 3337 3338
	if (UNIV_UNLIKELY(!prebuilt->index_usable)) {

		return(DB_MISSING_HISTORY);
	}

osku's avatar
osku committed
3339 3340
	if (UNIV_UNLIKELY(prebuilt->magic_n != ROW_PREBUILT_ALLOCATED)) {
		fprintf(stderr,
3341 3342 3343
			"InnoDB: Error: trying to free a corrupt\n"
			"InnoDB: table handle. Magic n %lu, table name ",
			(ulong) prebuilt->magic_n);
3344
		ut_print_name(stderr, trx, TRUE, prebuilt->table->name);
osku's avatar
osku committed
3345 3346
		putc('\n', stderr);

3347
		mem_analyze_corruption(prebuilt);
osku's avatar
osku committed
3348 3349 3350 3351

		ut_error;
	}

3352 3353 3354 3355 3356
#if 0
	/* August 19, 2005 by Heikki: temporarily disable this error
	print until the cursor lock count is done correctly.
	See bugs #12263 and #12456!*/

osku's avatar
osku committed
3357
	if (trx->n_mysql_tables_in_use == 0
3358
	    && UNIV_UNLIKELY(prebuilt->select_lock_type == LOCK_NONE)) {
osku's avatar
osku committed
3359 3360 3361 3362 3363
		/* Note that if MySQL uses an InnoDB temp table that it
		created inside LOCK TABLES, then n_mysql_tables_in_use can
		be zero; in that case select_lock_type is set to LOCK_X in
		::start_stmt. */

3364 3365 3366 3367
		fputs("InnoDB: Error: MySQL is trying to perform a SELECT\n"
		      "InnoDB: but it has not locked"
		      " any tables in ::external_lock()!\n",
		      stderr);
osku's avatar
osku committed
3368
		trx_print(stderr, trx, 600);
3369
		fputc('\n', stderr);
osku's avatar
osku committed
3370
	}
3371
#endif
osku's avatar
osku committed
3372

3373 3374 3375
#if 0
	fprintf(stderr, "Match mode %lu\n search tuple ",
		(ulong) match_mode);
osku's avatar
osku committed
3376
	dtuple_print(search_tuple);
3377 3378 3379
	fprintf(stderr, "N tables locked %lu\n",
		(ulong) trx->mysql_n_tables_locked);
#endif
osku's avatar
osku committed
3380 3381 3382 3383
	/*-------------------------------------------------------------*/
	/* PHASE 0: Release a possible s-latch we are holding on the
	adaptive hash index latch if there is someone waiting behind */

3384
	if (UNIV_UNLIKELY(rw_lock_get_writer(&btr_search_latch) != RW_LOCK_NOT_LOCKED)
3385
	    && trx->has_search_latch) {
osku's avatar
osku committed
3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396

		/* There is an x-latch request on the adaptive hash index:
		release the s-latch to reduce starvation and wait for
		BTR_SEA_TIMEOUT rounds before trying to keep it again over
		calls from MySQL */

		rw_lock_s_unlock(&btr_search_latch);
		trx->has_search_latch = FALSE;

		trx->search_latch_timeout = BTR_SEA_TIMEOUT;
	}
3397

3398
	/* Reset the new record lock info if srv_locks_unsafe_for_binlog
3399 3400 3401
	is set or session is using a READ COMMITED isolation level. Then
	we are able to remove the record locks set here on an individual
	row. */
3402
	prebuilt->new_rec_locks = 0;
osku's avatar
osku committed
3403 3404 3405 3406 3407 3408

	/*-------------------------------------------------------------*/
	/* PHASE 1: Try to pop the row from the prefetch cache */

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

osku's avatar
osku committed
3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432
		prebuilt->n_rows_fetched = 0;
		prebuilt->n_fetch_cached = 0;
		prebuilt->fetch_cache_first = 0;

		if (prebuilt->sel_graph == NULL) {
			/* 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! */
			}
3433

osku's avatar
osku committed
3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448
			prebuilt->n_rows_fetched = 0;
			prebuilt->n_fetch_cached = 0;
			prebuilt->fetch_cache_first = 0;

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

			prebuilt->n_rows_fetched++;

			srv_n_rows_read++;
			err = DB_SUCCESS;
			goto func_exit;
		}

		if (prebuilt->fetch_cache_first > 0
3449
		    && prebuilt->fetch_cache_first < MYSQL_FETCH_CACHE_SIZE) {
osku's avatar
osku committed
3450

3451 3452 3453
			/* The previous returned row was popped from the fetch
			cache, but the cache was not full at the time of the
			popping: no more rows can exist in the result set */
osku's avatar
osku committed
3454 3455 3456 3457

			err = DB_RECORD_NOT_FOUND;
			goto func_exit;
		}
3458

osku's avatar
osku committed
3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469
		prebuilt->n_rows_fetched++;

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

		mode = pcur->search_mode;
	}

	/* In a search where at most one record in the index may match, we
3470 3471
	can use a LOCK_REC_NOT_GAP type record lock when locking a
	non-delete-marked matching record.
osku's avatar
osku committed
3472

3473 3474 3475 3476
	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. */
3477

osku's avatar
osku committed
3478
	if (match_mode == ROW_SEL_EXACT
3479
	    && dict_index_is_unique(index)
3480 3481 3482 3483
	    && dtuple_get_n_fields(search_tuple)
	    == dict_index_get_n_unique(index)
	    && (dict_index_is_clust(index)
		|| !dtuple_contains_null(search_tuple))) {
osku's avatar
osku committed
3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497

		/* 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. */

3498 3499
		if (UNIV_UNLIKELY(direction != 0
				  && !prebuilt->used_in_HANDLER)) {
3500

osku's avatar
osku committed
3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517
			err = DB_RECORD_NOT_FOUND;
			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)
3518 3519 3520 3521 3522
	    && unique_search
	    && dict_index_is_clust(index)
	    && !prebuilt->templ_contains_blob
	    && !prebuilt->used_in_HANDLER
	    && (prebuilt->mysql_row_len < UNIV_PAGE_SIZE / 8)) {
osku's avatar
osku committed
3523 3524 3525 3526 3527 3528

		mode = PAGE_CUR_GE;

		unique_search_from_clust_index = TRUE;

		if (trx->mysql_n_tables_locked == 0
3529 3530 3531
		    && prebuilt->select_lock_type == LOCK_NONE
		    && trx->isolation_level > TRX_ISO_READ_UNCOMMITTED
		    && trx->read_view) {
osku's avatar
osku committed
3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544

			/* 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! */

3545
#ifndef UNIV_SEARCH_DEBUG
osku's avatar
osku committed
3546 3547 3548 3549 3550
			if (!trx->has_search_latch) {
				rw_lock_s_lock(&btr_search_latch);
				trx->has_search_latch = TRUE;
			}
#endif
3551 3552 3553
			switch (row_sel_try_search_shortcut_for_mysql(
					&rec, prebuilt, &offsets, &heap,
					&mtr)) {
osku's avatar
osku committed
3554 3555 3556
			case SEL_FOUND:
#ifdef UNIV_SEARCH_DEBUG
				ut_a(0 == cmp_dtuple_rec(search_tuple,
3557
							 rec, offsets));
3558
#endif
3559 3560 3561 3562 3563 3564
				/* 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). */

osku's avatar
osku committed
3565
				if (!row_sel_store_mysql_rec(buf, prebuilt,
3566
							     rec, offsets)) {
3567
					err = DB_TOO_BIG_RECORD;
osku's avatar
osku committed
3568 3569 3570

					/* We let the main loop to do the
					error handling */
3571
					goto shortcut_fails_too_big_rec;
osku's avatar
osku committed
3572
				}
3573 3574

				mtr_commit(&mtr);
osku's avatar
osku committed
3575 3576 3577 3578 3579

				/* ut_print_name(stderr, index->name);
				fputs(" shortcut\n", stderr); */

				srv_n_rows_read++;
3580

osku's avatar
osku committed
3581
				err = DB_SUCCESS;
3582
				goto release_search_latch_if_needed;
osku's avatar
osku committed
3583 3584

			case SEL_EXHAUSTED:
3585
				mtr_commit(&mtr);
osku's avatar
osku committed
3586 3587 3588 3589

				/* ut_print_name(stderr, index->name);
				fputs(" record not found 2\n", stderr); */

3590 3591
				err = DB_RECORD_NOT_FOUND;
release_search_latch_if_needed:
osku's avatar
osku committed
3592
				if (trx->search_latch_timeout > 0
3593
				    && trx->has_search_latch) {
osku's avatar
osku committed
3594 3595 3596

					trx->search_latch_timeout--;

3597
					rw_lock_s_unlock(&btr_search_latch);
osku's avatar
osku committed
3598 3599 3600 3601 3602 3603
					trx->has_search_latch = FALSE;
				}

				/* NOTE that we do NOT store the cursor
				position */
				goto func_exit;
3604 3605 3606 3607 3608 3609

			case SEL_RETRY:
				break;

			default:
				ut_ad(0);
osku's avatar
osku committed
3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622
			}
shortcut_fails_too_big_rec:
			mtr_commit(&mtr);
			mtr_start(&mtr);
		}
	}

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

	if (trx->has_search_latch) {
		rw_lock_s_unlock(&btr_search_latch);
		trx->has_search_latch = FALSE;
3623
	}
osku's avatar
osku committed
3624 3625 3626 3627

	trx_start_if_not_started(trx);

	if (trx->isolation_level <= TRX_ISO_READ_COMMITTED
3628
	    && prebuilt->select_lock_type != LOCK_NONE
3629
	    && trx->mysql_thd != NULL
3630 3631 3632
	    && thd_is_select(trx->mysql_thd)) {
		/* It is a plain locking SELECT and the isolation
		level is low: do not lock gaps */
osku's avatar
osku committed
3633

3634
		set_also_gap_locks = FALSE;
osku's avatar
osku committed
3635
	}
3636

osku's avatar
osku committed
3637 3638 3639
	/* Note that if the search mode was GE or G, then the cursor
	naturally moves upward (in fetch next) in alphabetical order,
	otherwise downward */
3640

osku's avatar
osku committed
3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655
	if (UNIV_UNLIKELY(direction == 0)) {
		if (mode == PAGE_CUR_GE || mode == PAGE_CUR_G) {
			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 = dict_table_get_first_index(index->table);

	if (UNIV_LIKELY(direction != 0)) {
3656 3657 3658
		ibool	need_to_process = sel_restore_position_for_mysql(
			&same_user_rec, BTR_SEARCH_LEAF,
			pcur, moves_up, &mtr);
3659 3660 3661

		if (UNIV_UNLIKELY(need_to_process)) {
			if (UNIV_UNLIKELY(prebuilt->row_read_type
3662
					  == ROW_READ_DID_SEMI_CONSISTENT)) {
3663 3664 3665 3666 3667 3668 3669
				/* 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
3670
				       != ROW_READ_DID_SEMI_CONSISTENT)) {
3671 3672 3673 3674 3675 3676 3677

			/* 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. */

osku's avatar
osku committed
3678 3679 3680 3681 3682 3683
			goto next_rec;
		}

	} else if (dtuple_get_n_fields(search_tuple) > 0) {

		btr_pcur_open_with_no_init(index, search_tuple, mode,
3684 3685
					   BTR_SEARCH_LEAF,
					   pcur, 0, &mtr);
osku's avatar
osku committed
3686 3687

		pcur->trx_if_known = trx;
3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699

		rec = btr_pcur_get_rec(pcur);

		if (!moves_up
		    && !page_rec_is_supremum(rec)
		    && set_also_gap_locks
		    && !(srv_locks_unsafe_for_binlog
			 || trx->isolation_level == TRX_ISO_READ_COMMITTED)
		    && prebuilt->select_lock_type != LOCK_NONE) {

			/* Try to place a gap lock on the next index record
			to prevent phantoms in ORDER BY ... DESC queries */
3700
			const rec_t*	next = page_rec_get_next_const(rec);
3701

3702
			offsets = rec_get_offsets(next, index, offsets,
3703 3704
						  ULINT_UNDEFINED, &heap);
			err = sel_set_rec_lock(btr_pcur_get_block(pcur),
3705
					       next, index, offsets,
3706 3707 3708 3709 3710 3711 3712 3713
					       prebuilt->select_lock_type,
					       LOCK_GAP, thr);

			if (err != DB_SUCCESS) {

				goto lock_wait_or_error;
			}
		}
osku's avatar
osku committed
3714 3715
	} else {
		if (mode == PAGE_CUR_G) {
3716 3717 3718
			btr_pcur_open_at_index_side(
				TRUE, index, BTR_SEARCH_LEAF, pcur, FALSE,
				&mtr);
osku's avatar
osku committed
3719
		} else if (mode == PAGE_CUR_L) {
3720 3721 3722
			btr_pcur_open_at_index_side(
				FALSE, index, BTR_SEARCH_LEAF, pcur, FALSE,
				&mtr);
osku's avatar
osku committed
3723 3724 3725 3726 3727 3728 3729
		}
	}

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

		if (trx->read_view == NULL
3730
		    && prebuilt->select_lock_type == LOCK_NONE) {
osku's avatar
osku committed
3731

3732 3733 3734 3735
			fputs("InnoDB: Error: MySQL is trying to"
			      " perform a consistent read\n"
			      "InnoDB: but the read view is not assigned!\n",
			      stderr);
osku's avatar
osku committed
3736
			trx_print(stderr, trx, 600);
3737
			fputc('\n', stderr);
osku's avatar
osku committed
3738 3739 3740
			ut_a(0);
		}
	} else if (prebuilt->select_lock_type == LOCK_NONE) {
3741
		/* This is a consistent read */
osku's avatar
osku committed
3742 3743 3744 3745 3746 3747
		/* Assign a read view for the query */

		trx_assign_read_view(trx);
		prebuilt->sql_stat_start = FALSE;
	} else {
		ulint	lock_mode;
3748
		if (prebuilt->select_lock_type == LOCK_S) {
osku's avatar
osku committed
3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764
			lock_mode = LOCK_IS;
		} else {
			lock_mode = LOCK_IX;
		}
		err = lock_table(0, index->table, lock_mode, thr);

		if (err != DB_SUCCESS) {

			goto lock_wait_or_error;
		}
		prebuilt->sql_stat_start = FALSE;
	}

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

osku's avatar
osku committed
3766 3767 3768
	rec = btr_pcur_get_rec(pcur);
	ut_ad(!!page_rec_is_comp(rec) == comp);
#ifdef UNIV_SEARCH_DEBUG
3769
	/*
osku's avatar
osku committed
3770 3771 3772
	fputs("Using ", stderr);
	dict_index_name_print(stderr, index);
	fprintf(stderr, " cnt %lu ; Page no %lu\n", cnt,
3773
	page_get_page_no(page_align(rec)));
osku's avatar
osku committed
3774
	rec_print(rec);
3775
	*/
osku's avatar
osku committed
3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789
#endif /* UNIV_SEARCH_DEBUG */

	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. */

		goto next_rec;
	}

	if (page_rec_is_supremum(rec)) {

		if (set_also_gap_locks
3790 3791 3792
		    && !(srv_locks_unsafe_for_binlog
			 || trx->isolation_level == TRX_ISO_READ_COMMITTED)
		    && prebuilt->select_lock_type != LOCK_NONE) {
osku's avatar
osku committed
3793 3794 3795

			/* Try to place a lock on the index record */

3796 3797 3798
			/* If innodb_locks_unsafe_for_binlog option is used
			or this session is using a READ COMMITTED isolation
			level we do not lock gaps. Supremum record is really
osku's avatar
osku committed
3799
			a gap and therefore we do not set locks there. */
3800

osku's avatar
osku committed
3801
			offsets = rec_get_offsets(rec, index, offsets,
3802
						  ULINT_UNDEFINED, &heap);
3803 3804
			err = sel_set_rec_lock(btr_pcur_get_block(pcur),
					       rec, index, offsets,
3805 3806
					       prebuilt->select_lock_type,
					       LOCK_ORDINARY, thr);
osku's avatar
osku committed
3807 3808 3809 3810 3811 3812 3813 3814

			if (err != DB_SUCCESS) {

				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 */
3815

osku's avatar
osku committed
3816 3817 3818 3819 3820 3821
		goto next_rec;
	}

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

osku's avatar
osku committed
3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841
	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) {
			ut_print_timestamp(stderr);
3842
			buf_page_print(page_align(rec), 0);
osku's avatar
osku committed
3843
			fprintf(stderr,
3844
				"\nInnoDB: rec address %p,"
3845
				" buf block fix count %lu\n",
3846
				(void*) rec, (ulong)
3847
				btr_cur_get_block(btr_pcur_get_btr_cur(pcur))
3848
				->page.buf_fix_count);
osku's avatar
osku committed
3849
			fprintf(stderr,
3850 3851 3852
				"InnoDB: Index corruption: rec offs %lu"
				" next offs %lu, page no %lu,\n"
				"InnoDB: ",
3853
				(ulong) page_offset(rec),
osku's avatar
osku committed
3854
				(ulong) next_offs,
3855
				(ulong) page_get_page_no(page_align(rec)));
osku's avatar
osku committed
3856 3857
			dict_index_name_print(stderr, trx, index);
			fputs(". Run CHECK TABLE. You may need to\n"
3858 3859 3860
			      "InnoDB: restore from a backup, or"
			      " dump + drop + reimport the table.\n",
			      stderr);
3861

osku's avatar
osku committed
3862 3863 3864 3865 3866 3867 3868 3869
			err = DB_CORRUPTION;

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

			fprintf(stderr,
3870 3871 3872
				"InnoDB: Index corruption: rec offs %lu"
				" next offs %lu, page no %lu,\n"
				"InnoDB: ",
3873
				(ulong) page_offset(rec),
3874
				(ulong) next_offs,
3875
				(ulong) page_get_page_no(page_align(rec)));
osku's avatar
osku committed
3876 3877
			dict_index_name_print(stderr, trx, index);
			fputs(". We try to skip the rest of the page.\n",
3878
			      stderr);
osku's avatar
osku committed
3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892

			btr_pcur_move_to_last_on_page(pcur, &mtr);

			goto next_rec;
		}
	}
	/*-------------------------------------------------------------*/

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

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

	if (UNIV_UNLIKELY(srv_force_recovery > 0)) {
		if (!rec_validate(rec, offsets)
3893
		    || !btr_index_rec_validate(rec, index, FALSE)) {
osku's avatar
osku committed
3894
			fprintf(stderr,
3895 3896 3897
				"InnoDB: Index corruption: rec offs %lu"
				" next offs %lu, page no %lu,\n"
				"InnoDB: ",
3898
				(ulong) page_offset(rec),
3899
				(ulong) next_offs,
3900
				(ulong) page_get_page_no(page_align(rec)));
osku's avatar
osku committed
3901 3902
			dict_index_name_print(stderr, trx, index);
			fputs(". We try to skip the record.\n",
3903
			      stderr);
osku's avatar
osku committed
3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918

			goto next_rec;
		}
	}

	/* 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); */
3919

osku's avatar
osku committed
3920 3921 3922
		if (0 != cmp_dtuple_rec(search_tuple, rec, offsets)) {

			if (set_also_gap_locks
3923 3924 3925 3926
			    && !(srv_locks_unsafe_for_binlog
				 || trx->isolation_level
				 == TRX_ISO_READ_COMMITTED)
			    && prebuilt->select_lock_type != LOCK_NONE) {
osku's avatar
osku committed
3927

3928
				/* Try to place a gap lock on the index
osku's avatar
osku committed
3929
				record only if innodb_locks_unsafe_for_binlog
3930 3931
				option is not set or this session is not
				using a READ COMMITTED isolation level. */
osku's avatar
osku committed
3932

3933
				err = sel_set_rec_lock(
3934
					btr_pcur_get_block(pcur),
3935 3936 3937
					rec, index, offsets,
					prebuilt->select_lock_type, LOCK_GAP,
					thr);
osku's avatar
osku committed
3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949

				if (err != DB_SUCCESS) {

					goto lock_wait_or_error;
				}
			}

			btr_pcur_store_position(pcur, &mtr);

			err = DB_RECORD_NOT_FOUND;
			/* ut_print_name(stderr, index->name);
			fputs(" record not found 3\n", stderr); */
3950

osku's avatar
osku committed
3951 3952 3953 3954 3955 3956
			goto normal_return;
		}

	} else if (match_mode == ROW_SEL_EXACT_PREFIX) {

		if (!cmp_dtuple_is_prefix_of_rec(search_tuple, rec, offsets)) {
3957

osku's avatar
osku committed
3958
			if (set_also_gap_locks
3959 3960 3961 3962
			    && !(srv_locks_unsafe_for_binlog
				 || trx->isolation_level
				 == TRX_ISO_READ_COMMITTED)
			    && prebuilt->select_lock_type != LOCK_NONE) {
osku's avatar
osku committed
3963

3964
				/* Try to place a gap lock on the index
osku's avatar
osku committed
3965
				record only if innodb_locks_unsafe_for_binlog
3966 3967
				option is not set or this session is not
				using a READ COMMITTED isolation level. */
osku's avatar
osku committed
3968

3969
				err = sel_set_rec_lock(
3970
					btr_pcur_get_block(pcur),
3971 3972 3973
					rec, index, offsets,
					prebuilt->select_lock_type, LOCK_GAP,
					thr);
osku's avatar
osku committed
3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999

				if (err != DB_SUCCESS) {

					goto lock_wait_or_error;
				}
			}

			btr_pcur_store_position(pcur, &mtr);

			err = DB_RECORD_NOT_FOUND;
			/* ut_print_name(stderr, index->name);
			fputs(" record not found 4\n", stderr); */

			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) {
		/* Try to place a lock on the index record; note that delete
		marked records are a special case in a unique search. If there
		is a non-delete marked record, then it is enough to lock its
		existence with LOCK_REC_NOT_GAP. */

4000 4001 4002
		/* If innodb_locks_unsafe_for_binlog option is used
		or this session is using a READ COMMITED isolation
		level we lock only the record, i.e., next-key locking is
osku's avatar
osku committed
4003 4004 4005 4006 4007
		not used. */

		ulint	lock_type;

		if (!set_also_gap_locks
4008 4009 4010
		    || srv_locks_unsafe_for_binlog
		    || trx->isolation_level == TRX_ISO_READ_COMMITTED
		    || (unique_search
4011
			&& !UNIV_UNLIKELY(rec_get_deleted_flag(rec, comp)))) {
osku's avatar
osku committed
4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029

			goto no_gap_lock;
		} else {
			lock_type = LOCK_ORDINARY;
		}

		/* If we are doing a 'greater or equal than a primary key
		value' search from a clustered index, and we find a record
		that has that exact primary key value, then there is no need
		to lock the gap before the record, because no insert in the
		gap can be in our search range. That is, no phantom row can
		appear that way.

		An example: if col1 is the primary key, the search is WHERE
		col1 >= 100, and we find a record where col1 = 100, then no
		need to lock the gap before that record. */

		if (index == clust_index
4030 4031 4032 4033 4034
		    && mode == PAGE_CUR_GE
		    && direction == 0
		    && dtuple_get_n_fields_cmp(search_tuple)
		    == dict_index_get_n_unique(index)
		    && 0 == cmp_dtuple_rec(search_tuple, rec, offsets)) {
osku's avatar
osku committed
4035 4036 4037 4038
no_gap_lock:
			lock_type = LOCK_REC_NOT_GAP;
		}

4039 4040
		err = sel_set_rec_lock(btr_pcur_get_block(pcur),
				       rec, index, offsets,
4041 4042
				       prebuilt->select_lock_type,
				       lock_type, thr);
osku's avatar
osku committed
4043

4044
		switch (err) {
4045
			const rec_t*	old_vers;
4046
		case DB_SUCCESS:
4047 4048 4049 4050 4051 4052
			if (srv_locks_unsafe_for_binlog
			    || trx->isolation_level == TRX_ISO_READ_COMMITTED) {
				/* Note that a record of
				prebuilt->index was locked. */
				prebuilt->new_rec_locks = 1;
			}
4053 4054 4055
			break;
		case DB_LOCK_WAIT:
			if (UNIV_LIKELY(prebuilt->row_read_type
4056
					!= ROW_READ_TRY_SEMI_CONSISTENT)
4057
			    || index != clust_index) {
4058 4059 4060 4061 4062 4063

				goto lock_wait_or_error;
			}

			/* The following call returns 'offsets'
			associated with 'old_vers' */
4064 4065 4066
			err = row_sel_build_committed_vers_for_mysql(
				clust_index, prebuilt, rec,
				&offsets, &heap, &old_vers, &mtr);
4067 4068 4069 4070 4071 4072 4073 4074 4075

			if (err != DB_SUCCESS) {

				goto lock_wait_or_error;
			}

			mutex_enter(&kernel_mutex);
			if (trx->was_chosen_as_deadlock_victim) {
				mutex_exit(&kernel_mutex);
4076
				err = DB_DEADLOCK;
4077 4078 4079 4080

				goto lock_wait_or_error;
			}
			if (UNIV_LIKELY(trx->wait_lock != NULL)) {
4081 4082
				lock_cancel_waiting_and_release(
					trx->wait_lock);
4083
				prebuilt->new_rec_locks = 0;
4084 4085 4086 4087 4088 4089 4090 4091
			} else {
				mutex_exit(&kernel_mutex);

				/* The lock was granted while we were
				searching for the last committed version.
				Do a normal locking read. */

				offsets = rec_get_offsets(rec, index, offsets,
4092 4093
							  ULINT_UNDEFINED,
							  &heap);
4094
				err = DB_SUCCESS;
4095 4096 4097
				/* Note that a record of
				prebuilt->index was locked. */
				prebuilt->new_rec_locks = 1;
4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111
				break;
			}
			mutex_exit(&kernel_mutex);

			if (old_vers == NULL) {
				/* The row was not yet committed */

				goto next_rec;
			}

			did_semi_consistent_read = TRUE;
			rec = old_vers;
			break;
		default:
osku's avatar
osku committed
4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122

			goto lock_wait_or_error;
		}
	} 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 */
4123

osku's avatar
osku committed
4124
		} else if (index == clust_index) {
4125

osku's avatar
osku committed
4126 4127 4128 4129 4130 4131
			/* 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 (UNIV_LIKELY(srv_force_recovery < 5)
4132 4133
			    && !lock_clust_rec_cons_read_sees(
				    rec, index, offsets, trx->read_view)) {
osku's avatar
osku committed
4134

4135
				rec_t*	old_vers;
osku's avatar
osku committed
4136 4137
				/* The following call returns 'offsets'
				associated with 'old_vers' */
4138 4139 4140 4141
				err = row_sel_build_prev_vers_for_mysql(
					trx->read_view, clust_index,
					prebuilt, rec, &offsets, &heap,
					&old_vers, &mtr);
4142

osku's avatar
osku committed
4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156
				if (err != DB_SUCCESS) {

					goto lock_wait_or_error;
				}

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

					goto next_rec;
				}

				rec = old_vers;
			}
4157
		} else if (!lock_sec_rec_cons_read_sees(rec, trx->read_view)) {
osku's avatar
osku committed
4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178
			/* 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 != clust_index);

			goto requires_clust_rec;
		}
	}

	/* 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 (UNIV_UNLIKELY(rec_get_deleted_flag(rec, comp))) {

		/* The record is delete-marked: we can skip it */

4179
		if ((srv_locks_unsafe_for_binlog
4180 4181 4182
		     || trx->isolation_level == TRX_ISO_READ_COMMITTED)
		    && prebuilt->select_lock_type != LOCK_NONE
		    && !did_semi_consistent_read) {
osku's avatar
osku committed
4183 4184 4185 4186 4187 4188

			/* No need to keep a lock on a delete-marked record
			if we do not want to use next-key locking. */

			row_unlock_for_mysql(prebuilt, TRUE);
		}
4189

4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206
		/* 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. 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) {
			err = DB_RECORD_NOT_FOUND;

			goto normal_return;
		}

osku's avatar
osku committed
4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229
		goto next_rec;
	}

	/* 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:
		/* 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;

		/* The following call returns 'offsets' associated with
		'clust_rec'. Note that 'clust_rec' can be an old version
		built for a consistent read. */
4230

osku's avatar
osku committed
4231
		err = row_sel_get_clust_rec_for_mysql(prebuilt, index, rec,
4232 4233
						      thr, &clust_rec,
						      &offsets, &heap, &mtr);
osku's avatar
osku committed
4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245
		if (err != DB_SUCCESS) {

			goto lock_wait_or_error;
		}

		if (clust_rec == NULL) {
			/* The record did not exist in the read view */
			ut_ad(prebuilt->select_lock_type == LOCK_NONE);

			goto next_rec;
		}

4246 4247 4248 4249 4250 4251 4252 4253 4254
		if ((srv_locks_unsafe_for_binlog
		     || trx->isolation_level == TRX_ISO_READ_COMMITTED)
		    && prebuilt->select_lock_type != LOCK_NONE) {
			/* Note that both the secondary index record
			and the clustered index record were locked. */
			ut_ad(prebuilt->new_rec_locks == 1);
			prebuilt->new_rec_locks = 2;
		}

osku's avatar
osku committed
4255 4256 4257 4258
		if (UNIV_UNLIKELY(rec_get_deleted_flag(clust_rec, comp))) {

			/* The record is delete marked: we can skip it */

4259
			if ((srv_locks_unsafe_for_binlog
4260 4261
			     || trx->isolation_level == TRX_ISO_READ_COMMITTED)
			    && prebuilt->select_lock_type != LOCK_NONE) {
osku's avatar
osku committed
4262 4263 4264 4265 4266 4267 4268 4269 4270 4271

				/* No need to keep a lock on a delete-marked
				record if we do not want to use next-key
				locking. */

				row_unlock_for_mysql(prebuilt, TRUE);
			}

			goto next_rec;
		}
4272

osku's avatar
osku committed
4273 4274
		if (prebuilt->need_to_access_clustered) {

4275
			result_rec = clust_rec;
osku's avatar
osku committed
4276 4277

			ut_ad(rec_offs_validate(result_rec, clust_index,
4278
						offsets));
osku's avatar
osku committed
4279 4280 4281 4282
		} else {
			/* We used 'offsets' for the clust rec, recalculate
			them for 'rec' */
			offsets = rec_get_offsets(rec, index, offsets,
4283
						  ULINT_UNDEFINED, &heap);
osku's avatar
osku committed
4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296
			result_rec = rec;
		}
	} 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));

4297 4298 4299 4300
	/* 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). */

osku's avatar
osku committed
4301
	if ((match_mode == ROW_SEL_EXACT
4302 4303 4304 4305 4306 4307 4308
	     || prebuilt->n_rows_fetched >= MYSQL_FETCH_CACHE_THRESHOLD)
	    && prebuilt->select_lock_type == LOCK_NONE
	    && !prebuilt->templ_contains_blob
	    && !prebuilt->clust_index_was_generated
	    && !prebuilt->used_in_HANDLER
	    && prebuilt->template_type
	    != ROW_MYSQL_DUMMY_TEMPLATE) {
osku's avatar
osku committed
4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319

		/* 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 we do
		not cache rows because there the cursor is a scrollable
		cursor. */

		row_sel_push_cache_row_for_mysql(prebuilt, result_rec,
4320
						 offsets);
osku's avatar
osku committed
4321
		if (prebuilt->n_fetch_cached == MYSQL_FETCH_CACHE_SIZE) {
4322

osku's avatar
osku committed
4323 4324 4325 4326 4327 4328 4329
			goto got_row;
		}

		goto next_rec;
	} else {
		if (prebuilt->template_type == ROW_MYSQL_DUMMY_TEMPLATE) {
			memcpy(buf + 4, result_rec
4330 4331
			       - rec_offs_extra_size(offsets),
			       rec_offs_size(offsets));
osku's avatar
osku committed
4332 4333 4334 4335
			mach_write_to_4(buf,
					rec_offs_extra_size(offsets) + 4);
		} else {
			if (!row_sel_store_mysql_rec(buf, prebuilt,
4336
						     result_rec, offsets)) {
osku's avatar
osku committed
4337 4338 4339 4340 4341 4342 4343 4344
				err = DB_TOO_BIG_RECORD;

				goto lock_wait_or_error;
			}
		}

		if (prebuilt->clust_index_was_generated) {
			if (result_rec != rec) {
4345 4346 4347
				offsets = rec_get_offsets(
					rec, index, offsets, ULINT_UNDEFINED,
					&heap);
osku's avatar
osku committed
4348 4349
			}
			row_sel_store_row_id_to_prebuilt(prebuilt, rec,
4350
							 index, offsets);
osku's avatar
osku committed
4351 4352 4353 4354 4355 4356 4357 4358 4359
		}
	}

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

got_row:
	/* 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
4360 4361
	return 'end of file'. Exceptions are locking reads and the MySQL
	HANDLER command where the user can move the cursor with PREV or NEXT
4362
	even after a unique search. */
osku's avatar
osku committed
4363 4364

	if (!unique_search_from_clust_index
4365 4366
	    || prebuilt->select_lock_type != LOCK_NONE
	    || prebuilt->used_in_HANDLER) {
osku's avatar
osku committed
4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377

		/* Inside an update always store the cursor position */

		btr_pcur_store_position(pcur, &mtr);
	}

	err = DB_SUCCESS;

	goto normal_return;

next_rec:
4378 4379
	/* Reset the old and new "did semi-consistent read" flags. */
	if (UNIV_UNLIKELY(prebuilt->row_read_type
4380
			  == ROW_READ_DID_SEMI_CONSISTENT)) {
4381 4382 4383
		prebuilt->row_read_type = ROW_READ_TRY_SEMI_CONSISTENT;
	}
	did_semi_consistent_read = FALSE;
4384
	prebuilt->new_rec_locks = 0;
4385

osku's avatar
osku committed
4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398
	/*-------------------------------------------------------------*/
	/* PHASE 5: Move the cursor to the next index record */

	if (UNIV_UNLIKELY(mtr_has_extra_clust_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. */

		btr_pcur_store_position(pcur, &mtr);

		mtr_commit(&mtr);
		mtr_has_extra_clust_latch = FALSE;
4399

osku's avatar
osku committed
4400 4401
		mtr_start(&mtr);
		if (sel_restore_position_for_mysql(&same_user_rec,
4402 4403
						   BTR_SEARCH_LEAF,
						   pcur, moves_up, &mtr)) {
osku's avatar
osku committed
4404 4405 4406 4407 4408 4409 4410 4411
#ifdef UNIV_SEARCH_DEBUG
			cnt++;
#endif /* UNIV_SEARCH_DEBUG */

			goto rec_loop;
		}
	}

4412
	if (moves_up) {
osku's avatar
osku committed
4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437
		if (UNIV_UNLIKELY(!btr_pcur_move_to_next(pcur, &mtr))) {
not_moved:
			btr_pcur_store_position(pcur, &mtr);

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

			goto normal_return;
		}
	} else {
		if (UNIV_UNLIKELY(!btr_pcur_move_to_prev(pcur, &mtr))) {
			goto not_moved;
		}
	}

#ifdef UNIV_SEARCH_DEBUG
	cnt++;
#endif /* UNIV_SEARCH_DEBUG */

	goto rec_loop;

lock_wait_or_error:
4438 4439
	/* Reset the old and new "did semi-consistent read" flags. */
	if (UNIV_UNLIKELY(prebuilt->row_read_type
4440
			  == ROW_READ_DID_SEMI_CONSISTENT)) {
4441 4442 4443 4444
		prebuilt->row_read_type = ROW_READ_TRY_SEMI_CONSISTENT;
	}
	did_semi_consistent_read = FALSE;

osku's avatar
osku committed
4445 4446 4447 4448 4449 4450
	/*-------------------------------------------------------------*/

	btr_pcur_store_position(pcur, &mtr);

	mtr_commit(&mtr);
	mtr_has_extra_clust_latch = FALSE;
4451

osku's avatar
osku committed
4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466
	trx->error_state = err;

	/* The following is a patch for MySQL */

	que_thr_stop_for_mysql(thr);

	thr->lock_state = QUE_THR_LOCK_ROW;

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

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

		sel_restore_position_for_mysql(&same_user_rec,
4467 4468
					       BTR_SEARCH_LEAF, pcur,
					       moves_up, &mtr);
4469 4470

		if ((srv_locks_unsafe_for_binlog
4471 4472
		     || trx->isolation_level == TRX_ISO_READ_COMMITTED)
		    && !same_user_rec) {
4473

osku's avatar
osku committed
4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489
			/* Since we were not able to restore the cursor
			on the same user record, we cannot use
			row_unlock_for_mysql() to unlock any records, and
			we must thus reset the new rec lock info. Since
			in lock0lock.c 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. */

4490
			prebuilt->new_rec_locks = 0;
osku's avatar
osku committed
4491
		}
4492

osku's avatar
osku committed
4493 4494 4495 4496 4497 4498 4499 4500
		mode = pcur->search_mode;

		goto rec_loop;
	}

	thr->lock_state = QUE_THR_LOCK_NOLOCK;

#ifdef UNIV_SEARCH_DEBUG
4501
	/*	fputs("Using ", stderr);
osku's avatar
osku committed
4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519
	dict_index_name_print(stderr, index);
	fprintf(stderr, " cnt %lu ret value %lu err\n", cnt, err); */
#endif /* UNIV_SEARCH_DEBUG */
	goto func_exit;

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

	mtr_commit(&mtr);

	if (prebuilt->n_fetch_cached > 0) {
		row_sel_pop_cached_row_for_mysql(buf, prebuilt);

		err = DB_SUCCESS;
	}

#ifdef UNIV_SEARCH_DEBUG
4520
	/*	fputs("Using ", stderr);
osku's avatar
osku committed
4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532
	dict_index_name_print(stderr, index);
	fprintf(stderr, " cnt %lu ret value %lu err\n", cnt, err); */
#endif /* UNIV_SEARCH_DEBUG */
	if (err == DB_SUCCESS) {
		srv_n_rows_read++;
	}

func_exit:
	trx->op_info = "";
	if (UNIV_LIKELY_NULL(heap)) {
		mem_heap_free(heap);
	}
4533 4534 4535 4536 4537

	/* 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
4538
	      || !did_semi_consistent_read);
4539 4540 4541 4542 4543 4544 4545 4546

	if (UNIV_UNLIKELY(prebuilt->row_read_type != ROW_READ_WITH_LOCKS)) {
		if (UNIV_UNLIKELY(did_semi_consistent_read)) {
			prebuilt->row_read_type = ROW_READ_DID_SEMI_CONSISTENT;
		} else {
			prebuilt->row_read_type = ROW_READ_TRY_SEMI_CONSISTENT;
		}
	}
osku's avatar
osku committed
4547 4548 4549
	return(err);
}

4550
/*******************************************************************//**
osku's avatar
osku committed
4551
Checks if MySQL at the moment is allowed for this table to retrieve a
4552 4553
consistent read result, or store it to the query cache.
@return	TRUE if storing or retrieving from the query cache is permitted */
4554
UNIV_INTERN
osku's avatar
osku committed
4555 4556 4557
ibool
row_search_check_if_query_cache_permitted(
/*======================================*/
4558 4559
	trx_t*		trx,		/*!< in: transaction object */
	const char*	norm_name)	/*!< in: concatenation of database name,
osku's avatar
osku committed
4560 4561 4562
					'/' char, table name */
{
	dict_table_t*	table;
4563
	ibool		ret	= FALSE;
osku's avatar
osku committed
4564

4565
	table = dict_table_get(norm_name, FALSE);
osku's avatar
osku committed
4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583

	if (table == NULL) {

		return(FALSE);
	}

	mutex_enter(&kernel_mutex);

	/* Start the transaction if it is not started yet */

	trx_start_if_not_started_low(trx);

	/* If there are locks on the table or some trx has invalidated the
	cache up to our trx id, then ret = FALSE.
	We do not check what type locks there are on the table, though only
	IX type locks actually would require ret = FALSE. */

	if (UT_LIST_GET_LEN(table->locks) == 0
4584 4585
	    && ut_dulint_cmp(trx->id,
			     table->query_cache_inv_trx_id) >= 0) {
osku's avatar
osku committed
4586 4587

		ret = TRUE;
4588

osku's avatar
osku committed
4589 4590 4591 4592
		/* If the isolation level is high, assign a read view for the
		transaction if it does not yet have one */

		if (trx->isolation_level >= TRX_ISO_REPEATABLE_READ
4593
		    && !trx->read_view) {
osku's avatar
osku committed
4594

4595 4596
			trx->read_view = read_view_open_now(
				trx->id, trx->global_read_view_heap);
osku's avatar
osku committed
4597 4598 4599
			trx->global_read_view = trx->read_view;
		}
	}
4600

osku's avatar
osku committed
4601 4602 4603 4604
	mutex_exit(&kernel_mutex);

	return(ret);
}
4605

4606
/*******************************************************************//**
4607
Read the AUTOINC column from the current row. If the value is less than
4608 4609
0 and the type is not unsigned then we reset the value to 0.
@return	value read from the column */
4610
static
4611
ib_uint64_t
4612 4613
row_search_autoinc_read_column(
/*===========================*/
4614 4615 4616
	dict_index_t*	index,		/*!< in: index to read from */
	const rec_t*	rec,		/*!< in: current rec */
	ulint		col_no,		/*!< in: column number */
4617
	ulint		mtype,		/*!< in: column main type */
4618
	ibool		unsigned_type)	/*!< in: signed or unsigned flag */
4619 4620 4621
{
	ulint		len;
	const byte*	data;
4622
	ib_uint64_t	value;
4623 4624 4625 4626
	mem_heap_t*	heap = NULL;
	ulint		offsets_[REC_OFFS_NORMAL_SIZE];
	ulint*		offsets	= offsets_;

4627
	rec_offs_init(offsets_);
4628

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

4631
	data = rec_get_nth_field(rec, offsets, col_no, &len);
4632 4633 4634

	ut_a(len != UNIV_SQL_NULL);

4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653
	switch (mtype) {
	case DATA_INT:
		ut_a(len <= sizeof value);
		value = mach_read_int_type(data, len, unsigned_type);
		break;

	case DATA_FLOAT:
		ut_a(len == sizeof(float));
		value = mach_float_read(data);
		break;

	case DATA_DOUBLE:
		ut_a(len == sizeof(double));
		value = mach_double_read(data);
		break;

	default:
		ut_error;
	}
4654 4655 4656 4657 4658

	if (UNIV_LIKELY_NULL(heap)) {
		mem_heap_free(heap);
	}

4659
	if (!unsigned_type && (ib_int64_t) value < 0) {
4660 4661
		value = 0;
	}
4662 4663 4664 4665

	return(value);
}

4666
/*******************************************************************//**
4667 4668
Get the last row.
@return	current rec or NULL */
4669 4670 4671 4672
static
const rec_t*
row_search_autoinc_get_rec(
/*=======================*/
4673 4674
	btr_pcur_t*	pcur,		/*!< in: the current cursor */
	mtr_t*		mtr)		/*!< in: mini transaction */
4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686
{
	do {
		const rec_t* rec = btr_pcur_get_rec(pcur);

		if (page_rec_is_user_rec(rec)) {
			return(rec);
		}
	} while (btr_pcur_move_to_prev(pcur, mtr));

	return(NULL);
}

4687
/*******************************************************************//**
4688
Read the max AUTOINC value from an index.
4689 4690
@return DB_SUCCESS if all OK else error code, DB_RECORD_NOT_FOUND if
column name can't be found in index */
4691
UNIV_INTERN
4692 4693 4694
ulint
row_search_max_autoinc(
/*===================*/
4695 4696 4697
	dict_index_t*	index,		/*!< in: index to search */
	const char*	col_name,	/*!< in: name of autoinc column */
	ib_uint64_t*	value)		/*!< out: AUTOINC value read */
4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738
{
	ulint		i;
	ulint		n_cols;
	dict_field_t*	dfield = NULL;
	ulint		error = DB_SUCCESS;

	n_cols = dict_index_get_n_ordering_defined_by_user(index);

	/* Search the index for the AUTOINC column name */
	for (i = 0; i < n_cols; ++i) {
		dfield = dict_index_get_nth_field(index, i);

		if (strcmp(col_name, dfield->name) == 0) {
			break;
		}
	}

	*value = 0;

	/* Must find the AUTOINC column name */
	if (i < n_cols && dfield) {
		mtr_t		mtr;
		btr_pcur_t	pcur;

		mtr_start(&mtr);

		/* Open at the high/right end (FALSE), and INIT
		cursor (TRUE) */
		btr_pcur_open_at_index_side(
			FALSE, index, BTR_SEARCH_LEAF, &pcur, TRUE, &mtr);

		if (page_get_n_recs(btr_pcur_get_page(&pcur)) > 0) {
			const rec_t*	rec;

			rec = row_search_autoinc_get_rec(&pcur, &mtr);

			if (rec != NULL) {
				ibool unsigned_type = (
					dfield->col->prtype & DATA_UNSIGNED);

				*value = row_search_autoinc_read_column(
4739 4740
					index, rec, i,
					dfield->col->mtype, unsigned_type);
4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752
			}
		}

		btr_pcur_close(&pcur);

		mtr_commit(&mtr);
	} else {
		error = DB_RECORD_NOT_FOUND;
	}

	return(error);
}