From f10d2b64bbb2ef7f5d3a082fbd0751d95480c4ca Mon Sep 17 00:00:00 2001 From: Andrew Werner Date: Fri, 28 May 2021 00:15:02 -0400 Subject: [PATCH] sql: SHOW CREATE TABLE treated unique constraints like unique indexes ``` root@localhost:26257/test> CREATE TABLE t (i INT PRIMARY KEY, j INT); CREATE TABLE root@localhost:26257/test> ALTER TABLE t ADD CONSTRAINT c UNIQUE (j); ALTER TABLE root@localhost:26257/test> CREATE UNIQUE INDEX idx ON t (j); CREATE INDEX ``` Before: ``` root@localhost:26257/test> SHOW CREATE TABLE t; table_name | create_statement -------------+------------------------------------------------ t | CREATE TABLE public.t ( | i INT8 NOT NULL, | j INT8 NULL, | CONSTRAINT "primary" PRIMARY KEY (i ASC), | UNIQUE INDEX c (j ASC), | UNIQUE INDEX idx (j ASC), | FAMILY "primary" (i, j) | ) ``` After: ``` demo@127.0.0.1:55792/movr> SHOW CREATE TABLE t; table_name | create_statement -------------+------------------------------------------------ t | CREATE TABLE public.t ( | i INT8 NOT NULL, | j INT8 NULL, | CONSTRAINT "primary" PRIMARY KEY (i ASC), | UNIQUE INDEX idx (j ASC), | FAMILY "primary" (i, j), | CONSTRAINT c UNIQUE (j) | ) ``` Release note (bug fix): UNIQUE constraints were displayed as UNIQUE INDEX entries in SHOW CREATE TABLE. --- pkg/sql/show_create.go | 4 ++++ pkg/sql/show_create_clauses.go | 22 ++++++++++++++++++++++ 2 files changed, 26 insertions(+) diff --git a/pkg/sql/show_create.go b/pkg/sql/show_create.go index f0e64bbe8708..b2492ba67aec 100644 --- a/pkg/sql/show_create.go +++ b/pkg/sql/show_create.go @@ -149,6 +149,10 @@ func ShowCreateTable( // clauses as well. includeInterleaveClause = true } + // Don't show indexes which represent unique constraints. + if idx.IsUnique() && !idx.IsCreatedExplicitly() { + continue + } if !idx.Primary() && includeInterleaveClause { // Showing the primary index is handled above. diff --git a/pkg/sql/show_create_clauses.go b/pkg/sql/show_create_clauses.go index c2ae8a78df1c..83d4a487019c 100644 --- a/pkg/sql/show_create_clauses.go +++ b/pkg/sql/show_create_clauses.go @@ -601,6 +601,28 @@ func showConstraintClause( f.WriteString(" NOT VALID") } } + for _, idx := range desc.AllIndexes() { + if !idx.IsUnique() || idx.IsCreatedExplicitly() || idx.Primary() { + continue + } + f.WriteString(",\n\t") + if len(idx.GetName()) > 0 { + f.WriteString("CONSTRAINT ") + formatQuoteNames(&f.Buffer, idx.GetName()) + f.WriteString(" ") + } + f.WriteString("UNIQUE ") + f.WriteString("(") + startIdx := idx.ExplicitColumnStartIdx() + for i := startIdx; i < idx.NumColumns(); i++ { + if i > startIdx { + f.WriteString(", ") + } + n := idx.GetColumnName(i) + f.FormatNameP(&n) + } + f.WriteString(")") + } f.WriteString("\n)") return nil }