pkg/sqlite/sqlite.go 762 B raw
1
// Package sqlite provides a shared SQLite bootstrap for andromeda Go apps.
2
package sqlite
3
4
import (
5
	"database/sql"
6
7
	_ "modernc.org/sqlite"
8
)
9
10
// Open opens a SQLite database at path with the connection settings and
11
// PRAGMAs used across andromeda Go apps. If schema is non-empty it is
12
// executed once after opening (typically CREATE TABLE IF NOT EXISTS ...).
13
func Open(path string, schema string) (*sql.DB, error) {
14
	db, err := sql.Open("sqlite", path)
15
	if err != nil {
16
		return nil, err
17
	}
18
	db.SetMaxOpenConns(1)
19
	db.SetMaxIdleConns(1)
20
	if _, err := db.Exec("PRAGMA foreign_keys = ON"); err != nil {
21
		db.Close()
22
		return nil, err
23
	}
24
	if schema != "" {
25
		if _, err := db.Exec(schema); err != nil {
26
			db.Close()
27
			return nil, err
28
		}
29
	}
30
	return db, nil
31
}