50 lines
817 B
Go
50 lines
817 B
Go
|
package main
|
||
|
|
||
|
import (
|
||
|
"database/sql"
|
||
|
"embed"
|
||
|
"log"
|
||
|
"net/url"
|
||
|
"os"
|
||
|
"path/filepath"
|
||
|
|
||
|
"github.com/amacneil/dbmate/v2/pkg/dbmate"
|
||
|
_ "github.com/amacneil/dbmate/v2/pkg/driver/sqlite"
|
||
|
_ "github.com/mattn/go-sqlite3"
|
||
|
)
|
||
|
|
||
|
//go:embed migrations/*.sql
|
||
|
var fs embed.FS
|
||
|
|
||
|
type database struct {
|
||
|
*sql.DB
|
||
|
}
|
||
|
|
||
|
func newDatabase(path string) *database {
|
||
|
url, err := url.Parse("sqlite3://")
|
||
|
if err != nil {
|
||
|
log.Fatal(err)
|
||
|
}
|
||
|
url.Path, err = filepath.Abs(path)
|
||
|
if err != nil {
|
||
|
log.Fatal(err)
|
||
|
}
|
||
|
|
||
|
dbmate := dbmate.New(url)
|
||
|
dbmate.AutoDumpSchema = false
|
||
|
dbmate.FS = fs
|
||
|
dbmate.MigrationsDir = []string{"migrations"}
|
||
|
dbmate.CreateAndMigrate()
|
||
|
|
||
|
if err := os.Chmod(url.Path, 0600); err != nil {
|
||
|
log.Fatal(err)
|
||
|
}
|
||
|
|
||
|
db, err := sql.Open("sqlite3", url.Path)
|
||
|
if err != nil {
|
||
|
log.Fatal(err)
|
||
|
}
|
||
|
|
||
|
return &database{db}
|
||
|
}
|