forked from goccy/bigquery-emulator
-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathmanager.go
More file actions
355 lines (298 loc) · 8.86 KB
/
manager.go
File metadata and controls
355 lines (298 loc) · 8.86 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
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
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
package connection
import (
"context"
"database/sql"
"fmt"
"sync"
"github.com/goccy/go-zetasqlite"
)
const (
// DefaultPoolSize is the default number of pre-initialized connections in the pool.
// This balances between connection reuse and resource usage.
DefaultPoolSize = 5
)
type Manager struct {
db *sql.DB
queries []string
connPool []*ManagedConnection
connChan chan *ManagedConnection
poolSize int
mu sync.Mutex
closeOnce sync.Once
closed bool
// Map transactions to their connection cache for prepared statement retrieval
txConnMap map[*sql.Tx]*ManagedConnection
txMu sync.RWMutex
}
func NewManager(ctx context.Context, db *sql.DB) (*Manager, error) {
poolSize := DefaultPoolSize
db.SetConnMaxLifetime(-1) // Keep connections alive
db.SetConnMaxIdleTime(-1)
connChan := make(chan *ManagedConnection, poolSize)
connPool := make([]*ManagedConnection, poolSize)
manager := &Manager{
db: db,
connPool: connPool,
connChan: connChan,
txConnMap: make(map[*sql.Tx]*ManagedConnection),
}
// Warm pool with managed connections
for i := 0; i < poolSize; i++ {
conn, err := db.Conn(ctx)
if err != nil {
return nil, fmt.Errorf("failed to create connection %d: %w", i, err)
}
managedConnection := &ManagedConnection{
zetasqliteConnection: conn,
stmts: make(map[string]*sql.Stmt),
queries: []string{},
manager: manager,
}
connPool[i] = managedConnection
connChan <- managedConnection
}
return manager, nil
}
// Close gracefully shuts down the repository
func (m *Manager) Close() (err error) {
m.closeOnce.Do(func() {
m.mu.Lock()
defer m.mu.Unlock()
m.closed = true
close(m.connChan)
for _, conn := range m.connPool {
if closeErr := conn.Close(); closeErr != nil && err == nil {
err = closeErr
}
}
})
return
}
type Tx struct {
tx *sql.Tx
conn *ManagedConnection
manager *Manager
committed bool
finalized bool
}
func (t *Tx) Tx() *sql.Tx {
return t.tx
}
// unregister removes this transaction from the manager's tracking map.
// It is idempotent and safe to call multiple times.
func (t *Tx) unregister() {
if t.finalized || t.manager == nil {
return
}
t.manager.txMu.Lock()
delete(t.manager.txConnMap, t.tx)
t.manager.txMu.Unlock()
t.finalized = true
}
func (t *Tx) Conn() *ManagedConnection { return t.conn }
func (t *Tx) RollbackIfNotCommitted() error {
defer t.unregister()
if t.committed {
return nil
}
return t.tx.Rollback()
}
func (t *Tx) Commit() error {
defer t.unregister()
if err := t.tx.Commit(); err != nil {
return err
}
t.committed = true
return nil
}
func (t *Tx) SetProjectAndDataset(projectID, datasetID string) {
t.conn.ProjectID = projectID
t.conn.DatasetID = datasetID
}
func (t *Tx) MetadataRepoMode() error {
if err := t.conn.zetasqliteConnection.Raw(func(c interface{}) error {
zetasqliteConn, ok := c.(*zetasqlite.ZetaSQLiteConn)
if !ok {
return fmt.Errorf("failed to get ZetaSQLiteConn from %T", c)
}
_ = zetasqliteConn.SetNamePath([]string{})
return nil
}); err != nil {
return fmt.Errorf("failed to setup connection: %w", err)
}
return nil
}
func (t *Tx) ContentRepoMode() error {
if err := t.conn.zetasqliteConnection.Raw(func(c interface{}) error {
zetasqliteConn, ok := c.(*zetasqlite.ZetaSQLiteConn)
if !ok {
return fmt.Errorf("failed to get ZetaSQLiteConn from %T", c)
}
if t.conn.DatasetID == "" {
_ = zetasqliteConn.SetNamePath([]string{t.conn.ProjectID})
} else {
_ = zetasqliteConn.SetNamePath([]string{t.conn.ProjectID, t.conn.DatasetID})
}
const maxNamePath = 3 // projectID and datasetID and tableID
zetasqliteConn.SetMaxNamePath(maxNamePath)
return nil
}); err != nil {
return fmt.Errorf("failed to setup connection: %w", err)
}
return nil
}
type ManagedConnection struct {
zetasqliteConnection *sql.Conn
stmts map[string]*sql.Stmt
queries []string
mu sync.RWMutex
manager *Manager // immutable after construction, safe for concurrent reads
ProjectID string
DatasetID string
}
func (c *ManagedConnection) GetStmt(name string) (*sql.Stmt, error) {
c.mu.RLock()
defer c.mu.RUnlock()
stmt, ok := c.stmts[name]
if !ok {
return nil, fmt.Errorf("statement not found: %s", name)
}
return stmt, nil
}
func (c *ManagedConnection) Close() (err error) {
c.mu.Lock()
defer c.mu.Unlock()
for _, stmt := range c.stmts {
if closeErr := stmt.Close(); closeErr != nil && err == nil {
err = closeErr
}
}
if closeErr := c.zetasqliteConnection.Close(); closeErr != nil && err == nil {
err = closeErr
}
return
}
func (c *ManagedConnection) ConfigureScope(projectID, datasetID string) *ManagedConnection {
c.ProjectID = projectID
c.DatasetID = datasetID
return c
}
// Raw executes the given function with the underlying ZetaSQLite connection.
func (c *ManagedConnection) Raw(fn func(interface{}) error) error {
return c.zetasqliteConnection.Raw(fn)
}
func (c *ManagedConnection) Begin(ctx context.Context) (*Tx, error) {
tx, err := c.zetasqliteConnection.BeginTx(ctx, nil)
if err != nil {
return nil, err
}
wrappedTx := &Tx{tx: tx, conn: c, manager: c.manager}
// Register transaction with manager if available
if c.manager != nil {
c.manager.txMu.Lock()
c.manager.txConnMap[tx] = c
c.manager.txMu.Unlock()
}
return wrappedTx, nil
}
// GetStatement retrieves a prepared statement for use within a transaction
func (m *Manager) GetStatement(ctx context.Context, tx *sql.Tx, name string) (*sql.Stmt, error) {
if tx == nil {
return nil, fmt.Errorf("transaction is nil")
}
m.txMu.RLock()
conn, ok := m.txConnMap[tx]
m.txMu.RUnlock()
if ok {
// Transaction is tracked in txConnMap, use pre-prepared statement
return conn.GetStmt(name)
}
// Transaction was created externally, prepare statement on the fly (this ideally never happens)
ctx = zetasqlite.WithQueryFormattingDisabled(ctx)
return tx.PrepareContext(ctx, name)
}
func (m *Manager) PrepareQueries(queries []string) error {
for _, conn := range m.connPool {
// Prepare specified SQLite queries for this connection
ctx := zetasqlite.WithQueryFormattingDisabled(context.Background())
for _, query := range queries {
stmt, err := conn.zetasqliteConnection.PrepareContext(ctx, query)
if err != nil {
return fmt.Errorf("failed to prepare statement %s: %w", query, err)
}
conn.stmts[query] = stmt
}
}
return nil
}
func (m *Manager) WithManagedConnection(ctx context.Context, fn func(ctx context.Context, conn *ManagedConnection) error) error {
select {
case conn := <-m.connChan:
defer func() {
m.connChan <- conn
}()
return fn(ctx, conn)
case <-ctx.Done():
return fmt.Errorf("context cancelled: %w", ctx.Err())
}
}
func (m *Manager) ExecuteWithTransaction(ctx context.Context, fn func(ctx context.Context, tx *Tx) error) error {
return m.WithManagedConnection(ctx, func(ctx context.Context, conn *ManagedConnection) error {
tx, err := conn.Begin(ctx)
if err != nil {
return fmt.Errorf("failed to begin transaction: %w", err)
}
// Transaction is automatically registered in Begin() and will be unregistered in Commit()/RollbackIfNotCommitted()
// Execute the user's function with the transaction
err = fn(ctx, tx)
if err != nil {
if rbErr := tx.RollbackIfNotCommitted(); rbErr != nil {
return fmt.Errorf("transaction failed: %w (rollback also failed: %v)", err, rbErr)
}
return err
}
if err = tx.Commit(); err != nil {
return fmt.Errorf("failed to commit transaction: %w", err)
}
return nil
})
}
func WithManagedConnection[T any](m *Manager, ctx context.Context,
fn func(context.Context, *ManagedConnection) (T, error)) (T, error) {
var zero T
if m.closed {
return zero, fmt.Errorf("repository is closed")
}
select {
case conn := <-m.connChan:
defer func() {
m.connChan <- conn
}()
return fn(ctx, conn)
case <-ctx.Done():
return zero, fmt.Errorf("context cancelled: %w", ctx.Err())
}
}
// ExecuteWithTransaction is a convenience wrapper for executing a function with a transaction
// This is useful for migrating code that used getConnection + BeginTx pattern
func ExecuteWithTransaction[T any](m *Manager, ctx context.Context, fn func(context.Context, *sql.Tx) (T, error)) (T, error) {
return WithManagedConnection[T](m, ctx, func(ctx context.Context, conn *ManagedConnection) (T, error) {
var zero T
tx, err := conn.Begin(ctx)
if err != nil {
return zero, fmt.Errorf("failed to begin transaction: %w", err)
}
// Execute the user's function with the transaction
result, err := fn(ctx, tx.Tx())
if err != nil {
if rbErr := tx.RollbackIfNotCommitted(); rbErr != nil {
return zero, fmt.Errorf("transaction failed: %w (rollback also failed: %v)", err, rbErr)
}
return zero, err
}
if err = tx.Commit(); err != nil {
return zero, fmt.Errorf("failed to commit transaction: %w", err)
}
return result, nil
})
}