Skip to content

Commit

Permalink
sql: fix pg_catalog.pg_constraint's confkey column
Browse files Browse the repository at this point in the history
Prior to this patch, all columns in the index were included instead of only the
ones being used in the foreign key reference.

Fixes cockroachdb#31545.

Release note (bug fix): Fix pg_catalog.pg_constraint's confkey column from
including columns that were not involved in the foreign key reference.
  • Loading branch information
BramGruneir committed Oct 19, 2018
1 parent 1f852af commit bfa1615
Show file tree
Hide file tree
Showing 2 changed files with 63 additions and 1 deletion.
58 changes: 58 additions & 0 deletions pkg/sql/logictest/testdata/logic_test/pg_catalog
Original file line number Diff line number Diff line change
Expand Up @@ -1624,3 +1624,61 @@ query OT
SELECT typ.oid, typ.typname FROM pg_attribute att JOIN pg_type typ ON atttypid=typ.oid WHERE attrelid='coltab'::regclass AND attname='a'
----
25 text

subtest 31545

# Test an index of 2 referencing an index of 2.
statement ok
CREATE TABLE a (
id_a_1 INT UNIQUE,
id_a_2 INT,
PRIMARY KEY (id_a_1, id_a_2)
)

statement ok
CREATE TABLE b (
id_b_1 INT,
id_b_2 INT,
PRIMARY KEY (id_b_1, id_b_2),
CONSTRAINT my_fkey FOREIGN KEY (id_b_1, id_b_2) REFERENCES a (id_a_1, id_a_2)
)

query TT colnames
SELECT conkey, confkey FROM pg_catalog.pg_constraint WHERE conname = 'my_fkey'
----
conkey confkey
{1,2} {1,2}

# Test an index of 3 referencing an index of 2.
statement ok
DROP TABLE b;
CREATE TABLE b (
id_b_1 INT,
id_b_2 INT,
id_b_3 INT,
PRIMARY KEY (id_b_1, id_b_2, id_b_3),
CONSTRAINT my_fkey FOREIGN KEY (id_b_1, id_b_2) REFERENCES a (id_a_1, id_a_2)
)

query TT colnames
SELECT conkey, confkey FROM pg_catalog.pg_constraint WHERE conname = 'my_fkey'
----
conkey confkey
{1,2} {1,2}

# Test an index of 3 referencing an index of 1.
statement ok
DROP TABLE b;
CREATE TABLE b (
id_b_1 INT,
id_b_2 INT,
id_b_3 INT,
PRIMARY KEY (id_b_1, id_b_2, id_b_3),
CONSTRAINT my_fkey FOREIGN KEY (id_b_1) REFERENCES a (id_a_1)
)

query TT colnames
SELECT conkey, confkey FROM pg_catalog.pg_constraint WHERE conname = 'my_fkey'
----
conkey confkey
{1} {1}
6 changes: 5 additions & 1 deletion pkg/sql/pg_catalog.go
Original file line number Diff line number Diff line change
Expand Up @@ -680,7 +680,11 @@ CREATE TABLE pg_catalog.pg_constraint (
confupdtype = fkActionNone
confdeltype = fkActionNone
confmatchtype = fkMatchTypeSimple
if conkey, err = colIDArrayToDatum(con.Index.ColumnIDs); err != nil {
columnIDs := con.Index.ColumnIDs
if con.FK.SharedPrefixLen < int32(len(columnIDs)) {
columnIDs = columnIDs[:con.FK.SharedPrefixLen]
}
if conkey, err = colIDArrayToDatum(columnIDs); err != nil {
return err
}
if confkey, err = colIDArrayToDatum(con.ReferencedIndex.ColumnIDs); err != nil {
Expand Down

0 comments on commit bfa1615

Please sign in to comment.