diff --git a/pkg/sql/plan/build_ddl_test.go b/pkg/sql/plan/build_ddl_test.go index f793f8fdf04b4..ea0612715e986 100644 --- a/pkg/sql/plan/build_ddl_test.go +++ b/pkg/sql/plan/build_ddl_test.go @@ -45,6 +45,37 @@ type rootSQLCompilerContext struct { calls int } +func TestBuildRenameTableUsesPriorDestinationAsNextSource(t *testing.T) { + stmt, err := parsers.ParseOne( + t.Context(), + dialect.MYSQL, + "rename table t1 to t2, t2 to t3", + 1, + ) + require.NoError(t, err) + defer stmt.Free() + + ctx := NewMockCompilerContext(false) + delete(ctx.tables, "t2") + delete(ctx.tables, "t3") + delete(ctx.objects, "t2") + delete(ctx.objects, "t3") + ctx.tables["t1"] = DeepCopyTableDef(ctx.tables["nation"], true) + ctx.tables["t1"].Name = "t1" + ctx.objects["t1"] = &ObjectRef{SchemaName: "tpch", ObjName: "t1"} + + p, err := BuildPlan(ctx, stmt, false) + require.NoError(t, err) + + renames := p.GetDdl().GetRenameTable().GetAlterTables() + require.Len(t, renames, 2) + require.Equal(t, "t1", renames[0].GetActions()[0].GetAlterName().GetOldName()) + require.Equal(t, "t2", renames[0].GetActions()[0].GetAlterName().GetNewName()) + require.Equal(t, "t2", renames[1].GetTableDef().GetName()) + require.Equal(t, "t2", renames[1].GetActions()[0].GetAlterName().GetOldName()) + require.Equal(t, "t3", renames[1].GetActions()[0].GetAlterName().GetNewName()) +} + func TestBuildDropTemporaryTableOnlyTargetsTemporaryTable(t *testing.T) { stmt, err := parsers.ParseOne(context.Background(), dialect.MYSQL, "drop temporary table nation", 1) require.NoError(t, err) diff --git a/test/distributed/cases/ddl/rename_table_chained.result b/test/distributed/cases/ddl/rename_table_chained.result index e5f505ddb625d..179eb73118169 100644 --- a/test/distributed/cases/ddl/rename_table_chained.result +++ b/test/distributed/cases/ddl/rename_table_chained.result @@ -12,6 +12,12 @@ id select * from t_shadow; id 100 +create table t1 (a int, b int); +insert into t1 values (24499, 3); +rename table t1 to t2, t2 to t3; +select * from t3; +a b +24499 3 drop table t_live, t_shadow; create table a (id int); create table b (id int); diff --git a/test/distributed/cases/ddl/rename_table_chained.sql b/test/distributed/cases/ddl/rename_table_chained.sql index 827646d147dd3..1cac8a6af30e6 100644 --- a/test/distributed/cases/ddl/rename_table_chained.sql +++ b/test/distributed/cases/ddl/rename_table_chained.sql @@ -17,6 +17,12 @@ rename table t_live to t_tmp, t_shadow to t_live, t_tmp to t_shadow; select * from t_live; select * from t_shadow; +-- #24499: a destination can be the source of the next rename pair +create table t1 (a int, b int); +insert into t1 values (24499, 3); +rename table t1 to t2, t2 to t3; +select * from t3; + -- 2-pair rename (non-conflicting) drop table t_live, t_shadow; create table a (id int);