go-sqlite3: Foreign key constraint just doesn't work

I am probably misunderstanding something, but it appears that foreign key constraints are ignored no matter what I do. Here’s an example:

package main

import (
	"database/sql"

	_ "github.com/mattn/go-sqlite3"
)

func main() {
	db, _ := sql.Open("sqlite3", "test.db")
	tx, _ := db.Begin()
	defer tx.Commit()
	tx.Exec("PRAGMA foreign_keys = ON")
	tx.Exec("create table foo (a)")
	tx.Exec("create table bar (a references foo(a))")
	_, err := tx.Exec("insert into bar values ('lol')")
	if err != nil {
		panic(err.Error())
	}
}

Expected result: panic. Actual result: test.db gets created, with the values being inconsistent with the foreign key constraint.

Why is this happening? I even recall using this package before with foreign keys without issue…

About this issue

  • Original URL
  • State: closed
  • Created 7 years ago
  • Comments: 15 (1 by maintainers)

Commits related to this issue

Most upvoted comments

@maharasheed The connection parameter is _foreign_keys (with a leading underscore).

db, err := sql.Open("sqlite3", "my.db?_foreign_keys=on")

Well, I’m thinking it’s possible to do with hook. But if many people want this feature, I’ll add this.