-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
options.go
104 lines (94 loc) · 2.5 KB
/
options.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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
package sqlite
import (
"database/sql"
"fmt"
)
// https://www.sqlite.org/pragma.html
type Option func(db *sql.DB) error
// Vacuum rebuilds the DB file to keep it tidy
func Vacuum() Option {
return Option(func(db *sql.DB) error {
sql := `VACUUM;`
_, err := db.Exec(sql)
if err != nil {
return fmt.Errorf("vacuum failed: %s", err)
}
return nil
})
}
// WalCheckpoint checkpoints the Write-Ahead-Log
func WALCheckpoint(mode string) Option {
return Option(func(db *sql.DB) error {
qry := fmt.Sprintf(`PRAGMA wal_checkpoint(%s);`, mode)
_, err := db.Exec(qry)
if err != nil {
return fmt.Errorf("%s: %s", err, qry)
}
return nil
})
}
// MaxOpenConnections sets the max open connections. Since the SQL package
// handles the connection pool, it's best to set this to 1 (one) so that the
// SQL package essentially wraps all writes in a mutex. This will slow down
// writes but will help avoid a locked DB.
func MaxOpenConnections(conns int) Option {
return Option(func(db *sql.DB) error {
db.SetMaxOpenConns(conns)
return nil
})
}
// Encoding set the encoding of the DB; should be "UTF-8"
func Encoding(charset string) Option {
return Option(func(db *sql.DB) error {
qry := fmt.Sprintf(`PRAGMA encoding='%s';`, charset)
_, err := db.Exec(qry)
if err != nil {
return fmt.Errorf("%s: %s", err, qry)
}
return nil
})
}
// JournalMode sets the journal mode for the DB, typically WAL
func JournalMode(mode string) Option {
return Option(func(db *sql.DB) error {
qry := fmt.Sprintf(`PRAGMA journal_mode=%s;`, mode)
_, err := db.Exec(qry)
if err != nil {
return fmt.Errorf("%s: %s", err, qry)
}
return nil
})
}
// PageSize the default is 4096 and is recommended
func PageSize(pageSize int) Option {
return Option(func(db *sql.DB) error {
qry := fmt.Sprintf(`PRAGMA page_size=%d;`, pageSize)
_, err := db.Exec(qry)
if err != nil {
return fmt.Errorf("%s: %s", err, qry)
}
return nil
})
}
// CacheSize defaults to '-2000' kibibytes which is 2.048MB
func CacheSize(cacheSize int) Option {
return Option(func(db *sql.DB) error {
qry := fmt.Sprintf(`PRAGMA cache_size=%d;`, cacheSize)
_, err := db.Exec(qry)
if err != nil {
return fmt.Errorf("%s: %s", err, qry)
}
return nil
})
}
// BusyTimeout 1000 milliseconds == 1 second
func BusyTimeout(milliseconds int) Option {
return Option(func(db *sql.DB) error {
qry := fmt.Sprintf(`PRAGMA busy_timeout=%d;`, milliseconds)
_, err := db.Exec(qry)
if err != nil {
return fmt.Errorf("%s: %s", err, qry)
}
return nil
})
}