1
0
dwelling-home/pkg/mindflow/database/sqlite/db.go

91 lines
1.8 KiB
Go

package sqlite
import (
"database/sql"
_ "embed"
"fmt"
"github.com/pkg/errors"
)
var (
//go:embed queries/schema.sql
querySchema string
//go:embed queries/categoryById.sql
queryCategoryById string
//go:embed queries/categoryNew.sql
queryCategoryNew string
//go:embed queries/postGetAll.sql
queryPostGetAll string
//go:embed queries/postNew.sql
queryPostNew string
//go:embed queries/postEdit.sql
queryPostEdit string
)
var (
stmtCategoryById *sql.Stmt
stmtCategoryNew *sql.Stmt
stmtPostGetAll *sql.Stmt
stmtPostNew *sql.Stmt
stmtPostEdit *sql.Stmt
)
func initDBStatements(db *sql.DB) error {
db.Exec("PRAGMA foreign_keys = ON;")
_, err := db.Exec(querySchema)
if err != nil {
return errors.Wrap(err, "failed to init schema")
}
stmtCategoryById, err = db.Prepare(queryCategoryById)
if err != nil {
return errors.Wrap(err, "failed to prepare queryCategoryById")
}
stmtCategoryNew, err = db.Prepare(queryCategoryNew)
if err != nil {
return errors.Wrap(err, "failed to prepare queryCategoryNew")
}
stmtPostGetAll, err = db.Prepare(queryPostGetAll)
if err != nil {
return errors.Wrap(err, "failed to prepare queryPostGetAll")
}
stmtPostNew, err = db.Prepare(queryPostNew)
if err != nil {
return errors.Wrap(err, "failed to prepare queryPostNew")
}
stmtPostEdit, err = db.Prepare(queryPostEdit)
if err != nil {
return errors.Wrap(err, "failed to prepare queryPostEdit")
}
return nil
}
type SQLiteMindflow struct {
db *sql.DB
}
func NewSQLiteMindflow(path string) (*SQLiteMindflow, error) {
db, err := sql.Open("sqlite3", dsn(path))
if err != nil {
return nil, err
}
if err := initDBStatements(db); err != nil {
return nil, err
}
return &SQLiteMindflow{db: db}, nil
}
func dsn(filePath string) string {
return fmt.Sprintf("file:%s?_journal=WAL&_mutex=full", filePath)
}