tarantool / tarantool/tarantool

Triggers and foreign key execution order in SQL

Open
#2,356 13 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

bug sql
Dominant language
Lua
Stars
3.7k
Forks
419
Avg merge
1d 23h
Merged PRs (30d)
88

Description

A problem with triggers in SQL.

box.sql.execute("CREATE TABLE b1 (s1 INT PRIMARY KEY, s2 INT);")
box.sql.execute("CREATE TABLE b2 (s1 INT PRIMARY KEY, s2 INT, FOREIGN KEY (s2)    REFERENCES b1 (s1));")
box.sql.execute("CREATE TABLE b3 (s1 VARCHAR(100) PRIMARY KEY);")
box.sql.execute("PRAGMA foreign_keys=on;")
box.sql.execute("CREATE TRIGGER b2_1 BEFORE INSERT ON b2 FOR EACH ROW WHEN   (SELECT COUNT(*) FROM b2) > 0 BEGIN INSERT INTO b3 VALUES ('before'); END;")
box.sql.execute("CREATE TRIGGER b2_2 AFTER INSERT ON b2 FOR EACH ROW WHEN (SELECT COUNT(*) FROM b2) > 0 BEGIN INSERT INTO b3 VALUES ('after'); END;")
box.sql.execute("INSERT INTO b2 VALUES (1,1);")
box.sql.execute("SELECT * FROM b3;")
box.sql.execute("SELECT * FROM b2;")

Result = the foreign-key check fails, there are two rows in table b3, and there is one row in table b2.
Actually there should be no rows in any tables, because the foreign-key
check failure should cause the INSERT to fail completely, but that is the
subject of a different issue. What matters here is: it seems that the
foreign-key check happens after the firing of the AFTER INSERT trigger.

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by running the supplied box.sql.execute reproduction with the b1, b2, and b3 tables and the b2_1 and b2_2 triggers. Trace the SQL insert path to determine when the foreign-key check runs relative to the BEFORE and AFTER triggers. Done means the execution order matches the intended foreign-key behavior described in the issue.

Written by the indexing model from the issue text.

Assessment

Tech stack
lua, sql
Domain
databases
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.