Skip to content

Commit

Permalink
Rollback on constraint failure
Browse files Browse the repository at this point in the history
  • Loading branch information
joshbuddy committed Aug 8, 2022
1 parent 3ccccfb commit 7b40448
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 1 deletion.
2 changes: 1 addition & 1 deletion sqlite3.go
Expand Up @@ -494,7 +494,7 @@ func (ai *aggInfo) Done(ctx *C.sqlite3_context) {
// Commit transaction.
func (tx *SQLiteTx) Commit() error {
_, err := tx.c.exec(context.Background(), "COMMIT", nil)
if err != nil && err.(Error).Code == C.SQLITE_BUSY {
if err != nil && (err.(Error).Code == C.SQLITE_BUSY || err.(Error).Code == C.SQLITE_CONSTRAINT) {
// sqlite3 will leave the transaction open in this scenario.
// However, database/sql considers the transaction complete once we
// return from Commit() - we must clean up to honour its semantics.
Expand Down
37 changes: 37 additions & 0 deletions sqlite3_test.go
Expand Up @@ -248,6 +248,43 @@ func TestForeignKeys(t *testing.T) {
}
}

func TestDeferredForeignKey(t *testing.T) {
fname := TempFilename(t)
uri := "file:" + fname + "?_foreign_keys=1"
db, err := sql.Open("sqlite3", uri)
if err != nil {
os.Remove(fname)
t.Errorf("sql.Open(\"sqlite3\", %q): %v", uri, err)
}
_, err = db.Exec("CREATE TABLE bar (id INTEGER PRIMARY KEY)")
if err != nil {
t.Errorf("failed creating tables: %v", err)
}
_, err = db.Exec("CREATE TABLE foo (bar_id INTEGER, FOREIGN KEY(bar_id) REFERENCES bar(id) DEFERRABLE INITIALLY DEFERRED)")
if err != nil {
t.Errorf("failed creating tables: %v", err)
}
tx, err := db.Begin()
if err != nil {
t.Errorf("Failed to begin transaction: %v", err)
}
_, err = tx.Exec("INSERT INTO foo (bar_id) VALUES (123)")
if err != nil {
t.Errorf("Failed to insert row: %v", err)
}
err = tx.Commit()
if err == nil {
t.Errorf("Expected an error: %v", err)
}
_, err = db.Begin()
if err != nil {
t.Errorf("Failed to begin transaction: %v", err)
}

db.Close()
os.Remove(fname)
}

func TestRecursiveTriggers(t *testing.T) {
cases := map[string]bool{
"?_recursive_triggers=1": true,
Expand Down

0 comments on commit 7b40448

Please sign in to comment.