-
Notifications
You must be signed in to change notification settings - Fork 7
/
sqlite-std.go
63 lines (55 loc) · 1.04 KB
/
sqlite-std.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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
// +build !js
// Copyright: Jonathan Hall
// License: GNU AGPL, Version 3 or later; http://www.gnu.org/licenses/agpl.html
package anki
import (
"fmt"
"io"
"io/ioutil"
"os"
"github.com/jmoiron/sqlx"
_ "github.com/mattn/go-sqlite3"
)
type DB struct {
*sqlx.DB
tmpFile string
}
func (db *DB) Close() (e error) {
if db.tmpFile != "" {
if err := os.Remove(db.tmpFile); err != nil {
fmt.Printf("Cannot remove file: %s", err)
e = err
}
}
if db.DB != nil {
if err := db.DB.Close(); err != nil {
e = err
}
}
return
}
func OpenDB(src io.Reader) (db *DB, e error) {
db = &DB{}
dbFile, err := dumpToTemp(src)
db.tmpFile = dbFile
if err != nil {
return db, err
}
sqldb, err := sqlx.Connect("sqlite3", dbFile)
if err != nil {
return db, err
}
db.DB = sqldb
return db, nil
}
func dumpToTemp(src io.Reader) (string, error) {
tmp, err := ioutil.TempFile("/tmp", "anki-sqlite3-")
if err != nil {
return "", err
}
defer tmp.Close()
if _, err := io.Copy(tmp, src); err != nil {
return "", err
}
return tmp.Name(), nil
}