<commit_before>/******************************************************
Insert into a table

(c) 1996 <NAME>

Created 4/20/1996 <NAME>
*******************************************************/

#include "row0ins.h"

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

#include "dict0dict.h"
#include "dict0boot.h"
#include "trx0undo.h"
#include "btr0btr.h"
#include "btr0cur.h"
#include "mach0data.h"
#include "que0que.h"
#include "row0upd.h"
#include "row0sel.h"
#include "row0row.h"
#include "rem0cmp.h"
#include "lock0lock.h"
#include "log0log.h"
#include "eval0eval.h"
#include "data0data.h"
#include "usr0sess.h"

#define	ROW_INS_PREV	1
#define	ROW_INS_NEXT	2


/*********************************************************************
This prototype is copied from /mysql/sql/ha_innodb.cc.
Invalidates the MySQL query cache for the table.
NOTE that the exact prototype of this function has to be in
/innobase/row/row0ins.c! */
extern
void
innobase_invalidate_query_cache(
/*============================*/
	trx_t*	trx,		/* in: transaction which modifies the table */
	char*	full_name,	/* in: concatenation of database name, null
				char '\0', table name, null char'\0';
				NOTE that in Windows this is always
				in LOWER CASE! */
	ulint	full_name_len);	/* in: full name length where also the null
				chars count */

/**********************************************************************
This function returns true if 

1) SQL-query in the current thread
is either REPLACE or LOAD DATA INFILE REPLACE. 

2) SQL-query in the current thread
is INSERT ON DUPLICATE KEY UPDATE.

NOTE that /mysql/innobase/row/row0ins.c must contain the 
prototype for this function ! */

ibool
innobase_query_is_update(void);

/*************************************************************************
Creates an insert node struct. */

ins_node_t*
ins_node_create(
/*============*/
					/* out, own: insert node struct */
	ulint		ins_type,	/* in: INS_VALUES, ... */
	dict_table_t*	table, 		/* in: table where to insert */
	mem_heap_t*	heap)		/* in: mem heap where created */
{
	ins_node_t*	node;

	node = mem_heap_alloc(heap, sizeof(ins_node_t));

	node->common.type = QUE_NODE_INSERT;

	node->ins_type = ins_type;

	node->state = INS_NODE_SET_IX_LOCK;
	node->table = table;
	node->index = NULL;
	node->entry = NULL;

	node->select = NULL;
	
	node->trx_id = ut_dulint_zero;
	
	node->entry_sys_heap = mem_heap_create(128);

	node->magic_n = INS_NODE_MAGIC_N;	
	
	return(node);
}

/***************************************************************
Creates an entry template for each index of a table. */
static
void
ins_node_create_entry_list(
/*=======================*/
	ins_node_t*	node)	/* in: row insert node */
{
	dict_index_t*	index;
	dtuple_t*	entry;

	ut_ad(node->entry_sys_heap);

	UT_LIST_INIT(node->entry_list);

	index = dict_table_get_first_index(node->table);
	
	while (index != NULL) {
		entry = row_build_index_entry(node->row, index,
							node->entry_sys_heap);
		UT_LIST_ADD_LAST(tuple_list, node->entry_list, entry);

		index = dict_table_get_next_index(index);
	}
}

/*********************************************************************
Adds system field buffers to a row. */
static
void
row_ins_alloc_sys_fields(
/*=====================*/
	ins_node_t*	node)	/* in: insert node */
{
	dtuple_t*	row;
	dict_table_t*	table;
	mem_heap_t*	heap;
	dict_col_t*	col;
	dfield_t*	dfield;
	ulint		len;
	byte*		ptr;

	row = node->row;
	table = node->table;
	heap = node->entry_sys_heap;

	ut_ad(row && table && heap);
	ut_ad(dtuple_get_n_fields(row) == dict_table_get_n_cols(table));

	/* 1. Allocate buffer for row id */

	col = dict_table_get_sys_col(table, DATA_ROW_ID);
	
	dfield = dtuple_get_nth_field(row, dict_col_get_no(col));

	ptr = mem_heap_alloc(heap, DATA_ROW_ID_LEN);
				
	dfield_set_data(dfield, ptr, DATA_ROW_ID_LEN);

	node->row_id_buf = ptr;

	if (table->type == DICT_TABLE_CLUSTER_MEMBER) {

		/* 2. Fill in the dfield for mix id */

		col = dict_table_get_sys_col(table, DATA_MIX_ID);
	
		dfield = dtuple_get_nth_field(row, dict_col_get_no(col));

		len = mach_dulint_get_compressed_size(table->mix_id);
		ptr = mem_heap_alloc(heap, DATA_MIX_ID_LEN);
				
		mach_dulint_write_compressed(ptr, table->mix_id);
		dfield_set_data(dfield, ptr, len);
	}

	/* 3. Allocate buffer for trx id */

	col = dict_table_get_sys_col(table, DATA_TRX_ID);
	
	dfield = dtuple_get_nth_field(row, dict_col_get_no(col));
	ptr = mem_heap_alloc(heap, DATA_TRX_ID_LEN);
				
	dfield_set_data(dfield, ptr, DATA_TRX_ID_LEN);

	node->trx_id_buf = ptr;

	/* 4. Allocate buffer for roll ptr */

	col = dict_table_get_sys_col(table, DATA_ROLL_PTR);
	
	dfield = dtuple_get_nth_field(row, dict_col_get_no(col));
	ptr = mem_heap_alloc(heap, DATA_ROLL_PTR_LEN);
				
	dfield_set_data(dfield, ptr, DATA_ROLL_PTR_LEN);
}

