|
15 | 15 | // rows in all tables in a database plus close the database |
16 | 16 | // connection. It is satisfied by *sql.DB. |
17 | 17 | type CleanUpDB interface { |
| 18 | + Begin() (*sql.Tx, error) |
18 | 19 | Exec(query string, args ...interface{}) (sql.Result, error) |
19 | 20 | Query(query string, args ...interface{}) (*sql.Rows, error) |
20 | 21 |
|
@@ -66,12 +67,35 @@ func deleteEverythingInAllTables(db CleanUpDB) error { |
66 | 67 | return err |
67 | 68 | } |
68 | 69 | 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 | + } |
69 | 83 | // 1 = 1 here prevents the MariaDB i_am_a_dummy setting from |
70 | 84 | // 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") |
72 | 87 | if err != nil { |
73 | 88 | return fmt.Errorf("unable to delete all rows from table %#v: %s", tn, err) |
74 | 89 | } |
| 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 | + |
75 | 99 | _, err = db.Exec("alter table `" + tn + "` AUTO_INCREMENT = 1") |
76 | 100 | if err != nil { |
77 | 101 | return fmt.Errorf("unable to reset autoincrement on table %#v: %s", tn, err) |
|
0 commit comments