👨‍👦

SQLiteで外部キー制約を利用するときの注意

2023/02/19に公開

結論

SQLiteでは外部キー制約をつけるための構文を利用することができるが、実際に機能を有効にするためにはPRAGMA foreign_key = ON;として、設定を有効にする必要があるみたいです。

詳細

公式ドキュメントには以下のように書かれています。

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.

Foreign key constraints are disabled by default (for backwards compatibility), so must be enabled separately for each database connection. (Note, however, that future releases of SQLite might change so that foreign key constraints enabled by default. Careful developers will not make any assumptions about whether or not foreign keys are enabled by default but will instead enable or disable them as necessary.)

つまり、後方互換のために機能自体は無効にしているから、各自で有効にしてね。とのことです。

参考サイト

背景

最近Flutterを勉強し始めて、SQLiteを使う機会がありました。そこで、外部キー制約をつけたのにも関わらず、親テーブルのレコードを消しても子テーブルのレコードが削除されないなぁと悩んでいました。
そこで原因を探っていたところ、この結論に辿り着きました。

Discussion