cockroachdb / cockroach

CockroachDB — the cloud native, distributed SQL database designed for high availability, effortless scale, and control over data placement.
https://www.cockroachlabs.com
Other
30.08k stars 3.8k forks source link

sql: check plans can be run twice in presence of AFTER triggers #133792

Open DrewKimball opened 1 hour ago

DrewKimball commented 1 hour ago

When running checks in parallel together, the current logic runs all checks from the main plan (which is used as a queue for any new checks produced by cascades and triggers). This is problematic, because once the post-query loop reaches a second iteration, the checks run in the previous iteration will run again. https://github.com/cockroachdb/cockroach/blob/2ebec1c6f4a99d516e83d0f323c3a5ab96991676/pkg/sql/distsql_running.go#L2215 We need to only run the checks from checksIdx on. Here is a logic test that will produce an unexpectedly found 2 active spans error:

statement ok
CREATE TABLE parent (k INT PRIMARY KEY);

statement ok
CREATE TABLE child (k INT PRIMARY KEY, v INT UNIQUE NOT NULL REFERENCES parent(k) ON UPDATE CASCADE ON DELETE CASCADE);
CREATE TABLE child2 (k INT PRIMARY KEY, v INT UNIQUE NOT NULL REFERENCES parent(k) ON UPDATE CASCADE ON DELETE CASCADE);

statement ok
CREATE TABLE grandchild (
  k INT PRIMARY KEY,
  v INT REFERENCES child(v) ON UPDATE CASCADE ON DELETE CASCADE,
  v2 INT REFERENCES child2(v) ON UPDATE CASCADE ON DELETE CASCADE
);

statement ok
INSERT INTO parent VALUES (1), (2), (3);
INSERT INTO child VALUES (1, 1), (2, 2), (3, 3);
INSERT INTO child2 VALUES (1, 1), (2, 2), (3, 3);
INSERT INTO grandchild VALUES (1, 1, 1), (2, 2, 2), (3, 2, 2), (4, 3, 3);

statement ok
CREATE FUNCTION g() RETURNS TRIGGER LANGUAGE PLpgSQL AS $$
  BEGIN
    RAISE NOTICE '% % ON %: % -> %', TG_WHEN, TG_OP, TG_TABLE_NAME, OLD, NEW;
    RETURN COALESCE(NEW, OLD);
  END
$$;

statement ok
CREATE TRIGGER bar AFTER INSERT OR UPDATE OR DELETE ON child FOR EACH ROW EXECUTE FUNCTION g();

statement ok
UPDATE parent SET k = k + 10 WHERE k < 3;

Note that this test has the same pattern as in #133784 - it just has a different trigger.

Jira issue: CRDB-43756

blathers-crl[bot] commented 1 hour ago

Hi @DrewKimball, please add branch-* labels to identify which branch(es) this C-bug affects.

:owl: Hoot! I am a Blathers, a bot for CockroachDB. My owner is dev-inf.