2010-12-18 8 views
8

フィーチャリストを何度もチェックしたところ、カスケードが機能するはずです。私はこのPythonスクリプトを実行すると は:カスケ​​ードが起こっていなかったことを証明sqlite 3.7.4でON DELETE CASCADEを動作させる方法は?

3.7.4 
[(1, 'abc')] 
[(1, 1)] 
[(1, 1)] 
[] 

#!/usr/bin/env python3 
import sqlite3 

print(sqlite3.sqlite_version) 

con = sqlite3.connect(':memory:') 

a = "create table a (id integer primary key, name text)" 
con.execute(a) 

b = "create table b (id integer primary key, r integer, foreign key(r) references a(id) on delete cascade)" 
con.execute(b) 
con.commit() 

a = "insert into a (name) values (\"abc\")" 
con.execute(a) 
con.commit() 

print(con.execute("select * from a").fetchall()) 

a = "insert into b (r) values (1)" 
con.execute(a) 
con.commit() 

print(con.execute("select * from b").fetchall()) 

a = "delete from a where id=1" 
con.execute(a) 
con.commit() 

print(con.execute("select * from b").fetchall()) 
print(con.execute("select * from a").fetchall()) 

を私はこれらの結果を得ます。カスケーディングと同じ結果を得るために何が間違っていたのですか?

答えて

9

SQLiteの外部キーは互換性のために無効になっています。データベースに接続するたびに手動で有効にする必要があります。

con.execute("PRAGMA foreign_keys = ON")

2

比べてこの問題のユーザーThibault Jことで、より良い答えがあります:Enable integrity checking with sqlite in django言う:私は新しいマイグレーションを、私のDBファイルを削除以前のすべての移行を除去し、作成したものの

from django.db.backends.signals import connection_created 
def activate_foreign_keys(sender, connection, **kwargs): 
    """Enable integrity constraint with sqlite.""" 
    if connection.vendor == 'sqlite': 
     cursor = connection.cursor() 
     cursor.execute('PRAGMA foreign_keys = ON;') 

connection_created.connect(activate_foreign_keys) 
+0

、これを私のために何の違いもありませんでした。テーブルは "on delete cascade"で期待通りに作成されませんでした。私はなぜそれが起こっていないのだろうかと思う。 –

関連する問題