From 83ef8f3427b541206ae3ffb24c1370c64cba5a81 Mon Sep 17 00:00:00 2001 From: Narayanan V Date: Tue, 16 Sep 2008 18:37:59 +0530 Subject: [PATCH] Bug#38338: REPLACE causes last_insert_id() to return an incorrect value Fix the write_record function to record auto increment values in a consistent way. --- mysql-test/r/auto_increment.result | 8 ++++++++ mysql-test/t/auto_increment.test | 12 +++++++++++- sql/sql_insert.cc | 11 +++++++++++ 3 files changed, 30 insertions(+), 1 deletion(-) diff --git a/mysql-test/r/auto_increment.result b/mysql-test/r/auto_increment.result index bc9daf43f14..a39b424827c 100644 --- a/mysql-test/r/auto_increment.result +++ b/mysql-test/r/auto_increment.result @@ -454,3 +454,11 @@ select last_insert_id(); last_insert_id() 3 drop table t1; +create table t1 (a int primary key auto_increment, b int, c int, e int, d timestamp default current_timestamp, unique(b),unique(c),unique(e)); +insert into t1 values(null,1,1,1,now()); +insert into t1 values(null,0,0,0,null); +replace into t1 values(null,1,0,2,null); +select last_insert_id(); +last_insert_id() +3 +drop table t1; diff --git a/mysql-test/t/auto_increment.test b/mysql-test/t/auto_increment.test index ff92c743960..47458c1f054 100644 --- a/mysql-test/t/auto_increment.test +++ b/mysql-test/t/auto_increment.test @@ -314,5 +314,15 @@ insert into t1 values(null,0,0,null); # this will delete two rows replace into t1 values(null,1,0,null); select last_insert_id(); - +drop table t1; + +# Test of REPLACE when it does a INSERT+DELETE for all the conflicting rows +# (i.e.) when there are three rows conflicting in unique key columns with +# a row that is being inserted, all the three rows will be deleted and then +# the new rows will be inserted. +create table t1 (a int primary key auto_increment, b int, c int, e int, d timestamp default current_timestamp, unique(b),unique(c),unique(e)); +insert into t1 values(null,1,1,1,now()); +insert into t1 values(null,0,0,0,null); +replace into t1 values(null,1,0,2,null); +select last_insert_id(); drop table t1; diff --git a/sql/sql_insert.cc b/sql/sql_insert.cc index ec8f85b43ab..268e040288e 100644 --- a/sql/sql_insert.cc +++ b/sql/sql_insert.cc @@ -1545,6 +1545,17 @@ int write_record(THD *thd, TABLE *table,COPY_INFO *info) } } } + + /* + If more than one iteration of the above while loop is done, from the second + one the row being inserted will have an explicit value in the autoinc field, + which was set at the first call of handler::update_auto_increment(). This + value is saved to avoid thd->insert_id_for_cur_row becoming 0. Use this saved + autoinc value. + */ + if (table->file->insert_id_for_cur_row == 0) + table->file->insert_id_for_cur_row= insert_id_for_cur_row; + thd->record_first_successful_insert_id_in_cur_stmt(table->file->insert_id_for_cur_row); /* Restore column maps if they where replaced during an duplicate key