Skip to content

Instantly share code, notes, and snippets.

@808codist
Created April 20, 2018 17:54
Show Gist options
  • Save 808codist/a80b6a36ba061cd4aca061ecd0a43e47 to your computer and use it in GitHub Desktop.
Save 808codist/a80b6a36ba061cd4aca061ecd0a43e47 to your computer and use it in GitHub Desktop.
golang sqlite foreign key example
package main
import (
"database/sql"
_ "github.com/mattn/go-sqlite3"
"log"
)
func main() {
db, err := sql.Open("sqlite3", ":memory:")
if err != nil {
log.Fatal("Failed to open database:", err)
}
defer db.Close()
execs := []struct {
stmt string
shouldFail bool
}{
{stmt: "PRAGMA foreign_keys = ON"},
{stmt: "CREATE TABLE foo (id TEXT NOT NULL PRIMARY KEY, an_int INTEGER)"},
{stmt: "CREATE TABLE foo_set(id TEXT NOT NULL PRIMARY KEY,FOREIGN KEY(id)REFERENCES foo(id)ON DELETE RESTRICT)"},
{stmt: "INSERT INTO foo VALUES ('id000', 10)"},
{stmt: "INSERT INTO foo VALUES ('idAbc', 11)"},
{stmt: "INSERT INTO foo_set VALUES ('id000')"},
{stmt: "INSERT INTO foo_set VALUES ('not a key in foo')", shouldFail: true}, // foreign key
{stmt: "DELETE FROM foo WHERE id = 'id000'", shouldFail: true}, // foreign key
{stmt: "DELETE FROM foo WHERE id = 'idAbc'"},
}
for _, exec := range execs {
_, err = db.Exec(exec.stmt)
hasFailed := err != nil
if exec.shouldFail != hasFailed {
expected := "succeed"
if exec.shouldFail {
expected = "fail"
}
log.Printf("'%s' should have %sed but did not: %s", exec.stmt, expected, err)
} else if exec.shouldFail {
log.Printf("'%s' failed as expected: %s", exec.stmt, err)
}
}
log.Println("finis")
}
@kargirwar
Copy link

This is simpler:
sqlite3, err := sql.Open("sqlite3", "file:test.db?_foreign_keys=true")

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment