Skip to content

Commit 6db612c

Browse files
committed
ignore foreign key constraints when clearing tables
1 parent 031d2f9 commit 6db612c

File tree

1 file changed

+25
-1
lines changed

1 file changed

+25
-1
lines changed

test/db.go

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ var (
1515
// rows in all tables in a database plus close the database
1616
// connection. It is satisfied by *sql.DB.
1717
type CleanUpDB interface {
18+
Begin() (*sql.Tx, error)
1819
Exec(query string, args ...interface{}) (sql.Result, error)
1920
Query(query string, args ...interface{}) (*sql.Rows, error)
2021

@@ -66,12 +67,35 @@ func deleteEverythingInAllTables(db CleanUpDB) error {
6667
return err
6768
}
6869
for _, tn := range ts {
70+
// We do this in a transaction to make sure that the foreign
71+
// key checks remain disabled even if the db object chooses
72+
// another connection to make the deletion on. Note that
73+
// `alter table` statements will silently cause transactions
74+
// to commit, so we do them outside of the transaction.
75+
tx, err := db.Begin()
76+
if err != nil {
77+
return fmt.Errorf("unable to start transaction to delete all rows from table %#v: %s", tn, err)
78+
}
79+
_, err = tx.Exec("set FOREIGN_KEY_CHECKS = 0")
80+
if err != nil {
81+
return fmt.Errorf("unable to disable FOREIGN_KEY_CHECKS to delete all rows from table %#v: %s", tn, err)
82+
}
6983
// 1 = 1 here prevents the MariaDB i_am_a_dummy setting from
7084
// rejecting the DELETE for not having a WHERE clause.
71-
_, err := db.Exec("delete from `" + tn + "` where 1 = 1")
85+
86+
_, err = tx.Exec("delete from `" + tn + "` where 1 = 1")
7287
if err != nil {
7388
return fmt.Errorf("unable to delete all rows from table %#v: %s", tn, err)
7489
}
90+
_, err = tx.Exec("set FOREIGN_KEY_CHECKS = 1")
91+
if err != nil {
92+
return fmt.Errorf("unable to re-enable FOREIGN_KEY_CHECKS to delete all rows from table %#v: %s", tn, err)
93+
}
94+
err = tx.Commit()
95+
if err != nil {
96+
return fmt.Errorf("unable to commit transaction to delete all rows from table %#v: %s", tn, err)
97+
}
98+
7599
_, err = db.Exec("alter table `" + tn + "` AUTO_INCREMENT = 1")
76100
if err != nil {
77101
return fmt.Errorf("unable to reset autoincrement on table %#v: %s", tn, err)

0 commit comments

Comments
 (0)