Add a restriction to an existing SQLite table

I am using SQLite, which does not support by adding a constraint to an existing table.

Therefore, I cannot do something like this (as an example):

ALTER TABLE [Customer]
ADD CONSTRAINT specify_either_phone_or_email
CHECK (([Phone] IS NOT NULL) OR ([Email] IS NOT NULL));

Are there any workarounds for this scenario?

I know:

  • I can add a constraint for the new table, but it is not new (and it is generated by my ORM, EF Core)
  • I can do a “table rebuild” (rename the table, create a new one, copy the old data, temp temp table), but it seems very complicated.

Ideas

  • Is there any way to copy a table into a new table with some schema changes?
  • Or somehow "get" the schema and edit it in the SQL script, and then add a table with this schema?
+4
1

, :

BEGIN;
CREATE TABLE Customer_new (
    [...],
    CHECK ([...])
);
INSERT INTO Customer_new SELECT * FROM Customer;
DROP TABLE Customer;
ALTER TABLE Customer_new RENAME TO Customer;
COMMIT;

, .schema Customer sqlite3 . CREATE TABLE, .


, .

( , .schema):

SELECT sql FROM sqlite_master WHERE type = 'table' AND name = 'Customer';

CHECK , sqlite_master PRAGMA writable_schema = 1; :

UPDATE sqlite_master SET sql='...' WHERE type='table' AND name='Customer';

.

. , . - , (, / , ), .

+6

Source: https://habr.com/ru/post/1672980/


All Articles