This question already has an answer here:
Error when trying to update sqlite database in android
(1 answer)
Closed 6 years ago.
Working with the artist/tracks example at https://www.sqlite.org/foreignkeys.html
I'd like to drop both tables. I would think that if I first drop tracks (which References artist) I could then drop artists:
stat_5.executeUpdate("drop table if exists tracks;");
stat_6.executeUpdate("drop table if exists artist;");
But this issues an exception "SQLException: foreign key constraint failed"
What am I missing?
The documentation says:
If foreign key constraints are enabled, a DROP TABLE command performs an implicit DELETE FROM command before removing the table from the database schema. [...] If the implicit DELETE FROM executed as part of a DROP TABLE command violates any immediate foreign key constraints, an error is returned and the table is not dropped.
Remove the data in the correct order so that all intermediate steps are valid.
Or just disable foreign constraint checking.
Related
I have a Xamarin.Forms app that uses a SQLite database locally on the device. Here's some sample data structure:
Table x: id, name
Table y: id, name
Table x_y: id, x_id, y_id
Since SQLite doesn't support altering columns, one of the schema updates we sent down in a patch did the following:
Rename table x to x_temp
Create new/updated table x
Insert all data from table x_temp into table x
Drop table if exists x
That seems to work just fine. However, when I'm attempting to run an insert statement on table x_y, I am getting a SQLite exception: "no such table: main.x_temp".
When I look at the SQLite query string while debugging there is no mention of table x_temp whatsoever. So, if I delete the entire database and re-create everything the insert works just fine.
I'm from a MSSQL background, am I not understanding something about SQLite in general? Is the foreign key constraint from table x_y trying to reference x_temp because I renamed the original table (I may have just answered my own question)? If that's the case, surely there is a way around this without having to cascade and re-create every table?
Any input would be appreciated. Thanks!
I believe that your issue may be related to the SQlite version in conjunction with whether or not Foreign Key Support has been turned on.
That is the likliehood is that :-
Is the foreign key constraint from table x_y trying to reference
x_temp because I renamed the original table (I may have just answered
my own question)?
Would be the issue, as you likely have Foreign Key Support turned on as per :-
Prior to version 3.26.0 (2018-12-01), FOREIGN KEY references to a table that is renamed were only edited if the PRAGMA foreign_keys=ON, or in other words if foreign key constraints were begin enforced.
With PRAGMA foreign_keys=OFF, FOREIGN KEY constraints would not be changed when the table that the foreign key referred to (the "parent table") was renamed.
Beginning with version 3.26.0, FOREIGN KEY constraints are always converted when a table is renamed, unless the PRAGMA legacy_alter_table=ON setting is engaged. The following table summaries the difference:
SQL As Understood By SQLite - ALTER TABLE
If that's the case, surely there is a way around this without having
to cascade and re-create every table?
Yes, as the latest version of SQlite on Android is 3.19.0 (I believe), then you can turn Foreign Key support off using the foreign_keys pragma when renaming the table.
Note Foreign Keys cannot be turned off within a transaction.
See SQL As Understood By SQLite - ALTER TABLE and PRAGMA foreign_keys = boolean;
Context:
I'm trying to upgrade a concrete5 installation from version 8.3.2 to 8.4.1. The upgrade process fails during execution of this SQL statement:
ALTER TABLE AreaLayoutsUsingPresets ADD CONSTRAINT FK_7A9049A1385521EA FOREIGN KEY (arLayoutID) REFERENCES AreaLayouts (arLayoutID) ON UPDATE CASCADE ON DELETE CASCADE
With:
SQLSTATE[HY000]: General error: 1005 Can't create table `concrete5`.`#sql-215_264a4` (errno: 121 "Duplicate key on write or update")
Investigating my database revealed that in information_schema in INNODB_SYS_FOREIGN there is the following entry:
ID FOR_NAME REF_NAME N_COLS TYPE
concrete5/FK_7A9049A1385521EA concrete5/#sql-215_26264 concrete5/AreaLayouts 1 5
Problem:
Now my understanding is, that I cannot modify the information_schema as it isn't a database but just a tabular representation of the system.
I'm wondering how do I get rid of that foreign key entry. The table concrete5/#sql-215_26264 does not exist (I can't find it on my server, nor does alter table or drop table find that table (I've tried with #mysql50# prefix and without it)). So the straight forward way of alter table to drop the foreign key fails because it can't find the table.
I guess I could mess with the upgrade script so that it creates a new foreign key ID, but I'd rather get rid of that zombie in my database. I've already tried to disable the foreign key checks, which then resulted in an error, telling me that the key cannot be added to the system tables (because it's already in there).
Reinstalling is rarely a cure for anything; but I am glad that it fixed your situation.
Table names such as #sql_... usually come from crashing in the middle of an ALTER or similar DDL. Such files can be removed. information_schema is derived from looking at the files, so I think removing the files will kill the zombie entries.
either prefix the SQL import with SET FOREIGN_KEY_CHECKS=0;
or your append it to your query ALTER TABLE...DISABLE KEYS;
... and better dump the whole database before messing around.
This question already has an answer here:
Add ON DELETE CASCADE behavior to an sqlite3 table after it has been created
(1 answer)
Closed 5 years ago.
I am adding constraints to tables in Sqlite as following:
alter table TagsI18N
add constraint FK_TagsI18N_TagId foreign key (TagId) references Tag(Id) on delete cascade on update cascade,
constraint FK_TagsI18N_LanguageCode foreign key (LanguageCode) references [Languages](Code) on delete cascade on update cascade;
I was using this code in SQL Server database but is not being accepted in SQLite.
How can I create such a constraint in Sqlite?
The ALTER command in SQLite3 is limited to adding columns or renaming tables, so you cannot do this. Instead, you must re-create the table with the desired constraints.
This question already has answers here:
Failed to enable constraints. One or more rows contain values violating non-null, unique, or foreign-key constraints
(26 answers)
Closed 8 years ago.
I have this query running against 2008R2. tblJoin is the table in between two tables(tblIncident and tblPatron) for many-to-many relationship.
While I am building the query in VS2012, in the Query Builder window when I execute the query it runs fine and gives me the desired results. However in the last step when I click on TestQuery and enter the parameter it gives an error:
"Failed to enable constraints.."
I checked the datatype and they all match against each other against the tables,
SELECT tblIncident.Inci_ID,
_tblJoin.PatronID,
_tblJoin.LName,
_tblJoin.FName,
_tblJoin.MI
FROM tblJoin INNER JOIN
tblIncident ON tblJoin.InciID = tblIncident.Inci_ID AND tblJoin.InciID = tblIncident.Inci_ID
WHERE (tblIncident.Inci_ID = #Inci_ID)
You need Check all the MaxLength property of the columns in your DataTable.
The column that I changed from "nvarchar(512)" to "nvarchar(MAX)" still had the 512 value on the MaxLength property so I changed to "-1" and it works!!.
You can solve this issue from this discussion
Failed to enable constraints. One or more rows contain values violating non-null, unique, or foreign-key constraints
There have many answers ....
Thanks Ramesh and Vignesh. Vignesh's comment made me think about the duplicate foreign key. So I kept the query but removed the foreign key (Incident ID), that made it worked. This is how my query looks like:
SELECT tblJoin.PatronID, tblJoin.LName, tblJoin.FName, tblJoin.MI FROM tblJoin
INNER JOIN tblIncident ON tblJoin.InciID = tblIncident.Inci_ID
WHERE (tblIncident.Inci_ID = #Inci_ID)
I am currently trying to create an sqlite database where I can import a table from another sqlite database (can't attach) and add some extra data to each column.
Since there is no INSERT OR UPDATE I came up with this:
I was thinking about splitting the data into two tables and join them afterwards so I can just dump the whole import into one table replacing everything that changed and manage the extra data separately since that does not change on import.
The first table (let's call it base_data) would look like
local_id | remote_id | base_data1 | base_data2 | ...
---------+-----------+------------+------------+----
besides the local_id everything would just be a mirror of the remote database (I'll probably add a sync timestamp but that does not matter now).
The second table would look similar but has remote_id set as foreign key
remote_id | extra_data1 | extra_data2 | ...
----------+-------------+-------------+----
CREATE TABLE extra_data (
remote_id INTEGER
REFERENCES base_data(remote_id)
ON DELETE CASCADE ON UPDATE CASCADE
DEFERRABLE INITIALLY DEFERRED,
extra_data1 TEXT,
extra_data2 TEXT,
/* etc */
)
Now my idea was to simply INSERT OR REPLACE INTO base_data ... values because the database I import from has no sync timestamp or whatsoever and I would have to compare everything to find out what row I have to UPDATE / what to INSERT.
But here lies the problem: INSERT OR REPLACE is actually a DELETE followed by an INSERT and the delete part triggers the foreign key ON DELETE which I thought I could prevent by making the constraint DEFERRED. It does not work if I wrap INSERT OR REPLACE in a transaction either. It's always deleting my extra data although the same foreign key exists after the statement.
Is it possible to stop ON DELETE to trigger until the INSERT OR REPLACE is finished? Maybe some special transaction mode / pragma ?
It seems work if I replace the ON DELETE CASCADE part by a trigger like:
CREATE TRIGGER on_delete_trigger
AFTER DELETE ON base_data
BEGIN
DELETE FROM extra_data WHERE extra_data.remote_id=OLD.remote_id;
END;
That trigger is only triggered by a DELETE statement and should solve my problem so far.
(Answer provided by the OP in the question)
Additional info by jmathew, citing the documentation:
When the REPLACE conflict resolution strategy deletes rows in order to satisfy a constraint, delete triggers fire if and only if recursive triggers are enabled.
Assuming you only have a single foreign key relationship on a primary key in your referenced table (as you do in your example), this proved to be a fairly painless solution for me.
Simply disable foreign key checks, run the replace query, then enable foreign keys again.
If the replace query is the only query that runs while foreign keys are disabled, you can be assured that no foreign keys will be fouled up. If you are inserting a new row, nothing will have had a chance to be linked to it yet and if you are replacing a row, the existing row will not be removed or have its primary key changed by the query so the constraint will still hold once foreign keys are re-enabled.
SQLlite code looks something like this:
PRAGMA foreign_keys=OFF;
INSERT OR REPLACE ...;
PRAGMA foreign_keys=ON;
What about the reasons of such behavior, there's an explanation from PostgreSQL team:
Yeah, this is per SQL spec as far as we can tell. Constraint checks can
be deferred till end of transaction, but "referential actions" are not
deferrable. They always happen during the triggering statement. For
instance SQL99 describes the result of a cascade deletion as being that
the referencing row is "marked for deletion" immediately, and then
All rows that are marked for deletion are effectively deleted
at the end of the SQL-statement, prior to the checking of any
integrity constraints.