row0sel.c 105 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 26 27 28 29 30 31 32
/*******************************************************
Select

(c) 1997 Innobase Oy

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"
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
33
#include "read0read.h"
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
34
#include "buf0lru.h"
35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52

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

53 54
/************************************************************************
Returns TRUE if the user-defined column values in a secondary index record
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
55 56
are alphabetically the same as the corresponding columns in the clustered
index record.
57 58
NOTE: the comparison is NOT done as a binary comparison, but character
fields are compared with collation! */
59 60 61 62
static
ibool
row_sel_sec_rec_is_for_clust_rec(
/*=============================*/
63 64 65 66 67 68 69
					/* out: TRUE if the secondary
					record is equal to the corresponding
					fields in the clustered record,
					when compared with collation */
	rec_t*		sec_rec,	/* in: secondary index record */
	dict_index_t*	sec_index,	/* in: secondary index */
	rec_t*		clust_rec,	/* in: clustered index record */
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
70
	dict_index_t*	clust_index)	/* in: clustered index */
71
{
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
72 73 74 75 76 77 78 79
	dict_field_t*	ifield;
        dict_col_t*     col;
        byte*           sec_field;
        ulint           sec_len;
        byte*           clust_field;
        ulint           clust_len;
        ulint           n;
        ulint           i;
80
	dtype_t*	cur_type;
81
	mem_heap_t*	heap		= NULL;
82 83
	ulint		clust_offsets_[REC_OFFS_NORMAL_SIZE];
	ulint		sec_offsets_[REC_OFFS_SMALL_SIZE];
84 85 86 87
	ulint*		clust_offs	= clust_offsets_;
	ulint*		sec_offs	= sec_offsets_;
	ibool		is_equal	= TRUE;

88 89 90
	*clust_offsets_ = (sizeof clust_offsets_) / sizeof *clust_offsets_;
	*sec_offsets_ = (sizeof sec_offsets_) / sizeof *sec_offsets_;

91 92 93 94
	clust_offs = rec_get_offsets(clust_rec, clust_index, clust_offs,
						ULINT_UNDEFINED, &heap);
	sec_offs = rec_get_offsets(sec_rec, sec_index, sec_offs,
						ULINT_UNDEFINED, &heap);
95

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
96
        n = dict_index_get_n_ordering_defined_by_user(sec_index);
97

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
98 99 100 101
        for (i = 0; i < n; i++) {
		ifield = dict_index_get_nth_field(sec_index, i);
                col = dict_field_get_col(ifield);
                
marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
102
		clust_field = rec_get_nth_field(clust_rec, clust_offs,
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
103 104
                                                dict_col_get_clust_pos(col),
                                                &clust_len);
marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
105
		sec_field = rec_get_nth_field(sec_rec, sec_offs, i, &sec_len);
106

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
107
		if (ifield->prefix_len > 0
108
		    && clust_len != UNIV_SQL_NULL) {
109

110 111 112
			cur_type = dict_col_get_type(
				dict_field_get_col(ifield));

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
113 114
			clust_len = dtype_get_at_most_n_mbchars(
				cur_type,
115
				ifield->prefix_len,
116
				clust_len, (char*) clust_field);
117 118
		}

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
119 120 121
                if (0 != cmp_data_data(dict_col_get_type(col),
                                        clust_field, clust_len,
                                        sec_field, sec_len)) {
122 123
			is_equal = FALSE;
			goto func_exit;
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
124 125 126
                }
        }

127 128 129 130 131
func_exit:
	if (heap) {
		mem_heap_free(heap);
	}
	return(is_equal);
132 133
}

134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285
/*************************************************************************
Creates a select node struct. */

sel_node_t*
sel_node_create(
/*============*/
				/* out, own: select node struct */
	mem_heap_t*	heap)	/* in: memory heap where created */
{
	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->select_will_do_update = FALSE;
	node->latch_mode = BTR_SEARCH_LEAF;

	node->plans = NULL;
	
	return(node);
}

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

void
sel_node_free_private(
/*==================*/
	sel_node_t*	node)	/* in: select node struct */
{
	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);
			}
		}
	}
}

/*************************************************************************
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(
/*=================*/
	sel_node_t*	node)	/* in: select node */
{
	que_node_t*	exp;

	exp = node->select_list;

	while (exp) {
		eval_exp(exp);

		exp = que_node_get_next(exp);
	}
}

/*************************************************************************
Assigns the values in the select list to the possible into-variables in
SELECT ... INTO ... */
UNIV_INLINE
void
sel_assign_into_var_values(
/*=======================*/
	sym_node_t*	var,	/* in: first variable in a list of variables */
	sel_node_t*	node)	/* in: select node */
{
	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);
	}
}

/*************************************************************************
Resets the aggregate value totals in the select list of an aggregate type
query. */
UNIV_INLINE
void
sel_reset_aggregate_vals(
/*=====================*/
	sel_node_t*	node)	/* in: select node */
{
	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);
	}	

	node->aggregate_already_fetched = FALSE;
}

/*************************************************************************
Copies the input variable values when an explicit cursor is opened. */
UNIV_INLINE
void
row_sel_copy_input_variable_vals(
/*=============================*/
	sel_node_t*	node)	/* in: select node */
{
	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);
	}
}

/*************************************************************************
Fetches the column values from a record. */
static
void
row_sel_fetch_columns(
/*==================*/
	dict_index_t*	index,	/* in: record index */
	rec_t*		rec,	/* in: record in a clustered or non-clustered
				index */
marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
286
	const ulint*	offsets,/* in: rec_get_offsets(rec, index) */
287 288 289 290 291 292 293 294 295
	sym_node_t*	column)	/* in: first column in a column list, or
				NULL */
{
	dfield_t*	val;
	ulint		index_type;
	ulint		field_no;
	byte*		data;
	ulint		len;
	
marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
296 297
	ut_ad(rec_offs_validate(rec, index, offsets));

298 299 300 301 302 303 304 305 306 307 308
	if (index->type & DICT_CLUSTERED) {
		index_type = SYM_CLUST_FIELD_NO;
	} else {
		index_type = SYM_SEC_FIELD_NO;
	}

	while (column) {
		field_no = column->field_nos[index_type];

		if (field_no != ULINT_UNDEFINED) {
	
marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
309
			data = rec_get_nth_field(rec, offsets, field_no, &len);
310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513
			
			if (column->copy_val) {
				eval_node_copy_and_alloc_val(column, data,
									len);
			} else {
				val = que_node_get_val(column);
				dfield_set_data(val, data, len);
			}
		}

		column = UT_LIST_GET_NEXT(col_var_list, column);
	}
}

/*************************************************************************
Allocates a prefetch buffer for a column when prefetch is first time done. */
static
void
sel_col_prefetch_buf_alloc(
/*=======================*/
	sym_node_t*	column)	/* in: symbol table node for a column */
{
	sel_buf_t*	sel_buf;
	ulint		i;

	ut_ad(que_node_get_type(column) == QUE_NODE_SYMBOL);
	
	column->prefetch_buf = mem_alloc(SEL_MAX_N_PREFETCH
							* sizeof(sel_buf_t));
	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;
	}
}

/*************************************************************************
Frees a prefetch buffer for a column, including the dynamically allocated
memory for data stored there. */

void
sel_col_prefetch_buf_free(
/*======================*/
	sel_buf_t*	prefetch_buf)	/* in, own: prefetch buffer */
{
	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);
		}
	}
}

/*************************************************************************
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(
/*===================*/
	plan_t*	plan)	/* in: plan node for a table */
{
	sym_node_t*	column;
	sel_buf_t*	sel_buf;
	dfield_t*	val;
	byte*		data;
	ulint		len;
	ulint		val_buf_size;
	
	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);
#ifdef UNIV_DEBUG
			dfield_set_data(val, NULL, 0);
#endif
			goto next_col;
		}

		ut_ad(column->prefetch_buf);

		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);
		
		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++;
}

/*************************************************************************
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(
/*====================*/
	plan_t*	plan)	/* in: plan node for a table */
{
	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: */
		
		ut_ad(plan->first_prefetched == 0);
	}

	plan->n_rows_prefetched++;
	
	ut_ad(pos < SEL_MAX_N_PREFETCH);
	
	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;
		}
		
		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);
		
		sel_buf->data = data;
		sel_buf->len = len;
		sel_buf->val_buf_size = val_buf_size;
next_col:		
		column = UT_LIST_GET_NEXT(col_var_list, column);
	}
}

/*************************************************************************
Builds a previous version of a clustered index record for a consistent read */
static
ulint
row_sel_build_prev_vers(
/*====================*/
					/* out: DB_SUCCESS or error code */
	read_view_t*	read_view,	/* in: read view */
	plan_t*		plan,		/* in: plan node for table */
	rec_t*		rec,		/* in: record in a clustered index */
514 515 516 517
	ulint**		offsets,	/* in/out: offsets returned by
					rec_get_offsets(rec, plan->index) */
	mem_heap_t**	offset_heap,	/* in/out: memory heap from which
					the offsets are allocated */
518 519 520 521 522 523 524 525 526 527 528 529 530 531 532
	rec_t**		old_vers,	/* out: old version, or NULL if the
					record does not exist in the view:
					i.e., it was freshly inserted
					afterwards */
	mtr_t*		mtr)		/* in: mtr */
{
	ulint	err;

	if (plan->old_vers_heap) {
		mem_heap_empty(plan->old_vers_heap);
	} else {
		plan->old_vers_heap = mem_heap_create(512);
	}
	
	err = row_vers_build_for_consistent_read(rec, mtr, plan->index,
533 534
					offsets, read_view, offset_heap,
					plan->old_vers_heap, old_vers);
535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627
	return(err);
}

/*************************************************************************
Tests the conditions which determine when the index segment we are searching
through has been exhausted. */
UNIV_INLINE
ibool
row_sel_test_end_conds(
/*===================*/
 			/* out: TRUE if row passed the tests */
	plan_t*	plan)	/* in: plan for the table; the column values must
			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 */
	
	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);
}

/*************************************************************************
Tests the other conditions. */
UNIV_INLINE
ibool
row_sel_test_other_conds(
/*=====================*/
			/* out: TRUE if row passed the tests */
	plan_t*	plan)	/* in: plan for the table; the column values must
			already have been retrieved */
{
	func_node_t*	cond;
	
	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);
}

/*************************************************************************
Retrieves the clustered index record corresponding to a record in a
non-clustered index. Does the necessary locking. */
static
ulint
row_sel_get_clust_rec(
/*==================*/
				/* out: DB_SUCCESS or error code */
	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
				it, NULL if the old version did not exist
				in the read view, i.e., it was a fresh
				inserted version */
	mtr_t*		mtr)	/* in: mtr used to get access to the
				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;
628
	mem_heap_t*	heap		= NULL;
629
	ulint		offsets_[REC_OFFS_NORMAL_SIZE];
630
	ulint*		offsets		= offsets_;
631
	*offsets_ = (sizeof offsets_) / sizeof *offsets_;
marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
632 633 634

	offsets = rec_get_offsets(rec,
				btr_pcur_get_btr_cur(&plan->pcur)->index,
635
				offsets, ULINT_UNDEFINED, &heap);
636
	
marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
637
	row_build_row_ref_fast(plan->clust_ref, plan->clust_map, rec, offsets);
638 639 640 641 642 643 644 645 646

	index = dict_table_get_first_index(plan->table);
	
	btr_pcur_open_with_no_init(index, plan->clust_ref, PAGE_CUR_LE,
				node->latch_mode, &(plan->clust_pcur),
				0, mtr);

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

647 648 649 650 651 652
	/* 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)
            || btr_pcur_get_low_match(&(plan->clust_pcur))
	       < dict_index_get_n_unique(index)) {
653
	
marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
654
		ut_a(rec_get_deleted_flag(rec, plan->table->comp));
655 656 657 658 659 660 661 662 663 664 665 666 667 668 669
		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. */

		clust_rec = NULL;

		goto func_exit;
	}
670

671 672
	offsets = rec_get_offsets(clust_rec, index, offsets,
						ULINT_UNDEFINED, &heap);
marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
673