/*************************************************************************
Sets a new row to insert for an INS_DIRECT node. This function is only used
if we have constructed the row separately, which is a rare case; this
function is quite slow. */

void
ins_node_set_new_row(
/*=================*/
	ins_node_t*	node,	/* in: insert node */
	dtuple_t*	row)	/* in: new row (or first row) for the node */
{
	node->state = INS_NODE_SET_IX_LOCK;
	node->index = NULL;
	node->entry = NULL;

	node->row = row;

	mem_heap_empty(node->entry_sys_heap);

	/* Create templates for index entries */
			
	ins_node_create_entry_list(node);

	/* Allocate from entry_sys_heap buffers for sys fields */

	row_ins_alloc_sys_fields(node);

	/* As we allocated a new trx id buf, the trx id should be written
	there again: */

	node->trx_id = ut_dulint_zero;
}

/***********************************************************************
Does an insert operation by updating a delete-marked existing record
in the index. This situation can occur if the delete-marked record is
kept in the index for consistent reads. */
static
ulint
row_ins_sec_index_entry_by_modify(
/*==============================*/
				/* out: DB_SUCCESS or error code */
	ulint		mode,	/* in: BTR_MODIFY_LEAF or BTR_MODIFY_TREE,
				depending on whether mtr holds just a leaf
				latch or also a tree latch */
	btr_cur_t*	cursor,	/* in: B-tree cursor */
	dtuple_t*	entry,	/* in: index entry to insert */
	que_thr_t*	thr,	/* in: query thread */
	mtr_t*		mtr)	/* in: mtr */
{
	big_rec_t*	dummy_big_rec;
	mem_heap_t*	heap;
	upd_t*		update;
	rec_t*		rec;
	ulint		err;
	
	rec = btr_cur_get_rec(cursor);
	
	ut_ad((cursor->index->type & DICT_CLUSTERED) == 0);
	ut_ad(rec_get_deleted_flag(rec, cursor->index->table->comp));
	
	/* We know that in the alphabetical ordering, entry and rec are
	identified. But in their binary form there may be differences if
	there are char fields in them. Therefore we have to calculate the
	difference. */
	
	heap = mem_heap_create(1024);
	
	update = row_upd_build_sec_rec_difference_binary(cursor->index,
				entry, rec, thr_get_trx(thr), heap);
	if (mode == BTR_MODIFY_LEAF) {
		/* Try an optimistic updating of the record, keeping changes
		within the page */

		err = btr_cur_optimistic_update(BTR_KEEP_SYS_FLAG, cursor,
						update, 0, thr, mtr);
		if (err == DB_OVERFLOW || err == DB_UNDERFLOW) {
			err = DB_FAIL;
		}
	} else  {
		ut_a(mode == BTR_MODIFY_TREE);
		err = btr_cur_pessimistic_update(BTR_KEEP_SYS_FLAG, cursor,
					&dummy_big_rec, update, 0, thr, mtr);
	}

	mem_heap_free(heap);

	return(err);
}

