################################################################################
#
# Executes INSERT ... SELECT statements.
#
################################################################################

SET autocommit = 0;
START TRANSACTION;

# We need this to determine how many rows to update after insert (we may insert mulitple rows).
let $pk_before= `SELECT MAX(`pk`) FROM t1`;

# Insert rows unless we have duplicate values in unique indexes.
# WHERE conditions are more or less arbitrary.
--error 0, ER_LOCK_DEADLOCK, ER_LOCK_WAIT_TIMEOUT, ER_CHECKREAD, ER_DUP_ENTRY
INSERT INTO t1 (`id`, `int1`, `int1_key`, `int1_unique`,
                       `int2`, `int2_key`, `int2_unique`,
                       `for_update`, `is_uncommitted`, `is_consistent`)
               SELECT src.`id`, src.`int1`, src.`int1_key`, src.`int1_unique`,
                      src.`int2`, src.`int2_key`, src.`int2_unique`,
                      src.`for_update`, src.`is_uncommitted`, src.`is_consistent`
               FROM t1 AS src
               WHERE (src.`pk` BETWEEN 1000 AND 1049) AND (src.`id` > 0) AND (src.`is_consistent` = 1) AND (src.`int1_unique` MOD 8 = 0)
               ON DUPLICATE KEY UPDATE `int1_unique`= src.`int1_unique` + CONNECTION_ID() + 1000, `int2_unique`= src.`int2_unique` - (CONNECTION_ID()+1000);

--source suite/engines/rr_trx/include/check_for_error_rollback.inc

# ROW_COUNT may be negative. If positive (and non-zero), update the rows we inserted.
let $rows = `SELECT @rows:=ROW_COUNT()`;

# Make sure $rows is never negative (to avoid infitite loop below).
if(`SELECT IF(@rows < 1, 1, 0)`)
{
    let $rows = 0;
}

--echo *** Updating id and connection_id if we actually inserted something (query log disabled)...
# Conditional, so skip query log
--disable_query_log
# We risk duplicate entries... in that case @@last_insert_id is 0
while ($rows)
{
    # We actually inserted a row, so update id, conn_id, timestamp
    --error 0, ER_LOCK_DEADLOCK, ER_LOCK_WAIT_TIMEOUT, ER_CHECKREAD
    eval UPDATE t1 SET `connection_id` = CONNECTION_ID(), `id` = 2 WHERE `pk` = $pk_before + $rows;
    --dec $rows
}
--enable_query_log

COMMIT;