674 675
	if (!node->read_view) {
		/* Try to place a lock on the index record */
676
        
677
		/* If innodb_locks_unsafe_for_binlog option is used, 
marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
678 679 680
		we lock only the record, i.e., next-key locking is
		not used. */
		ulint	lock_type;
681 682

		if (srv_locks_unsafe_for_binlog) {
marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
683
			lock_type = LOCK_REC_NOT_GAP;
684
		} else {
marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
685
			lock_type = LOCK_ORDINARY;
686 687
		}

marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
688 689 690 691
		err = lock_clust_rec_read_check_and_lock(0,
				clust_rec, index, offsets,
				node->row_lock_mode, lock_type, thr);

692
		if (err != DB_SUCCESS) {
693

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

700 701
		old_vers = NULL;

marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
702
		if (!lock_clust_rec_cons_read_sees(clust_rec, index, offsets,
703 704 705
							node->read_view)) {

			err = row_sel_build_prev_vers(node->read_view, plan,
706 707
						clust_rec, &offsets, &heap,
						&old_vers, mtr);
708 709
			if (err != DB_SUCCESS) {

710
				goto err_exit;
711 712 713 714 715
			}

			clust_rec = old_vers;

			if (clust_rec == NULL) {
marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
716
				goto func_exit;
717 718
			}
		}
719 720 721 722 723 724 725 726 727 728 729 730 731 732

		/* 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. */
		
marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
733
		if ((old_vers || rec_get_deleted_flag(rec, plan->table->comp))
734 735 736
		    && !row_sel_sec_rec_is_for_clust_rec(rec, plan->index,
							clust_rec, index)) {
			clust_rec = NULL;
marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
737
			goto func_exit;
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
738
		}
739 740 741
	}

	/* Fetch the columns needed in test conditions */
marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
742 743

	row_sel_fetch_columns(index, clust_rec, offsets,
744
					UT_LIST_GET_FIRST(plan->columns));
745
func_exit:
746
	*out_rec = clust_rec;
747 748 749 750 751 752
	err = DB_SUCCESS;
err_exit:
	if (heap) {
		mem_heap_free(heap);
	}
	return(err);
753 754 755 756 757 758 759 760 761 762 763
}

/*************************************************************************
Sets a lock on a record. */
UNIV_INLINE
ulint
sel_set_rec_lock(
/*=============*/
				/* out: DB_SUCCESS or error code */
	rec_t*		rec,	/* in: record */
	dict_index_t*	index,	/* in: index */
marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
764
	const ulint*	offsets,/* in: rec_get_offsets(rec, index) */
765
	ulint		mode,	/* in: lock mode */
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
766
	ulint		type, 	/* in: LOCK_ORDINARY, LOCK_GAP, or LOC_REC_NOT_GAP */
767 768
	que_thr_t*	thr)	/* in: query thread */	
{
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
769
	trx_t*	trx;
770 771
	ulint	err;

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
772 773 774 775 776 777 778 779 780
	trx = thr_get_trx(thr);	

	if (UT_LIST_GET_LEN(trx->trx_locks) > 10000) {
		if (buf_LRU_buf_pool_running_out()) {
			
			return(DB_LOCK_TABLE_FULL);
		}
	}

781
	if (index->type & DICT_CLUSTERED) {
marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
782 783
		err = lock_clust_rec_read_check_and_lock(0,
					rec, index, offsets, mode, type, thr);
784
	} else {
marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
785 786
		err = lock_sec_rec_read_check_and_lock(0,
					rec, index, offsets, mode, type, thr);
787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869
	}

	return(err);
}

/*************************************************************************
Opens a pcur to a table index. */
static
void
row_sel_open_pcur(
/*==============*/
	sel_node_t*	node,		/* in: select node */
	plan_t*		plan,		/* in: table plan */
	ibool		search_latch_locked,
					/* in: TRUE if the thread currently
					has the search latch locked in
					s-mode */
	mtr_t*		mtr)		/* in: mtr */
{
	dict_index_t*	index;
	func_node_t*	cond;
	que_node_t*	exp;
	ulint		n_fields;
	ulint		has_search_latch = 0;	/* RW_S_LATCH or 0 */ 
	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));
	
		cond = UT_LIST_GET_NEXT(cond_list, cond);
	}
	
	if (plan->tuple) {
		n_fields = dtuple_get_n_fields(plan->tuple);
	
		if (plan->n_exact_match < n_fields) {
			/* There is a non-exact match field which must be
			evaluated separately */
			
			eval_exp(plan->tuple_exps[n_fields - 1]);
		}
		
		for (i = 0; i < n_fields; i++) {
			exp = plan->tuple_exps[i];
	
			dfield_copy_data(dtuple_get_nth_field(plan->tuple, i),
							que_node_get_val(exp));
		}
	
		/* Open pcur to the index */
	
		btr_pcur_open_with_no_init(index, plan->tuple, plan->mode,
					node->latch_mode, &(plan->pcur),
					has_search_latch, mtr);
	} else {
		/* Open the cursor to the start or the end of the index
		(FALSE: no init) */

		btr_pcur_open_at_index_side(plan->asc, index, node->latch_mode,
						&(plan->pcur), FALSE, mtr);
	}

	ut_ad(plan->n_rows_prefetched == 0);
	ut_ad(plan->n_rows_fetched == 0);
	ut_ad(plan->cursor_at_end == FALSE);
 
	plan->pcur_is_open = TRUE;
}

/*************************************************************************
Restores a stored pcur position to a table index. */
870
static
871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919
ibool
row_sel_restore_pcur_pos(
/*=====================*/
				/* out: 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 */
	sel_node_t*	node,	/* in: select node */
	plan_t*		plan,	/* in: table plan */
	mtr_t*		mtr)	/* in: mtr */
{
	ibool	equal_position;
	ulint	relative_position;

	ut_ad(!plan->cursor_at_end);
	
	relative_position = btr_pcur_get_rel_pos(&(plan->pcur));

	equal_position = btr_pcur_restore_position(node->latch_mode,
							&(plan->pcur), mtr);

	/* If the cursor is traveling upwards, and relative_position is
	
	(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);
		}

920 921
		ut_ad(relative_position == BTR_PCUR_AFTER
		      || relative_position == BTR_PCUR_AFTER_LAST_IN_TREE);
922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942

		return(FALSE);
	}

	/* If the cursor is traveling downwards, and relative_position is
	
	(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. */

943 944
	if (relative_position == BTR_PCUR_BEFORE
	    || relative_position == BTR_PCUR_BEFORE_FIRST_IN_TREE) {
945 946 947 948 949 950 951 952 953 954 955 956 957 958

		return(FALSE);
	}

	if (relative_position == BTR_PCUR_ON) {

		if (equal_position) {

			return(plan->stored_cursor_rec_processed);
		}

		return(FALSE);
	}

959 960
	ut_ad(relative_position == BTR_PCUR_AFTER
		      || relative_position == BTR_PCUR_AFTER_LAST_IN_TREE);
961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993

	return(TRUE);
}

/*************************************************************************
Resets a plan cursor to a closed state. */
UNIV_INLINE
void
plan_reset_cursor(
/*==============*/
	plan_t*	plan)	/* in: plan */
{	
	plan->pcur_is_open = FALSE;
	plan->cursor_at_end = FALSE;	
	plan->n_rows_fetched = 0;
	plan->n_rows_prefetched = 0;
}
	
/*************************************************************************
Tries to do a shortcut to fetch a clustered index record with a unique key,
using the hash index if possible (not always). */
static
ulint
row_sel_try_search_shortcut(
/*========================*/
				/* out: SEL_FOUND, SEL_EXHAUSTED, SEL_RETRY */
	sel_node_t*	node,	/* in: select node for a consistent read */
	plan_t*		plan,	/* in: plan for a unique search in clustered
				index */
	mtr_t*		mtr)	/* in: mtr */
{
	dict_index_t*	index;
	rec_t*		rec;
994
	mem_heap_t*	heap		= NULL;
995
	ulint		offsets_[REC_OFFS_NORMAL_SIZE];
996 997
	ulint*		offsets		= offsets_;
	ulint		ret;
998
	*offsets_ = (sizeof offsets_) / sizeof *offsets_;
999 1000 1001 1002 1003 1004

	index = plan->index;

	ut_ad(node->read_view);
	ut_ad(plan->unique_search);
	ut_ad(!plan->must_get_clust);
1005
#ifdef UNIV_SYNC_DEBUG
1006
	ut_ad(rw_lock_own(&btr_search_latch, RW_LOCK_SHARED));
1007
#endif /* UNIV_SYNC_DEBUG */
1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031
	
	row_sel_open_pcur(node, plan, TRUE, mtr);

	rec = btr_pcur_get_rec(&(plan->pcur));
	
	if (!page_rec_is_user_rec(rec)) {

		return(SEL_RETRY);
	}

	ut_ad(plan->mode == PAGE_CUR_GE);
	
	/* 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 tuple */ 

	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 */
			
1032
	offsets = rec_get_offsets(rec, index, offsets, ULINT_UNDEFINED, &heap);
marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
1033

1034
	if (index->type & DICT_CLUSTERED) {
marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
1035
		if (!lock_clust_rec_cons_read_sees(rec, index, offsets,
1036
							node->read_view)) {
1037 1038
			ret = SEL_RETRY;
			goto func_exit;
1039 1040 1041
		}
	} else if (!lock_sec_rec_cons_read_sees(rec, index, node->read_view)) {

1042 1043
		ret = SEL_RETRY;
		goto func_exit;
1044 1045 1046 1047
	}

	/* Test deleted flag. Fetch the columns needed in test conditions. */

marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
1048 1049 1050 1051
	row_sel_fetch_columns(index, rec, offsets,
				UT_LIST_GET_FIRST(plan->columns));

	if (rec_get_deleted_flag(rec, plan->table->comp)) {
1052

1053 1054
		ret = SEL_EXHAUSTED;
		goto func_exit;
1055 1056 1057 1058 1059 1060
	}

	/* Test the rest of search conditions */
	
	if (!row_sel_test_other_conds(plan)) {

1061 1062
		ret = SEL_EXHAUSTED;
		goto func_exit;
1063 1064 1065 1066 1067
	}

	ut_ad(plan->pcur.latch_mode == node->latch_mode);

	plan->n_rows_fetched++;
1068 1069 1070 1071
func_exit:
	if (heap) {
		mem_heap_free(heap);
	}
1072 1073 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 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119
	return(SEL_FOUND);
}

