bluebell/initdb.go

43 lines
969 B
Go
Raw Normal View History

2024-08-10 13:28:30 +01:00
package bluebell
import (
"database/sql"
"embed"
"errors"
"github.com/1f349/bluebell/database"
2024-08-16 16:48:50 +01:00
"github.com/golang-migrate/migrate/v4"
"github.com/golang-migrate/migrate/v4/database/sqlite3"
2024-08-10 13:28:30 +01:00
"github.com/golang-migrate/migrate/v4/source/iofs"
)
//go:embed database/migrations/*.sql
var migrations embed.FS
func InitDB(p string) (*database.Queries, error) {
2025-01-08 17:49:41 +00:00
dbOpen, err := sql.Open("sqlite3", p)
2024-08-10 13:28:30 +01:00
if err != nil {
return nil, err
}
2025-01-08 17:49:41 +00:00
return InitRawDB(dbOpen)
}
func InitRawDB(dbOpen *sql.DB) (*database.Queries, error) {
dbDrv, err := sqlite3.WithInstance(dbOpen, &sqlite3.Config{})
2024-08-10 13:28:30 +01:00
if err != nil {
return nil, err
}
2025-01-08 17:49:41 +00:00
migDrv, err := iofs.New(migrations, "database/migrations")
2024-08-10 13:28:30 +01:00
if err != nil {
return nil, err
}
mig, err := migrate.NewWithInstance("iofs", migDrv, "sqlite3", dbDrv)
2024-08-10 13:28:30 +01:00
if err != nil {
return nil, err
}
err = mig.Up()
if err != nil && !errors.Is(err, migrate.ErrNoChange) {
return nil, err
}
return database.New(dbOpen), nil
}