/***********************************************************************
Does an insert operation by delete unmarking and updating a delete marked
existing record in the index. This situation can occur if the delete marked
record is kept in the index for consistent reads. */
static
ulint
row_ins_clust_index_entry_by_modify(
/*================================*/
				/* out: DB_SUCCESS, DB_FAIL, or error code */
	ulint		mode,	/* in: BTR_MODIFY_LEAF or BTR_MODIFY_TREE,
				depending on whether mtr holds just a leaf
				latch or also a tree latch */
	btr_cur_t*	cursor,	/* in: B-tree cursor */
	big_rec_t**	big_rec,/* out: possible big rec vector of fields
				which have to be stored externally by the
				caller */
	dtuple_t*	entry,	/* in: index entry to insert */
	ulint*		ext_vec,/* in: array containing field numbers of
				externally stored fields in entry, or NULL */
	ulint		n_ext_vec,/* in: number of fields in ext_vec */
	que_thr_t*	thr,	/* in: query thread */
	mtr_t*		mtr)	/* in: mtr */
{
	mem_heap_t*	heap;
	rec_t*		rec;
	upd_t*		update;
	ulint		err;
	
	ut_ad(cursor->index->type & DICT_CLUSTERED);
	
	*big_rec = NULL;

	rec = btr_cur_get_rec(cursor);

	ut_ad(rec_get_deleted_flag(rec, cursor->index->table->comp));

	heap = mem_heap_create(1024);
	
	/* Build an update vector containing all the fields to be modified;
	NOTE that this vector may NOT contain system columns trx_id or
	roll_ptr */
	
	update = row_upd_build_difference_binary(cursor->index, entry, ext_vec,
			n_ext_vec, rec, thr_get_trx(thr), heap);
	if (mode == BTR_MODIFY_LEAF) {
		/* Try optimistic updating of the record, keeping changes
		within the page */

		err = btr_cur_optimistic_update(0, cursor, update, 0, thr,
								   mtr);
		if (err == DB_OVERFLOW || err == DB_UNDERFLOW) {
			err = DB_FAIL;
		}
	} else  {
		ut_a(mode == BTR_MODIFY_TREE);
		err = btr_cur_pessimistic_update(0, cursor, big_rec, update,
								0, thr, mtr);
	}
	
	mem_heap_free(heap);

	return(err);
}

/*************************************************************************
Returns TRUE if in a cascaded update/delete an ancestor node of node
updates (not DELETE, but UPDATE) table. */
static
ibool
row_ins_cascade_ancestor_updates_table(
/*===================================*/
				/* out: TRUE if an ancestor updates table */
	que_node_t*	node,	/* in: node in a query graph */
	dict_table_t*	table)	/* in: table */
{
	que_node_t*	parent;
	upd_node_t*	upd_node;

	parent = que_node_get_parent(node);
	
	while (que_node_get_type(parent) == QUE_NODE_UPDATE) {

		upd_node = parent;

		if (upd_node->table == table && upd_node->is_delete == FALSE) {

			return(TRUE);
		}

		parent = que_node_get_parent(parent);

		ut_a(parent);
	}

	return(FALSE);
}
	
/*************************************************************************
Returns the number of ancestor UPDATE or DELETE nodes of a
cascaded update/delete node. */
static
ulint
row_ins_cascade_n_ancestors(
/*========================*/
				/* out: number of ancestors */
	que_node_t*	node)	/* in: node in a query graph */
{
	que_node_t*	parent;
	ulint		n_ancestors = 0;

	parent = que_node_get_parent(node);
	
	while (que_node_get_type(parent) == QUE_NODE_UPDATE) {
		n_ancestors++;

		parent = que_node_get_parent(parent);

		ut_a(parent);
	}

	return(n_ancestors);
}
	