/*************************************************************************
Performs a select step. */
static
ulint
row_sel(
/*====*/
				/* out: DB_SUCCESS or error code */
	sel_node_t*	node,	/* in: select node */
	que_thr_t*	thr)	/* in: query thread */
{
	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;
	
		/* 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: */

	ibool		cons_read_requires_clust_rec	= FALSE;
	ulint		cost_counter			= 0;
	ibool		cursor_just_opened;
	ibool		must_go_to_next;
	ibool		leaf_contains_updates 		= FALSE;
					/* TRUE if select_will_do_update is
					TRUE and the current clustered index
					leaf page has been updated during
					the current mtr: mtr must be committed
					at the same time as the leaf x-latch
					is released */
	ibool		mtr_has_extra_clust_latch 	= FALSE;
					/* 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 */
	ulint		found_flag;
	ulint		err;
1120
	mem_heap_t*	heap				= NULL;
1121
	ulint		offsets_[REC_OFFS_NORMAL_SIZE];
1122
	ulint*		offsets				= offsets_;
1123
	*offsets_ = (sizeof offsets_) / sizeof *offsets_;
marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
1124

1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272
	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
	   ----------
	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(leaf_contains_updates == FALSE);
	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 */
	
	mtr_start(&mtr);

	if (consistent_read && plan->unique_search && !plan->pcur_is_open
						&& !plan->must_get_clust) {
		if (!search_latch_locked) {
			rw_lock_s_lock(&btr_search_latch);

			search_latch_locked = TRUE;
		} else if (btr_search_latch.writer_is_wait_ex) {

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

		row_sel_open_pcur(node, plan, search_latch_locked, &mtr);

		cursor_just_opened = TRUE;

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

		must_go_to_next = row_sel_restore_pcur_pos(node, plan, &mtr);

		cursor_just_opened = FALSE;

		if (must_go_to_next) {
			/* We have already processed the cursor record: move
			to the next */
		
			goto next_rec;
		}
	}
	
rec_loop:
	/* RECORD LOOP
	   -----------
	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. */
	
	ut_ad(mtr_has_extra_clust_latch == FALSE);

	rec = btr_pcur_get_rec(&(plan->pcur));
	
	/* PHASE 1: Set a lock if specified */

	if (!node->asc && cursor_just_opened
		&& (rec != page_get_supremum_rec(buf_frame_align(rec)))) {

		/* 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. */
		
		if (!consistent_read) {
1273

1274
			/* If innodb_locks_unsafe_for_binlog option is used,
marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
1275 1276 1277 1278 1279
			we lock only the record, i.e., next-key locking is
			not used. */

			rec_t*	next_rec = page_rec_get_next(rec);
			ulint	lock_type;
1280 1281
			offsets = rec_get_offsets(next_rec, index, offsets,
						ULINT_UNDEFINED, &heap);
1282 1283

			if (srv_locks_unsafe_for_binlog) {
marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
1284
				lock_type = LOCK_REC_NOT_GAP;
1285
			} else {
marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
1286
				lock_type = LOCK_ORDINARY;
1287 1288
			}

marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
1289 1290 1291
			err = sel_set_rec_lock(next_rec, index, offsets,
					node->row_lock_mode, lock_type, thr);

1292
			if (err != DB_SUCCESS) {
1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316
				/* Note that in this case we will store in pcur
				the PREDECESSOR of the record we are waiting
				the lock for */
				
				goto lock_wait_or_error;
			}
		}
	}

	if (rec == page_get_infimum_rec(buf_frame_align(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) {
		/* Try to place a lock on the index record */	

1317
		/* If innodb_locks_unsafe_for_binlog option is used,
marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
1318 1319 1320 1321
		we lock only the record, i.e., next-key locking is
		not used. */

		ulint	lock_type;
1322 1323
		offsets = rec_get_offsets(rec, index, offsets,
						ULINT_UNDEFINED, &heap);
1324

1325
		if (srv_locks_unsafe_for_binlog) {
marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
1326
			lock_type = LOCK_REC_NOT_GAP;
1327
		} else {
marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
1328
			lock_type = LOCK_ORDINARY;
1329
		}
1330

marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
1331 1332 1333
		err = sel_set_rec_lock(rec, index, offsets,
					node->row_lock_mode, lock_type, thr);

1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394
		if (err != DB_SUCCESS) {

			goto lock_wait_or_error;
		}
	}

	if (rec == page_get_supremum_rec(buf_frame_align(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) {
		
		/* 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;
	}
	
	/* PHASE 2: Check a mixed index mix id if needed */

	if (plan->unique_search && cursor_just_opened) {

		ut_ad(plan->mode == PAGE_CUR_GE);
	
		/* 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
		tuple */ 

		if (btr_pcur_get_up_match(&(plan->pcur))
						< plan->n_exact_match) {
			goto table_exhausted;
		}

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

	} else if (plan->mixed_index) {
	    	/* We have to check if the record in a mixed cluster belongs
	    	to this table */

	 	if (!dict_is_mixed_table_rec(plan->table, rec)) {

	    		goto next_rec;
	    	}
	}

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

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

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

		if (index->type & DICT_CLUSTERED) {
			
marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
1404
			if (!lock_clust_rec_cons_read_sees(rec, index, offsets,
1405 1406 1407
							node->read_view)) {

				err = row_sel_build_prev_vers(node->read_view,
1408 1409 1410
							plan, rec,
							&offsets, &heap,
							&old_vers, &mtr);
1411 1412 1413 1414 1415 1416
				if (err != DB_SUCCESS) {

					goto lock_wait_or_error;
				}

				if (old_vers == NULL) {
1417 1418 1419
					offsets = rec_get_offsets(
						rec, index, offsets,
						ULINT_UNDEFINED, &heap);
1420
					row_sel_fetch_columns(index, rec,
marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
1421
					    offsets,
1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443
					    UT_LIST_GET_FIRST(plan->columns));

					if (!row_sel_test_end_conds(plan)) {

						goto table_exhausted;
					}

					goto next_rec;
				}

				rec = old_vers;
			}
		} else if (!lock_sec_rec_cons_read_sees(rec, index,
							node->read_view)) {
			cons_read_requires_clust_rec = TRUE;
		}
	}

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

	/* Fetch the columns needed in test conditions */
	
marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
1444 1445
	row_sel_fetch_columns(index, rec, offsets,
					UT_LIST_GET_FIRST(plan->columns));
1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459

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

marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
1460 1461
	if (rec_get_deleted_flag(rec, plan->table->comp)
			&& !cons_read_requires_clust_rec) {
1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503

		/* 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) {
			
			goto table_exhausted;
		}
		
		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,
									&mtr);
		mtr_has_extra_clust_latch = TRUE;
		
		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;
		}

marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
1504
		if (rec_get_deleted_flag(clust_rec, plan->table->comp)) {
1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661

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

	/* PHASE 6: Test the rest of search conditions */
	
	if (!row_sel_test_other_conds(plan)) {

		if (plan->unique_search) {
			
			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 */
	
	plan->n_rows_fetched++;

	ut_ad(plan->pcur.latch_mode == node->latch_mode);

	if (node->select_will_do_update) {
		/* This is a searched update and we can do the update in-place,
		saving CPU time */

		row_upd_in_place_in_select(node, thr, &mtr);

		leaf_contains_updates = TRUE;

		/* When the database is in the online backup mode, the number
		of log records for a single mtr should be small: increment the
		cost counter to ensure it */
		
		cost_counter += 1 + (SEL_COST_LIMIT / 8);

		if (plan->unique_search) {

			goto table_exhausted;			
		}

		goto next_rec;
	}	

	if ((plan->n_rows_fetched <= SEL_PREFETCH_LIMIT)
				|| plan->unique_search || plan->no_prefetch) {

		/* No prefetch in operation: go to the next table */
	
		goto next_table;
	}

	sel_push_prefetched_row(plan);

	if (plan->n_rows_prefetched == SEL_MAX_N_PREFETCH) {

		/* The prefetch buffer is now full */
		
		sel_pop_prefetched_row(plan);

		goto next_table;
	}

next_rec:	
	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;
	}
	
	if (leaf_contains_updates
		&& btr_pcur_is_after_last_on_page(&(plan->pcur), &mtr)) {

		/* We must commit &mtr if we are moving to a different page,
		because we have done updates to the x-latched leaf page, and
		the latch would be released in btr_pcur_move_to_next, without
		&mtr getting committed there */

		ut_ad(node->asc);

		goto commit_mtr_for_a_while;
	}

	if (node->asc) {
		moved = btr_pcur_move_to_next(&(plan->pcur), &mtr);
	} else {
		moved = btr_pcur_move_to_prev(&(plan->pcur), &mtr);
	}

	if (!moved) {
		
		goto table_exhausted;
	}

	cursor_just_opened = FALSE;

	/* END OF RECORD LOOP
	   ------------------ */
	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 */

	ut_ad(btr_pcur_is_on_user_rec(&(plan->pcur), &mtr));
	
	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);

	leaf_contains_updates = FALSE;
	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 */
	
	if (node->fetch_table + 1 == node->n_tables) {

		sel_eval_select_list(node);

		if (node->is_aggregate) {

			goto table_loop;			
		}

		sel_assign_into_var_values(node->into_list, node);
		
		thr->run_node = que_node_get_parent(node);

		if (search_latch_locked) {
			rw_lock_s_unlock(&btr_search_latch);
		}
marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
1662

1663 1664
		err = DB_SUCCESS;
		goto func_exit;
1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696
	}

	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 */
	
	plan_reset_cursor(sel_node_get_nth_plan(node, node->fetch_table));
	
	goto table_loop;

table_exhausted:
	/* The table cursor pcur reached the result set end: backtrack to the
	previous table in the join if we do not have cached prefetched rows */	

	plan->cursor_at_end = TRUE;

	mtr_commit(&mtr);

	leaf_contains_updates = FALSE;
	mtr_has_extra_clust_latch = FALSE;
	
	if (plan->n_rows_prefetched > 0) {
		/* The table became exhausted during a prefetch */
	
		sel_pop_prefetched_row(plan);

		goto next_table_no_mtr;
	}

table_exhausted_no_mtr:
	if (node->fetch_table == 0) {
1697
		err = DB_SUCCESS;
1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710

		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);

			if (search_latch_locked) {
				rw_lock_s_unlock(&btr_search_latch);
			}
		
1711
			goto func_exit;
1712 1713 1714 1715 1716 1717 1718 1719 1720 1721
		}

		node->state = SEL_NODE_NO_MORE_ROWS;
		
		thr->run_node = que_node_get_parent(node);

		if (search_latch_locked) {
			rw_lock_s_unlock(&btr_search_latch);
		}
		
1722
		goto func_exit;
1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745
	}

	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,
	which would result in the phantom problem. */ 

	ut_ad(!search_latch_locked);

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

	mtr_commit(&mtr);
		
	ut_ad(sync_thread_levels_empty_gen(TRUE));
1746 1747
	err = DB_SUCCESS;
	goto func_exit;
1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781

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
	&mtr would not be committed and the latches released. */ 

	plan->stored_cursor_rec_processed = TRUE;

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

	mtr_commit(&mtr);

	leaf_contains_updates = FALSE;
	mtr_has_extra_clust_latch = FALSE;
	
	ut_ad(sync_thread_levels_empty_gen(TRUE));

	goto table_loop;

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

	ut_ad(!btr_pcur_is_before_first_on_page(&(plan->pcur), &mtr)
							|| !node->asc);
	ut_ad(!search_latch_locked);

	plan->stored_cursor_rec_processed = FALSE;
	btr_pcur_store_position(&(plan->pcur), &mtr);
	
	mtr_commit(&mtr);
		
	ut_ad(sync_thread_levels_empty_gen(TRUE));

1782 1783 1784 1785
func_exit:
	if (heap) {
		mem_heap_free(heap);
	}
1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890
	return(err);
}

/**************************************************************************
Performs a select step. This is a high-level function used in SQL execution
graphs. */

que_thr_t*
row_sel_step(
/*=========*/
				/* out: query thread to run next or NULL */
	que_thr_t*	thr)	/* in: query thread */
{
	ulint		i_lock_mode;
	sym_node_t*	table_node;
	sel_node_t*	node;
	ulint		err;

	ut_ad(thr);
	
	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 */
			node->read_view = trx_assign_read_view(
							thr_get_trx(thr));
		} else {
			if (node->set_x_locks) {
				i_lock_mode = LOCK_IX;
			} else {
				i_lock_mode = LOCK_IS;
			}
	
			table_node = node->table_list;
	
			while (table_node) {
				err = lock_table(0, table_node->table,
							i_lock_mode, thr);
				if (err != DB_SUCCESS) {
	
					que_thr_handle_error(thr, DB_ERROR,
								NULL, 0);
					return(NULL);
				}
	
				table_node = que_node_get_next(table_node);
			}
		}
	
		/* 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) */

		if (node->explicit_cursor &&
				UT_LIST_GET_FIRST(node->copy_variables)) {

			row_sel_copy_input_variable_vals(node);
		}
		
		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: */
	
	thr->graph->last_sel_node = node;

	if (err == DB_SUCCESS) {
		/* Ok: do nothing */

	} else if (err == DB_LOCK_WAIT) {

		return(NULL);
	} else {
		/* SQL error detected */
monty@mishka.local's avatar
monty@mishka.local committed
1891
		fprintf(stderr, "SQL error %lu\n", (ulong) err);
1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940

		que_thr_handle_error(thr, DB_ERROR, NULL, 0);

		return(NULL);
	}

	return(thr);
} 

/**************************************************************************
Performs a fetch for a cursor. */

que_thr_t*
fetch_step(
/*=======*/
				/* out: query thread to run next or NULL */
	que_thr_t*	thr)	/* in: query thread */
{
	sel_node_t*	sel_node;
	fetch_node_t*	node;

	ut_ad(thr);
	
	node = thr->run_node;
	sel_node = node->cursor_def;
	
	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) {
			
			sel_assign_into_var_values(node->into_list, sel_node);
		}

		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 */
		
	sel_node->common.parent = node;
	
	if (sel_node->state == SEL_NODE_CLOSED) {
		/* SQL error detected */
monty@mishka.local's avatar
monty@mishka.local committed
1941
		fprintf(stderr, "SQL error %lu\n", (ulong)DB_ERROR);
1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001

		que_thr_handle_error(thr, DB_ERROR, NULL, 0);

		return(NULL);
	}

	thr->run_node = sel_node;

	return(thr);
} 

/***************************************************************
Prints a row in a select result. */

que_thr_t*
row_printf_step(
/*============*/
				/* out: query thread to run next or NULL */
	que_thr_t*	thr)	/* in: query thread */
{
	row_printf_node_t*	node;
	sel_node_t*		sel_node;
	que_node_t*		arg;

	ut_ad(thr);
	
	node = thr->run_node;
	
	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)) {
	
		/* Reset the cursor */
		sel_node->state = SEL_NODE_OPEN;

		/* Fetch next row to print */

		thr->run_node = sel_node;
		
		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);
	
		return(thr);
	}

	arg = sel_node->select_list;

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

2002
		fputs(" ::: ", stderr);
2003 2004 2005 2006

		arg = que_node_get_next(arg);
	}

2007
	putc('\n', stderr);
2008 2009 2010 2011 2012 2013 2014 2015 2016

	/* Fetch next row to print */

	thr->run_node = sel_node;

	return(thr);
} 

/********************************************************************
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2017 2018 2019 2020 2021
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. */
2022 2023 2024 2025 2026 2027 2028 2029 2030 2031

void
row_sel_convert_mysql_key_to_innobase(
/*==================================*/
	dtuple_t*	tuple,		/* in: tuple where to build;
					NOTE: we assume that the type info
					in the tuple is already according
					to index! */
	byte*		buf,		/* in: buffer to use in field
					conversions */
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2032
	ulint		buf_len,	/* in: buffer length */
2033 2034
	dict_index_t*	index,		/* in: index of the key value */
	byte*		key_ptr,	/* in: MySQL key value */
2035 2036
	ulint		key_len,	/* in: MySQL key value length */
	trx_t*		trx)		/* in: transaction */
