Skip to content

Commit

Permalink
sql: do not allow reference FK partial unique constraints
Browse files Browse the repository at this point in the history
This commit prevents users from creating a FK with a reference column
that has a partial unique constraint. These constraints do not guarantee
uniqueness in the entire table so they cannot be used.

There is no release note because these constraints are gated behind the
experimental_enable_unique_without_index_constraints session variable.

Release note: None
  • Loading branch information
mgartner committed Feb 21, 2021
1 parent 8b6f3c8 commit 0a5de20
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 3 deletions.
7 changes: 7 additions & 0 deletions pkg/sql/catalog/tabledesc/table.go
Original file line number Diff line number Diff line change
Expand Up @@ -362,6 +362,13 @@ func FindFKReferencedUniqueConstraint(
uniqueWithoutIndexConstraints := referencedTable.GetUniqueWithoutIndexConstraints()
for i := range uniqueWithoutIndexConstraints {
c := &uniqueWithoutIndexConstraints[i]

// A partial unique constraint cannot be a reference constraint for a
// FK.
if c.IsPartial() {
continue
}

// TODO(rytaft): We should allow out-of-order unique constraints, as long
// as they have the same columns.
if descpb.ColumnIDs(c.ColumnIDs).Equals(referencedColIDs) {
Expand Down
13 changes: 10 additions & 3 deletions pkg/sql/logictest/testdata/logic_test/fk
Original file line number Diff line number Diff line change
Expand Up @@ -3634,11 +3634,18 @@ statement ok
CREATE TABLE child2 (c INT PRIMARY KEY, p INT REFERENCES db1.public.parent(p))

# Test that foreign keys cannot reference columns that are indexed by a partial
# unique index. Partial unique indexes do not guarantee uniqueness in the entire
# table.
# unique index or a partial unique constraint. Partial unique indexes and
# constraints do not guarantee uniqueness in the entire table.

statement ok
CREATE TABLE partial_parent (p INT, UNIQUE INDEX (p) WHERE p > 100)
SET experimental_enable_unique_without_index_constraints = true

statement ok
CREATE TABLE partial_parent (
p INT,
UNIQUE INDEX (p) WHERE p > 100,
UNIQUE WITHOUT INDEX (p) WHERE p > 0
)

statement error there is no unique constraint matching given keys for referenced table partial_parent
CREATE TABLE partial_child (p INT REFERENCES partial_parent (p))
Expand Down

0 comments on commit 0a5de20

Please sign in to comment.