/**********************************************************************
Calculates the update vector node->cascade->update for a child table in
a cascaded update. */
static
ulint
row_ins_cascade_calc_update_vec(
/*============================*/
					/* out: number of fields in the
					calculated update vector; the value
					can also be 0 if no foreign key
					fields changed; the returned value
					is ULINT_UNDEFINED if the column
					type in the child table is too short
					to fit the new value in the parent
					table: that means the update fails */
	upd_node_t*	node,		/* in: update node of the parent
					table */
	dict_foreign_t*	foreign,	/* in: foreign key constraint whose
					type is != 0 */
	mem_heap_t*	heap)		/* in: memory heap to use as
					temporary storage */
{
	upd_node_t*	cascade		= node->cascade_node;
	dict_table_t*	table		= foreign->foreign_table;
	dict_index_t*	index		= foreign->foreign_index;
	upd_t*		update;
	upd_field_t*	ufield;
	dict_table_t*	parent_table;
	dict_index_t*	parent_index;
	upd_t*		parent_update;
	upd_field_t*	parent_ufield;
	ulint		n_fields_updated;
	ulint           parent_field_no;
	dtype_t*	type;
	ulint		i;
	ulint		j;
	    	
	ut_a(node && foreign && cascade && table && index);

	/* Calculate the appropriate update vector which will set the fields
	in the child index record to the same value (possibly padded with 
	spaces if the column is a fixed length CHAR or FIXBINARY column) as
	the referenced index record will get in the update. */

	parent_table = node->table;
	ut_a(parent_table == foreign->referenced_table);
	parent_index = foreign->referenced_index;
	parent_update = node->update;
		
	update = cascade->update;

	update->info_bits = 0;
	update->n_fields = foreign->n_fields;
		
	n_fields_updated = 0;

	for (i = 0; i < foreign->n_fields; i++) {

		parent_field_no = dict_table_get_nth_col_pos(
					parent_table,
					dict_index_get_nth_col_no(
							parent_index, i));

		for (j = 0; j < parent_update->n_fields; j++) {
			parent_ufield = parent_update->fields + j;
		
			if (parent_ufield->field_no == parent_field_no) {

				ulint	min_size;

				/* A field in the parent index record is
				updated. Let us make the update vector
				field for the child table. */

 				ufield = update->fields + n_fields_updated;

				ufield->field_no =
					dict_table_get_nth_col_pos(table,
					dict_index_get_nth_col_no(index, i));
				ufield->exp = NULL;

				ufield->new_val = parent_ufield->new_val;

				type = dict_index_get_nth_type(index, i);

				/* Do not allow a NOT NULL column to be
				updated as NULL */

				if (ufield->new_val.len == UNIV_SQL_NULL
				    && (type->prtype & DATA_NOT_NULL)) {

				        return(ULINT_UNDEFINED);
				}

				/* If the new value would not fit in the
				column, do not allow the update */

				if (ufield->new_val.len != UNIV_SQL_NULL
				    && dtype_get_at_most_n_mbchars(
						type, dtype_get_len(type),
						ufield->new_val.len,
						ufield->new_val.data)
				    < ufield->new_val.len) {

					return(ULINT_UNDEFINED);
				}

				/* If the parent column type has a different
				length than the child column type, we may
				need to pad with spaces the new value of the
				child column */

				min_size = dtype_get_min_size(type);

				if (min_size
				    && ufield->new_val.len != UNIV_SQL_NULL
				    && ufield->new_val.len < min_size) {

					char*		pad_start;
					const char*	pad_end;
				        ufield->new_val.data =
						mem_heap_alloc(heap,
								min_size);
					pad_start =
						((char*) ufield->new_val.data)
						+ ufield->new_val.len;
					pad_end =
						((char*) ufield->new_val.data)
						+ min_size;
					ufield->new_val.len = min_size;
					ut_memcpy(ufield->new_val.data,
						parent_ufield->new_val.data,
						parent_ufield->new_val.len);

					switch (UNIV_EXPECT(
						dtype_get_mbminlen(type), 1)) {
					default:
						ut_error;
					case 1:
						/* space=0x20 */
						memset(pad_start, 0x20,
							pad_end - pad_start);
						break;
					case 2:
						/* space=0x0020 */
						ut_a(!(ufield->new_val.len
									% 2));
						ut_a(!(min_size % 2));
						do {
							*pad_start++ = 0x00;
							*pad_start++ = 0x20;
						} while (pad_start < pad_end);
						break;
					}
				}

				ufield->extern_storage = FALSE;

				n_fields_updated++;
			}
		}
	}

	update->n_fields = n_fields_updated;

	return(n_fields_updated);
}

/*************************************************************************
Set detailed error message associated with foreign key errors for
the given transaction. */
static
void
row_ins_set_detailed(
/*=================*/
	trx_t*		trx,		/* in: transaction */
	dict_foreign_t*	foreign)	/* in: foreign key constraint */
{
	mutex_enter(&srv_misc_tmpfile_mutex);
	rewind(srv_misc_tmpfile);

	ut_print_name(srv_misc_tmpfile, trx, foreign->foreign_table_name);
	dict_print_info_on_foreign_key_in_create_format(srv_misc_tmpfile,
				trx, foreign, FALSE);
	trx_set_detailed_error_from_file(trx, srv_misc_tmpfile);

	mutex_exit(&srv_misc_tmpfile_mutex);
}

