Codevault initial commit
This commit is contained in:
30
internal/db/db.go
Normal file
30
internal/db/db.go
Normal file
@@ -0,0 +1,30 @@
|
||||
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
|
||||
}
|
||||
Reference in New Issue
Block a user