-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsql.go
More file actions
416 lines (340 loc) · 10 KB
/
sql.go
File metadata and controls
416 lines (340 loc) · 10 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
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
package database
import (
"context"
"database/sql"
"fmt"
"sync/atomic"
"time"
"github.com/uptrace/bun"
"github.com/uptrace/bun/dialect/mysqldialect"
"github.com/uptrace/bun/dialect/pgdialect"
"github.com/uptrace/bun/dialect/sqlitedialect"
"github.com/uptrace/bun/schema"
// Import SQL drivers.
_ "github.com/go-sql-driver/mysql"
_ "github.com/lib/pq"
_ "github.com/mattn/go-sqlite3"
"github.com/xraph/forge"
"github.com/xraph/forge/errors"
"github.com/xraph/forge/internal/logger"
"github.com/xraph/go-utils/metrics"
)
// SQLDatabase wraps Bun ORM for SQL databases.
type SQLDatabase struct {
name string
dbType DatabaseType
config DatabaseConfig
// Native access
sqlDB *sql.DB // Raw database/sql connection
bun *bun.DB // Bun ORM instance
// Connection state
state atomic.Int32
logger forge.Logger
metrics forge.Metrics
}
// NewSQLDatabase creates a new SQL database instance.
func NewSQLDatabase(config DatabaseConfig, logger forge.Logger, metrics forge.Metrics) (*SQLDatabase, error) {
db := &SQLDatabase{
name: config.Name,
dbType: config.Type,
config: config,
logger: logger,
metrics: metrics,
}
db.state.Store(int32(StateDisconnected))
return db, nil
}
// Open establishes the database connection with retry logic.
func (d *SQLDatabase) Open(ctx context.Context) error {
d.state.Store(int32(StateConnecting))
var lastErr error
for attempt := 0; attempt <= d.config.MaxRetries; attempt++ {
if attempt > 0 {
d.state.Store(int32(StateReconnecting))
// Apply exponential backoff with jitter
delay := min(d.config.RetryDelay*time.Duration(1<<uint(attempt-1)), 30*time.Second)
d.logger.Info("retrying database connection",
logger.String("name", d.name),
logger.Int("attempt", attempt+1),
logger.Int("max_attempts", d.config.MaxRetries+1),
logger.Duration("delay", delay),
)
select {
case <-time.After(delay):
case <-ctx.Done():
d.state.Store(int32(StateError))
return ctx.Err()
}
}
if err := d.openAttempt(ctx); err != nil {
lastErr = err
d.logger.Warn("database connection attempt failed",
logger.String("name", d.name),
logger.Int("attempt", attempt+1),
logger.Error(err),
)
continue
}
d.state.Store(int32(StateConnected))
d.logger.Debug("database opened",
logger.String("name", d.name),
logger.String("type", string(d.dbType)),
logger.String("dsn", MaskDSN(d.config.DSN, d.dbType)),
logger.Int("max_open", d.config.MaxOpenConns),
logger.Int("attempts", attempt+1),
)
return nil
}
d.state.Store(int32(StateError))
return ErrConnectionFailed(d.name, d.dbType, fmt.Errorf("failed after %d attempts: %w", d.config.MaxRetries+1, lastErr))
}
// openAttempt performs a single connection attempt.
func (d *SQLDatabase) openAttempt(ctx context.Context) error {
// Add timeout for connection
connectCtx := ctx
if d.config.ConnectionTimeout > 0 {
var cancel context.CancelFunc
connectCtx, cancel = context.WithTimeout(ctx, d.config.ConnectionTimeout)
defer cancel()
}
// Open raw SQL connection
sqlDB, err := sql.Open(d.driverName(), d.config.DSN)
if err != nil {
return fmt.Errorf("failed to open database: %w", err)
}
// Configure connection pool
sqlDB.SetMaxOpenConns(d.config.MaxOpenConns)
sqlDB.SetMaxIdleConns(d.config.MaxIdleConns)
sqlDB.SetConnMaxLifetime(d.config.ConnMaxLifetime)
sqlDB.SetConnMaxIdleTime(d.config.ConnMaxIdleTime)
// Verify connection
if err := sqlDB.PingContext(connectCtx); err != nil {
sqlDB.Close()
return fmt.Errorf("failed to ping database: %w", err)
}
d.sqlDB = sqlDB
// Wrap with Bun ORM
d.bun = bun.NewDB(sqlDB, d.dialect())
// Add query hook for observability
hook := d.queryHook()
if d.config.AutoExplainThreshold > 0 {
// Use enhanced observability hook with auto-explain
hook = NewObservabilityQueryHook(
d.logger,
d.metrics,
d.name,
d.dbType,
d.config.SlowQueryThreshold,
d.config.DisableSlowQueryLogging,
).WithAutoExplain(d.config.AutoExplainThreshold)
}
d.bun.AddQueryHook(hook)
return nil
}
// Close closes the database connection.
func (d *SQLDatabase) Close(ctx context.Context) error {
if d.bun != nil {
err := d.bun.Close()
if err != nil {
d.state.Store(int32(StateError))
return ErrConnectionFailed(d.name, d.dbType, fmt.Errorf("failed to close: %w", err))
}
d.state.Store(int32(StateDisconnected))
d.logger.Debug("database closed", logger.String("name", d.name))
return nil
}
return nil
}
// Ping checks database connectivity.
func (d *SQLDatabase) Ping(ctx context.Context) error {
if d.sqlDB == nil {
return ErrDatabaseNotOpened(d.name)
}
// Add timeout if configured
pingCtx := ctx
if d.config.ConnectionTimeout > 0 {
var cancel context.CancelFunc
pingCtx, cancel = context.WithTimeout(ctx, d.config.ConnectionTimeout)
defer cancel()
}
return d.sqlDB.PingContext(pingCtx)
}
// IsOpen returns whether the database is connected.
func (d *SQLDatabase) IsOpen() bool {
return d.State() == StateConnected
}
// State returns the current connection state.
func (d *SQLDatabase) State() ConnectionState {
return ConnectionState(d.state.Load())
}
// Name returns the database name.
func (d *SQLDatabase) Name() string {
return d.name
}
// Type returns the database type.
func (d *SQLDatabase) Type() DatabaseType {
return d.dbType
}
// Driver returns the raw *sql.DB for native driver access.
func (d *SQLDatabase) Driver() any {
return d.sqlDB
}
// DB returns the raw *sql.DB.
func (d *SQLDatabase) DB() *sql.DB {
return d.sqlDB
}
// Bun returns the Bun ORM instance.
func (d *SQLDatabase) Bun() *bun.DB {
return d.bun
}
// Health returns the health status.
func (d *SQLDatabase) Health(ctx context.Context) HealthStatus {
start := time.Now()
status := HealthStatus{
CheckedAt: time.Now(),
}
if err := d.Ping(ctx); err != nil {
status.Healthy = false
status.Message = err.Error()
return status
}
status.Healthy = true
status.Message = "ok"
status.Latency = time.Since(start)
return status
}
// Stats returns connection pool statistics.
func (d *SQLDatabase) Stats() DatabaseStats {
if d.sqlDB == nil {
return DatabaseStats{}
}
stats := d.sqlDB.Stats()
return DatabaseStats{
OpenConnections: stats.OpenConnections,
InUse: stats.InUse,
Idle: stats.Idle,
WaitCount: stats.WaitCount,
WaitDuration: stats.WaitDuration,
MaxIdleClosed: stats.MaxIdleClosed,
MaxLifetimeClosed: stats.MaxLifetimeClosed,
}
}
// Transaction executes a function in a SQL transaction with panic recovery.
func (d *SQLDatabase) Transaction(ctx context.Context, fn func(tx bun.Tx) error) (err error) {
return d.bun.RunInTx(ctx, nil, func(ctx context.Context, tx bun.Tx) (err error) {
defer func() {
if r := recover(); r != nil {
err = ErrPanicRecovered(d.name, d.dbType, r)
d.logger.Error("panic recovered in transaction",
logger.String("db", d.name),
logger.Any("panic", r),
)
if d.metrics != nil {
d.metrics.Counter("db_transaction_panics",
metrics.WithLabel("db", d.name),
).Inc()
}
}
}()
return fn(tx)
})
}
// TransactionWithOptions executes a function in a SQL transaction with options and panic recovery.
func (d *SQLDatabase) TransactionWithOptions(ctx context.Context, opts *sql.TxOptions, fn func(tx bun.Tx) error) (err error) {
return d.bun.RunInTx(ctx, opts, func(ctx context.Context, tx bun.Tx) (err error) {
defer func() {
if r := recover(); r != nil {
err = ErrPanicRecovered(d.name, d.dbType, r)
d.logger.Error("panic recovered in transaction",
logger.String("db", d.name),
logger.Any("panic", r),
)
if d.metrics != nil {
d.metrics.Counter("db_transaction_panics",
metrics.WithLabel("db", d.name),
).Inc()
}
}
}()
return fn(tx)
})
}
// Helper: Get driver name.
func (d *SQLDatabase) driverName() string {
switch d.dbType {
case TypePostgres:
return "postgres"
case TypeMySQL:
return "mysql"
case TypeSQLite:
return "sqlite3"
default:
return string(d.dbType)
}
}
// Helper: Get Bun dialect.
func (d *SQLDatabase) dialect() schema.Dialect {
switch d.dbType {
case TypePostgres:
return pgdialect.New()
case TypeMySQL:
return mysqldialect.New()
case TypeSQLite:
return sqlitedialect.New()
default:
return pgdialect.New()
}
}
// Helper: Query hook for observability.
func (d *SQLDatabase) queryHook() bun.QueryHook {
return &QueryHook{
logger: d.logger,
metrics: d.metrics,
dbName: d.name,
slowQueryThreshold: d.config.SlowQueryThreshold,
disableSlowQueryLogging: d.config.DisableSlowQueryLogging,
}
}
// QueryHook provides observability for Bun queries.
type QueryHook struct {
logger forge.Logger
metrics forge.Metrics
dbName string
slowQueryThreshold time.Duration
disableSlowQueryLogging bool
}
// BeforeQuery is called before query execution.
func (h *QueryHook) BeforeQuery(ctx context.Context, event *bun.QueryEvent) context.Context {
return ctx
}
// AfterQuery is called after query execution.
func (h *QueryHook) AfterQuery(ctx context.Context, event *bun.QueryEvent) {
duration := time.Since(event.StartTime)
// Log slow queries using configurable threshold
if !h.disableSlowQueryLogging && duration > h.slowQueryThreshold {
h.logger.Warn("slow query detected",
logger.String("db", h.dbName),
logger.String("query", event.Query),
logger.Duration("duration", duration),
logger.Duration("threshold", h.slowQueryThreshold),
)
}
// Record metrics
if h.metrics != nil {
h.metrics.Histogram("db_query_duration",
metrics.WithLabel("db", h.dbName),
metrics.WithLabel("operation", event.Operation()),
).Observe(duration.Seconds())
if event.Err != nil && !errors.Is(event.Err, sql.ErrNoRows) {
h.metrics.Counter("db_query_errors",
metrics.WithLabel("db", h.dbName),
metrics.WithLabel("operation", event.Operation()),
).Inc()
h.logger.Error("query error",
logger.String("db", h.dbName),
logger.String("query", event.Query),
logger.Error(event.Err),
)
}
}
}