2037
{
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2038
	byte*		original_buf	= buf;
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2039
	byte*		original_key_ptr = key_ptr;
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2040
	dict_field_t*	field;
2041
	dfield_t*	dfield;
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2042 2043 2044 2045
	ulint		data_offset;
	ulint		data_len;
	ulint		data_field_len;
	ibool		is_null;
2046 2047
	byte*		key_end;
	ulint		n_fields = 0;
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2048
	ulint		type;
2049
	
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2050 2051
	/* For documentation of the key value storage format in MySQL, see
	ha_innobase::store_key_val_for_row() in ha_innodb.cc. */
2052

2053 2054 2055 2056 2057 2058 2059
	key_end = key_ptr + key_len;

	/* Permit us to access any field in the tuple (ULINT_MAX): */
	
	dtuple_set_n_fields(tuple, ULINT_MAX);

	dfield = dtuple_get_nth_field(tuple, 0);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2060
	field = dict_index_get_nth_field(index, 0);
2061 2062

	if (dfield_get_type(dfield)->mtype == DATA_SYS) {
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2063 2064 2065 2066 2067
		/* 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. */
2068 2069 2070 2071 2072 2073 2074 2075 2076 2077

		ut_a(key_len == DATA_ROW_ID_LEN);

		dfield_set_data(dfield, key_ptr, DATA_ROW_ID_LEN);
					
		dtuple_set_n_fields(tuple, 1);

		return;
	}

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2078
	while (key_ptr < key_end) {
2079

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2080 2081 2082 2083 2084
		ut_a(dict_col_get_type(field->col)->mtype
		     == dfield_get_type(dfield)->mtype);

		data_offset = 0;
		is_null = FALSE;
2085 2086 2087 2088 2089

    		if (!(dfield_get_type(dfield)->prtype & DATA_NOT_NULL)) {
    			/* The first byte in the field tells if this is
    			an SQL NULL value */
    			
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2090
			data_offset = 1;
2091

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2092
 			if (*key_ptr != 0) {
2093 2094
      				dfield_set_data(dfield, NULL, UNIV_SQL_NULL);

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2095
				is_null = TRUE;
2096 2097 2098
      			}
      		}

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2099 2100 2101 2102
		type = dfield_get_type(dfield)->mtype;

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

2103 2104 2105 2106 2107 2108
		if (type == DATA_BLOB || ( type == DATA_VARCHAR &&
			dtype_get_mysql_type(dfield_get_type(dfield))
					== DATA_MYSQL_TRUE_VARCHAR)) {

			/* The key field is a column prefix of a BLOB,
			TEXT, OR TRUE VARCHAR type column */
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2109 2110 2111 2112 2113

			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
2114 2115 2116 2117 2118 2119 2120 2121 2122
			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]
				   + 256 * key_ptr[data_offset + 1];
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2123
			data_field_len = data_offset + 2 + field->prefix_len;
2124 2125 2126 2127

			if (type == DATA_BLOB) {
				data_offset += 2;
			}
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2128 2129 2130 2131

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

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2132
		} else if (field->prefix_len > 0) {
2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143
			/* 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? */

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154
		        data_len = field->prefix_len;
			data_field_len = data_offset + data_len;
		} else {
			data_len = dfield_get_type(dfield)->len;
			data_field_len = data_offset + data_len;
		}

		/* Storing may use at most data_len bytes of buf */
		
		if (!is_null) {
		        row_mysql_store_col_in_innobase_format(
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2155 2156 2157 2158 2159 2160
					dfield,
					buf,
					FALSE, /* MySQL key value format col */
					key_ptr + data_offset,
					data_len,
					index->table->comp);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2161 2162 2163 2164
			buf += data_len;
		}

    		key_ptr += data_field_len;
2165 2166

		if (key_ptr > key_end) {
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2167 2168
			/* The last field in key was not a complete key field
			but a prefix of it.
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2169

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2170 2171 2172 2173 2174
		        Print a warning about this! HA_READ_PREFIX_LAST does
			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. */
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2175 2176 2177

		        ut_print_timestamp(stderr);
			
2178
			fputs(
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2179
  "  InnoDB: Warning: using a partial-field key prefix in search.\n"
2180 2181 2182
  "InnoDB: ", stderr);
			dict_index_name_print(stderr, trx, index);
			fprintf(stderr, ". Last data field length %lu bytes,\n"
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2183
  "InnoDB: key ptr now exceeds key end by %lu bytes.\n"
2184
  "InnoDB: Key value in the MySQL format:\n",
2185 2186
					  (ulong) data_field_len,
					  (ulong) (key_ptr - key_end));
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2187
			fflush(stderr);
monty@mishka.local's avatar
monty@mishka.local committed
2188
			ut_print_buf(stderr, original_key_ptr, key_len);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2189
			fprintf(stderr, "\n");
2190

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2191 2192 2193
			if (!is_null) {
			        dfield->len -= (ulint)(key_ptr - key_end);
			}
2194 2195
		}

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2196 2197
		n_fields++;    		
    		field++;
2198 2199 2200
		dfield++;
  	}

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2201 2202 2203 2204
	ut_a(buf <= original_buf + buf_len);

 	/* We set the length of tuple to n_fields: we assume that the memory
	area allocated for it is big enough (usually bigger than n_fields). */
2205 2206 2207 2208 2209 2210
 	
 	dtuple_set_n_fields(tuple, n_fields);
}

/******************************************************************
Stores the row id to the prebuilt struct. */
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2211
static
2212 2213 2214 2215 2216
void
row_sel_store_row_id_to_prebuilt(
/*=============================*/
	row_prebuilt_t*	prebuilt,	/* in: prebuilt */
	rec_t*		index_rec,	/* in: record */
marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
2217 2218 2219
	dict_index_t*	index,		/* in: index of the record */
	const ulint*	offsets)	/* in: rec_get_offsets
					(index_rec, index) */
2220 2221 2222
{
	byte*	data;
	ulint	len;
marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
2223 2224 2225 2226

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

	data = rec_get_nth_field(index_rec, offsets,
2227 2228
			dict_index_get_sys_col_pos(index, DATA_ROW_ID), &len);

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2229 2230
	if (len != DATA_ROW_ID_LEN) {
	        fprintf(stderr,
monty@mishka.local's avatar
monty@mishka.local committed
2231
"InnoDB: Error: Row id field is wrong length %lu in ", (ulong) len);
2232
		dict_index_name_print(stderr, prebuilt->trx, index);
2233 2234
		fprintf(stderr, "\n"
"InnoDB: Field number %lu, record:\n",
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2235
		    (ulong) dict_index_get_sys_col_pos(index, DATA_ROW_ID));
2236
		rec_print_new(stderr, index_rec, offsets);
2237
		putc('\n', stderr);
2238
		ut_error;
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2239
	}
2240 2241 2242 2243 2244

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

/******************************************************************
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2245 2246 2247
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
2248 2249 2250 2251 2252 2253 2254
void
row_sel_field_store_in_mysql_format(
/*================================*/
	byte*	dest,	/* in/out: buffer where to store; NOTE 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' */
2255 2256 2257
	const mysql_row_templ_t* templ,	/* in: MySQL column template.
			Its following fields are referenced:
			type, is_unsigned, mysql_col_len, mbminlen, mbmaxlen */
2258
	byte*	data,	/* in: data to store */
2259
	ulint	len)	/* in: length of the data */
2260 2261
{
	byte*	ptr;
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2262 2263
	byte*	field_end;
	byte*	pad_ptr;
2264 2265 2266

	ut_ad(len != UNIV_SQL_NULL);

2267
	if (templ->type == DATA_INT) {
2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281
		/* 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++;
		}

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

2286
		ut_ad(templ->mysql_col_len == len);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2287 2288 2289 2290 2291 2292 2293 2294 2295 2296
	} else if (templ->type == DATA_VARCHAR
	           || templ->type == DATA_VARMYSQL
		   || templ->type == DATA_BINARY) {

		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. */
2297
		
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2298 2299 2300 2301 2302
			dest = row_mysql_store_true_var_len(dest, len,
						templ->mysql_length_bytes);
		}

		/* Copy the actual data */
2303 2304
		ut_memcpy(dest, data, len);
		
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340
		/* 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. */
			
		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. */
				
				if (pad_ptr < field_end) {
					*pad_ptr = 0x20;
					pad_ptr++;
				}
			}
			
			/* 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);
		}
2341
	} else if (templ->type == DATA_BLOB) {
2342 2343 2344
		/* Store a pointer to the BLOB buffer to dest: the BLOB was
		already copied to the buffer in row_sel_store_mysql_rec */

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2345 2346
		row_mysql_store_blob_ref(dest, templ->mysql_col_len, data,
									len);
2347
	} else if (templ->type == DATA_MYSQL) {
2348 2349
		memcpy(dest, data, len);

2350 2351
		ut_a(templ->mysql_col_len >= len);
		ut_a(templ->mbmaxlen >= templ->mbminlen);
2352

2353
		ut_a(templ->mbmaxlen > templ->mbminlen
2354
			|| templ->mysql_col_len == len);
2355
		ut_a(!templ->mbmaxlen
2356
			|| !(templ->mysql_col_len % templ->mbmaxlen));
2357
		ut_a(len * templ->mbmaxlen >= templ->mysql_col_len);
2358 2359

		if (templ->mbminlen != templ->mbmaxlen) {
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2360
			/* Pad with spaces. This undoes the stripping
2361 2362
			done in row0mysql.ic, function
			row_mysql_store_col_in_innobase_format(). */
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2363

2364 2365
			memset(dest + len, 0x20, templ->mysql_col_len - len);
		}
2366 2367 2368 2369 2370 2371 2372 2373 2374
	} else {
		ut_a(templ->type == DATA_CHAR
			|| templ->type == DATA_FIXBINARY
			/*|| templ->type == DATA_SYS_CHILD
			|| templ->type == DATA_SYS*/
			|| templ->type == DATA_FLOAT
			|| templ->type == DATA_DOUBLE
			|| templ->type == DATA_DECIMAL);
		ut_ad(templ->mysql_col_len == len);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2375

2376
		memcpy(dest, data, len);
2377 2378 2379 2380 2381 2382 2383 2384 2385
	}
}

/******************************************************************
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
be needed in the query. */
static
2386
ibool
2387 2388
row_sel_store_mysql_rec(
/*====================*/
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2389 2390 2391 2392
					/* out: TRUE if success, FALSE if
					could not allocate memory for a BLOB
					(though we may also assert in that
					case) */
2393 2394
	byte*		mysql_rec,	/* out: row in the MySQL format */
	row_prebuilt_t*	prebuilt,	/* in: prebuilt struct */
marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
2395
	rec_t*		rec,		/* in: Innobase record in the index
2396 2397
					which was described in prebuilt's
					template */
marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
2398 2399
	const ulint*	offsets)	/* in: array returned by
					rec_get_offsets() */
