-
Notifications
You must be signed in to change notification settings - Fork 0
/
db.go
228 lines (191 loc) · 6.11 KB
/
db.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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
// Package database provides a high-level relational database interface with schema migration,
// connection pooling, prepared statement, and embedded query support, wrapping around
// [zombiezen.com/go/sqlite]'s CGo-free sqlite interface
package database
import (
"context"
"io/fs"
"strings"
"sync"
"github.com/pkg/errors"
"zombiezen.com/go/sqlite"
"zombiezen.com/go/sqlite/sqlitemigration"
"zombiezen.com/go/sqlite/sqlitex"
)
// Options
type DBOption func(*DB)
func WithPrepareConnQueries(queries fs.FS) DBOption {
return func(db *DB) {
db.prepareConnQueries = queries
}
}
// DB
type DB struct {
Config Config
prepareConnQueries fs.FS
// Connection management
connPools map[*sqlite.Conn]*sqlitex.Pool
connPoolsL *sync.RWMutex
writePool *sqlitex.Pool
readPool *sqlitex.Pool
}
func NewDB(c Config, opts ...DBOption) (db *DB) {
db = &DB{
Config: c,
connPools: make(map[*sqlite.Conn]*sqlitex.Pool),
connPoolsL: &sync.RWMutex{},
}
for _, storeOption := range opts {
storeOption(db)
}
return db
}
func (db *DB) Open() (err error) {
if db.writePool, err = sqlitex.Open(
db.Config.URI, db.Config.Flags|sqlite.OpenReadWrite|sqlite.OpenCreate, db.Config.WritePoolSize,
); err != nil {
return errors.Wrap(err, "couldn't open writer pool")
}
if db.readPool, err = sqlitex.Open(
db.Config.URI, db.Config.Flags|sqlite.OpenReadOnly, db.Config.ReadPoolSize,
); err != nil {
return errors.Wrap(err, "couldn't open reader pool")
}
return nil
}
func (db *DB) Close() error {
if err := db.writePool.Close(); err != nil {
return errors.Wrap(err, "couldn't close writer pool")
}
if err := db.readPool.Close(); err != nil {
return errors.Wrap(err, "couldn't close reader pool")
}
return nil
}
// Connection Acquisition
func (db *DB) prepare(conn *sqlite.Conn, pool *sqlitex.Pool) error {
if db.prepareConnQueries == nil {
return nil
}
db.connPoolsL.RLock()
_, initialized := db.connPools[conn]
db.connPoolsL.RUnlock()
if initialized {
return nil
}
// TODO: embed the pragma queries for foreign keys, synchronous, and auto-checkpoint, and
// make it easy to parameterize them from environment variables, and also make it easy to add
// additional queries
queries, err := readQueries(db.prepareConnQueries, filterQuery)
if err != nil {
return errors.Wrap(err, "couldn't read connection preparation queries")
}
for _, query := range queries {
// We run these as transient queries because non-transient query caching is per-connection, so
// query caching provides no benefit for queries which are only run once per connection.
if err := sqlitex.ExecuteTransient(conn, strings.TrimSpace(query), nil); err != nil {
return errors.Wrap(err, "couldn't run connection preparation query")
}
}
db.connPoolsL.Lock()
defer db.connPoolsL.Unlock()
db.connPools[conn] = pool
return nil
}
func (db *DB) acquire(ctx context.Context, writable bool) (*sqlite.Conn, error) {
pool := db.readPool
if writable {
pool = db.writePool
}
conn := pool.Get(ctx)
if conn == nil {
if err := ctx.Err(); err != nil {
return nil, errors.Wrap(err, "couldn't get connection from pool")
}
return nil, errors.New("couldn't get connection from a closed pool")
}
if err := db.prepare(conn, pool); err != nil {
pool.Put(conn)
return nil, errors.Wrap(err, "couldn't prepare connection")
}
return conn, nil
}
func (db *DB) AcquireReader(ctx context.Context) (*sqlite.Conn, error) {
conn, err := db.acquire(ctx, false)
return conn, errors.Wrap(err, "couldn't acquire reader")
}
func (db *DB) AcquireWriter(ctx context.Context) (*sqlite.Conn, error) {
conn, err := db.acquire(ctx, true)
return conn, errors.Wrap(err, "couldn't acquire writer")
}
func (db *DB) ReleaseReader(conn *sqlite.Conn) {
go db.readPool.Put(conn)
}
func (db *DB) ReleaseWriter(conn *sqlite.Conn) {
// TODO: for writer connections, run the sqlite PRAGMA optimize command in the goroutine, with a
// PRAGMA analysis_limit=1000 on the connection, if it hasn't been run on that connection for a
// while. Log an error if it fails.
go db.writePool.Put(conn)
}
func (db *DB) Migrate(ctx context.Context, schema sqlitemigration.Schema) error {
// TODO: also implement down-migrations
conn, err := db.AcquireWriter(ctx)
if err != nil {
return errors.Wrap(err, "couldn't acquire connection to migrate schemas")
}
defer db.ReleaseWriter(conn)
err = sqlitemigration.Migrate(ctx, conn, schema)
return errors.Wrap(err, "couldn't migrate schemas")
}
// Statement Execution
func (db *DB) ExecuteInsertion(
ctx context.Context, query string, namedParams map[string]interface{},
) error {
conn, err := db.AcquireWriter(ctx)
if err != nil {
return errors.Wrap(err, "couldn't acquire writer to perform insertion")
}
defer db.ReleaseWriter(conn)
return ExecuteInsertion(conn, query, namedParams)
}
func (db *DB) ExecuteInsertionForID(
ctx context.Context, query string, namedParams map[string]interface{},
) (rowID int64, err error) {
conn, err := db.AcquireWriter(ctx)
if err != nil {
return 0, errors.Wrap(err, "couldn't acquire writer to perform insertion")
}
defer db.ReleaseWriter(conn)
return ExecuteInsertionForID(conn, query, namedParams)
}
func (db *DB) ExecuteUpdate(
ctx context.Context, query string, namedParams map[string]interface{},
) error {
conn, err := db.AcquireWriter(ctx)
if err != nil {
return errors.Wrap(err, "couldn't acquire writer to perform update")
}
defer db.ReleaseWriter(conn)
return ExecuteUpdate(conn, query, namedParams)
}
func (db *DB) ExecuteDelete(
ctx context.Context, query string, namedParams map[string]interface{},
) error {
conn, err := db.AcquireWriter(ctx)
if err != nil {
return errors.Wrap(err, "couldn't acquire writer to perform delete")
}
defer db.ReleaseWriter(conn)
return ExecuteDelete(conn, query, namedParams)
}
func (db *DB) ExecuteSelection(
ctx context.Context, query string, namedParams map[string]interface{},
resultFunc func(s *sqlite.Stmt) error,
) error {
conn, err := db.AcquireReader(ctx)
if err != nil {
return errors.Wrap(err, "couldn't acquire reader to perform selection")
}
defer db.ReleaseReader(conn)
return ExecuteSelection(conn, query, namedParams, resultFunc)
}