-
Notifications
You must be signed in to change notification settings - Fork 211
/
database.go
320 lines (287 loc) · 7.89 KB
/
database.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
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
package sql
import (
"context"
"errors"
"fmt"
"time"
"crawshaw.io/sqlite"
"crawshaw.io/sqlite/sqlitex"
"github.com/prometheus/client_golang/prometheus"
)
var (
// ErrNoConnection is returned if pooled connection is not available.
ErrNoConnection = errors.New("database: no free connection")
// ErrNotFound is returned if requested record is not found.
ErrNotFound = errors.New("database: not found")
// ErrObjectExists is returned if database constraints didn't allow to insert an object.
ErrObjectExists = errors.New("database: object exists")
)
const (
beginDefault = "BEGIN;"
beginImmediate = "BEGIN IMMEDIATE;"
)
// Executor is an interface for executing raw statement.
type Executor interface {
Exec(string, Encoder, Decoder) (int, error)
}
// Statement is an sqlite statement.
type Statement = sqlite.Stmt
// Encoder for parameters.
// Both positional parameters:
// select block from blocks where id = ?1;
//
// and named parameters are supported:
// select blocks from blocks where id = @id;
//
// For complete information see https://www.sqlite.org/c3ref/bind_blob.html.
type Encoder func(*Statement)
// Decoder for sqlite rows.
type Decoder func(*Statement) bool
func defaultConf() *conf {
return &conf{
connections: 16,
migrations: embeddedMigrations,
}
}
type conf struct {
flags sqlite.OpenFlags
connections int
migrations Migrations
enableLatency bool
}
// WithConnections overwrites number of pooled connections.
func WithConnections(n int) Opt {
return func(c *conf) {
c.connections = n
}
}
// WithMigrations overwrites embedded migrations.
func WithMigrations(migrations Migrations) Opt {
return func(c *conf) {
c.migrations = migrations
}
}
// WithLatencyMetering enables metric that track latency for every database query.
// Note that it will be a significant amount of data, and should not be enabled on
// multiple nodes by default.
func WithLatencyMetering(enable bool) Opt {
return func(c *conf) {
c.enableLatency = enable
}
}
// Opt for configuring database.
type Opt func(c *conf)
// InMemory database for testing.
func InMemory(opts ...Opt) *Database {
opts = append(opts, WithConnections(1))
db, err := Open("file::memory:?mode=memory", opts...)
if err != nil {
panic(err)
}
return db
}
// Open database with options.
//
// Database is opened in WAL mode and pragma synchronous=normal.
// https://sqlite.org/wal.html
// https://www.sqlite.org/pragma.html#pragma_synchronous
func Open(uri string, opts ...Opt) (*Database, error) {
config := defaultConf()
for _, opt := range opts {
opt(config)
}
pool, err := sqlitex.Open(uri, config.flags, config.connections)
if err != nil {
return nil, fmt.Errorf("open db %s: %w", uri, err)
}
db := &Database{pool: pool}
if config.enableLatency {
db.latency = newQueryLatency()
}
if config.migrations != nil {
tx, err := db.Tx(context.Background())
if err != nil {
return nil, err
}
err = config.migrations(tx)
if err == nil {
tx.Commit()
}
tx.Release()
if err != nil {
return nil, err
}
}
for i := 0; i < config.connections; i++ {
conn := pool.Get(context.Background())
if err := registerFunctions(conn); err != nil {
return nil, err
}
defer pool.Put(conn)
}
return db, nil
}
// Database is an instance of sqlite database.
type Database struct {
pool *sqlitex.Pool
latency *prometheus.HistogramVec
}
func (db *Database) getTx(ctx context.Context, initstmt string) (*Tx, error) {
conn := db.pool.Get(ctx)
if conn == nil {
return nil, ErrNoConnection
}
tx := &Tx{db: db, conn: conn}
if err := tx.begin(initstmt); err != nil {
return nil, err
}
return tx, nil
}
func (db *Database) withTx(ctx context.Context, initstmt string, exec func(*Tx) error) error {
tx, err := db.getTx(ctx, initstmt)
if err != nil {
return err
}
defer tx.Release()
if err := exec(tx); err != nil {
return err
}
return tx.Commit()
}
// Tx creates deferred sqlite transaction.
//
// Deferred transactions are not started until the first statement.
// Transaction may be started in read mode and automatically upgraded to write mode
// after one of the write statements.
//
// https://www.sqlite.org/lang_transaction.html
func (db *Database) Tx(ctx context.Context) (*Tx, error) {
return db.getTx(ctx, beginDefault)
}
// WithTx will pass initialized deferred transaction to exec callback.
// Will commit only if error is nil.
func (db *Database) WithTx(ctx context.Context, exec func(*Tx) error) error {
return db.withTx(ctx, beginImmediate, exec)
}
// TxImmediate creates immediate transaction.
//
// IMMEDIATE cause the database connection to start a new write immediately, without waiting
// for a write statement. The BEGIN IMMEDIATE might fail with SQLITE_BUSY if another write
// transaction is already active on another database connection.
func (db *Database) TxImmediate(ctx context.Context) (*Tx, error) {
return db.getTx(ctx, beginImmediate)
}
// WithTxImmediate will pass initialized immediate transaction to exec callback.
// Will commit only if error is nil.
func (db *Database) WithTxImmediate(ctx context.Context, exec func(*Tx) error) error {
return db.withTx(ctx, beginImmediate, exec)
}
// Exec statement using one of the connection from the pool.
//
// If you care about atomicity of the operation (for example writing rewards to multiple accounts)
// Tx should be used. Otherwise sqlite will not guarantee that all side-effects of operations are
// applied to the database if machine crashes.
//
// Note that Exec will block until database is closed or statement has finished.
// If application needs to control statement execution lifetime use one of the transaction.
func (db *Database) Exec(query string, encoder Encoder, decoder Decoder) (int, error) {
conn := db.pool.Get(context.Background())
if conn == nil {
return 0, ErrNoConnection
}
defer db.pool.Put(conn)
if db.latency != nil {
start := time.Now()
defer func() {
db.latency.WithLabelValues(query).Observe(float64(time.Since(start)))
}()
}
return exec(conn, query, encoder, decoder)
}
// Close closes all pooled connections.
func (db *Database) Close() error {
if err := db.pool.Close(); err != nil {
return fmt.Errorf("close pool %w", err)
}
return nil
}
func exec(conn *sqlite.Conn, query string, encoder Encoder, decoder Decoder) (int, error) {
stmt, err := conn.Prepare(query)
if err != nil {
return 0, fmt.Errorf("prepare %s: %w", query, err)
}
if encoder != nil {
encoder(stmt)
}
defer stmt.ClearBindings()
rows := 0
for {
row, err := stmt.Step()
if err != nil {
code := sqlite.ErrCode(err)
if code == sqlite.SQLITE_CONSTRAINT_PRIMARYKEY {
return 0, ErrObjectExists
}
return 0, fmt.Errorf("step %d: %w", rows, err)
}
if !row {
return rows, nil
}
rows++
// exhaust iterator
if decoder == nil {
continue
}
if !decoder(stmt) {
if err := stmt.Reset(); err != nil {
return rows, fmt.Errorf("statement reset %w", err)
}
return rows, nil
}
}
}
// Tx is wrapper for database transaction.
type Tx struct {
db *Database
conn *sqlite.Conn
committed bool
err error
}
func (tx *Tx) begin(initstmt string) error {
stmt := tx.conn.Prep(initstmt)
_, err := stmt.Step()
if err != nil {
return fmt.Errorf("begin: %w", err)
}
return nil
}
// Commit transaction.
func (tx *Tx) Commit() error {
stmt := tx.conn.Prep("COMMIT;")
_, tx.err = stmt.Step()
if tx.err != nil {
return tx.err
}
tx.committed = true
return nil
}
// Release transaction. Every transaction that was created must be released.
func (tx *Tx) Release() error {
defer tx.db.pool.Put(tx.conn)
if tx.committed {
return nil
}
stmt := tx.conn.Prep("ROLLBACK")
_, tx.err = stmt.Step()
return tx.err
}
// Exec query.
func (tx *Tx) Exec(query string, encoder Encoder, decoder Decoder) (int, error) {
if tx.db.latency != nil {
start := time.Now()
defer func() {
tx.db.latency.WithLabelValues(query).Observe(float64(time.Since(start)))
}()
}
return exec(tx.conn, query, encoder, decoder)
}