2400
{
2401 2402
	mysql_row_templ_t*	templ;
	mem_heap_t*		extern_field_heap	= NULL;
2403 2404 2405
	byte*			data;
	ulint			len;
	byte*			blob_buf;
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2406
	int			pad_char;
2407
	ulint			i;
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2408
	
2409
	ut_ad(prebuilt->mysql_template);
marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
2410 2411
	ut_ad(rec_offs_validate(rec, NULL, offsets));

2412 2413 2414 2415 2416 2417 2418 2419 2420
	if (prebuilt->blob_heap != NULL) {
		mem_heap_free(prebuilt->blob_heap);
		prebuilt->blob_heap = NULL;
	}

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

		templ = prebuilt->mysql_template + i;

marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
2421 2422
		data = rec_get_nth_field(rec, offsets,
					templ->rec_field_no, &len);
2423

marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
2424
		if (rec_offs_nth_extern(offsets, templ->rec_field_no)) {
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2425

2426 2427 2428
			/* Copy an externally stored field to the temporary
			heap */

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2429
			ut_a(!prebuilt->trx->has_search_latch);
2430 2431 2432

			extern_field_heap = mem_heap_create(UNIV_PAGE_SIZE);

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2433 2434 2435 2436
			/* NOTE: if we are retrieving a big BLOB, we may
			already run out of memory in the next call, which
			causes an assert */

2437
			data = btr_rec_copy_externally_stored_field(rec,
marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
2438
					offsets, templ->rec_field_no, &len,
2439 2440 2441 2442 2443
					extern_field_heap);

			ut_a(len != UNIV_SQL_NULL);
		}

2444 2445 2446
		if (len != UNIV_SQL_NULL) {
			if (templ->type == DATA_BLOB) {

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2447
				ut_a(prebuilt->templ_contains_blob);
2448

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2449 2450 2451 2452
				/* A heuristic test that we can allocate the
				memory for a big BLOB. We have a safety margin
				of 1000000 bytes. Since the test takes some
				CPU time, we do not use it for small BLOBs. */
2453 2454 2455 2456

				if (len > 2000000
				    && !ut_test_malloc(len + 1000000)) {

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2457 2458 2459
					ut_print_timestamp(stderr);
					fprintf(stderr,
"  InnoDB: Warning: could not allocate %lu + 1000000 bytes to retrieve\n"
2460 2461 2462 2463 2464
"InnoDB: a big column. Table name ", (ulong) len);
					ut_print_name(stderr,
						prebuilt->trx,
						prebuilt->table->name);
					putc('\n', stderr);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2465 2466 2467 2468 2469

					if (extern_field_heap) {
						mem_heap_free(
							extern_field_heap);
					}
2470 2471 2472
					return(FALSE);
				}

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2473 2474
				/* Copy the BLOB data to the BLOB heap of
				prebuilt */
2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486

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

				blob_buf = mem_heap_alloc(prebuilt->blob_heap,
									len);
				ut_memcpy(blob_buf, data, len);

				data = blob_buf;
			}
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2487
		
2488 2489
			row_sel_field_store_in_mysql_format(
				mysql_rec + templ->mysql_col_offset,
2490
				templ, data, len);
2491

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2492
			/* Cleanup */
2493
			if (extern_field_heap) {
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2494
 				mem_heap_free(extern_field_heap);
2495
				extern_field_heap = NULL;
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2496 2497
 			}
			
2498
			if (templ->mysql_null_bit_mask) {
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2499 2500
				/* It is a nullable column with a non-NULL
				value */
2501 2502 2503
				mysql_rec[templ->mysql_null_byte_offset] &=
					~(byte) (templ->mysql_null_bit_mask);
			}
2504
		} else {
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2505
		        /* MySQL seems to assume the field for an SQL NULL
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2506 2507
		        value is set to zero or space. Not taking this into
			account caused seg faults with NULL BLOB fields, and
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2508 2509 2510
		        bug number 154 in the MySQL bug database: GROUP BY
		        and DISTINCT could treat NULL values inequal. */

2511 2512
			mysql_rec[templ->mysql_null_byte_offset] |=
					(byte) (templ->mysql_null_bit_mask);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526
			if (templ->type == DATA_VARCHAR
			    || templ->type == DATA_CHAR
			    || templ->type == DATA_BINARY
			    || templ->type == DATA_FIXBINARY
			    || templ->type == DATA_MYSQL
			    || templ->type == DATA_VARMYSQL) {
			        /* MySQL pads all non-BLOB and non-TEXT
				string types with space ' ' */
			    
				pad_char = ' ';
			} else {
				pad_char = '\0';
			}

2527
			/* Handle UCS2 strings differently. */
2528
			if (pad_char != '\0' && templ->mbminlen == 2) {
2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540
				/* There are two bytes per char, so the length
				has to be an even number. */
				ut_a(!(templ->mysql_col_len & 1));
				data = mysql_rec + templ->mysql_col_offset;
				len = templ->mysql_col_len;
				/* Pad with 0x0020. */
				while (len >= 2) {
					*data++ = 0x00;
					*data++ = 0x20;
					len -= 2;
				}
			} else {
2541
				ut_ad(!pad_char || templ->mbminlen == 1);
2542 2543 2544
				memset(mysql_rec + templ->mysql_col_offset,
					pad_char, templ->mysql_col_len);
			}
2545
		}
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2546
	} 
2547 2548

	return(TRUE);
2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561
}

/*************************************************************************
Builds a previous version of a clustered index record for a consistent read */
static
ulint
row_sel_build_prev_vers_for_mysql(
/*==============================*/
					/* out: DB_SUCCESS or error code */
	read_view_t*	read_view,	/* in: read view */
	dict_index_t*	clust_index,	/* in: clustered index */
	row_prebuilt_t*	prebuilt,	/* in: prebuilt struct */
	rec_t*		rec,		/* in: record in a clustered index */
2562 2563 2564 2565
	ulint**		offsets,	/* in/out: offsets returned by
					rec_get_offsets(rec, clust_index) */
	mem_heap_t**	offset_heap,	/* in/out: memory heap from which
					the offsets are allocated */
2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580
	rec_t**		old_vers,	/* out: old version, or NULL if the
					record does not exist in the view:
					i.e., it was freshly inserted
					afterwards */
	mtr_t*		mtr)		/* in: mtr */
{
	ulint	err;

	if (prebuilt->old_vers_heap) {
		mem_heap_empty(prebuilt->old_vers_heap);
	} else {
		prebuilt->old_vers_heap = mem_heap_create(200);
	}
	
	err = row_vers_build_for_consistent_read(rec, mtr, clust_index,
2581 2582
					offsets, read_view, offset_heap,
					prebuilt->old_vers_heap, old_vers);
2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596
	return(err);
}

/*************************************************************************
Retrieves the clustered index record corresponding to a record in a
non-clustered index. Does the necessary locking. Used in the MySQL
interface. */
static
ulint
row_sel_get_clust_rec_for_mysql(
/*============================*/
				/* out: DB_SUCCESS or error code */
	row_prebuilt_t*	prebuilt,/* in: prebuilt struct in the handle */
	dict_index_t*	sec_index,/* in: secondary index where rec resides */
2597 2598 2599 2600
	rec_t*		rec,	/* in: record in a non-clustered index; if
				this is a locking read, then rec is not
				allowed to be delete-marked, and that would
				not make sense either */
2601 2602 2603 2604 2605
	que_thr_t*	thr,	/* in: query thread */
	rec_t**		out_rec,/* out: clustered record or an old version of
				it, NULL if the old version did not exist
				in the read view, i.e., it was a fresh
				inserted version */
2606 2607 2608 2609
	ulint**		offsets,/* out: offsets returned by
				rec_get_offsets(out_rec, clust_index) */
	mem_heap_t**	offset_heap,/* in/out: memory heap from which
				the offsets are allocated */
2610 2611 2612 2613 2614 2615 2616 2617 2618
	mtr_t*		mtr)	/* in: mtr used to get access to the
				non-clustered record; the same mtr is used to
				access the clustered index */
{
	dict_index_t*	clust_index;
	rec_t*		clust_rec;
	rec_t*		old_vers;
	ulint		err;
	trx_t*		trx;
2619

2620
	*out_rec = NULL;
2621
	trx = thr_get_trx(thr);
2622
	
2623
	row_build_row_ref_in_tuple(prebuilt->clust_ref, sec_index, rec, trx);
2624 2625 2626 2627 2628 2629 2630 2631 2632

	clust_index = dict_table_get_first_index(sec_index->table);
	
	btr_pcur_open_with_no_init(clust_index, prebuilt->clust_ref,
			PAGE_CUR_LE, BTR_SEARCH_LEAF,
			prebuilt->clust_pcur, 0, mtr);

	clust_rec = btr_pcur_get_rec(prebuilt->clust_pcur);

2633 2634
	/* Note: only if the search ends up on a non-infimum record is the
	low_match value the real match to the search tuple */
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2635

2636 2637 2638
	if (!page_rec_is_user_rec(clust_rec)
	    || btr_pcur_get_low_match(prebuilt->clust_pcur)
	       < dict_index_get_n_unique(clust_index)) {
2639 2640 2641 2642 2643 2644 2645 2646 2647
	
		/* 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. */
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2648

marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
2649
		if (!rec_get_deleted_flag(rec, sec_index->table->comp)
2650 2651
		    || prebuilt->select_lock_type != LOCK_NONE) {
		        ut_print_timestamp(stderr);
2652 2653 2654
			fputs("  InnoDB: error clustered record"
				" for sec rec not found\n"
				"InnoDB: ", stderr);
2655
			dict_index_name_print(stderr, trx, sec_index);
2656 2657
			fputs("\n"
				"InnoDB: sec index record ", stderr);
2658
			rec_print(stderr, rec, sec_index);
2659 2660
			fputs("\n"
				"InnoDB: clust index record ", stderr);
2661
			rec_print(stderr, clust_rec, clust_index);
2662
			putc('\n', stderr);
2663
			trx_print(stderr, trx);
2664 2665

			fputs("\n"
2666
"InnoDB: Submit a detailed bug report to http://bugs.mysql.com\n", stderr);
2667
		}
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2668 2669 2670 2671 2672

		clust_rec = NULL;

		goto func_exit;
	}
2673

2674 2675
	*offsets = rec_get_offsets(clust_rec, clust_index, *offsets,
					ULINT_UNDEFINED, offset_heap);
marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
2676

2677
	if (prebuilt->select_lock_type != LOCK_NONE) {
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2678 2679 2680
		/* 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 */
2681 2682
		
		err = lock_clust_rec_read_check_and_lock(0, clust_rec,
2683
					clust_index, *offsets,
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2684 2685
					prebuilt->select_lock_type,
					LOCK_REC_NOT_GAP, thr);
2686 2687
		if (err != DB_SUCCESS) {

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

2694
		old_vers = NULL;
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2695 2696 2697 2698 2699 2700

		/* 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
		    && !lock_clust_rec_cons_read_sees(clust_rec, clust_index,
2701
						*offsets, trx->read_view)) {
2702 2703 2704 2705

			err = row_sel_build_prev_vers_for_mysql(
					trx->read_view, clust_index,
					prebuilt, clust_rec,
2706
					offsets, offset_heap,
2707 2708 2709 2710
					&old_vers, mtr);
						
			if (err != DB_SUCCESS) {

2711
				goto err_exit;
2712 2713 2714 2715
			}

			clust_rec = old_vers;
		}
2716 2717 2718 2719 2720 2721 2722

		/* 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
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2723
		id corresponds to it: we have to go to the clustered index
2724 2725 2726 2727 2728 2729
		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. */
		
marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
2730 2731
		if (clust_rec && (old_vers
			|| rec_get_deleted_flag(rec, sec_index->table->comp))
2732 2733 2734
		    && !row_sel_sec_rec_is_for_clust_rec(rec, sec_index,
						clust_rec, clust_index)) {
			clust_rec = NULL;
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2735 2736 2737 2738 2739 2740
		} else {
#ifdef UNIV_SEARCH_DEBUG
			ut_a(clust_rec == NULL ||
			    row_sel_sec_rec_is_for_clust_rec(rec, sec_index,
						clust_rec, clust_index));
#endif		
2741
		}
2742 2743
	}

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2744
func_exit:
2745 2746 2747 2748 2749 2750 2751 2752
	*out_rec = clust_rec;

	if (prebuilt->select_lock_type == LOCK_X) {
		/* We may use the cursor in update: store its position */
		
		btr_pcur_store_position(prebuilt->clust_pcur, mtr);
	}

2753 2754 2755
	err = DB_SUCCESS;
err_exit:
	return(err);
2756 2757 2758 2759
}

/************************************************************************
Restores cursor position after it has been stored. We have to take into
2760
account that the record cursor was positioned on may have been deleted.
2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797
Then we may have to move the cursor one step up or down. */
static
ibool
sel_restore_position_for_mysql(
/*===========================*/
					/* out: 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) */
	ulint		latch_mode,	/* in: latch mode wished in
					restoration */
	btr_pcur_t*	pcur,		/* in: cursor whose position
					has been stored */
	ibool		moves_up,	/* in: TRUE if the cursor moves up
					in the index */
	mtr_t*		mtr)		/* in: mtr; CAUTION: may commit
					mtr temporarily! */
{
	ibool	success;
	ulint	relative_position;

	relative_position = pcur->rel_pos;
	
	success = btr_pcur_restore_position(latch_mode, pcur, mtr);

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

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

		return(TRUE);
	}

2798 2799 2800
	if (relative_position == BTR_PCUR_AFTER
	    || relative_position == BTR_PCUR_AFTER_LAST_IN_TREE) {

2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811
		if (moves_up) {
			return(TRUE);
		}
					
		if (btr_pcur_is_on_user_rec(pcur, mtr)) {
			btr_pcur_move_to_prev(pcur, mtr);
		}

		return(TRUE);
	}

2812 2813
	ut_ad(relative_position == BTR_PCUR_BEFORE
	     || relative_position == BTR_PCUR_BEFORE_FIRST_IN_TREE);
2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831
	
	if (moves_up && btr_pcur_is_on_user_rec(pcur, mtr)) {
		btr_pcur_move_to_next(pcur, mtr);
	}

	return(TRUE);
}

