forked from elves/elvish
-
Notifications
You must be signed in to change notification settings - Fork 0
/
store.go
46 lines (37 loc) · 973 Bytes
/
store.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
package store
import (
"database/sql"
"fmt"
"net/url"
_ "github.com/mattn/go-sqlite3" // enable the "sqlite3" SQL driver
)
type Store struct {
db *sql.DB
}
var createTable = map[string]string{}
// DefaultDB returns the default database for storage.
func DefaultDB(dataDir string) (*sql.DB, error) {
uri := "file:" + url.QueryEscape(dataDir+"/db") +
"?mode=rwc&cache=shared&vfs=unix-dotfile"
return sql.Open("sqlite3", uri)
}
// NewStore creates a new Store with the default database.
func NewStore(dataDir string) (*Store, error) {
db, err := DefaultDB(dataDir)
if err != nil {
return nil, err
}
return NewStoreDB(db)
}
// NewStoreDB creates a new Store with a custom database. The database must be
// a SQLite database.
func NewStoreDB(db *sql.DB) (*Store, error) {
st := &Store{db}
for t, q := range createTable {
_, err := db.Exec(q)
if err != nil {
return nil, fmt.Errorf("failed to create table %s: %v", t, q)
}
}
return st, nil
}