-
Notifications
You must be signed in to change notification settings - Fork 6
/
database.go
273 lines (220 loc) · 6.34 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
package toolbelt
import (
"context"
"embed"
"errors"
"fmt"
"io"
"io/fs"
"os"
"path/filepath"
"runtime"
"slices"
"strings"
"time"
"google.golang.org/protobuf/types/known/timestamppb"
"zombiezen.com/go/sqlite"
"zombiezen.com/go/sqlite/sqlitemigration"
"zombiezen.com/go/sqlite/sqlitex"
)
type Database struct {
filename string
migrations []string
writePool *sqlitex.Pool
readPool *sqlitex.Pool
}
type TxFn func(tx *sqlite.Conn) error
func NewDatabase(ctx context.Context, dbFilename string, migrations []string) (*Database, error) {
if dbFilename == "" {
return nil, fmt.Errorf("database filename is required")
}
db := &Database{
filename: dbFilename,
migrations: migrations,
}
if err := db.Reset(ctx, false); err != nil {
return nil, fmt.Errorf("failed to reset database: %w", err)
}
return db, nil
}
func (db *Database) WriteWithoutTx(ctx context.Context, fn TxFn) error {
conn, err := db.writePool.Take(ctx)
if err != nil {
return fmt.Errorf("failed to take write connection: %w", err)
}
if conn == nil {
return fmt.Errorf("could not get write connection from pool")
}
defer db.writePool.Put(conn)
if err := fn(conn); err != nil {
return fmt.Errorf("could not execute write transaction: %w", err)
}
return nil
}
func (db *Database) Reset(ctx context.Context, shouldClear bool) (err error) {
if err := db.Close(); err != nil {
return fmt.Errorf("could not close database: %w", err)
}
if shouldClear {
if err := os.RemoveAll(db.filename + "*"); err != nil {
return fmt.Errorf("could not remove database file: %w", err)
}
}
if err := os.MkdirAll(filepath.Dir(db.filename), 0755); err != nil {
return fmt.Errorf("could not create database directory: %w", err)
}
uri := fmt.Sprintf("file:%s?_journal_mode=WAL&_synchronous=NORMAL", db.filename)
db.writePool, err = sqlitex.NewPool(uri, sqlitex.PoolOptions{
PoolSize: 1,
PrepareConn: func(conn *sqlite.Conn) error {
// Enable foreign keys. See https://sqlite.org/foreignkeys.html
return sqlitex.ExecuteTransient(conn, "PRAGMA foreign_keys = ON;", nil)
},
})
if err != nil {
return fmt.Errorf("could not open write pool: %w", err)
}
db.readPool, err = sqlitex.NewPool(uri, sqlitex.PoolOptions{
PoolSize: runtime.NumCPU(),
})
schema := sqlitemigration.Schema{Migrations: db.migrations}
conn, err := db.writePool.Take(ctx)
if err != nil {
return fmt.Errorf("failed to take write connection: %w", err)
}
defer db.writePool.Put(conn)
if err := sqlitemigration.Migrate(ctx, conn, schema); err != nil {
return fmt.Errorf("failed to migrate database: %w", err)
}
return nil
}
func (db *Database) Close() error {
errs := []error{}
if db.writePool != nil {
errs = append(errs, db.writePool.Close())
}
if db.readPool != nil {
errs = append(errs, db.readPool.Close())
}
return errors.Join(errs...)
}
func (db *Database) WriteTX(ctx context.Context, fn TxFn) (err error) {
conn, err := db.writePool.Take(ctx)
if err != nil {
return fmt.Errorf("failed to take write connection: %w", err)
}
if conn == nil {
return fmt.Errorf("could not get write connection from pool")
}
defer db.writePool.Put(conn)
endFn, err := sqlitex.ImmediateTransaction(conn)
if err != nil {
return fmt.Errorf("could not start transaction: %w", err)
}
defer endFn(&err)
if err := fn(conn); err != nil {
return fmt.Errorf("could not execute write transaction: %w", err)
}
return nil
}
func (db *Database) ReadTX(ctx context.Context, fn TxFn) (err error) {
conn, err := db.readPool.Take(ctx)
if err != nil {
return fmt.Errorf("failed to take read connection: %w", err)
}
if conn == nil {
return fmt.Errorf("could not get read connection from pool")
}
defer db.readPool.Put(conn)
endFn := sqlitex.Transaction(conn)
defer endFn(&err)
if err := fn(conn); err != nil {
return fmt.Errorf("could not execute read transaction: %w", err)
}
return nil
}
const (
secondsInADay = 86400
UnixEpochJulianDay = 2440587.5
)
var (
JulianZeroTime = JulianDayToTime(0)
)
// TimeToJulianDay converts a time.Time into a Julian day.
func TimeToJulianDay(t time.Time) float64 {
return float64(t.UTC().Unix())/secondsInADay + UnixEpochJulianDay
}
// JulianDayToTime converts a Julian day into a time.Time.
func JulianDayToTime(d float64) time.Time {
return time.Unix(int64((d-UnixEpochJulianDay)*secondsInADay), 0).UTC()
}
func JulianNow() float64 {
return TimeToJulianDay(time.Now())
}
func TimestampJulian(ts *timestamppb.Timestamp) float64 {
return TimeToJulianDay(ts.AsTime())
}
func JulianDayToTimestamp(f float64) *timestamppb.Timestamp {
t := JulianDayToTime(f)
return timestamppb.New(t)
}
func StmtJulianToTimestamp(stmt *sqlite.Stmt, colName string) *timestamppb.Timestamp {
julianDays := stmt.GetFloat(colName)
return JulianDayToTimestamp(julianDays)
}
func StmtJulianToTime(stmt *sqlite.Stmt, colName string) time.Time {
julianDays := stmt.GetFloat(colName)
return JulianDayToTime(julianDays)
}
func DurationToMilliseconds(d time.Duration) int64 {
return int64(d / time.Millisecond)
}
func MillisecondsToDuration(ms int64) time.Duration {
return time.Duration(ms) * time.Millisecond
}
func StmtBytes(stmt *sqlite.Stmt, colName string) []byte {
bl := stmt.GetLen(colName)
if bl == 0 {
return nil
}
buf := make([]byte, bl)
if writtent := stmt.GetBytes(colName, buf); writtent != bl {
return nil
}
return buf
}
func StmtBytesByCol(stmt *sqlite.Stmt, col int) []byte {
bl := stmt.ColumnLen(col)
if bl == 0 {
return nil
}
buf := make([]byte, bl)
if writtent := stmt.ColumnBytes(col, buf); writtent != bl {
return nil
}
return buf
}
func MigrationsFromFS(migrationsFS embed.FS, migrationsDir string) ([]string, error) {
migrationsFiles, err := migrationsFS.ReadDir(migrationsDir)
if err != nil {
return nil, fmt.Errorf("failed to read migrations directory: %w", err)
}
slices.SortFunc(migrationsFiles, func(a, b fs.DirEntry) int {
return strings.Compare(a.Name(), b.Name())
})
migrations := make([]string, len(migrationsFiles))
for i, file := range migrationsFiles {
fn := filepath.Join(migrationsDir, file.Name())
f, err := migrationsFS.Open(fn)
if err != nil {
return nil, fmt.Errorf("failed to open migration file: %w", err)
}
defer f.Close()
content, err := io.ReadAll(f)
if err != nil {
return nil, fmt.Errorf("failed to read migration file: %w", err)
}
migrations[i] = string(content)
}
return migrations, nil
}