package model import ( "database/sql" "embed" "log" _ "github.com/mattn/go-sqlite3" ) var db *sql.DB //go:embed sql/*.sql var sqlCode embed.FS func GetSql(code string) (string, error) { query, err := sqlCode.ReadFile("sql/" + code + ".sql") if err != nil { return "", err } return string(query), nil } func InitDatabase(path string) { var err error db, err = sql.Open("sqlite3", path) if err != nil { log.Fatal(err) } err = db.Ping() if err != nil { log.Fatal(err) } // FIXME roll back migration on error query, err := GetSql(`migrate`) if err != nil { log.Fatal(err) } _, err = db.Exec(query) if err != nil { log.Fatal(err) } } func InjectTestRecipes() { recipes := RecipeTestData() tx, err := NewTx() if err != nil { log.Fatalf("Failed to inject test recipes: %v\n", err) } for _, recipe := range recipes { err = recipe.Create(tx) if err != nil { Rollback(tx) log.Fatalf("Failed to inject test recipe: %v\n", err) } } err = tx.Commit() if err != nil { log.Fatalf("Failed to inject test recipe: %v\n", err) } } func CloseDatabase() { var err error = db.Close() if err != nil { log.Printf("Failed to close database: %v\n", err) } else { log.Println("Closed database") } } func NewTx() (*sql.Tx, error) { return db.Begin() } func Rollback(tx *sql.Tx) { err := tx.Rollback() if err != nil { log.Printf("Failed to rollback transaction: %v\n", err) } }