/************************************************************************
Pops a cached row for MySQL from the fetch cache. */
UNIV_INLINE
void
row_sel_pop_cached_row_for_mysql(
/*=============================*/
	byte*		buf,		/* in/out: buffer where to copy the
					row */
	row_prebuilt_t*	prebuilt)	/* in: prebuilt struct */
{
2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849
	ulint			i;
	mysql_row_templ_t*	templ;
	byte*			cached_rec;
        ut_ad(prebuilt->n_fetch_cached > 0);
	
	if (prebuilt->keep_other_fields_on_keyread)
	{
		/* Copy cache record field by field, don't touch fields that 
		are not covered by current key */
		cached_rec = 
			prebuilt->fetch_cache[prebuilt->fetch_cache_first];

		for (i = 0; i < prebuilt->n_template; i++) {
			templ = prebuilt->mysql_template + i;
			ut_memcpy(
				buf + templ->mysql_col_offset, 
				cached_rec + templ->mysql_col_offset,
				templ->mysql_col_len);
2850
			/* Copy NULL bit of the current field from cached_rec 
2851
			to buf */
2852
			if (templ->mysql_null_bit_mask)
2853
			{
2854 2855 2856 2857
				buf[templ->mysql_null_byte_offset] ^=
				  (buf[templ->mysql_null_byte_offset] ^
				   cached_rec[templ->mysql_null_byte_offset]) &
				  (byte)templ->mysql_null_bit_mask;
2858
			}
2859 2860 2861 2862 2863 2864 2865
		}
	}
	else
	{
		ut_memcpy(buf, prebuilt->fetch_cache[prebuilt->fetch_cache_first],
				prebuilt->mysql_row_len);
	}
2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880
	prebuilt->n_fetch_cached--;
	prebuilt->fetch_cache_first++;

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

/************************************************************************
Pushes a row for MySQL to the fetch cache. */
UNIV_INLINE
void
row_sel_push_cache_row_for_mysql(
/*=============================*/
	row_prebuilt_t*	prebuilt,	/* in: prebuilt struct */
marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
2881 2882
	rec_t*		rec,		/* in: record to push */
	const ulint*	offsets)	/* in: rec_get_offsets() */
2883
{
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2884
	byte*	buf;
2885 2886 2887
	ulint	i;

	ut_ad(prebuilt->n_fetch_cached < MYSQL_FETCH_CACHE_SIZE);
marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
2888
	ut_ad(rec_offs_validate(rec, NULL, offsets));
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2889
	ut_a(!prebuilt->templ_contains_blob);
2890 2891 2892 2893 2894

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

		for (i = 0; i < MYSQL_FETCH_CACHE_SIZE; i++) {
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906

			/* A user has reported memory corruption in these
			buffers in Linux. Put magic numbers there to help
			to track a possible bug. */
			
			buf = mem_alloc(prebuilt->mysql_row_len + 8);

			prebuilt->fetch_cache[i] = buf + 4;
				
			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);
2907 2908 2909 2910 2911
		}
	}

	ut_ad(prebuilt->fetch_cache_first == 0);

2912
	if (!row_sel_store_mysql_rec(
2913
			prebuilt->fetch_cache[prebuilt->n_fetch_cached],
2914 2915 2916
			prebuilt, rec, offsets)) {
		ut_error;
	}
2917 2918 2919

	prebuilt->n_fetch_cached++;
}
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2920

2921 2922 2923
/*************************************************************************
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
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2924
mode is PAGE_CUR_GE, it is a consistent read, there is a read view in trx,
2925 2926 2927 2928 2929 2930 2931 2932
btr search latch has been locked in S-mode. */
static
ulint
row_sel_try_search_shortcut_for_mysql(
/*==================================*/
				/* out: SEL_FOUND, SEL_EXHAUSTED, SEL_RETRY */
	rec_t**		out_rec,/* out: record if found */
	row_prebuilt_t*	prebuilt,/* in: prebuilt struct */
2933 2934
	ulint**		offsets,/* in/out: for rec_get_offsets(*out_rec) */
	mem_heap_t**	heap,	/* in/out: heap for rec_get_offsets() */
2935 2936 2937 2938 2939 2940 2941 2942 2943
	mtr_t*		mtr)	/* in: started mtr */
{
	dict_index_t*	index		= prebuilt->index;
	dtuple_t*	search_tuple	= prebuilt->search_tuple;
	btr_pcur_t*	pcur		= prebuilt->pcur;
	trx_t*		trx		= prebuilt->trx;
	rec_t*		rec;
	
	ut_ad(index->type & DICT_CLUSTERED);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2944
	ut_ad(!prebuilt->templ_contains_blob);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2945
	
2946 2947
	btr_pcur_open_with_no_init(index, search_tuple, PAGE_CUR_GE,
					BTR_SEARCH_LEAF, pcur,
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2948 2949 2950 2951 2952 2953
#ifndef UNIV_SEARCH_DEBUG
					RW_S_LATCH,
#else
					0,
#endif
					mtr);
2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971
	rec = btr_pcur_get_rec(pcur);
	
	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
	fields in the user record matched to the search tuple */ 

	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 */
marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
2972

2973 2974
	*offsets = rec_get_offsets(rec, index, *offsets,
					ULINT_UNDEFINED, heap);
marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
2975 2976 2977

	if (!lock_clust_rec_cons_read_sees(rec, index,
				*offsets, trx->read_view)) {
2978 2979 2980 2981

		return(SEL_RETRY);
	}

marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
2982
	if (rec_get_deleted_flag(rec, index->table->comp)) {
2983 2984 2985 2986 2987 2988 2989 2990 2991

		return(SEL_EXHAUSTED);
	}

	*out_rec = rec;
	
	return(SEL_FOUND);
}

2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003
/************************************************************************
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
position and fetch next or fetch prev must not be tried to the cursor! */

ulint
row_search_for_mysql(
/*=================*/
					/* out: DB_SUCCESS,
					DB_RECORD_NOT_FOUND, 
3004
					DB_END_OF_INDEX, DB_DEADLOCK,
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3005
					DB_LOCK_TABLE_FULL, DB_CORRUPTION,
3006
					or DB_TOO_BIG_RECORD */
3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034
	byte*		buf,		/* in/out: buffer for the fetched
					row in the MySQL format */
	ulint		mode,		/* in: search mode PAGE_CUR_L, ... */
	row_prebuilt_t*	prebuilt,	/* in: prebuilt struct for the
					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' */
	ulint		match_mode,	/* in: 0 or ROW_SEL_EXACT or
					ROW_SEL_EXACT_PREFIX */ 
	ulint		direction)	/* in: 0 or ROW_SEL_NEXT or
					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;
	dtuple_t*	search_tuple	= prebuilt->search_tuple;
	btr_pcur_t*	pcur		= prebuilt->pcur;
	trx_t*		trx		= prebuilt->trx;
	dict_index_t*	clust_index;
	que_thr_t*	thr;
	rec_t*		rec;
	rec_t*		index_rec;
	rec_t*		clust_rec;
	rec_t*		old_vers;
3035
	ulint		err             = DB_SUCCESS;
3036 3037 3038
	ibool		moved;
	ibool		cons_read_requires_clust_rec;
	ibool		was_lock_wait;
3039
	ulint		shortcut;
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3040
	ibool		unique_search			= FALSE;
3041 3042 3043
	ibool		unique_search_from_clust_index	= FALSE;
	ibool		mtr_has_extra_clust_latch 	= FALSE;
	ibool		moves_up 			= FALSE;
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3044 3045 3046 3047 3048 3049
	ibool		set_also_gap_locks		= TRUE;
					/* if the query is a plain
					locking SELECT, and the isolation
					level is <= TRX_ISO_READ_COMMITTED,
					then this is set to FALSE */
	ibool		success;
marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
3050
	ibool		comp;
3051
	ulint		cnt				= 0;
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3052
	ulint		next_offs;
3053
	mtr_t		mtr;
3054
	mem_heap_t*	heap				= NULL;
3055
	ulint		offsets_[REC_OFFS_NORMAL_SIZE];
3056
	ulint*		offsets				= offsets_;
3057 3058
	*offsets_ = (sizeof offsets_) / sizeof *offsets_;

3059 3060
	ut_ad(index && pcur && search_tuple);
	ut_ad(trx->mysql_thread_id == os_thread_get_curr_id());
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075

	if (prebuilt->table->ibd_file_missing) {
	        ut_print_timestamp(stderr);
	        fprintf(stderr, "  InnoDB: Error:\n"
"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"
"http://dev.mysql.com/doc/mysql/en/InnoDB_troubleshooting_datadict.html\n"
"InnoDB: how you can resolve the problem.\n",
				prebuilt->table->name);
		return(DB_ERROR);
	}

heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
3076 3077 3078
	if (prebuilt->magic_n != ROW_PREBUILT_ALLOCATED) {
		fprintf(stderr,
		"InnoDB: Error: trying to free a corrupt\n"
3079
		"InnoDB: table handle. Magic n %lu, table name ",
monty@mishka.local's avatar
monty@mishka.local committed
3080
		(ulong) prebuilt->magic_n);
3081
		ut_print_name(stderr, trx, prebuilt->table->name);
3082
		putc('\n', stderr);
heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
3083 3084 3085

		mem_analyze_corruption((byte*)prebuilt);

3086
		ut_error;
heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
3087 3088
	}

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3089 3090 3091 3092 3093 3094 3095
	if (trx->n_mysql_tables_in_use == 0
            && prebuilt->select_lock_type == LOCK_NONE) {
		/* 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. */

monty@mishka.local's avatar
monty@mishka.local committed
3096
		fputs(
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3097
"InnoDB: Error: MySQL is trying to perform a SELECT\n"
monty@mishka.local's avatar
monty@mishka.local committed
3098 3099 3100 3101
"InnoDB: but it has not locked any tables in ::external_lock()!\n",
                      stderr);
		trx_print(stderr, trx);
                fputc('\n', stderr);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3102 3103
	}