/*************************************************************************
Reports a foreign key error associated with an update or a delete of a
parent table index entry. */
static
void
row_ins_foreign_report_err(
/*=======================*/
	const char*	errstr,		/* in: error string from the viewpoint
					of the parent table */
	que_thr_t*	thr,		/* in: query thread whose run_node
					is an update node */
	dict_foreign_t*	foreign,	/* in: foreign key constraint */
	rec_t*		rec,		/* in: a matching index record in the<commit_msg>trunk: Remove error introduced in r87 of branches/5.0, ported in r88: In row_ins_set_detailed(), truncate the tmpfile by os_file_set_eof(), because trx_set_detailed_error_from_file() does not call ftell() to determine the actual length of the file.  This bug resulted in trash being appended to foreign key error messages.<commit_after>/******************************************************
Insert into a table

(c) 1996 <NAME>

Created 4/20/1996 <NAME>
*******************************************************/

#include "row0ins.h"

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

#include "dict0dict.h"
#include "dict0boot.h"
#include "trx0undo.h"
#include "btr0btr.h"
#include "btr0cur.h"
#include "mach0data.h"
#include "que0que.h"
#include "row0upd.h"
#include "row0sel.h"
#include "row0row.h"
#include "rem0cmp.h"
#include "lock0lock.h"
#include "log0log.h"
#include "eval0eval.h"
#include "data0data.h"
#include "usr0sess.h"

#define	ROW_INS_PREV	1
#define	ROW_INS_NEXT	2


/*********************************************************************
This prototype is copied from /mysql/sql/ha_innodb.cc.
Invalidates the MySQL query cache for the table.
NOTE that the exact prototype of this function has to be in
/innobase/row/row0ins.c! */
extern
void
innobase_invalidate_query_cache(
/*============================*/
	trx_t*	trx,		/* in: transaction which modifies the table */
	char*	full_name,	/* in: concatenation of database name, null
				char '\0', table name, null char'\0';
				NOTE that in Windows this is always
				in LOWER CASE! */
	ulint	full_name_len);	/* in: full name length where also the null
				chars count */

/**********************************************************************
This function returns true if 

1) SQL-query in the current thread
is either REPLACE or LOAD DATA INFILE REPLACE. 

2) SQL-query in the current thread
is INSERT ON DUPLICATE KEY UPDATE.

NOTE that /mysql/innobase/row/row0ins.c must contain the 
prototype for this function ! */

ibool
innobase_query_is_update(void);

/*************************************************************************
Creates an insert node struct. */

ins_node_t*
ins_node_create(
/*============*/
					/* out, own: insert node struct */
	ulint		ins_type,	/* in: INS_VALUES, ... */
	dict_table_t*	table, 		/* in: table where to insert */
	mem_heap_t*	heap)		/* in: mem heap where created */
{
	ins_node_t*	node;

	node = mem_heap_alloc(heap, sizeof(ins_node_t));

	node->common.type = QUE_NODE_INSERT;

	node->ins_type = ins_type;

	node->state = INS_NODE_SET_IX_LOCK;
	node->table = table;
	node->index = NULL;
	node->entry = NULL;

	node->select = NULL;
	
	node->trx_id = ut_dulint_zero;
	
	node->entry_sys_heap = mem_heap_create(128);

	node->magic_n = INS_NODE_MAGIC_N;	
	
	return(node);
}

/***************************************************************
Creates an entry template for each index of a table. */
static
void
ins_node_create_entry_list(
/*=======================*/
	ins_node_t*	node)	/* in: row insert node */
{
	dict_index_t*	index;
	dtuple_t*	entry;

	ut_ad(node->entry_sys_heap);

	UT_LIST_INIT(node->entry_list);

	index = dict_table_get_first_index(node->table);
	
	while (index != NULL) {
		entry = row_build_index_entry(node->row, index,
							node->entry_sys_heap);
		UT_LIST_ADD_LAST(tuple_list, node->entry_list, entry);

		index = dict_table_get_next_index(index);
	}
}

/*********************************************************************
Adds system field buffers to a row. */
static
void
row_ins_alloc_sys_fields(
/*=====================*/
	ins_node_t*	node)	/* in: insert node */
{
	dtuple_t*	row;
	dict_table_t*	table;
	mem_heap_t*	heap;
	dict_col_t*	col;
	dfield_t*	dfield;
	ulint		len;
	byte*		ptr;

	row = node->row;
	table = node->table;
	heap = node->entry_sys_heap;

	ut_ad(row && table && heap);
	ut_ad(dtuple_get_n_fields(row) == dict_table_get_n_cols(table));

	/* 1. Allocate buffer for row id */

	col = dict_table_get_sys_col(table, DATA_ROW_ID);
	
	dfield = dtuple_get_nth_field(row, dict_col_get_no(col));

	ptr = mem_heap_alloc(heap, DATA_ROW_ID_LEN);
				
	dfield_set_data(dfield, ptr, DATA_ROW_ID_LEN);

	node->row_id_buf = ptr;

	if (table->type == DICT_TABLE_CLUSTER_MEMBER) {

		/* 2. Fill in the dfield for mix id */

		col = dict_table_get_sys_col(table, DATA_MIX_ID);
	
		dfield = dtuple_get_nth_field(row, dict_col_get_no(col));

		len = mach_dulint_get_compressed_size(table->mix_id);
		ptr = mem_heap_alloc(heap, DATA_MIX_ID_LEN);
				
		mach_dulint_write_compressed(ptr, table->mix_id);
		dfield_set_data(dfield, ptr, len);
	}

	/* 3. Allocate buffer for trx id */

	col = dict_table_get_sys_col(table, DATA_TRX_ID);
	
	dfield = dtuple_get_nth_field(row, dict_col_get_no(col));
	ptr = mem_heap_alloc(heap, DATA_TRX_ID_LEN);
				
	dfield_set_data(dfield, ptr, DATA_TRX_ID_LEN);

	node->trx_id_buf = ptr;

	/* 4. Allocate buffer for roll ptr */

	col = dict_table_get_sys_col(table, DATA_ROLL_PTR);
	
	dfield = dtuple_get_nth_field(row, dict_col_get_no(col));
	ptr = mem_heap_alloc(heap, DATA_ROLL_PTR_LEN);
				
	dfield_set_data(dfield, ptr, DATA_ROLL_PTR_LEN);
}

/*************************************************************************
Sets a new row to insert for an INS_DIRECT node. This function is only used
if we have constructed the row separately, which is a rare case; this
function is quite slow. */

void
ins_node_set_new_row(
/*=================*/
	ins_node_t*	node,	/* in: insert node */
	dtuple_t*	row)	/* in: new row (or first row) for the node */
{
	node->state = INS_NODE_SET_IX_LOCK;
	node->index = NULL;
	node->entry = NULL;

	node->row = row;

	mem_heap_empty(node->entry_sys_heap);

	/* Create templates for index entries */
			
	ins_node_create_entry_list(node);

	/* Allocate from entry_sys_heap buffers for sys fields */

	row_ins_alloc_sys_fields(node);

	/* As we allocated a new trx id buf, the trx id should be written
	there again: */

	node->trx_id = ut_dulint_zero;
}

/***********************************************************************
Does an insert operation by updating a delete-marked existing record
in the index. This situation can occur if the delete-marked record is
kept in the index for consistent reads. */
static
ulint
row_ins_sec_index_entry_by_modify(
/*==============================*/
				/* out: DB_SUCCESS or error code */
	ulint		mode,	/* in: BTR_MODIFY_LEAF or BTR_MODIFY_TREE,
				depending on whether mtr holds just a leaf
				latch or also a tree latch */
	btr_cur_t*	cursor,	/* in: B-tree cursor */
	dtuple_t*	entry,	/* in: index entry to insert */
	que_thr_t*	thr,	/* in: query thread */
	mtr_t*		mtr)	/* in: mtr */
{
	big_rec_t*	dummy_big_rec;
	mem_heap_t*	heap;
	upd_t*		update;
	rec_t*		rec;
	ulint		err;
	
	rec = btr_cur_get_rec(cursor);
	
	ut_ad((cursor->index->type & DICT_CLUSTERED) == 0);
	ut_ad(rec_get_deleted_flag(rec, cursor->index->table->comp));
	
	/* We know that in the alphabetical ordering, entry and rec are
	identified. But in their binary form there may be differences if
	there are char fields in them. Therefore we have to calculate the
	difference. */
	
	heap = mem_heap_create(1024);
	
	update = row_upd_build_sec_rec_difference_binary(cursor->index,
				entry, rec, thr_get_trx(thr), heap);
	if (mode == BTR_MODIFY_LEAF) {
		/* Try an optimistic updating of the record, keeping changes
		within the page */

		err = btr_cur_optimistic_update(BTR_KEEP_SYS_FLAG, cursor,
						update, 0, thr, mtr);
		if (err == DB_OVERFLOW || err == DB_UNDERFLOW) {
			err = DB_FAIL;
		}
	} else  {
		ut_a(mode == BTR_MODIFY_TREE);
		err = btr_cur_pessimistic_update(BTR_KEEP_SYS_FLAG, cursor,
					&dummy_big_rec, update, 0, thr, mtr);
	}

	mem_heap_free(heap);

	return(err);
}

/***********************************************************************
Does an insert operation by delete unmarking and updating a delete marked
existing record in the index. This situation can occur if the delete marked
record is kept in the index for consistent reads. */
static
ulint
row_ins_clust_index_entry_by_modify(
/*================================*/
				/* out: DB_SUCCESS, DB_FAIL, or error code */
	ulint		mode,	/* in: BTR_MODIFY_LEAF or BTR_MODIFY_TREE,
				depending on whether mtr holds just a leaf
				latch or also a tree latch */
	btr_cur_t*	cursor,	/* in: B-tree cursor */
	big_rec_t**	big_rec,/* out: possible big rec vector of fields
				which have to be stored externally by the
				caller */
	dtuple_t*	entry,	/* in: index entry to insert */
	ulint*		ext_vec,/* in: array containing field numbers of
				externally stored fields in entry, or NULL */
	ulint		n_ext_vec,/* in: number of fields in ext_vec */
	que_thr_t*	thr,	/* in: query thread */
	mtr_t*		mtr)	/* in: mtr */
{
	mem_heap_t*	heap;
	rec_t*		rec;
	upd_t*		update;
	ulint		err;
	
	ut_ad(cursor->index->type & DICT_CLUSTERED);
	
	*big_rec = NULL;

	rec = btr_cur_get_rec(cursor);

	ut_ad(rec_get_deleted_flag(rec, cursor->index->table->comp));

	heap = mem_heap_create(1024);
	
	/* Build an update vector containing all the fields to be modified;
	NOTE that this vector may NOT contain system columns trx_id or
	roll_ptr */
	
	update = row_upd_build_difference_binary(cursor->index, entry, ext_vec,
			n_ext_vec, rec, thr_get_trx(thr), heap);
	if (mode == BTR_MODIFY_LEAF) {
		/* Try optimistic updating of the record, keeping changes
		within the page */

		err = btr_cur_optimistic_update(0, cursor, update, 0, thr,
								   mtr);
		if (err == DB_OVERFLOW || err == DB_UNDERFLOW) {
			err = DB_FAIL;
		}
	} else  {
		ut_a(mode == BTR_MODIFY_TREE);
		err = btr_cur_pessimistic_update(0, cursor, big_rec, update,
								0, thr, mtr);
	}
	
	mem_heap_free(heap);

	return(err);
}

/*************************************************************************
Returns TRUE if in a cascaded update/delete an ancestor node of node
updates (not DELETE, but UPDATE) table. */
static
ibool
row_ins_cascade_ancestor_updates_table(
/*===================================*/
				/* out: TRUE if an ancestor updates table */
	que_node_t*	node,	/* in: node in a query graph */
	dict_table_t*	table)	/* in: table */
{
	que_node_t*	parent;
	upd_node_t*	upd_node;

	parent = que_node_get_parent(node);
	
	while (que_node_get_type(parent) == QUE_NODE_UPDATE) {

		upd_node = parent;

		if (upd_node->table == table && upd_node->is_delete == FALSE) {

			return(TRUE);
		}

		parent = que_node_get_parent(parent);

		ut_a(parent);
	}

	return(FALSE);
}
	
/*************************************************************************
Returns the number of ancestor UPDATE or DELETE nodes of a
cascaded update/delete node. */
static
ulint
row_ins_cascade_n_ancestors(
/*========================*/
				/* out: number of ancestors */
	que_node_t*	node)	/* in: node in a query graph */
{
	que_node_t*	parent;
	ulint		n_ancestors = 0;

	parent = que_node_get_parent(node);
	
	while (que_node_get_type(parent) == QUE_NODE_UPDATE) {
		n_ancestors++;

		parent = que_node_get_parent(parent);

		ut_a(parent);
	}

	return(n_ancestors);
}
	
/**********************************************************************
Calculates the update vector node->cascade->update for a child table in
a cascaded update. */
static
ulint
row_ins_cascade_calc_update_vec(
/*============================*/
					/* out: number of fields in the
					calculated update vector; the value
					can also be 0 if no foreign key
					fields changed; the returned value
					is ULINT_UNDEFINED if the column
					type in the child table is too short
					to fit the new value in the parent
					table: that means the update fails */
	upd_node_t*	node,		/* in: update node of the parent
					table */
	dict_foreign_t*	foreign,	/* in: foreign key constraint whose
					type is != 0 */
	mem_heap_t*	heap)		/* in: memory heap to use as
					temporary storage */
{
	upd_node_t*	cascade		= node->cascade_node;
	dict_table_t*	table		= foreign->foreign_table;
	dict_index_t*	index		= foreign->foreign_index;
	upd_t*		update;
	upd_field_t*	ufield;
	dict_table_t*	parent_table;
	dict_index_t*	parent_index;
	upd_t*		parent_update;
	upd_field_t*	parent_ufield;
	ulint		n_fields_updated;
	ulint           parent_field_no;
	dtype_t*	type;
	ulint		i;
	ulint		j;
	    	
	ut_a(node && foreign && cascade && table && index);

	/* Calculate the appropriate update vector which will set the fields
	in the child index record to the same value (possibly padded with 
	spaces if the column is a fixed length CHAR or FIXBINARY column) as
	the referenced index record will get in the update. */

	parent_table = node->table;
	ut_a(parent_table == foreign->referenced_table);
	parent_index = foreign->referenced_index;
	parent_update = node->update;
		
	update = cascade->update;

	update->info_bits = 0;
	update->n_fields = foreign->n_fields;
		
	n_fields_updated = 0;

	for (i = 0; i < foreign->n_fields; i++) {

		parent_field_no = dict_table_get_nth_col_pos(
					parent_table,
					dict_index_get_nth_col_no(
							parent_index, i));

		for (j = 0; j < parent_update->n_fields; j++) {
			parent_ufield = parent_update->fields + j;
		
			if (parent_ufield->field_no == parent_field_no) {

				ulint	min_size;

				/* A field in the parent index record is
				updated. Let us make the update vector
				field for the child table. */

 				ufield = update->fields + n_fields_updated;

				ufield->field_no =
					dict_table_get_nth_col_pos(table,
					dict_index_get_nth_col_no(index, i));
				ufield->exp = NULL;

				ufield->new_val = parent_ufield->new_val;

				type = dict_index_get_nth_type(index, i);

				/* Do not allow a NOT NULL column to be
				updated as NULL */

				if (ufield->new_val.len == UNIV_SQL_NULL
				    && (type->prtype & DATA_NOT_NULL)) {

				        return(ULINT_UNDEFINED);
				}

				/* If the new value would not fit in the
				column, do not allow the update */

				if (ufield->new_val.len != UNIV_SQL_NULL
				    && dtype_get_at_most_n_mbchars(
						type, dtype_get_len(type),
						ufield->new_val.len,
						ufield->new_val.data)
				    < ufield->new_val.len) {

					return(ULINT_UNDEFINED);
				}

				/* If the parent column type has a different
				length than the child column type, we may
				need to pad with spaces the new value of the
				child column */

				min_size = dtype_get_min_size(type);

				if (min_size
				    && ufield->new_val.len != UNIV_SQL_NULL
				    && ufield->new_val.len < min_size) {

					char*		pad_start;
					const char*	pad_end;
				        ufield->new_val.data =
						mem_heap_alloc(heap,
								min_size);
					pad_start =
						((char*) ufield->new_val.data)
						+ ufield->new_val.len;
					pad_end =
						((char*) ufield->new_val.data)
						+ min_size;
					ufield->new_val.len = min_size;
					ut_memcpy(ufield->new_val.data,
						parent_ufield->new_val.data,
						parent_ufield->new_val.len);

					switch (UNIV_EXPECT(
						dtype_get_mbminlen(type), 1)) {
					default:
						ut_error;
					case 1:
						/* space=0x20 */
						memset(pad_start, 0x20,
							pad_end - pad_start);
						break;
					case 2:
						/* space=0x0020 */
						ut_a(!(ufield->new_val.len
									% 2));
						ut_a(!(min_size % 2));
						do {
							*pad_start++ = 0x00;
							*pad_start++ = 0x20;
						} while (pad_start < pad_end);
						break;
					}
				}

				ufield->extern_storage = FALSE;

				n_fields_updated++;
			}
		}
	}

	update->n_fields = n_fields_updated;

	return(n_fields_updated);
}

/*************************************************************************
Set detailed error message associated with foreign key errors for
the given transaction. */
static
void
row_ins_set_detailed(
/*=================*/
	trx_t*		trx,		/* in: transaction */
	dict_foreign_t*	foreign)	/* in: foreign key constraint */
{
	mutex_enter(&srv_misc_tmpfile_mutex);
	rewind(srv_misc_tmpfile);

	if (os_file_set_eof(srv_misc_tmpfile)) {
		ut_print_name(srv_misc_tmpfile, trx,
				foreign->foreign_table_name);
		dict_print_info_on_foreign_key_in_create_format(
				srv_misc_tmpfile,
				trx, foreign, FALSE);
		trx_set_detailed_error_from_file(trx, srv_misc_tmpfile);
	} else {
		trx_set_detailed_error(trx, "temp file operation failed");
	}

	mutex_exit(&srv_misc_tmpfile_mutex);
}

/*************************************************************************
Reports a foreign key error associated with an update or a delete of a
parent table index entry. */
static
void
row_ins_foreign_report_err(
/*=======================*/
	const char*	errstr,		/* in: error string from the viewpoint
					of the parent table */
	que_thr_t*	thr,		/* in: query thread whose run_node
					is an update node */
	dict_foreign_t*	foreign,	/* in: foreign key constraint */
	rec_t*		rec,		/* in: a matching index record in the
{'fraction_non_alphanumeric': 0.1785247942668003, 'fraction_numerical': 0.005526707357808752, 'mean_word_length': 3.968617984308992, 'pattern_counts': {'":': 0, '<': 17, '<?xml version=': 0, '>': 179, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6762396', 'n_tokens_mistral': 13148, 'n_tokens_neox': 11472, 'n_words': 2991}