Skip to content

Commit

Permalink
sql: disqualify partial unique indexes as foreign key reference indexes
Browse files Browse the repository at this point in the history
Release justification: This is a critical bug fix for a new feature,
partial indexes.

Release note (bug fix): Foreign keys can no longer reference columns
that are only indexed by a partial unique index. A partial unique index
does not guarantee uniqueness in the entire table, therefore the column
indexed is not guaranteed to be a unique key.
  • Loading branch information
mgartner committed Oct 19, 2020
1 parent 4930466 commit 3ee3d65
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 2 deletions.
4 changes: 2 additions & 2 deletions pkg/sql/catalog/descpb/index.go
Original file line number Diff line number Diff line change
Expand Up @@ -160,13 +160,13 @@ func (desc *IndexDescriptor) ColNamesString() string {
// IsValidOriginIndex returns whether the index can serve as an origin index for a foreign
// key constraint with the provided set of originColIDs.
func (desc *IndexDescriptor) IsValidOriginIndex(originColIDs ColumnIDs) bool {
return ColumnIDs(desc.ColumnIDs).HasPrefix(originColIDs)
return !desc.IsPartial() && ColumnIDs(desc.ColumnIDs).HasPrefix(originColIDs)
}

// IsValidReferencedIndex returns whether the index can serve as a referenced index for a foreign
// key constraint with the provided set of referencedColumnIDs.
func (desc *IndexDescriptor) IsValidReferencedIndex(referencedColIDs ColumnIDs) bool {
return desc.Unique && ColumnIDs(desc.ColumnIDs).Equals(referencedColIDs)
return desc.Unique && !desc.IsPartial() && ColumnIDs(desc.ColumnIDs).Equals(referencedColIDs)
}

// HasOldStoredColumns returns whether the index has stored columns in the old
Expand Down
10 changes: 10 additions & 0 deletions pkg/sql/logictest/testdata/logic_test/fk
Original file line number Diff line number Diff line change
Expand Up @@ -3626,3 +3626,13 @@ USE db2

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.

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

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))
3 changes: 3 additions & 0 deletions pkg/sql/opt/testutils/testcat/create_table.go
Original file line number Diff line number Diff line change
Expand Up @@ -365,6 +365,9 @@ func (tc *Catalog) resolveFK(tab *Table, d *tree.ForeignKeyConstraintTableDef) {
return false
}
}
if _, isPartialIndex := idx.Predicate(); isPartialIndex {
return false
}
return true
}

Expand Down

0 comments on commit 3ee3d65

Please sign in to comment.