3

I have set PRAGMA foreign_keys=ON;

I'm trying to delete some records in a sqlite3 table and it displays Error: constraint failed

sqlite> delete from auth_user where id = 110;
Error: constraint failed

It works if the PRAGMA foreign_keys was OFF. The database has so many tables and the error is so vague. I think other database systems will list the tables that reference the primary key if we attempt deletion.

What is the efficient way I can find all the tables that reference that particular primary key id=110?

Schema:

CREATE TABLE "auth_user" (
    "id" integer NOT NULL PRIMARY KEY,
    "username" varchar(30) NOT NULL UNIQUE,
    "first_name" varchar(30) NOT NULL,
    "last_name" varchar(30) NOT NULL,
    "email" varchar(75) NOT NULL,
    "password" varchar(128) NOT NULL,
    "is_staff" bool NOT NULL,
    "is_active" bool NOT NULL,
    "is_superuser" bool NOT NULL,
    "last_login" datetime NOT NULL,
    "date_joined" datetime NOT NULL
);
Vigneshwaran
  • 3,265
  • 6
  • 23
  • 36

1 Answers1

5

I don't think there is a clear-cut way to list the foreign key constraints with SQLite. You can however list all tables with such constraints as shown below. You can then parse the returned SQL to find the constraints.

Say you have a two parent-child tables:

sqlite> PRAGMA foreign_keys=ON;
sqlite> create table Parent (
   ...>     Id INTEGER PRIMARY KEY AUTOINCREMENT, 
   ...>     foo TEXT);
sqlite> create table Child (
   ...>     Id INTEGER PRIMARY KEY AUTOINCREMENT, 
   ...>     ParentId INTEGER NOT NULL, 
   ...>     bar TEXT,
   ...>     FOREIGN KEY (ParentId) REFERENCES Parent(Id));

You can list the CREATE TABLE statements that have foreign keys:

sqlite> SELECT sql FROM sqlite_master WHERE sql LIKE '%REFERENCES%';
CREATE TABLE Child (
    Id INTEGER PRIMARY KEY AUTOINCREMENT, 
    ParentId INTEGER NOT NULL, 
    bar TEXT,
    FOREIGN KEY (ParentId) REFERENCES Parent(Id))

You may already know this, but deleting rows that are constrained some foreign key while foreign keys are turned off kinda breaks referential integrity of the database, so I can only advise you against doing that.