-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdatabase.go
More file actions
614 lines (528 loc) · 15.9 KB
/
database.go
File metadata and controls
614 lines (528 loc) · 15.9 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
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
package module
import (
"context"
"database/sql"
"fmt"
"math"
"regexp"
"sort"
"strings"
"sync"
"time"
"github.com/CrisisTextLine/modular"
)
// validIdentifier matches safe SQL identifiers (alphanumeric, underscore, dot for schema.table).
var validIdentifier = regexp.MustCompile(`^[a-zA-Z_][a-zA-Z0-9_.]*$`)
// validateIdentifier checks that a SQL identifier (table/column name) is safe.
func validateIdentifier(name string) error {
if !validIdentifier.MatchString(name) {
return fmt.Errorf("invalid SQL identifier: %q", name)
}
return nil
}
// DatabaseTLSConfig holds TLS settings for database connections.
type DatabaseTLSConfig struct {
// Mode controls SSL behaviour: disable | require | verify-ca | verify-full (PostgreSQL naming).
Mode string `json:"mode" yaml:"mode"`
CAFile string `json:"ca_file" yaml:"ca_file"`
}
// DatabaseConfig holds configuration for the workflow database module
type DatabaseConfig struct {
Driver string `json:"driver" yaml:"driver"`
DSN string `json:"dsn" yaml:"dsn"`
MaxOpenConns int `json:"maxOpenConns" yaml:"maxOpenConns"`
MaxIdleConns int `json:"maxIdleConns" yaml:"maxIdleConns"`
ConnMaxLifetime time.Duration `json:"connMaxLifetime" yaml:"connMaxLifetime"`
MigrationsDir string `json:"migrationsDir" yaml:"migrationsDir"`
TLS DatabaseTLSConfig `json:"tls" yaml:"tls"`
}
// QueryResult represents the result of a query
type QueryResult struct {
Columns []string `json:"columns"`
Rows []map[string]any `json:"rows"`
Count int `json:"count"`
}
// WorkflowDatabase wraps database/sql for workflow use
type WorkflowDatabase struct {
name string
config DatabaseConfig
db *sql.DB
mu sync.RWMutex
}
// NewWorkflowDatabase creates a new WorkflowDatabase module
func NewWorkflowDatabase(name string, config DatabaseConfig) *WorkflowDatabase {
return &WorkflowDatabase{
name: name,
config: config,
}
}
// Name returns the module name
func (w *WorkflowDatabase) Name() string {
return w.name
}
// Init registers the database as a service
func (w *WorkflowDatabase) Init(app modular.Application) error {
return app.RegisterService(w.name, w)
}
// ProvidesServices declares the service this module provides, enabling proper
// dependency ordering in the modular framework.
func (w *WorkflowDatabase) ProvidesServices() []modular.ServiceProvider {
return []modular.ServiceProvider{
{
Name: w.name,
Description: "Workflow Database: " + w.name,
Instance: w,
},
}
}
// RequiresServices returns no dependencies.
func (w *WorkflowDatabase) RequiresServices() []modular.ServiceDependency {
return nil
}
// buildDSN returns the DSN with TLS parameters appended for supported drivers.
func (w *WorkflowDatabase) buildDSN() string {
dsn := w.config.DSN
mode := w.config.TLS.Mode
if mode == "" || mode == "disable" {
return dsn
}
switch w.config.Driver {
case "postgres", "pgx", "pgx/v5":
sep := "?"
if strings.ContainsRune(dsn, '?') {
sep = "&"
}
dsn += sep + "sslmode=" + mode
if w.config.TLS.CAFile != "" {
dsn += "&sslrootcert=" + w.config.TLS.CAFile
}
}
return dsn
}
// Open opens the database connection using config
func (w *WorkflowDatabase) Open() (*sql.DB, error) {
w.mu.Lock()
defer w.mu.Unlock()
if w.db != nil {
return w.db, nil
}
db, err := sql.Open(w.config.Driver, w.buildDSN())
if err != nil {
return nil, fmt.Errorf("failed to open database: %w", err)
}
if w.config.MaxOpenConns > 0 {
db.SetMaxOpenConns(w.config.MaxOpenConns)
}
if w.config.MaxIdleConns > 0 {
db.SetMaxIdleConns(w.config.MaxIdleConns)
}
if w.config.ConnMaxLifetime > 0 {
db.SetConnMaxLifetime(w.config.ConnMaxLifetime)
}
w.db = db
return db, nil
}
// Start opens the database connection during application startup so that
// pipeline steps (db_query, db_exec) can use DB() without requiring a
// separate persistence.store module.
func (w *WorkflowDatabase) Start(ctx context.Context) error {
if w.config.DSN == "" {
return nil // no DSN configured, skip auto-open
}
_, err := w.Open()
return err
}
// Stop closes the database connection during application shutdown.
func (w *WorkflowDatabase) Stop(ctx context.Context) error {
return w.Close()
}
// Close closes the database connection
func (w *WorkflowDatabase) Close() error {
w.mu.Lock()
defer w.mu.Unlock()
if w.db != nil {
err := w.db.Close()
w.db = nil
return err
}
return nil
}
// DB returns the underlying *sql.DB
func (w *WorkflowDatabase) DB() *sql.DB {
w.mu.RLock()
defer w.mu.RUnlock()
return w.db
}
// DriverName returns the configured database driver (e.g. "pgx", "sqlite3").
func (w *WorkflowDatabase) DriverName() string {
return w.config.Driver
}
// Ping checks the database connection
func (w *WorkflowDatabase) Ping(ctx context.Context) error {
w.mu.RLock()
db := w.db
w.mu.RUnlock()
if db == nil {
return fmt.Errorf("database not open")
}
return db.PingContext(ctx)
}
// Query executes a query and returns structured results
func (w *WorkflowDatabase) Query(ctx context.Context, sqlStr string, args ...any) (*QueryResult, error) {
w.mu.RLock()
db := w.db
w.mu.RUnlock()
if db == nil {
return nil, fmt.Errorf("database not open")
}
rows, err := db.QueryContext(ctx, sqlStr, args...)
if err != nil {
return nil, fmt.Errorf("query failed: %w", err)
}
defer func() { _ = rows.Close() }()
columns, err := rows.Columns()
if err != nil {
return nil, fmt.Errorf("failed to get columns: %w", err)
}
result := &QueryResult{
Columns: columns,
Rows: make([]map[string]any, 0),
}
for rows.Next() {
values := make([]any, len(columns))
valuePtrs := make([]any, len(columns))
for i := range values {
valuePtrs[i] = &values[i]
}
if err := rows.Scan(valuePtrs...); err != nil {
return nil, fmt.Errorf("failed to scan row: %w", err)
}
row := make(map[string]any)
for i, col := range columns {
val := values[i]
// Convert byte slices to strings for readability
if b, ok := val.([]byte); ok {
row[col] = string(b)
} else {
row[col] = val
}
}
result.Rows = append(result.Rows, row)
}
if err := rows.Err(); err != nil {
return nil, fmt.Errorf("rows iteration error: %w", err)
}
result.Count = len(result.Rows)
return result, nil
}
// Execute executes a statement and returns rows affected
func (w *WorkflowDatabase) Execute(ctx context.Context, sqlStr string, args ...any) (int64, error) {
w.mu.RLock()
db := w.db
w.mu.RUnlock()
if db == nil {
return 0, fmt.Errorf("database not open")
}
result, err := db.ExecContext(ctx, sqlStr, args...)
if err != nil {
return 0, fmt.Errorf("execute failed: %w", err)
}
rowsAffected, err := result.RowsAffected()
if err != nil {
return 0, fmt.Errorf("failed to get rows affected: %w", err)
}
return rowsAffected, nil
}
// InsertRow builds and executes an INSERT statement
func (w *WorkflowDatabase) InsertRow(ctx context.Context, table string, data map[string]any) (int64, error) {
if len(data) == 0 {
return 0, fmt.Errorf("no data to insert")
}
if err := validateIdentifier(table); err != nil {
return 0, fmt.Errorf("invalid table name: %w", err)
}
// Sort keys for deterministic SQL generation
keys := make([]string, 0, len(data))
for k := range data {
keys = append(keys, k)
}
sort.Strings(keys)
columns := make([]string, len(keys))
placeholders := make([]string, len(keys))
values := make([]any, len(keys))
for i, k := range keys {
if err := validateIdentifier(k); err != nil {
return 0, fmt.Errorf("invalid column name: %w", err)
}
columns[i] = k
placeholders[i] = fmt.Sprintf("$%d", i+1)
values[i] = data[k]
}
sqlStr := fmt.Sprintf("INSERT INTO %s (%s) VALUES (%s)",
table,
strings.Join(columns, ", "),
strings.Join(placeholders, ", "),
)
return w.Execute(ctx, sqlStr, values...)
}
// UpdateRows builds and executes an UPDATE statement
func (w *WorkflowDatabase) UpdateRows(ctx context.Context, table string, data map[string]any, where string, whereArgs ...any) (int64, error) {
if len(data) == 0 {
return 0, fmt.Errorf("no data to update")
}
if err := validateIdentifier(table); err != nil {
return 0, fmt.Errorf("invalid table name: %w", err)
}
// Overflow check for allocation size
if len(data) > math.MaxInt-len(whereArgs) {
return 0, fmt.Errorf("too many parameters: data(%d) + whereArgs(%d) overflows", len(data), len(whereArgs))
}
// Sort keys for deterministic SQL generation
keys := make([]string, 0, len(data))
for k := range data {
keys = append(keys, k)
}
sort.Strings(keys)
setClauses := make([]string, len(keys))
values := make([]any, 0, len(keys)+len(whereArgs))
for i, k := range keys {
if err := validateIdentifier(k); err != nil {
return 0, fmt.Errorf("invalid column name: %w", err)
}
setClauses[i] = fmt.Sprintf("%s = $%d", k, i+1)
values = append(values, data[k])
}
sqlStr := fmt.Sprintf("UPDATE %s SET %s",
table,
strings.Join(setClauses, ", "),
)
if where != "" {
sqlStr += " WHERE " + where
values = append(values, whereArgs...)
}
return w.Execute(ctx, sqlStr, values...)
}
// DeleteRows builds and executes a DELETE statement
func (w *WorkflowDatabase) DeleteRows(ctx context.Context, table string, where string, whereArgs ...any) (int64, error) {
if err := validateIdentifier(table); err != nil {
return 0, fmt.Errorf("invalid table name: %w", err)
}
sqlStr := fmt.Sprintf("DELETE FROM %s", table)
if where != "" {
sqlStr += " WHERE " + where
}
return w.Execute(ctx, sqlStr, whereArgs...)
}
// BuildInsertSQL builds an INSERT SQL string and returns it with values (exported for testing).
// Returns an error if table or column names contain unsafe characters.
func BuildInsertSQL(table string, data map[string]any) (string, []any, error) {
if len(data) == 0 {
return "", nil, nil
}
if err := validateIdentifier(table); err != nil {
return "", nil, fmt.Errorf("invalid table name: %w", err)
}
keys := make([]string, 0, len(data))
for k := range data {
keys = append(keys, k)
}
sort.Strings(keys)
columns := make([]string, len(keys))
placeholders := make([]string, len(keys))
values := make([]any, len(keys))
for i, k := range keys {
if err := validateIdentifier(k); err != nil {
return "", nil, fmt.Errorf("invalid column name: %w", err)
}
columns[i] = k
placeholders[i] = fmt.Sprintf("$%d", i+1)
values[i] = data[k]
}
sqlStr := fmt.Sprintf("INSERT INTO %s (%s) VALUES (%s)",
table,
strings.Join(columns, ", "),
strings.Join(placeholders, ", "),
)
return sqlStr, values, nil
}
// BuildUpdateSQL builds an UPDATE SQL string and returns it with values (exported for testing).
// Returns an error if table or column names contain unsafe characters.
func BuildUpdateSQL(table string, data map[string]any, where string, whereArgs ...any) (string, []any, error) {
if len(data) == 0 {
return "", nil, nil
}
if err := validateIdentifier(table); err != nil {
return "", nil, fmt.Errorf("invalid table name: %w", err)
}
keys := make([]string, 0, len(data))
for k := range data {
keys = append(keys, k)
}
sort.Strings(keys)
setClauses := make([]string, len(keys))
values := make([]any, 0, len(keys)+len(whereArgs))
for i, k := range keys {
if err := validateIdentifier(k); err != nil {
return "", nil, fmt.Errorf("invalid column name: %w", err)
}
setClauses[i] = fmt.Sprintf("%s = $%d", k, i+1)
values = append(values, data[k])
}
sqlStr := fmt.Sprintf("UPDATE %s SET %s",
table,
strings.Join(setClauses, ", "),
)
if where != "" {
sqlStr += " WHERE " + where
values = append(values, whereArgs...)
}
return sqlStr, values, nil
}
// BuildDeleteSQL builds a DELETE SQL string (exported for testing).
// Returns an error if the table name contains unsafe characters.
func BuildDeleteSQL(table string, where string, whereArgs ...any) (string, []any, error) {
if err := validateIdentifier(table); err != nil {
return "", nil, fmt.Errorf("invalid table name: %w", err)
}
sqlStr := fmt.Sprintf("DELETE FROM %s", table)
var values []any
if where != "" {
sqlStr += " WHERE " + where
values = whereArgs
}
return sqlStr, values, nil
}
// DatabaseIntegrationConnector implements IntegrationConnector for database operations
type DatabaseIntegrationConnector struct {
name string
db *WorkflowDatabase
connected bool
}
// NewDatabaseIntegrationConnector creates a new database integration connector
func NewDatabaseIntegrationConnector(name string, db *WorkflowDatabase) *DatabaseIntegrationConnector {
return &DatabaseIntegrationConnector{
name: name,
db: db,
}
}
// GetName returns the connector name
func (c *DatabaseIntegrationConnector) GetName() string {
return c.name
}
// Connect opens the database connection
func (c *DatabaseIntegrationConnector) Connect(ctx context.Context) error {
_, err := c.db.Open()
if err != nil {
return fmt.Errorf("failed to connect database: %w", err)
}
c.connected = true
return nil
}
// Disconnect closes the database connection
func (c *DatabaseIntegrationConnector) Disconnect(ctx context.Context) error {
c.connected = false
return c.db.Close()
}
// IsConnected returns whether the connector is connected
func (c *DatabaseIntegrationConnector) IsConnected() bool {
return c.connected
}
// Execute dispatches to the appropriate WorkflowDatabase method based on action
func (c *DatabaseIntegrationConnector) Execute(ctx context.Context, action string, params map[string]any) (map[string]any, error) {
if !c.connected {
return nil, fmt.Errorf("connector not connected")
}
switch action {
case "query":
sqlStr, _ := params["sql"].(string)
if sqlStr == "" {
return nil, fmt.Errorf("sql parameter required for query action")
}
args := extractArgs(params)
result, err := c.db.Query(ctx, sqlStr, args...)
if err != nil {
return nil, err
}
return map[string]any{
"columns": result.Columns,
"rows": result.Rows,
"count": result.Count,
}, nil
case "execute":
sqlStr, _ := params["sql"].(string)
if sqlStr == "" {
return nil, fmt.Errorf("sql parameter required for execute action")
}
args := extractArgs(params)
rowsAffected, err := c.db.Execute(ctx, sqlStr, args...)
if err != nil {
return nil, err
}
return map[string]any{
"rowsAffected": rowsAffected,
}, nil
case "insert":
table, _ := params["table"].(string)
if table == "" {
return nil, fmt.Errorf("table parameter required for insert action")
}
data, _ := params["data"].(map[string]any)
if len(data) == 0 {
return nil, fmt.Errorf("data parameter required for insert action")
}
rowsAffected, err := c.db.InsertRow(ctx, table, data)
if err != nil {
return nil, err
}
return map[string]any{
"rowsAffected": rowsAffected,
}, nil
case "update":
table, _ := params["table"].(string)
if table == "" {
return nil, fmt.Errorf("table parameter required for update action")
}
data, _ := params["data"].(map[string]any)
if len(data) == 0 {
return nil, fmt.Errorf("data parameter required for update action")
}
where, _ := params["where"].(string)
whereArgs := extractArgs(params)
rowsAffected, err := c.db.UpdateRows(ctx, table, data, where, whereArgs...)
if err != nil {
return nil, err
}
return map[string]any{
"rowsAffected": rowsAffected,
}, nil
case "delete":
table, _ := params["table"].(string)
if table == "" {
return nil, fmt.Errorf("table parameter required for delete action")
}
where, _ := params["where"].(string)
whereArgs := extractArgs(params)
rowsAffected, err := c.db.DeleteRows(ctx, table, where, whereArgs...)
if err != nil {
return nil, err
}
return map[string]any{
"rowsAffected": rowsAffected,
}, nil
default:
return nil, fmt.Errorf("unsupported action: %s (supported: query, execute, insert, update, delete)", action)
}
}
// extractArgs extracts the "args" parameter as a slice of interface{}
func extractArgs(params map[string]any) []any {
argsRaw, ok := params["args"]
if !ok {
return nil
}
switch v := argsRaw.(type) {
case []any:
return v
default:
return []any{v}
}
}