monty@mishka.local's avatar
monty@mishka.local committed
3104
/*	fprintf(stderr, "Match mode %lu\n search tuple ", (ulong) match_mode);
3105 3106
	dtuple_print(search_tuple);
	
3107
	fprintf(stderr, "N tables locked %lu\n", trx->mysql_n_tables_locked);
3108
*/
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126
	/*-------------------------------------------------------------*/
	/* PHASE 0: Release a possible s-latch we are holding on the
	adaptive hash index latch if there is someone waiting behind */

	if (trx->has_search_latch
	    && btr_search_latch.writer != RW_LOCK_NOT_LOCKED) {

		/* 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;
	}
	
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3127 3128 3129
	/*-------------------------------------------------------------*/
	/* PHASE 1: Try to pop the row from the prefetch cache */

3130
	if (direction == 0) {
marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
3131
		trx->op_info = "starting index read";
3132
	
3133 3134 3135 3136 3137 3138 3139 3140 3141
		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 {
marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
3142
		trx->op_info = "fetching rows";
3143

3144 3145 3146 3147 3148 3149
		if (prebuilt->n_rows_fetched == 0) {
			prebuilt->fetch_direction = direction;
		}

		if (direction != prebuilt->fetch_direction) {
			if (prebuilt->n_fetch_cached > 0) {
3150
				ut_error;
3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165
				/* TODO: scrollable cursor: restore cursor to
				the place of the latest returned row,
				or better: prevent caching for a scroll
				cursor! */
			}
		
			prebuilt->n_rows_fetched = 0;
			prebuilt->n_fetch_cached = 0;
			prebuilt->fetch_cache_first = 0;

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

			prebuilt->n_rows_fetched++;

3166
			srv_n_rows_read++;
3167 3168
			err = DB_SUCCESS;
			goto func_exit;
3169 3170 3171 3172 3173 3174 3175 3176
		}

		if (prebuilt->fetch_cache_first > 0
		    && prebuilt->fetch_cache_first < MYSQL_FETCH_CACHE_SIZE) {

		    	/* 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 */
3177 3178 3179

			err = DB_RECORD_NOT_FOUND;
			goto func_exit;
3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191
		}
		
		prebuilt->n_rows_fetched++;

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

		mode = pcur->search_mode;
	}

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3192
	/* In a search where at most one record in the index may match, we
3193
	can use a LOCK_REC_NOT_GAP type record lock when locking a non-delete-
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3194 3195
	marked matching record.

3196
	Note that in a unique secondary index there may be different delete-
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3197 3198
	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
3199
	delete-marked records. */
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3200 3201
	
	if (match_mode == ROW_SEL_EXACT
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3202 3203
	    && index->type & DICT_UNIQUE
	    && dtuple_get_n_fields(search_tuple)
3204 3205 3206 3207 3208 3209 3210 3211 3212 3213
					== dict_index_get_n_unique(index)
	    && (index->type & DICT_CLUSTERED
		 || !dtuple_contains_null(search_tuple))) {

		/* Note above that a UNIQUE secondary index can contain many
		rows with the same key value if one of the columns is the SQL
		null. A clustered index under MySQL can never contain null
		columns because we demand that all the columns in primary key
		are non-null. */

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3214
		unique_search = TRUE;
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3215 3216 3217 3218 3219 3220 3221 3222

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

		if (direction != 0 && !prebuilt->used_in_HANDLER) {
        
3223 3224
			err = DB_RECORD_NOT_FOUND;
			goto func_exit;
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3225
		}
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3226 3227
	}

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3228 3229
	mtr_start(&mtr);

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3230 3231 3232 3233 3234 3235 3236 3237 3238
	/*-------------------------------------------------------------*/
	/* 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 */

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3239
	if (unique_search
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3240
	    && index->type & DICT_CLUSTERED
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3241
	    && direction == 0
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3242
	    && !prebuilt->templ_contains_blob
3243
	    && !prebuilt->used_in_HANDLER
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3244
	    && (prebuilt->mysql_row_len < UNIV_PAGE_SIZE / 8)) {
3245 3246 3247 3248

		mode = PAGE_CUR_GE;

		unique_search_from_clust_index = TRUE;
3249

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3250 3251
		if (trx->mysql_n_tables_locked == 0
		    && prebuilt->select_lock_type == LOCK_NONE
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3252 3253
		    && trx->isolation_level > TRX_ISO_READ_UNCOMMITTED
		    && trx->read_view) {
3254 3255 3256 3257

			/* 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
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3258 3259 3260 3261 3262 3263 3264 3265
			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! */
3266

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3267
#ifndef UNIV_SEARCH_DEBUG			
3268 3269 3270 3271
			if (!trx->has_search_latch) {
				rw_lock_s_lock(&btr_search_latch);
				trx->has_search_latch = TRUE;
			}
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3272
#endif
3273
			shortcut = row_sel_try_search_shortcut_for_mysql(&rec,
3274
					prebuilt, &offsets, &heap, &mtr);
3275
			if (shortcut == SEL_FOUND) {
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3276
#ifdef UNIV_SEARCH_DEBUG
marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
3277 3278
				ut_a(0 == cmp_dtuple_rec(search_tuple,
							rec, offsets));
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3279
#endif 
3280
				if (!row_sel_store_mysql_rec(buf, prebuilt,
marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
3281
							rec, offsets)) {
3282 3283
 					err = DB_TOO_BIG_RECORD;

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3284 3285 3286
					/* We let the main loop to do the
					error handling */
 					goto shortcut_fails_too_big_rec;
3287
				}
3288 3289 3290
	
 				mtr_commit(&mtr);

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

3294
				srv_n_rows_read++;
3295 3296 3297
				
				if (trx->search_latch_timeout > 0
				    && trx->has_search_latch) {
3298

3299 3300 3301 3302 3303 3304
					trx->search_latch_timeout--;

			        	rw_lock_s_unlock(&btr_search_latch);
					trx->has_search_latch = FALSE;
				}    	
				
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3305 3306
				/* NOTE that we do NOT store the cursor
				position */
3307 3308
				err = DB_SUCCESS;
				goto func_exit;
3309 3310 3311 3312 3313
			
			} else if (shortcut == SEL_EXHAUSTED) {

 				mtr_commit(&mtr);

3314 3315
				/* ut_print_name(stderr, index->name);
				fputs(" record not found 2\n", stderr); */
3316 3317 3318 3319 3320 3321 3322 3323 3324 3325

				if (trx->search_latch_timeout > 0
				    && trx->has_search_latch) {

					trx->search_latch_timeout--;

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

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3326 3327 3328
				/* NOTE that we do NOT store the cursor
				position */

3329 3330
				err = DB_RECORD_NOT_FOUND;
				goto func_exit;
3331
			}
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3332
shortcut_fails_too_big_rec:
3333 3334
			mtr_commit(&mtr);
			mtr_start(&mtr);
3335
		}
3336
	}
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3337 3338 3339 3340

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

3341 3342 3343 3344 3345
	if (trx->has_search_latch) {
		rw_lock_s_unlock(&btr_search_latch);
		trx->has_search_latch = FALSE;
	}			

monty@donna.mysql.fi's avatar
Merge  
monty@donna.mysql.fi committed
3346
	trx_start_if_not_started(trx);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363

	if (trx->isolation_level <= TRX_ISO_READ_COMMITTED
	    && prebuilt->select_lock_type != LOCK_NONE
	    && trx->mysql_query_str) {

		/* Scan the MySQL query string; check if SELECT is the first
	        word there */

		dict_accept(*trx->mysql_query_str, "SELECT", &success);

		if (success) {
			/* It is a plain locking SELECT and the isolation
			level is low: do not lock gaps */

			set_also_gap_locks = FALSE;
		}
	}
monty@donna.mysql.fi's avatar
Merge  
monty@donna.mysql.fi committed
3364
	
3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407
	/* Note that if the search mode was GE or G, then the cursor
	naturally moves upward (in fetch next) in alphabetical order,
	otherwise downward */
	
	if (direction == 0) {
		if (mode == PAGE_CUR_GE || mode == PAGE_CUR_G) {
			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 (direction != 0) {		
		moved = sel_restore_position_for_mysql(BTR_SEARCH_LEAF, pcur,
							moves_up, &mtr);
		if (!moved) {
			goto next_rec;
		}

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

		btr_pcur_open_with_no_init(index, search_tuple, mode,
					BTR_SEARCH_LEAF,
					pcur, 0, &mtr);
	} else {
		if (mode == PAGE_CUR_G) {
			btr_pcur_open_at_index_side(TRUE, index,
					BTR_SEARCH_LEAF, pcur, FALSE, &mtr);
		} else if (mode == PAGE_CUR_L) {
			btr_pcur_open_at_index_side(FALSE, index,
					BTR_SEARCH_LEAF, pcur, FALSE, &mtr);
		}
	}

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

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3408 3409
		if (trx->read_view == NULL
		    && prebuilt->select_lock_type == LOCK_NONE) {
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3410

monty@mishka.local's avatar
monty@mishka.local committed
3411
			fputs(
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3412
"InnoDB: Error: MySQL is trying to perform a consistent read\n"
monty@mishka.local's avatar
monty@mishka.local committed
3413 3414 3415
"InnoDB: but the read view is not assigned!\n", stderr);
			trx_print(stderr, trx);
                        fputc('\n', stderr);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3416 3417
			ut_a(0);
		}
3418
	} else if (prebuilt->select_lock_type == LOCK_NONE) {
monty@donna.mysql.fi's avatar
Merge  
monty@donna.mysql.fi committed
3419
		/* This is a consistent read */	
3420 3421 3422 3423
		/* Assign a read view for the query */

		trx_assign_read_view(trx);
		prebuilt->sql_stat_start = FALSE;
monty@donna.mysql.fi's avatar
Merge  
monty@donna.mysql.fi committed
3424
	} else {
3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438
		if (prebuilt->select_lock_type == LOCK_S) {		
			err = lock_table(0, index->table, LOCK_IS, thr);
		} else {
			err = lock_table(0, index->table, LOCK_IX, thr);
		}

		if (err != DB_SUCCESS) {

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

rec_loop:
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3439 3440 3441
	/*-------------------------------------------------------------*/
	/* PHASE 4: Look for matching records in a loop */
	
3442
	rec = btr_pcur_get_rec(pcur);
marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
3443 3444
	comp = index->table->comp;
	ut_ad(comp == page_is_comp(buf_frame_align(rec)));
3445
/*
3446 3447 3448
	fputs("Using ", stderr);
	dict_index_name_print(stderr, index);
	fprintf(stderr, " cnt %lu ; Page no %lu\n", cnt,
3449 3450 3451
			buf_frame_get_page_no(buf_frame_align(rec)));
	rec_print(rec);
*/
3452 3453 3454 3455 3456 3457 3458 3459 3460
	if (rec == page_get_infimum_rec(buf_frame_align(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;
	}

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3461
	if (rec == page_get_supremum_rec(buf_frame_align(rec))) {
3462

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3463 3464
		if (prebuilt->select_lock_type != LOCK_NONE
		    && set_also_gap_locks) {
3465

3466
			/* Try to place a lock on the index record */
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3467

3468 3469 3470 3471
			/* If innodb_locks_unsafe_for_binlog option is used,
			we do not lock gaps. Supremum record is really
			a gap and therefore we do not set locks there. */
			
3472 3473 3474
			if (!srv_locks_unsafe_for_binlog) {
				offsets = rec_get_offsets(rec, index, offsets,
						ULINT_UNDEFINED, &heap);
marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
3475
				err = sel_set_rec_lock(rec, index, offsets,
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3476 3477
						prebuilt->select_lock_type,
						LOCK_ORDINARY, thr);
3478
			}
3479 3480

			if (err != DB_SUCCESS) {
3481

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3482 3483 3484
				goto lock_wait_or_error;
			}
		}
3485
		/* A page supremum record cannot be in the result set: skip
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3486
		it now that we have placed a possible lock on it */
3487 3488 3489 3490
		
		goto next_rec;
	}

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3491 3492 3493 3494
	/*-------------------------------------------------------------*/
	/* Do sanity checks in case our cursor has bumped into page
	corruption */
	
marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
3495
	next_offs = rec_get_next_offs(rec, comp);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3496

marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
3497 3498 3499
	if (next_offs >= UNIV_PAGE_SIZE
		|| next_offs <
		(ulint) (comp ? PAGE_NEW_SUPREMUM : PAGE_OLD_SUPREMUM)) {
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3500 3501 3502

		if (srv_force_recovery == 0 || moves_up == FALSE) {
			ut_print_timestamp(stderr);
3503
			buf_page_print(buf_frame_align(rec));
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3504
			fprintf(stderr,
3505 3506 3507 3508
"\nInnoDB: rec address %p, first buffer frame %p\n"
"InnoDB: buffer pool high end %p, buf block fix count %lu\n",
				rec, buf_pool->frame_zero,
				buf_pool->high_end,
3509
				(ulong)buf_block_align(rec)->buf_fix_count);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3510
			fprintf(stderr,
3511
"InnoDB: Index corruption: rec offs %lu next offs %lu, page no %lu,\n"
3512
"InnoDB: ",
monty@mishka.local's avatar
monty@mishka.local committed
3513 3514 3515
				(ulong) (rec - buf_frame_align(rec)),
				(ulong) next_offs,
				(ulong) buf_frame_get_page_no(rec));
3516
			dict_index_name_print(stderr, trx, index);
3517
			fputs(". Run CHECK TABLE. You may need to\n"
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3518
"InnoDB: restore from a backup, or dump + drop + reimport the table.\n",
monty@mishka.local's avatar
monty@mishka.local committed
3519
			      stderr);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3520 3521 3522 3523 3524 3525 3526 3527 3528 3529
		
			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,
"InnoDB: Index corruption: rec offs %lu next offs %lu, page no %lu,\n"
3530
"InnoDB: ",
3531 3532
			   (ulong) (rec - buf_frame_align(rec)),
			   (ulong) next_offs,
monty@mishka.local's avatar
monty@mishka.local committed
3533
			   (ulong) buf_frame_get_page_no(rec));
3534
			dict_index_name_print(stderr, trx, index);
3535 3536
			fputs(". We try to skip the rest of the page.\n",
				stderr);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3537 3538 3539 3540 3541 3542 3543

			btr_pcur_move_to_last_on_page(pcur, &mtr);

			goto next_rec;
		}
	}

3544
	offsets = rec_get_offsets(rec, index, offsets, ULINT_UNDEFINED, &heap);
marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
3545

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3546
	if (srv_force_recovery > 0) {
marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
3547 3548
		if (!rec_validate(rec, offsets)
		|| !btr_index_rec_validate(rec, index, FALSE)) {
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3549
			fprintf(stderr,
3550 3551
"InnoDB: Index corruption: rec offs %lu next offs %lu, page no %lu,\n"
"InnoDB: ",
3552 3553
			   (ulong) (rec - buf_frame_align(rec)),
			   (ulong) next_offs,
monty@mishka.local's avatar
monty@mishka.local committed
3554
			   (ulong) buf_frame_get_page_no(rec));
3555
			dict_index_name_print(stderr, trx, index);
3556 3557
			fputs(". We try to skip the record.\n",
				stderr);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3558 3559 3560 3561 3562 3563

			goto next_rec;
		}
	}

	/*-------------------------------------------------------------*/
3564

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3565 3566 3567 3568
	/* 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. */
3569

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3570
	if (match_mode == ROW_SEL_EXACT) {
3571 3572 3573
		/* Test if the index record matches completely to search_tuple
		in prebuilt: if not, then we return with DB_RECORD_NOT_FOUND */

3574
		/* fputs("Comparing rec and search tuple\n", stderr); */
3575
		
marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
3576
		if (0 != cmp_dtuple_rec(search_tuple, rec, offsets)) {
3577

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3578 3579 3580
			if (prebuilt->select_lock_type != LOCK_NONE
		    	    && set_also_gap_locks) {

3581 3582 3583 3584 3585 3586 3587
				/* Try to place a gap lock on the index 
				record only if innodb_locks_unsafe_for_binlog
				option is not set */

				if (srv_locks_unsafe_for_binlog == FALSE) { 

					err = sel_set_rec_lock(rec, index,
marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
3588
						offsets,
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3589 3590
						prebuilt->select_lock_type,
						LOCK_GAP, thr);
3591 3592
				}

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3593 3594 3595 3596 3597 3598
				if (err != DB_SUCCESS) {

					goto lock_wait_or_error;
				}
			}

3599 3600
			btr_pcur_store_position(pcur, &mtr);

3601
			err = DB_RECORD_NOT_FOUND;
3602 3603
			/* ut_print_name(stderr, index->name);
			fputs(" record not found 3\n", stderr); */
3604
			
3605 3606 3607 3608 3609
			goto normal_return;
		}

	} else if (match_mode == ROW_SEL_EXACT_PREFIX) {

marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
3610
		if (!cmp_dtuple_is_prefix_of_rec(search_tuple, rec, offsets)) {
3611
			
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3612 3613 3614
			if (prebuilt->select_lock_type != LOCK_NONE
			    && set_also_gap_locks) {

3615 3616 3617 3618 3619 3620 3621
				/* Try to place a gap lock on the index 
				record only if innodb_locks_unsafe_for_binlog
				option is not set */

				if (srv_locks_unsafe_for_binlog == FALSE) {

					err = sel_set_rec_lock(rec, index,
marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
3622
						offsets,
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3623 3624
						prebuilt->select_lock_type,
						LOCK_GAP, thr);
3625 3626
				}

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3627 3628 3629 3630 3631 3632
				if (err != DB_SUCCESS) {

					goto lock_wait_or_error;
				}
			}

3633 3634
			btr_pcur_store_position(pcur, &mtr);

3635
			err = DB_RECORD_NOT_FOUND;
3636 3637
			/* ut_print_name(stderr, index->name);
			fputs(" record not found 4\n", stderr); */
3638 3639 3640 3641 3642 3643 3644 3645

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

3646 3647
	cons_read_requires_clust_rec = FALSE;

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3648 3649 3650 3651 3652 3653
	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. */

marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
3654 3655
		ulint	lock_type;

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3656
		if (!set_also_gap_locks
marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
3657 3658
		    || (unique_search && !rec_get_deleted_flag(rec, comp))) {
			lock_type = LOCK_REC_NOT_GAP;
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3659
		} else {
3660
			/* If innodb_locks_unsafe_for_binlog option is used, 
marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
3661
			we lock only the record, i.e., next-key locking is
3662 3663
			not used. */

marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
3664 3665
	                if (srv_locks_unsafe_for_binlog) {
				lock_type = LOCK_REC_NOT_GAP;
3666
			} else {
marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
3667 3668
				lock_type = LOCK_ORDINARY;
 			}
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3669
		}
marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
3670 3671 3672 3673 3674

		err = sel_set_rec_lock(rec, index, offsets,
					prebuilt->select_lock_type,
					lock_type, thr);

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3675
		if (err != DB_SUCCESS) {
3676

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3677 3678 3679
			goto lock_wait_or_error;
		}
	} else {
3680 3681 3682
		/* This is a non-locking consistent read: if necessary, fetch
		a previous version of the record */

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3683 3684 3685 3686 3687 3688
		if (trx->isolation_level == TRX_ISO_READ_UNCOMMITTED) {

			/* Do nothing: we let a non-locking SELECT read the
			latest version of the record */
		
		} else if (index == clust_index) {
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3689
			  
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3690 3691 3692 3693 3694 3695
			/* Fetch a previous version of the row if the current
			one is not visible in the snapshot; if we have a very
			high force recovery level set, we try to avoid crashes
			by skipping this lookup */

			if (srv_force_recovery < 5
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3696
                            && !lock_clust_rec_cons_read_sees(rec, index,
marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
3697
						offsets, trx->read_view)) {
3698 3699 3700 3701

				err = row_sel_build_prev_vers_for_mysql(
						trx->read_view, clust_index,
						prebuilt, rec,
3702
						&offsets, &heap,
3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730
						&old_vers, &mtr);
						
				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;
			}
		} else if (!lock_sec_rec_cons_read_sees(rec, index,
							trx->read_view)) {
			/* 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. */
			
			cons_read_requires_clust_rec = TRUE;
		}
	}

marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
3731 3732
	if (rec_get_deleted_flag(rec, comp)
			&& !cons_read_requires_clust_rec) {
3733

3734
		/* The record is delete-marked: we can skip it if this is
3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745
		not a consistent read which might see an earlier version
		of a non-clustered index record */
		
		goto next_rec;
	}

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

	index_rec = rec;

marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
3746 3747 3748 3749 3750 3751
	/* Before and after the following "if" block, "offsets" will be
	related to "rec", which may be in "index", a secondary index or
	the clustered index ("clust_index").  However, after this "if" block,
	"rec" may be pointing to "clust_rec" of "clust_index". */
	ut_ad(rec_offs_validate(rec, index, offsets));

3752 3753 3754 3755 3756 3757 3758 3759 3760
	if (index != clust_index && (cons_read_requires_clust_rec
				|| prebuilt->need_to_access_clustered)) {

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

		mtr_has_extra_clust_latch = TRUE;
		
		err = row_sel_get_clust_rec_for_mysql(prebuilt, index, rec,
3761 3762
							thr, &clust_rec,
							&offsets, &heap, &mtr);
3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774
		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;
		}

marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
3775
		if (rec_get_deleted_flag(clust_rec, comp)) {
3776 3777 3778 3779 3780

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

			goto next_rec;
		}
3781 3782 3783
		
		if (prebuilt->need_to_access_clustered) {
		        rec = clust_rec;
3784 3785 3786
			ut_ad(rec_offs_validate(rec, clust_index, offsets));
		} else {
			offsets = rec_get_offsets(rec, index, offsets,
3787
						ULINT_UNDEFINED, &heap);
3788
		}
marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
3789 3790
	}

3791
	/* We found a qualifying row */
3792 3793 3794 3795
	ut_ad(rec_offs_validate(rec,
				rec == clust_rec ? clust_index : index,
				offsets));

3796 3797
	if (prebuilt->n_rows_fetched >= MYSQL_FETCH_CACHE_THRESHOLD
			&& prebuilt->select_lock_type == LOCK_NONE
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3798
			&& !prebuilt->templ_contains_blob
3799
			&& !prebuilt->clust_index_was_generated
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3800
			&& !prebuilt->used_in_HANDLER
3801 3802
	                && prebuilt->template_type
	                                 != ROW_MYSQL_DUMMY_TEMPLATE) {
3803 3804 3805

		/* Inside an update, for example, we do not cache rows,
		since we may use the cursor position to do the actual
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3806 3807 3808
		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
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3809 3810 3811
		are BLOBs in the fields to be fetched. In HANDLER we do
		not cache rows because there the cursor is a scrollable
		cursor. */
3812

marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
3813
		row_sel_push_cache_row_for_mysql(prebuilt, rec, offsets);
3814 3815 3816 3817 3818 3819 3820 3821

		if (prebuilt->n_fetch_cached == MYSQL_FETCH_CACHE_SIZE) {
			
			goto got_row;
		}

		goto next_rec;
	} else {
3822
		if (prebuilt->template_type == ROW_MYSQL_DUMMY_TEMPLATE) {
marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
3823 3824 3825 3826
			memcpy(buf + 4, rec - rec_offs_extra_size(offsets),
					rec_offs_size(offsets));
			mach_write_to_4(buf,
					rec_offs_extra_size(offsets) + 4);
3827
		} else {
marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
3828 3829
			if (!row_sel_store_mysql_rec(buf, prebuilt,
							rec, offsets)) {
3830 3831 3832 3833
				err = DB_TOO_BIG_RECORD;

				goto lock_wait_or_error;
			}
3834
		}
3835 3836

		if (prebuilt->clust_index_was_generated) {
3837 3838 3839
			if (rec != index_rec) {
				offsets = rec_get_offsets(
						index_rec, index, offsets,
3840
						ULINT_UNDEFINED, &heap);
3841
			}
3842
			row_sel_store_row_id_to_prebuilt(prebuilt, index_rec,
marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
3843
							index, offsets);
3844 3845 3846
		}
	}
got_row:
3847 3848 3849 3850 3851 3852
	/* We have an optimization to save CPU time: if this is a consistent
	read on a unique condition on the clustered index, then we do not
	store the pcur position, because any fetch next or prev will anyway
	return 'end of file'. An exception is the MySQL HANDLER command
	where the user can move the cursor with PREV or NEXT even after
	a unique search. */
3853 3854

	if (!unique_search_from_clust_index
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3855 3856
	    || prebuilt->select_lock_type == LOCK_X
	    || prebuilt->used_in_HANDLER) {
3857 3858 3859 3860 3861 3862

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

		btr_pcur_store_position(pcur, &mtr);
	}

3863
	err = DB_SUCCESS;
3864 3865

	goto normal_return;
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3866

3867
next_rec:
3868
	/*-------------------------------------------------------------*/
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3869 3870
	/* PHASE 5: Move the cursor to the next index record */
	
3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885
	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. */

		btr_pcur_store_position(pcur, &mtr);

		mtr_commit(&mtr);
		mtr_has_extra_clust_latch = FALSE;
	
		mtr_start(&mtr);
		moved = sel_restore_position_for_mysql(BTR_SEARCH_LEAF, pcur,
							moves_up, &mtr);
		if (moved) {
3886 3887
			cnt++;

3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901
			goto rec_loop;
		}
	}

	if (moves_up) {		
		moved = btr_pcur_move_to_next(pcur, &mtr);
	} else {
		moved = btr_pcur_move_to_prev(pcur, &mtr);
	}

	if (!moved) {
		btr_pcur_store_position(pcur, &mtr);

		if (match_mode != 0) {
3902
			err = DB_RECORD_NOT_FOUND;
3903
		} else {
3904
			err = DB_END_OF_INDEX;
3905 3906 3907 3908 3909
		}

		goto normal_return;
	}

3910 3911
	cnt++;

3912
	goto rec_loop;
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3913

3914
lock_wait_or_error:
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3915 3916
	/*-------------------------------------------------------------*/

3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927
	btr_pcur_store_position(pcur, &mtr);

	mtr_commit(&mtr);
	mtr_has_extra_clust_latch = FALSE;
		
	trx->error_state = err;

	/* The following is a patch for MySQL */

	que_thr_stop_for_mysql(thr);

vtkachenko@intelp4d.mysql.com's avatar
vtkachenko@intelp4d.mysql.com committed
3928
  thr->lock_state= QUE_THR_LOCK_ROW;
3929
	was_lock_wait = row_mysql_handle_errors(&err, trx, thr, NULL);
vtkachenko@intelp4d.mysql.com's avatar
vtkachenko@intelp4d.mysql.com committed
3930
  thr->lock_state= QUE_THR_LOCK_NOLOCK;
vtkachenko@intelp4d.mysql.com's avatar
vtkachenko@intelp4d.mysql.com committed
3931

3932 3933 3934 3935 3936 3937 3938 3939 3940
	if (was_lock_wait) {
		mtr_start(&mtr);

		sel_restore_position_for_mysql(BTR_SEARCH_LEAF, pcur,
							moves_up, &mtr);
		mode = pcur->search_mode;

		goto rec_loop;
	}
3941

3942 3943 3944
/*	fputs("Using ", stderr);
	dict_index_name_print(stderr, index);
	fprintf(stderr, " cnt %lu ret value %lu err\n", cnt, err); */
3945
	goto func_exit;
3946 3947

normal_return:
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3948
	/*-------------------------------------------------------------*/
3949 3950 3951 3952 3953 3954 3955
	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);

3956
		err = DB_SUCCESS;
3957 3958
	}

3959 3960 3961
/*	fputs("Using ", stderr);
	dict_index_name_print(stderr, index);
	fprintf(stderr, " cnt %lu ret value %lu err\n", cnt, err); */
3962
	if (err == DB_SUCCESS) {
3963 3964 3965
		srv_n_rows_read++;
	}

3966
func_exit:
marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
3967
	trx->op_info = "";
3968 3969 3970 3971
	if (heap) {
		mem_heap_free(heap);
	}
	return(err);
3972
}
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3973 3974 3975 3976 3977 3978 3979 3980

/***********************************************************************
Checks if MySQL at the moment is allowed for this table to retrieve a
consistent read result, or store it to the query cache. */

ibool
row_search_check_if_query_cache_permitted(
/*======================================*/
3981 3982 3983 3984 3985
					/* out: TRUE if storing or retrieving
					from the query cache is permitted */
	trx_t*		trx,		/* in: transaction object */
	const char*	norm_name)	/* in: concatenation of database name,
					'/' char, table name */
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012
{
	dict_table_t*	table;
	ibool		ret 	= FALSE;

	table = dict_table_get(norm_name, trx);

	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
	    && ut_dulint_cmp(trx->id, table->query_cache_inv_trx_id) >= 0) {

		ret = TRUE;
		
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
4013 4014 4015 4016 4017
		/* 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
		    && !trx->read_view) {
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
4018 4019 4020 4021 4022 4023 4024 4025 4026 4027

			trx->read_view = read_view_open_now(trx,
						trx->read_view_heap);
		}
	}
	
	mutex_exit(&kernel_mutex);

	return(ret);
}