Foreign Key constraint doesn't work - sqlite

I have two tables, theme and quiz, here is their definition:
CREATE TABLE "theme" ("id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL , "nom" VARCHAR NOT NULL );
CREATE TABLE quiz(
id INTEGER PRIMARY KEY,
nom VARCHAR(256) NOT NULL,
theme INTEGER NOT NULL,
niveau INTEGER NOT NULL,
pass INTEGER DEFAULT 1 NOT NULL,
jok INTEGER DEFAULT 1 NOT NULL,
etat INTEGER DEFAULT 0 NOT NULL,
FOREIGN KEY (theme) REFERENCES theme(id)
);
The field id (the primary key) in the table theme is a Foreign Key in the quiz table.
When i try to insert a record in the table quiz which contain the value 30 for example as a foreign key, the record is inserted successfully in the quiz table although there is no record in the theme table with the id = 30, i mean, wasn't supposed to interdict this insert since i had a Foreign key constraint?

Are you sure foreign key support is enabled?
Assuming the library is compiled with foreign key constraints enabled,
it must still be enabled by the application at runtime, using the
PRAGMA foreign_keys command. For example:
sqlite> PRAGMA foreign_keys = ON;

Related

Cannot restart Strapi after making changes to Content Types (using SQLite)

I have followed the quickstart setup for Strapi, which as I understand sets up an SQLite Database. I created one collection type (painting) which worked without problems, but whenever I try to add a new one or make changes to the existing one the server does not restart and I receive the following error output in my console:
[2022-05-23 16:53:16.323] error: CREATE TABLE _knex_temp_alter889 (id integer not null primary key autoincrement PRIMARY KEY AUTOINCREMENT NOT NULL, title varchar(255) NULL, artist varchar(255) NULL, created_at datetime NULL, updated_at datetime NULL, published_at datetime NULL, created_by_id integer NULL, updated_by_id integer NULL, CONSTRAINT paintings_created_by_id_fk FOREIGN KEY (created_by_id) REFERENCES admin_users (id) ON DELETE SET NULL, CONSTRAINT paintings_updated_by_id_fk FOREIGN KEY (updated_by_id) REFERENCES admin_users (id) ON DELETE SET NULL, CONSTRAINT paintings_created_by_id_fk FOREIGN KEY (created_by_id) REFERENCES admin_users (id) ON DELETE SET NULL, CONSTRAINT paintings_updated_by_id_fk FOREIGN KEY (updated_by_id) REFERENCES admin_users (id) ON DELETE SET NULL) - table "_knex_temp_alter889" has more than one primary key
SqliteError: CREATE TABLE _knex_temp_alter889 (id integer not null primary key autoincrement PRIMARY KEY AUTOINCREMENT NOT NULL, title varchar(255) NULL, artist varchar(255) NULL, created_at datetime NULL, updated_at datetime NULL, published_at datetime NULL, created_by_id integer NULL, updated_by_id integer NULL, CONSTRAINT paintings_created_by_id_fk FOREIGN KEY (created_by_id) REFERENCES admin_users (id) ON DELETE SET NULL, CONSTRAINT paintings_updated_by_id_fk FOREIGN KEY (updated_by_id) REFERENCES admin_users (id) ON DELETE SET NULL, CONSTRAINT paintings_created_by_id_fk FOREIGN KEY (created_by_id) REFERENCES admin_users (id) ON DELETE SET NULL, CONSTRAINT paintings_updated_by_id_fk FOREIGN KEY (updated_by_id) REFERENCES admin_users (id) ON DELETE SET NULL) - table "_knex_temp_alter889" has more than one primary key
Deleting the changes I made in my content-types files is currently the only way I have of getting the server to run again. How do I fix this?
So, I ended up creating a new project. Problem seems to have been that I added a field named 'ID', which I assume messed everything up because it conflicted with the automatically assigned ID-System.

Strange org.sqlite.SQLiteException: [SQLITE_ERROR] SQL error or missing database (foreign key mismatch -

I'm running into org.sqlite.SQLiteException: [SQLITE_ERROR] SQL error or missing database (foreign key mismatch - ... with a statement, that proceeds without any complaints using the normal SQLite-frontend. This creates the crucial part of my database:
CREATE TABLE IF NOT EXISTS artists (
aid INTEGER PRIMARY KEY AUTOINCREMENT,
aname VARCHAR(200) NOT NULL,
CONSTRAINT one UNIQUE(aname)
);
CREATE TABLE IF NOT EXISTS discs (
did INTEGER PRIMARY KEY AUTOINCREMENT,
testAddCD1 BIGINT(10) NOT NULL,
dtitle VARCHAR(125) NOT NULL,
dreleaseyear YEAR(4) DEFAULT NULL,
dlang VARCHAR(3) DEFAULT NULL
);
CREATE TABLE IF NOT EXISTS tracks (
discs_did INTEGER NOT NULL,
tnumber INT(4) NOT NULL,
ttitle VARCHAR(125) NOT NULL,
tseconds INT(4) NOT NULL,
CONSTRAINT pk PRIMARY KEY(discs_did, tnumber),
CONSTRAINT fk FOREIGN KEY(discs_did) REFERENCES discs(did) ON DELETE RESTRICT ON UPDATE RESTRICT,
CONSTRAINT val CHECK(tseconds> 0)
);
CREATE TABLE IF NOT EXISTS track_by_artist (
discs_did INTEGER NOT NULL,
tracks_tnumber INT(4) NOT NULL,
artists_aid INTEGER NOT NULL,
CONSTRAINT pk PRIMARY KEY(discs_did, tracks_tnumber, artists_aid),
CONSTRAINT fk1 FOREIGN KEY(discs_did) REFERENCES discs(did) ON DELETE RESTRICT ON UPDATE RESTRICT,
CONSTRAINT fk2 FOREIGN KEY(tracks_tnumber) REFERENCES tracks(tnumber) ON DELETE RESTRICT ON UPDATE RESTRICT,
CONSTRAINT fk3 FOREIGN KEY(artists_aid) REFERENCES artists(aid) ON DELETE RESTRICT ON UPDATE RESTRICT
The database gets created and the JDBC-driver inserts an artist, a disc and the disc's tracks - all good. The final insert should assign an artist to a track and looks like
INSERT INTO track_by_artist (discs_did, tracks_tnumber, artists_aid) VALUES (1, 1, 1);
Using the JDBC this yields
SQLite-Error #1
org.sqlite.SQLiteException: [SQLITE_ERROR] SQL error or missing database (foreign key mismatch - "track_by_artist" referencing "tracks")
at org.sqlite.core.DB.newSQLException(DB.java:1012)
at org.sqlite.core.DB.newSQLException(DB.java:1024)
at org.sqlite.core.DB.throwex(DB.java:989)
at org.sqlite.core.NativeDB.prepare_utf8(Native Method)
at org.sqlite.core.NativeDB.prepare(NativeDB.java:134)
at org.sqlite.core.DB.prepare(DB.java:257)
at org.sqlite.core.CorePreparedStatement.<init>(CorePreparedStatement.java:45)
at org.sqlite.jdbc3.JDBC3PreparedStatement.<init>(JDBC3PreparedStatement.java:30)
at org.sqlite.jdbc4.JDBC4PreparedStatement.<init>(JDBC4PreparedStatement.java:25)
at org.sqlite.jdbc4.JDBC4Connection.prepareStatement(JDBC4Connection.java:35)
at org.sqlite.jdbc3.JDBC3Connection.prepareStatement(JDBC3Connection.java:241)
at org.sqlite.jdbc3.JDBC3Connection.prepareStatement(JDBC3Connection.java:205)
Issuing the same SQL-Insert with SQLite's text-frontend works like cream.
I'm a little lost and don't know what to do about my Java-code.
Some advise, pls?
Chris
The problem is that in track_by_artist you defined this foreign key constraint:
CONSTRAINT fk2 FOREIGN KEY(tracks_tnumber) REFERENCES tracks(tnumber) ON DELETE RESTRICT ON UPDATE RESTRICT
although tnumber in tracks is not UNIQUE (and it shouldn't be).
A foreign key's parent must be defined as UNIQUE.
In tracks the PRIMARY KEY is defined as the combination of discs_did and tnumber, which makes sense, so the combination of these 2 columns is unique.
What you can do is define in track_by_artist a composite foreign key for the columns discs_did and tracks_tnumber that reference discs_did and tnumber of tracks:
CREATE TABLE IF NOT EXISTS track_by_artist (
discs_did INTEGER NOT NULL,
tracks_tnumber INT(4) NOT NULL,
artists_aid INTEGER NOT NULL,
CONSTRAINT pk PRIMARY KEY(discs_did, tracks_tnumber, artists_aid),
CONSTRAINT fk1 FOREIGN KEY(discs_did, tracks_tnumber) REFERENCES tracks(discs_did, tnumber) ON DELETE RESTRICT ON UPDATE RESTRICT,
CONSTRAINT fk2 FOREIGN KEY(artists_aid) REFERENCES artists(aid) ON DELETE RESTRICT ON UPDATE RESTRICT
);
This way you don't need a separate foreign key definition for discs_did.

Recursive foreign key 'on delete cascade'

CREATE TABLE IF NOT EXISTS type (
tid INTEGER NOT NULL,
uuid VARCHAR NOT NULL,
name VARCHAR NOT NULL,
CONSTRAINT PK PRIMARY KEY (tid),
CONSTRAINT UNQ_0 UNIQUE (uuid),
CONSTRAINT UNQ_1 UNIQUE (name)
);
CREATE INDEX IDX_type_0 ON type (tid,uuid,name);
CREATE TABLE IF NOT EXISTS object (
oid VARCHAR NOT NULL,
timestamp VARCHAR NOT NULL,
tid INTEGER NOT NULL,
CONSTRAINT FK_tid FOREIGN KEY (tid) REFERENCES type(tid) ON UPDATE CASCADE ON DELETE CASCADE,
CONSTRAINT UNQ_0 UNIQUE (oid)
);
CREATE INDEX IDX_object_0 ON object (oid,timestamp,tid);
CREATE TABLE IF NOT EXISTS object_user_owner (
uid INTEGER NOT NULL,
oid VARCHAR NOT NULL,
CONSTRAINT FK_uid FOREIGN KEY (uid) REFERENCES user(uid) ON UPDATE CASCADE ON DELETE CASCADE,
CONSTRAINT FK_oid FOREIGN KEY (oid) REFERENCES object(oid) ON UPDATE CASCADE ON DELETE CASCADE,
CONSTRAINT UNQ_0 UNIQUE (oid,uid)
);
CREATE INDEX IDX_object_user_owner_0 ON object_user_owner (uid,oid);
CREATE TABLE IF NOT EXISTS user (
uid INTEGER NOT NULL,
uuid VARCHAR NOT NULL,
name VARCHAR NOT NULL,
password VARCHAR NOT NULL,
salt VARCHAR NOT NULL,
timestamp VARCHAR NOT NULL,
lastaccess VARCHAR NOT NULL,
CONSTRAINT PK PRIMARY KEY (uid),
CONSTRAINT UNQ_0 UNIQUE (uuid),
CONSTRAINT UNQ_1 UNIQUE (name)
);
CREATE INDEX IDX_user_0 ON user (uid,uuid,name);
The above three sqlite3 tables contain foreign keys. The problem is the deletion of a key in the upper table type. When I try do delete I get 'FOREIGN KEY constraint failed' Error. Deleting a from the lowest table object_user_owner before deleting a type works. I think sqlite does not check any recursive cascade constraints. Does anyone have experienced this too or is anything wrong with my design?

foreign key mismatch on delete command for unrelated record

I have the following 5 tables defined with a few records inserted into the 1st 4. This is using sqlite 3.7.1.7 with foreign key constaint enabled.
create table if not exists subject (id varchar(50) primary key,desc varchar(100));
insert into subject (id,desc) values ("subject1","test subject");
create table if not exists subjectlevel (id_subject_id varchar(50) references subject(id) on delete cascade, id integer not null, desc varchar(100) not null, questmcmaxselections integer not null, primary key (id_subject_id,id));
insert into subjectlevel (id_subject_id,id,desc,questmcmaxselections) values ("subject1",1,"test subject1 level 1",4);
insert into subjectlevel (id_subject_id,id,desc,questmcmaxselections) values ("subject1",2,"test subject1 level 2",4);
create table if not exists questmc (id integer primary key, text varchar(300) not null, includeallanswers int not null, subject_id varchar(50), subjectlevel_id integer, foreign key (subject_id, subjectlevel_id) references subjectlevel (id_subject_id,id) on delete cascade);
insert into questmc (text,includeallanswers,subject_id,subjectlevel_id) values ("this is a _ question", 1, "subject1",1);
create table if not exists questmcselection (id integer primary key, text varchar(100) not null, subject_id varchar(50), subjectlevel_id integer, foreign key (subject_id, subjectlevel_id) references subjectlevel (id_subject_id,id) on delete cascade);
insert into questmcselection (text,subject_id,subjectlevel_id) values ("this is a solution","subject1",1);
create table if not exists questmc_questmcselection(id integer primary key, answer integer not null, questmc_id integer, questmcselection_id integer, subject_id varchar(50), subjectlevel_id integer, foreign key (questmc_id) references questmc(id) on delete cascade, foreign key (questmcselection_id) references questmcselection (id) on delete cascade, foreign key (subject_id,subjectlevel_id) references questmc (subject_id,subjectlevel_id) on delete cascade, foreign key (subject_id,subjectlevel_id) references questmcselection (subject_id,subjectlevel_id));
if i attempt to delete the second record in the subjectlevel table, i get a foreign key mismatch error as long as table questmc_questmcselection is defined.
sqlite> delete from subjectlevel where id=2;
Error: foreign key mismatch - "questmc_questmcselection" referencing "questmcselection"
questmc, questmcselection, and questmc_questmcselection have no related existing records that should prevent this deletion. Any idea why this error occurs?
This error has nothing to do with this particular subjectlevel record.
Your problem is that your tables lack the required indexes.
This was not reported earlier because that DELETE statement was the first command that required SQLite to check the consistency of the database schema.
Based on CL's answer -
sqlite> create table parent(a);
sqlite> create table child(a, FOREIGN KEY (a) REFERENCES parent(a));
sqlite> pragma foreign_keys = ON;
sqlite> insert into parent values(3);
sqlite> insert into child values (3);
Error: foreign key mismatch - "child" referencing "parent"
sqlite> create unique index p_a on parent(a);
sqlite> insert into child values (3);
sqlite> _
From the documentation:
Usually, the parent key of a foreign key constraint is the primary key
of the parent table. If [not], then the parent key columns must be
collectively subject to a UNIQUE constraint or have a UNIQUE index [which uses]
the collation sequences ... in the CREATE TABLE
statement for the parent table.
i.e. the alternative is:
sqlite> create table parent(a, b, UNIQUE (a, b));
sqlite> create table child (x, y, FOREIGN KEY (x, y) REFERENCES parent(a, b));
(this also highlights multi-column foreign keys; they work with indexes too...)

SQLite foreign key mismatch error

Why am I getting a SQLite "foreign key mismatch" error when executing script below?
DELETE
FROM rlsconfig
WHERE importer_config_id=2 and
program_mode_config_id=1
Here is main table definition:
CREATE TABLE [RLSConfig] (
"rlsconfig_id" integer PRIMARY KEY AUTOINCREMENT NOT NULL,
"importer_config_id" integer NOT NULL,
"program_mode_config_id" integer NOT NULL,
"l2_channel_config_id" integer NOT NULL,
"rls_fixed_width" integer NOT NULL
,
FOREIGN KEY ([importer_config_id])
REFERENCES [ImporterConfig]([importer_config_id]),
FOREIGN KEY ([program_mode_config_id])
REFERENCES [ImporterConfig]([importer_config_id]),
FOREIGN KEY ([importer_config_id])
REFERENCES [ImporterConfig]([program_mode_config_id]),
FOREIGN KEY ([program_mode_config_id])
REFERENCES [ImporterConfig]([program_mode_config_id])
)
and referenced table:
CREATE TABLE [ImporterConfig] (
"importer_config_id" integer NOT NULL,
"program_mode_config_id" integer NOT NULL,
"selected" integer NOT NULL DEFAULT 0,
"combined_config_id" integer NOT NULL,
"description" varchar(50) NOT NULL COLLATE NOCASE,
"date_created" datetime NOT NULL DEFAULT (CURRENT_TIMESTAMP),
PRIMARY KEY ([program_mode_config_id], [importer_config_id])
,
FOREIGN KEY ([program_mode_config_id])
REFERENCES [ProgramModeConfig]([program_mode_config_id])
)
When you use a foreign key over a table that has a composite primary key you must use a composite foreign key with all the fields that are in the primary key of the referenced table.
Example:
CREATE TABLE IF NOT EXISTS parents
(
key1 INTEGER NOT NULL,
key2 INTEGER NOT NULL,
not_key INTEGER DEFAULT 0,
PRIMARY KEY ( key1, key2 )
);
CREATE TABLE IF NOT EXISTS childs
(
child_key INTEGER NOT NULL,
parentKey1 INTEGER NOT NULL,
parentKey2 INTEGER NOT NULL,
some_data INTEGER,
PRIMARY KEY ( child_key ),
FOREIGN KEY ( parentKey1, parentKey2 ) REFERENCES parents( key1, key2 )
);
I am not sure about SQLite. But I found this link on google. http://www.sqlite.org/foreignkeys.html.
Some of the reasons can be
The parent table does not exist, or
The parent key columns named in the foreign key constraint do not exist, or
The parent key columns named in the foreign key constraint are not the primary key of the parent table and are not subject to a unique constraint using collating sequence specified in the CREATE TABLE, or
The child table references the primary key of the parent without specifying the primary key columns and the number of primary key columns in the parent do not match the number of child key columns.
Unfortunately, SQLite gives this error all the time without mentioning WHICH foreign key constraint failed. You are left to try to check them one by one, which often doesn't work, and then rebuild the table without the constraints and add them back one by one until you find the problem. SQLite is great in a lot of ways, but this isn't one of them.

Resources