package model import ( "database/sql" "embed" "log" "fmt" _ "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 ConnectDatabase(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) } } func Transaction(f func(*sql.Tx) error) error { tx, err := db.Begin() if err != nil { return err } err = f(tx) if err != nil { rollbackErr := tx.Rollback() if rollbackErr != nil { return fmt.Errorf("Failed rollback '%w' after failed transaction '%w'", rollbackErr, err) } } return tx.Commit() } func MigrateDatabase() { query, err := GetSql(`migrate`) if err != nil { log.Fatal(err) } err = Transaction(func(tx *sql.Tx) error { _, err := tx.Exec(query) if err != nil { return err } return nil }) if err != nil { log.Fatalf("Migration failed: %v\n", err) } } func InjectTestRecipes() { Transaction(func(tx *sql.Tx) error { recipes := RecipeTestData() for _, recipe := range recipes { err := recipe.Create(tx) if err != nil { return err } } return nil }) } func DisconnectDatabase() { var err error = db.Close() if err != nil { log.Printf("Failed to close database: %v\n", err) } else { log.Println("Closed database") } }