-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsnapshot.store.sqlite.go
More file actions
186 lines (162 loc) · 4.76 KB
/
Copy pathsnapshot.store.sqlite.go
File metadata and controls
186 lines (162 loc) · 4.76 KB
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
package store
import (
"context"
"database/sql"
"fmt"
"time"
"github.com/gradientzero/comby/v3"
_ "modernc.org/sqlite"
)
// SnapshotStoreSQLiteOption configures the SQLite snapshot store.
type SnapshotStoreSQLiteOption func(*snapshotStoreSQLiteConfig)
type snapshotStoreSQLiteConfig struct {
MaxOpenConns int
ConnMaxIdleTime time.Duration
}
// SnapshotStoreSQLiteWithMaxOpenConns sets the maximum number of open connections.
func SnapshotStoreSQLiteWithMaxOpenConns(n int) SnapshotStoreSQLiteOption {
return func(c *snapshotStoreSQLiteConfig) { c.MaxOpenConns = n }
}
// SnapshotStoreSQLiteWithConnMaxIdleTime sets the maximum connection idle time.
func SnapshotStoreSQLiteWithConnMaxIdleTime(d time.Duration) SnapshotStoreSQLiteOption {
return func(c *snapshotStoreSQLiteConfig) { c.ConnMaxIdleTime = d }
}
// Make sure it implements interfaces
var _ comby.SnapshotStore = (*snapshotStoreSQLite)(nil)
type snapshotStoreSQLite struct {
db *sql.DB
config snapshotStoreSQLiteConfig
path string
}
func NewSnapshotStoreSQLite(path string, opts ...SnapshotStoreSQLiteOption) comby.SnapshotStore {
s := &snapshotStoreSQLite{
path: path,
}
for _, opt := range opts {
opt(&s.config)
}
return s
}
func (s *snapshotStoreSQLite) connect(ctx context.Context) (*sql.DB, error) {
db, err := sql.Open("sqlite", s.path)
if err != nil {
return nil, err
}
maxOpenConns := 1
if s.config.MaxOpenConns > 0 {
maxOpenConns = s.config.MaxOpenConns
}
db.SetMaxOpenConns(maxOpenConns)
if s.config.ConnMaxIdleTime > 0 {
db.SetConnMaxIdleTime(s.config.ConnMaxIdleTime)
} else {
db.SetConnMaxIdleTime(5 * time.Minute)
}
query := `
PRAGMA journal_mode=WAL;
PRAGMA synchronous=NORMAL;
PRAGMA busy_timeout=5000;
`
if _, err := db.ExecContext(ctx, query); err != nil {
return nil, err
}
return db, nil
}
func (s *snapshotStoreSQLite) migrate(ctx context.Context) error {
query := `
CREATE TABLE IF NOT EXISTS snapshots (
aggregate_uuid TEXT PRIMARY KEY,
tenant_uuid TEXT,
workspace_uuid TEXT,
domain TEXT NOT NULL,
version INTEGER NOT NULL,
data BLOB NOT NULL,
created_at INTEGER NOT NULL
);
CREATE INDEX IF NOT EXISTS "snapshots_tenant_index" ON "snapshots" ("tenant_uuid" ASC);
CREATE INDEX IF NOT EXISTS "snapshots_workspace_index" ON "snapshots" ("workspace_uuid" ASC);
`
if _, err := s.db.ExecContext(ctx, query); err != nil {
return err
}
// migrate existing databases: add tenant_uuid + workspace_uuid columns if they don't exist
for _, col := range []string{"tenant_uuid", "workspace_uuid"} {
var count int
if err := s.db.QueryRowContext(ctx, fmt.Sprintf(`SELECT COUNT(*) FROM pragma_table_info('snapshots') WHERE name='%s'`, col)).Scan(&count); err != nil {
return err
}
if count == 0 {
if _, err := s.db.ExecContext(ctx, fmt.Sprintf(`ALTER TABLE snapshots ADD COLUMN %s TEXT`, col)); err != nil {
return err
}
}
}
return nil
}
func (s *snapshotStoreSQLite) Init(ctx context.Context) error {
db, err := s.connect(ctx)
if err != nil {
return err
}
s.db = db
if err := s.migrate(ctx); err != nil {
return err
}
return nil
}
func (s *snapshotStoreSQLite) Save(ctx context.Context, model *comby.SnapshotStoreModel) error {
if model == nil {
return fmt.Errorf("snapshot model is nil")
}
query := `INSERT INTO snapshots (aggregate_uuid, tenant_uuid, workspace_uuid, domain, version, data, created_at)
VALUES (?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(aggregate_uuid) DO UPDATE SET
tenant_uuid=excluded.tenant_uuid,
workspace_uuid=excluded.workspace_uuid,
domain=excluded.domain,
version=excluded.version,
data=excluded.data,
created_at=excluded.created_at;`
_, err := s.db.ExecContext(ctx, query,
model.AggregateUuid,
model.TenantUuid,
model.WorkspaceUuid,
model.Domain,
model.Version,
model.Data,
model.CreatedAt,
)
return err
}
func (s *snapshotStoreSQLite) GetLatest(ctx context.Context, aggregateUuid string) (*comby.SnapshotStoreModel, error) {
query := `SELECT aggregate_uuid, COALESCE(tenant_uuid, ''), COALESCE(workspace_uuid, ''), domain, version, data, created_at
FROM snapshots WHERE aggregate_uuid=? LIMIT 1;`
row := s.db.QueryRowContext(ctx, query, aggregateUuid)
var model comby.SnapshotStoreModel
if err := row.Scan(
&model.AggregateUuid,
&model.TenantUuid,
&model.WorkspaceUuid,
&model.Domain,
&model.Version,
&model.Data,
&model.CreatedAt,
); err != nil {
if err == sql.ErrNoRows {
return nil, nil
}
return nil, err
}
return &model, nil
}
func (s *snapshotStoreSQLite) Delete(ctx context.Context, aggregateUuid string) error {
query := `DELETE FROM snapshots WHERE aggregate_uuid=?;`
_, err := s.db.ExecContext(ctx, query, aggregateUuid)
return err
}
func (s *snapshotStoreSQLite) Close(ctx context.Context) error {
if s.db != nil {
return s.db.Close()
}
return nil
}