31 lines
689 B
Go
31 lines
689 B
Go
package db
|
|
|
|
import (
|
|
"database/sql"
|
|
_ "embed"
|
|
"fmt"
|
|
|
|
_ "modernc.org/sqlite"
|
|
)
|
|
|
|
//go:embed schema.sql
|
|
var schema string
|
|
|
|
// Open opens (creating the file if it does not exist) the SQLite database at path
|
|
// and applies the embedded schema.
|
|
func Open(path string) (*sql.DB, error) {
|
|
dsn := fmt.Sprintf("file:%s?_pragma=journal_mode(WAL)&_pragma=busy_timeout(5000)", path)
|
|
database, err := sql.Open("sqlite", dsn)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("could not open database: %w", err)
|
|
}
|
|
database.SetMaxOpenConns(1)
|
|
|
|
if _, err := database.Exec(schema); err != nil {
|
|
_ = database.Close()
|
|
return nil, fmt.Errorf("could not apply schema: %w", err)
|
|
}
|
|
|
|
return database, nil
|
|
}
|