Skip to content

Commit 15549f3

Browse files
felixxmerlend-aasland
authored andcommitted
pythongh-108364: In sqlite3, disable foreign keys before dumping SQL schema (python#113957)
sqlite3.Connection.iterdump now ensures that foreign key support is disabled before dumping the database schema, if there is any foreign key violation. Co-authored-by: Erlend E. Aasland <[email protected]>
1 parent ed9c72b commit 15549f3

File tree

3 files changed

+18
-3
lines changed

3 files changed

+18
-3
lines changed

Lib/sqlite3/dump.py

+4
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,10 @@ def _iterdump(connection):
2626

2727
writeable_schema = False
2828
cu = connection.cursor()
29+
# Disable foreign key constraints, if there is any foreign key violation.
30+
violations = cu.execute("PRAGMA foreign_key_check").fetchall()
31+
if violations:
32+
yield('PRAGMA foreign_keys=OFF;')
2933
yield('BEGIN TRANSACTION;')
3034

3135
# sqlite_master table contains the SQL CREATE statements for the database.

Lib/test/test_sqlite3/test_dump.py

+11-3
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,8 @@ def test_table_dump(self):
2020
,
2121
"CREATE TABLE t1(id integer primary key, s1 text, " \
2222
"t1_i1 integer not null, i2 integer, unique (s1), " \
23-
"constraint t1_idx1 unique (i2));"
23+
"constraint t1_idx1 unique (i2), " \
24+
"constraint t1_i1_idx1 unique (t1_i1));"
2425
,
2526
"INSERT INTO \"t1\" VALUES(1,'foo',10,20);"
2627
,
@@ -30,6 +31,9 @@ def test_table_dump(self):
3031
"t2_i2 integer, primary key (id)," \
3132
"foreign key(t2_i1) references t1(t1_i1));"
3233
,
34+
# Foreign key violation.
35+
"INSERT INTO \"t2\" VALUES(1,2,3);"
36+
,
3337
"CREATE TRIGGER trigger_1 update of t1_i1 on t1 " \
3438
"begin " \
3539
"update t2 set t2_i1 = new.t1_i1 where t2_i1 = old.t1_i1; " \
@@ -41,8 +45,12 @@ def test_table_dump(self):
4145
[self.cu.execute(s) for s in expected_sqls]
4246
i = self.cx.iterdump()
4347
actual_sqls = [s for s in i]
44-
expected_sqls = ['BEGIN TRANSACTION;'] + expected_sqls + \
45-
['COMMIT;']
48+
expected_sqls = [
49+
"PRAGMA foreign_keys=OFF;",
50+
"BEGIN TRANSACTION;",
51+
*expected_sqls,
52+
"COMMIT;",
53+
]
4654
[self.assertEqual(expected_sqls[i], actual_sqls[i])
4755
for i in range(len(expected_sqls))]
4856

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
:meth:`sqlite3.Connection.iterdump` now ensures that foreign key support is
2+
disabled before dumping the database schema, if there is any foreign key
3+
violation. Patch by Erlend E. Aasland and Mariusz Felisiak.

0 commit comments

Comments
 (0)