Skip to content

Commit

Permalink
sql: fix accidental FK check skips
Browse files Browse the repository at this point in the history
This change fixes a bug in the insert fast path where we accidentally
skip subsequent FK checks when a FK check can be skipped due to NULL
value.

Note that this bug does not manifest when optbuilder can determine
that the check can be elided entirely; notably, this is always the
case for non-prepared statements which insert a single row.

Fixes cockroachdb#68307.

Release note (bug fix): fixed missing foreign key checks in some cases
when there are multiple checks and the inserted data contains a NULL
for one of the checks.
  • Loading branch information
RaduBerinde authored and Sajjad Rizvi committed Aug 10, 2021
1 parent a733c00 commit b1d4b98
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 2 deletions.
4 changes: 2 additions & 2 deletions pkg/sql/insert_fast_path.go
Original file line number Diff line number Diff line change
Expand Up @@ -162,8 +162,8 @@ func (r *insertFastPathRun) addFKChecks(
return c.errorForRow(inputRow)
}
// We have a row with only NULLS, or a row with some NULLs and match
// method PARTIAL. We can ignore this row.
return nil
// method PARTIAL. We can skip this FK check for this row.
continue
}

span, err := c.generateSpan(inputRow)
Expand Down
17 changes: 17 additions & 0 deletions pkg/sql/logictest/testdata/logic_test/fk
Original file line number Diff line number Diff line change
Expand Up @@ -3791,3 +3791,20 @@ statement error insert on table "reference_constraint_different_order_child" vio
INSERT
INTO reference_constraint_different_order_child
VALUES (99, 1, 2, 3, 'child_val')

# Regression test for #68307.
statement ok
CREATE TABLE t1 (a INT8 PRIMARY KEY);
CREATE TABLE t2 (a INT8 PRIMARY KEY);
CREATE TABLE t3 (a INT8 PRIMARY KEY, b INT8 REFERENCES t1 (a), c INT8 REFERENCES t2 (a));
INSERT INTO t1 VALUES (1);
INSERT INTO t2 VALUES (1);

statement error violates foreign key constraint "fk_b_ref_t1"
INSERT INTO t3 VALUES (1, 1, 1), (2, 2, NULL)

statement error violates foreign key constraint "fk_c_ref_t2"
INSERT INTO t3 VALUES (1, 1, 1), (2, NULL, 2)

statement ok
DROP TABLE t3, t1, t2

0 comments on commit b1d4b98

Please sign in to comment.