From c587797175ef4e4daeaaf8ff2cf770f15d3fbb29 Mon Sep 17 00:00:00 2001 From: Oliver Tan Date: Wed, 31 Mar 2021 18:39:33 +1100 Subject: [PATCH] sql: fix ALTER PRIMARY KEY with virtual columns on the table Release note (bug fix): Fix a bug where ALTER PRIMARY KEY would fail if the table contained virtual columns. --- pkg/sql/alter_primary_key.go | 5 +++++ .../testdata/logic_test/alter_primary_key | 21 +++++++++++++++++++ 2 files changed, 26 insertions(+) diff --git a/pkg/sql/alter_primary_key.go b/pkg/sql/alter_primary_key.go index bb28f4126660..59b11381ab8a 100644 --- a/pkg/sql/alter_primary_key.go +++ b/pkg/sql/alter_primary_key.go @@ -235,6 +235,11 @@ func (p *planner) AlterPrimaryKey( // to consider the indexed columns to be newPrimaryIndexDesc.ColumnIDs. newPrimaryIndexDesc.StoreColumnNames, newPrimaryIndexDesc.StoreColumnIDs = nil, nil for _, col := range tableDesc.Columns { + // We do not store virtual columns. + if col.Virtual { + continue + } + containsCol := false for _, colID := range newPrimaryIndexDesc.ColumnIDs { if colID == col.ID { diff --git a/pkg/sql/logictest/testdata/logic_test/alter_primary_key b/pkg/sql/logictest/testdata/logic_test/alter_primary_key index 6fa66b1f19e7..82d846e63033 100644 --- a/pkg/sql/logictest/testdata/logic_test/alter_primary_key +++ b/pkg/sql/logictest/testdata/logic_test/alter_primary_key @@ -1404,3 +1404,24 @@ drop table child3; statement ok drop table parent3; + +statement ok +CREATE TABLE table_with_virtual_cols ( + id INT PRIMARY KEY, + new_pk INT NOT NULL, + virtual_col INT AS (1::int) VIRTUAL, + FAMILY (id, new_pk) +); +ALTER TABLE table_with_virtual_cols ALTER PRIMARY KEY USING COLUMNS (new_pk) + +query TT +SHOW CREATE TABLE table_with_virtual_cols +---- +table_with_virtual_cols CREATE TABLE public.table_with_virtual_cols ( + id INT8 NOT NULL, + new_pk INT8 NOT NULL, + virtual_col INT8 NULL AS (1:::INT8) VIRTUAL, + CONSTRAINT "primary" PRIMARY KEY (new_pk ASC), + UNIQUE INDEX table_with_virtual_cols_id_key (id ASC), + FAMILY fam_0_id_new_pk (id, new_pk) +)