This repository has been archived by the owner on Oct 3, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 4
/
init.go
89 lines (78 loc) · 1.57 KB
/
init.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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
package db
import (
"database/sql"
"fmt"
"os"
"path/filepath"
"strings"
"sync"
"github.com/Masterminds/squirrel"
"github.com/bakape/captchouli/v2/common"
_ "github.com/mattn/go-sqlite3"
)
var (
db *sql.DB
sq squirrel.StatementBuilderType
// To avoid locking "database locked" errors. Hard limitation of SQLite,
// when used from multiple threads. Lock appropriately for read and write
// queries.
dbMu sync.RWMutex
)
// Open a database connection
func Open() (err error) {
// Create root dir, id it does not exist
_, err = os.Stat(common.RootDir)
if err != nil {
if os.IsNotExist(err) {
err = os.MkdirAll(filepath.Join(common.RootDir, "images"),
os.ModeDir|0700)
if err != nil {
return
}
} else {
return
}
}
db, err = sql.Open("sqlite3",
fmt.Sprintf("file:%s?cache=shared&mode=rwc",
filepath.Join(common.RootDir, "db.db")))
if err != nil {
return
}
sq = squirrel.StatementBuilder.RunWith(squirrel.NewStmtCacheProxy(db))
var currentVersion int
err = sq.Select("val").
From("main").
Where("id = 'version'").
QueryRow().
Scan(¤tVersion)
if err != nil {
if s := err.Error(); strings.HasPrefix(s, "no such table") {
err = nil
} else {
return
}
}
err = runMigrations(currentVersion, version)
if err != nil {
return
}
if !common.IsTest {
go runUpkeepTasks()
}
return
}
// Close database connection
func Close() error {
dbMu.Lock()
defer dbMu.Unlock()
return db.Close()
}
// Open database for testing purposes
func OpenForTests() {
common.IsTest = true
err := Open()
if err != nil {
panic(err)
}
}