Created
April 20, 2018 17:54
-
-
Save 808codist/a80b6a36ba061cd4aca061ecd0a43e47 to your computer and use it in GitHub Desktop.
golang sqlite foreign key example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is simpler:
sqlite3, err := sql.Open("sqlite3", "file:test.db?_foreign_keys=true")