-
Notifications
You must be signed in to change notification settings - Fork 0
/
comfy.go
618 lines (540 loc) · 14.4 KB
/
comfy.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
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
615
616
617
618
package comfylite3
import (
"context"
"database/sql"
"fmt"
"math"
"sort"
"sync"
"sync/atomic"
"time"
"github.com/davidroman0O/retrypool"
_ "github.com/mattn/go-sqlite3"
)
// Callback provided by a developer to be executed when the scheduler is ready for it
type SqlFn func(db *sql.DB) (interface{}, error)
type workItem struct {
id uint64
fn SqlFn
result chan interface{}
}
// Default Memory Connection
const memoryConn = "file::memory:?_mutex=full&cache=shared&_timeout=5000"
// Default File Connection
const fileConn = "file:%s?cache=shared&mode=rwc&_journal_mode=WAL&_timeout=5000"
type onPanic func(v interface{}, stackTrace string)
type Migration struct {
Version uint
Label string
Up func(tx *sql.Tx) error
Down func(tx *sql.Tx) error
}
// Create a new migration with a version, label, and up and down functions.
func NewMigration(version uint, label string, up, down func(tx *sql.Tx) error) Migration {
return Migration{
Version: version,
Label: label,
Up: up,
Down: down,
}
}
// ComfyDB is a wrapper around sqlite3 that provides a simple API for executing SQL queries with goroutines.
type ComfyDB struct {
db *sql.DB
count atomic.Uint64
results sync.Map
migrations []Migration
migrationTableName string
memory bool
path string
conn string
pool *retrypool.Pool[*workItem]
poolOptions []retrypool.Option[*workItem]
}
type ComfyOption func(*ComfyDB)
// WithMigrationTableName sets the name of the migration table.
func WithMigrationTableName(name string) ComfyOption {
return func(o *ComfyDB) {
o.migrationTableName = name
}
}
// WithPath sets the path of the database file.
func WithPath(path string) ComfyOption {
return func(o *ComfyDB) {
o.path = path
o.memory = false
}
}
// WithMemory sets the database to be in-memory.
func WithMemory() ComfyOption {
return func(o *ComfyDB) {
o.memory = true
}
}
// WithConnection sets a custom connection string for the database.
func WithConnection(conn string) ComfyOption {
return func(o *ComfyDB) {
o.conn = conn
}
}
// Records your migrations for your database.
func WithMigration(migrations ...Migration) ComfyOption {
return func(c *ComfyDB) {
c.migrations = append(c.migrations, migrations...)
}
}
// WithRetryAttempts sets maximum retry attempts for failed operations
func WithRetryAttempts(attempts int) ComfyOption {
return func(c *ComfyDB) {
c.poolOptions = append(c.poolOptions, retrypool.WithAttempts[*workItem](attempts))
}
}
// WithRetryDelay sets delay between retries
func WithRetryDelay(delay time.Duration) ComfyOption {
return func(c *ComfyDB) {
c.poolOptions = append(c.poolOptions, retrypool.WithDelay[*workItem](delay))
}
}
// WithPanicHandler sets custom panic handler
func WithPanicHandler(handler onPanic) ComfyOption {
return func(c *ComfyDB) {
c.poolOptions = append(c.poolOptions, retrypool.WithPanicHandler[*workItem](func(task *workItem, v interface{}, stackTrace string) {
handler(v, stackTrace)
}))
}
}
// Close the database connection.
func (c *ComfyDB) Close() error {
// Close the retrypool
if err := c.pool.Shutdown(); err != nil {
if err != context.Canceled {
return err
}
}
// Close the database connection
return c.db.Close()
}
// Prepare the eventual creation of the migration table.
func (c *ComfyDB) prepareMigration() error {
newTableID := c.New(func(db *sql.DB) (interface{}, error) {
_, err := db.Exec(fmt.Sprintf(`
CREATE TABLE IF NOT EXISTS %v (
id INTEGER PRIMARY KEY AUTOINCREMENT,
version INTEGER UNIQUE NOT NULL,
description VARCHAR(255) UNIQUE NOT NULL
)`, c.migrationTableName))
return nil, err
})
result, err := c.WaitFor(newTableID)
if err != nil {
return err
}
if errResult, ok := result.(error); ok {
return errResult
}
return nil
}
// Sort the migrations by version.
func (c *ComfyDB) sort() []Migration {
cp := make([]Migration, len(c.migrations))
copy(cp, c.migrations)
sort.Slice(cp, func(i, j int) bool {
return cp[i].Version < cp[j].Version
})
return cp
}
// Create a new ComfyLite3 wrapper around sqlite3.
// Instantiate a scheduler to process your queries.
func New(opts ...ComfyOption) (*ComfyDB, error) {
c := &ComfyDB{
memory: true,
migrations: []Migration{},
migrationTableName: "_migrations",
poolOptions: make([]retrypool.Option[*workItem], 0),
}
c.count.Store(1)
for _, opt := range opts {
opt(c)
}
// Open the database connection
var err error
if c.conn != "" {
c.db, err = sql.Open("sqlite3", c.conn)
} else if c.memory {
c.db, err = sql.Open("sqlite3", memoryConn)
} else {
if c.path == "" {
return nil, fmt.Errorf("path is required")
}
c.db, err = sql.Open("sqlite3", fmt.Sprintf(fileConn, c.path))
}
if err != nil {
return nil, err
}
c.db.SetMaxOpenConns(1)
c.db.SetMaxIdleConns(1)
// Initialize the retrypool with a single worker
c.pool = retrypool.New[*workItem](
context.Background(),
[]retrypool.Worker[*workItem]{c},
c.poolOptions...,
)
// Prepare migrations
if err := c.prepareMigration(); err != nil {
return nil, err
}
return c, nil
}
// Implement the Worker interface from retrypool
func (c *ComfyDB) Run(ctx context.Context, item *workItem) error {
// Execute the function
res, err := item.fn(c.db)
// Store the result
if err != nil {
item.result <- err
} else {
item.result <- res
}
close(item.result)
return nil
}
// New adds a new SQL function to be executed
func (c *ComfyDB) New(fn SqlFn) uint64 {
// Check if we're about to overflow and reset if necessary
if c.count.Load() == math.MaxUint64 {
c.count.Store(1) // Reset to 1
}
item := &workItem{
id: c.count.Add(1),
fn: fn,
result: make(chan interface{}, 1),
}
// Store the work item
c.results.Store(item.id, item)
// Dispatch the work item to the retrypool
err := c.pool.Submit(item)
if err != nil {
// Handle the error appropriately
// For now, let's panic
panic(fmt.Sprintf("Failed to dispatch work item: %v", err))
}
return item.id
}
// WaitFor waits for the result of a workID (your query).
func (c *ComfyDB) WaitFor(workID uint64) (interface{}, error) {
value, ok := c.results.Load(workID)
if !ok {
return nil, fmt.Errorf("workID not found")
}
item := value.(*workItem)
// Wait for the result
select {
case res := <-item.result:
// Delete the item from the results map after consuming the result
c.results.Delete(workID)
return res, nil
case <-time.After(30 * time.Second):
return nil, fmt.Errorf("timeout waiting for result")
}
}
// WaitForChn waits for the result of a workID (your query) and returns a channel.
func (c *ComfyDB) WaitForChn(workID uint64) <-chan interface{} {
value, ok := c.results.Load(workID)
if !ok {
ch := make(chan interface{})
close(ch)
return ch
}
item := value.(*workItem)
// Create a channel to return
resultCh := make(chan interface{}, 1)
go func() {
res := <-item.result
// Delete the item from the results map after consuming the result
c.results.Delete(workID)
resultCh <- res
close(resultCh)
}()
return resultCh
}
// Migrate up all the available migrations.
func (c *ComfyDB) Up(ctx context.Context) error {
if err := c.prepareMigration(); err != nil {
return err
}
index, err := c.Index()
if err != nil {
return err
}
migrationExists := map[uint]bool{}
for _, v := range index {
migrationExists[v] = true
}
localSorted := c.sort()
migrationUpID := c.New(func(db *sql.DB) (interface{}, error) {
tx, err := db.BeginTx(ctx, nil)
if err != nil {
return nil, err
}
defer tx.Rollback()
for _, migration := range localSorted {
if migration.Version == 0 || migration.Label == "" {
return nil, fmt.Errorf("invalid migration: version and label must be set")
}
if migration.Up == nil || migration.Down == nil {
return nil, fmt.Errorf("invalid migration: up and down must be set")
}
if migrationExists[migration.Version] {
continue
}
if err := migration.Up(tx); err != nil {
return nil, err
}
if _, err := tx.ExecContext(ctx, fmt.Sprintf("INSERT INTO %v (version, description) VALUES (?, ?)", c.migrationTableName), migration.Version, migration.Label); err != nil {
return nil, fmt.Errorf("failed to insert migration (version=%v, description=%s): %w", migration.Version, migration.Label, err)
}
}
return nil, tx.Commit()
})
result, err := c.WaitFor(migrationUpID)
if err != nil {
return err
}
if errResult, ok := result.(error); ok {
return errResult
}
return nil
}
// Migrate down using the amount of iterations to rollback.
func (c *ComfyDB) Down(ctx context.Context, amount int) error {
if err := c.prepareMigration(); err != nil {
return err
}
index, err := c.Index()
if err != nil {
return err
}
if len(index) == 0 {
return fmt.Errorf("no migrations to rollback")
}
if amount > len(index) {
amount = len(index)
}
migrationExists := map[uint]bool{}
for _, v := range index {
migrationExists[v] = true
}
localSorted := c.sort()
migrationDownID := c.New(func(db *sql.DB) (interface{}, error) {
tx, err := db.BeginTx(ctx, nil)
if err != nil {
return nil, err
}
defer tx.Rollback()
for i := len(index) - 1; i >= len(index)-amount; i-- {
migration := localSorted[index[i]-1]
if migration.Version == 0 || migration.Label == "" {
return nil, fmt.Errorf("invalid migration: version and label must be set")
}
if migration.Up == nil || migration.Down == nil {
return nil, fmt.Errorf("invalid migration: up and down must be set")
}
if !migrationExists[migration.Version] {
return nil, fmt.Errorf("migration (version=%v, label=%s) doesn't exist", migration.Version, migration.Label)
}
if err := migration.Down(tx); err != nil {
return nil, err
}
if _, err := tx.ExecContext(ctx, fmt.Sprintf("DELETE FROM %v WHERE version = ?", c.migrationTableName), migration.Version); err != nil {
return nil, fmt.Errorf("failed to delete migration (version=%v, label=%s): %w", migration.Version, migration.Label, err)
}
}
return nil, tx.Commit()
})
result, err := c.WaitFor(migrationDownID)
if err != nil {
return err
}
if errResult, ok := result.(error); ok {
return errResult
}
return nil
}
// Get all versions of the migrations.
func (c *ComfyDB) Index() ([]uint, error) {
currentIndexID := c.New(func(db *sql.DB) (interface{}, error) {
var versions []uint
rows, err := db.Query(fmt.Sprintf("SELECT version FROM %v ORDER BY version ASC", c.migrationTableName))
if err != nil {
return nil, err
}
defer rows.Close()
for rows.Next() {
var version uint
if err := rows.Scan(&version); err != nil {
return nil, err
}
versions = append(versions, version)
}
return versions, nil
})
result, err := c.WaitFor(currentIndexID)
if err != nil {
return nil, err
}
switch value := result.(type) {
case []uint:
return value, nil
case error:
if value == sql.ErrNoRows {
return []uint{}, nil
}
return nil, value
default:
return nil, fmt.Errorf("unexpected type")
}
}
// Get all migrations.
func (c *ComfyDB) Migrations() ([]Migration, error) {
migrationsID := c.New(func(db *sql.DB) (interface{}, error) {
var migrations []Migration
rows, err := db.Query(fmt.Sprintf("SELECT version, description FROM %v ORDER BY version ASC", c.migrationTableName))
if err != nil {
return nil, err
}
defer rows.Close()
for rows.Next() {
var version uint
var description string
if err := rows.Scan(&version, &description); err != nil {
return nil, err
}
migrations = append(migrations, Migration{
Version: version,
Label: description,
})
}
return migrations, nil
})
result, err := c.WaitFor(migrationsID)
if err != nil {
return nil, err
}
switch value := result.(type) {
case []Migration:
return value, nil
case error:
if value == sql.ErrNoRows {
return []Migration{}, nil
}
return nil, value
default:
return nil, fmt.Errorf("unexpected type")
}
}
// Get current version of the migrations.
func (c *ComfyDB) Version() (uint, error) {
versionID := c.New(func(db *sql.DB) (interface{}, error) {
var version uint
row := db.QueryRow(fmt.Sprintf("SELECT version FROM %v ORDER BY version DESC LIMIT 1", c.migrationTableName))
err := row.Scan(&version)
if err != nil {
if err == sql.ErrNoRows {
return uint(0), nil
}
return nil, err
}
return version, nil
})
result, err := c.WaitFor(versionID)
if err != nil {
return 0, err
}
switch value := result.(type) {
case uint:
return value, nil
case error:
return 0, value
default:
return 0, fmt.Errorf("unexpected type")
}
}
// Properties of one column in a table.
// Columns: cid name type notnull dflt_value pk
type Column struct {
CID int
Name string
Type string
NotNull bool
DfltValue *string
Pk bool
}
// Show all tables in the database.
// Returns a slice of the names of the tables.
func (c *ComfyDB) ShowTables() ([]string, error) {
tablesID := c.New(func(db *sql.DB) (interface{}, error) {
rows, err := db.Query("SELECT name FROM sqlite_master WHERE type='table'")
if err != nil {
return nil, err
}
defer rows.Close()
var tables []string
for rows.Next() {
var table string
if err := rows.Scan(&table); err != nil {
return nil, err
}
tables = append(tables, table)
}
return tables, nil
})
result, err := c.WaitFor(tablesID)
if err != nil {
return nil, err
}
switch value := result.(type) {
case []string:
return value, nil
case error:
return nil, value
default:
return nil, fmt.Errorf("unexpected type")
}
}
// Show all columns in a table.
func (c *ComfyDB) ShowColumns(table string) ([]Column, error) {
columnsID := c.New(func(db *sql.DB) (interface{}, error) {
rows, err := db.Query(fmt.Sprintf("PRAGMA table_info('%v')", table))
if err != nil {
return nil, err
}
defer rows.Close()
var cols []Column
for rows.Next() {
var col Column
// cid name type notnull dflt_value pk
if err := rows.Scan(&col.CID, &col.Name, &col.Type, &col.NotNull, &col.DfltValue, &col.Pk); err != nil {
return nil, err
}
cols = append(cols, col)
}
return cols, nil
})
result, err := c.WaitFor(columnsID)
if err != nil {
return nil, err
}
switch value := result.(type) {
case []Column:
return value, nil
case error:
return nil, value
default:
return nil, fmt.Errorf("unexpected type")
}
}
// RunSQL allows executing a custom SQL function and waits for its result.
func (c *ComfyDB) RunSQL(fn SqlFn) (interface{}, error) {
workID := c.New(fn)
return c.WaitFor(workID)
}