且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

创建sqlite3表后将其添加到DELETE CASCADE行为

更新时间:2023-12-01 13:15:40

SQLite的 ALTER TABLE 命令不能执行您想要的操作。

SQLite's ALTER TABLE command cannot do what you want.

但是,可以绕过SQL解释器并更改内部表定义直接。
SQLite将表定义存储为 CREATE TABLE 命令的文本副本,该副本在其 sqlite_master ;查看此查询的结果:

However, it is possible to bypass the SQL interpreter and change the internal table definition directly. SQLite stores table definitions as a textual copy of the CREATE TABLE command in its sqlite_master table; check out the result of this query:

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

将级联规范添加到该字符串,然后启用对 sqlite_master PRAGMA writable_schema = 1; 并将新表定义写入其中:

Add your cascade specification to that string, then enable write access to sqlite_master with PRAGMA writable_schema=1; and write your new table definition into it:

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

然后重新打开数据库。

警告:这仅适用于不更改表的磁盘格式的更改。如果您确实进行了任何更改,从而改变了记录格式(例如,添加/删除字段或修改 rowid ),则数据库将崩溃。

WARNING: This works only for changes that do not change the on-disk format of the table. If you do make any change that changes the record format (such as adding/removing fields, or modifying the rowid), your database will blow up horribly.