SQLite User Forum

constraint names not used in foreign key error messages
Login

constraint names not used in foreign key error messages

(1) By Donal Fellows (dkfellows) on 2022-06-08 11:20:41 [link] [source]

If you do this (tried with https://sqlite.org/fiddle/ but affects multiple versions):

PRAGMA foreign_keys = true;
CREATE TABLE IF NOT EXISTS x(id INTEGER PRIMARY KEY AUTOINCREMENT);
CREATE TABLE IF NOT EXISTS y(foo CONSTRAINT "foobar" REFERENCES x(id));
INSERT INTO y(foo) VALUES(123);
You get an error message (this is correct):
FOREIGN KEY constraint failed
(plus information about the line number, etc.)

But you don't get the explicit name of the constraint (foobar in this case). In a non-trivial schema, it would be really nice to know which constraint failed, just like you can get with providing an explicit name for CHECK constraints.

Or am I doing something wrong?

(2) By Richard Hipp (drh) on 2022-06-08 11:24:29 in reply to 1 [source]

SQLite itself does not know which constraint failed.

The Foreign Key constraint mechanism works by using a counter of failed constraints. When a constraint fails the counter increments. When a constraint is resolved later on within the same statement, the counter decrements. If at the end of the statement (or transaction) the counter is non-zero, then you get an error.

(4) By Donal Fellows (dkfellows) on 2022-06-08 11:34:08 in reply to 2 [link] [source]

That's a shame, as debugging big schemas (i.e., the fault is either in the schema or the data, not the engine) is currently a bit annoying. I was very pleased that CHECK constraints can be usefully labelled and hoped that this was true for other major category of constraints in my schema.

In theory, I guess you could have somewhere a variable that's set (once, at the point the first FK failure is detected) to the name of the failed constraint; there might be others, but then there'd be a place to start looking for what went wrong. But I don't know how practical that would be to do, or what the performance impact would be. On the other hand, at the point when this fires off then we're already off the happy path...

(3) By Stephan Beal (stephan) on 2022-06-08 11:34:00 in reply to 1 [link] [source]

If you do this (tried with https://sqlite.org/fiddle/ but affects multiple versions):

Project milestone: AFAIK you're the first person to report having tested with /fiddle before posting :).

(5) By Donal Fellows (dkfellows) on 2022-06-08 11:35:36 in reply to 3 [link] [source]

I'm able to test stuff locally, but it's with a significantly older version and I didn't want to report anything that's already fixed. ;-)