-
Notifications
You must be signed in to change notification settings - Fork 147
Expand file tree
/
Copy pathriver_job.sql.go
More file actions
1393 lines (1329 loc) · 37.1 KB
/
river_job.sql.go
File metadata and controls
1393 lines (1329 loc) · 37.1 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
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.29.0
// source: river_job.sql
package dbsqlc
import (
"context"
"database/sql"
"strings"
"time"
)
const jobCancel = `-- name: JobCancel :one
UPDATE /* TEMPLATE: schema */river_job
SET
-- If the job is actively running, we want to let its current client and
-- producer handle the cancellation. Otherwise, immediately cancel it.
state = CASE WHEN state = 'running' THEN state ELSE 'cancelled' END,
finalized_at = CASE WHEN state = 'running' THEN finalized_at ELSE coalesce(cast(?1 AS text), datetime('now', 'subsec')) END,
-- Mark the job as cancelled by query so that the rescuer knows not to
-- rescue it, even if it gets stuck in the running state:
metadata = json_set(metadata, '$.cancel_attempted_at', cast(?2 AS text))
WHERE id = ?3
AND state NOT IN ('cancelled', 'completed', 'discarded')
AND finalized_at IS NULL
RETURNING id, args, attempt, attempted_at, attempted_by, created_at, errors, finalized_at, kind, max_attempts, metadata, priority, queue, state, scheduled_at, tags, unique_key, unique_states
`
type JobCancelParams struct {
Now *string
CancelAttemptedAt string
ID int64
}
// Differs by necessity from other drivers because SQLite doesn't support
// `UPDATE` inside CTEs so we can't retry if running but select otherwise.
// Instead, the driver uses a transaction to optimisticaly try an update, but
// perform a subsequent fetch on a not found to return the right status.
//
// I had to invert the last 'AND' expression below (was an 'ANT NOT) due to an
// sqlc bug. Something about sqlc's SQLite parser cannot detect a parameter
// inside an `AND NOT`.
func (q *Queries) JobCancel(ctx context.Context, db DBTX, arg *JobCancelParams) (*RiverJob, error) {
row := db.QueryRowContext(ctx, jobCancel, arg.Now, arg.CancelAttemptedAt, arg.ID)
var i RiverJob
err := row.Scan(
&i.ID,
&i.Args,
&i.Attempt,
&i.AttemptedAt,
&i.AttemptedBy,
&i.CreatedAt,
&i.Errors,
&i.FinalizedAt,
&i.Kind,
&i.MaxAttempts,
&i.Metadata,
&i.Priority,
&i.Queue,
&i.State,
&i.ScheduledAt,
&i.Tags,
&i.UniqueKey,
&i.UniqueStates,
)
return &i, err
}
const jobCountByState = `-- name: JobCountByState :one
SELECT count(*)
FROM /* TEMPLATE: schema */river_job
WHERE state = ?1
`
func (q *Queries) JobCountByState(ctx context.Context, db DBTX, state string) (int64, error) {
row := db.QueryRowContext(ctx, jobCountByState, state)
var count int64
err := row.Scan(&count)
return count, err
}
const jobDelete = `-- name: JobDelete :one
DELETE
FROM /* TEMPLATE: schema */river_job
WHERE id = ?1
-- Do not touch running jobs:
AND river_job.state != 'running'
RETURNING id, args, attempt, attempted_at, attempted_by, created_at, errors, finalized_at, kind, max_attempts, metadata, priority, queue, state, scheduled_at, tags, unique_key, unique_states
`
// Differs by necessity from other drivers because SQLite doesn't support
// `DELETE` inside CTEs so we can't delete if running but select otherwise.
// Instead, the driver uses a transaction to optimisticaly try a delete, but
// perform a subsequent fetch on a not found to return the right status.
func (q *Queries) JobDelete(ctx context.Context, db DBTX, id int64) (*RiverJob, error) {
row := db.QueryRowContext(ctx, jobDelete, id)
var i RiverJob
err := row.Scan(
&i.ID,
&i.Args,
&i.Attempt,
&i.AttemptedAt,
&i.AttemptedBy,
&i.CreatedAt,
&i.Errors,
&i.FinalizedAt,
&i.Kind,
&i.MaxAttempts,
&i.Metadata,
&i.Priority,
&i.Queue,
&i.State,
&i.ScheduledAt,
&i.Tags,
&i.UniqueKey,
&i.UniqueStates,
)
return &i, err
}
const jobDeleteBefore = `-- name: JobDeleteBefore :execresult
DELETE FROM /* TEMPLATE: schema */river_job
WHERE id IN (
SELECT id
FROM /* TEMPLATE: schema */river_job
WHERE
(state = 'cancelled' AND finalized_at < cast(?1 AS text)) OR
(state = 'completed' AND finalized_at < cast(?2 AS text)) OR
(state = 'discarded' AND finalized_at < cast(?3 AS text))
ORDER BY id
LIMIT ?4
)
`
type JobDeleteBeforeParams struct {
CancelledFinalizedAtHorizon string
CompletedFinalizedAtHorizon string
DiscardedFinalizedAtHorizon string
Max int64
}
func (q *Queries) JobDeleteBefore(ctx context.Context, db DBTX, arg *JobDeleteBeforeParams) (sql.Result, error) {
return db.ExecContext(ctx, jobDeleteBefore,
arg.CancelledFinalizedAtHorizon,
arg.CompletedFinalizedAtHorizon,
arg.DiscardedFinalizedAtHorizon,
arg.Max,
)
}
const jobGetAvailable = `-- name: JobGetAvailable :many
UPDATE /* TEMPLATE: schema */river_job
SET
attempt = river_job.attempt + 1,
attempted_at = coalesce(cast(?1 AS text), datetime('now', 'subsec')),
attempted_by = json_insert(coalesce(attempted_by, json('[]')), '$[#]', cast(?2 AS text)),
state = 'running'
WHERE id IN (
SELECT id
FROM /* TEMPLATE: schema */river_job
WHERE
priority >= 0
AND river_job.queue = ?3
AND scheduled_at <= coalesce(cast(?1 AS text), datetime('now', 'subsec'))
AND state = 'available'
ORDER BY
priority ASC,
scheduled_at ASC,
id ASC
LIMIT ?4
)
RETURNING id, args, attempt, attempted_at, attempted_by, created_at, errors, finalized_at, kind, max_attempts, metadata, priority, queue, state, scheduled_at, tags, unique_key, unique_states
`
type JobGetAvailableParams struct {
Now *string
AttemptedBy string
Queue string
Max int64
}
// Differs from the Postgres version in that we don't have `FOR UPDATE SKIP
// LOCKED`. It doesn't exist in SQLite, but more aptly, there's only one writer
// on SQLite at a time, so nothing else has the rows locked.
func (q *Queries) JobGetAvailable(ctx context.Context, db DBTX, arg *JobGetAvailableParams) ([]*RiverJob, error) {
rows, err := db.QueryContext(ctx, jobGetAvailable,
arg.Now,
arg.AttemptedBy,
arg.Queue,
arg.Max,
)
if err != nil {
return nil, err
}
defer rows.Close()
var items []*RiverJob
for rows.Next() {
var i RiverJob
if err := rows.Scan(
&i.ID,
&i.Args,
&i.Attempt,
&i.AttemptedAt,
&i.AttemptedBy,
&i.CreatedAt,
&i.Errors,
&i.FinalizedAt,
&i.Kind,
&i.MaxAttempts,
&i.Metadata,
&i.Priority,
&i.Queue,
&i.State,
&i.ScheduledAt,
&i.Tags,
&i.UniqueKey,
&i.UniqueStates,
); err != nil {
return nil, err
}
items = append(items, &i)
}
if err := rows.Close(); err != nil {
return nil, err
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const jobGetByID = `-- name: JobGetByID :one
SELECT id, args, attempt, attempted_at, attempted_by, created_at, errors, finalized_at, kind, max_attempts, metadata, priority, queue, state, scheduled_at, tags, unique_key, unique_states
FROM /* TEMPLATE: schema */river_job
WHERE id = ?1
LIMIT 1
`
func (q *Queries) JobGetByID(ctx context.Context, db DBTX, id int64) (*RiverJob, error) {
row := db.QueryRowContext(ctx, jobGetByID, id)
var i RiverJob
err := row.Scan(
&i.ID,
&i.Args,
&i.Attempt,
&i.AttemptedAt,
&i.AttemptedBy,
&i.CreatedAt,
&i.Errors,
&i.FinalizedAt,
&i.Kind,
&i.MaxAttempts,
&i.Metadata,
&i.Priority,
&i.Queue,
&i.State,
&i.ScheduledAt,
&i.Tags,
&i.UniqueKey,
&i.UniqueStates,
)
return &i, err
}
const jobGetByIDMany = `-- name: JobGetByIDMany :many
SELECT id, args, attempt, attempted_at, attempted_by, created_at, errors, finalized_at, kind, max_attempts, metadata, priority, queue, state, scheduled_at, tags, unique_key, unique_states
FROM /* TEMPLATE: schema */river_job
WHERE id IN (/*SLICE:id*/?)
ORDER BY id
`
func (q *Queries) JobGetByIDMany(ctx context.Context, db DBTX, id []int64) ([]*RiverJob, error) {
query := jobGetByIDMany
var queryParams []interface{}
if len(id) > 0 {
for _, v := range id {
queryParams = append(queryParams, v)
}
query = strings.Replace(query, "/*SLICE:id*/?", strings.Repeat(",?", len(id))[1:], 1)
} else {
query = strings.Replace(query, "/*SLICE:id*/?", "NULL", 1)
}
rows, err := db.QueryContext(ctx, query, queryParams...)
if err != nil {
return nil, err
}
defer rows.Close()
var items []*RiverJob
for rows.Next() {
var i RiverJob
if err := rows.Scan(
&i.ID,
&i.Args,
&i.Attempt,
&i.AttemptedAt,
&i.AttemptedBy,
&i.CreatedAt,
&i.Errors,
&i.FinalizedAt,
&i.Kind,
&i.MaxAttempts,
&i.Metadata,
&i.Priority,
&i.Queue,
&i.State,
&i.ScheduledAt,
&i.Tags,
&i.UniqueKey,
&i.UniqueStates,
); err != nil {
return nil, err
}
items = append(items, &i)
}
if err := rows.Close(); err != nil {
return nil, err
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const jobGetByKindMany = `-- name: JobGetByKindMany :many
SELECT id, args, attempt, attempted_at, attempted_by, created_at, errors, finalized_at, kind, max_attempts, metadata, priority, queue, state, scheduled_at, tags, unique_key, unique_states
FROM /* TEMPLATE: schema */river_job
WHERE kind IN (/*SLICE:kind*/?)
ORDER BY id
`
func (q *Queries) JobGetByKindMany(ctx context.Context, db DBTX, kind []string) ([]*RiverJob, error) {
query := jobGetByKindMany
var queryParams []interface{}
if len(kind) > 0 {
for _, v := range kind {
queryParams = append(queryParams, v)
}
query = strings.Replace(query, "/*SLICE:kind*/?", strings.Repeat(",?", len(kind))[1:], 1)
} else {
query = strings.Replace(query, "/*SLICE:kind*/?", "NULL", 1)
}
rows, err := db.QueryContext(ctx, query, queryParams...)
if err != nil {
return nil, err
}
defer rows.Close()
var items []*RiverJob
for rows.Next() {
var i RiverJob
if err := rows.Scan(
&i.ID,
&i.Args,
&i.Attempt,
&i.AttemptedAt,
&i.AttemptedBy,
&i.CreatedAt,
&i.Errors,
&i.FinalizedAt,
&i.Kind,
&i.MaxAttempts,
&i.Metadata,
&i.Priority,
&i.Queue,
&i.State,
&i.ScheduledAt,
&i.Tags,
&i.UniqueKey,
&i.UniqueStates,
); err != nil {
return nil, err
}
items = append(items, &i)
}
if err := rows.Close(); err != nil {
return nil, err
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const jobGetStuck = `-- name: JobGetStuck :many
SELECT id, args, attempt, attempted_at, attempted_by, created_at, errors, finalized_at, kind, max_attempts, metadata, priority, queue, state, scheduled_at, tags, unique_key, unique_states
FROM /* TEMPLATE: schema */river_job
WHERE state = 'running'
AND attempted_at < cast(?1 AS text)
ORDER BY id
LIMIT ?2
`
type JobGetStuckParams struct {
StuckHorizon string
Max int64
}
func (q *Queries) JobGetStuck(ctx context.Context, db DBTX, arg *JobGetStuckParams) ([]*RiverJob, error) {
rows, err := db.QueryContext(ctx, jobGetStuck, arg.StuckHorizon, arg.Max)
if err != nil {
return nil, err
}
defer rows.Close()
var items []*RiverJob
for rows.Next() {
var i RiverJob
if err := rows.Scan(
&i.ID,
&i.Args,
&i.Attempt,
&i.AttemptedAt,
&i.AttemptedBy,
&i.CreatedAt,
&i.Errors,
&i.FinalizedAt,
&i.Kind,
&i.MaxAttempts,
&i.Metadata,
&i.Priority,
&i.Queue,
&i.State,
&i.ScheduledAt,
&i.Tags,
&i.UniqueKey,
&i.UniqueStates,
); err != nil {
return nil, err
}
items = append(items, &i)
}
if err := rows.Close(); err != nil {
return nil, err
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const jobInsertFast = `-- name: JobInsertFast :one
INSERT INTO /* TEMPLATE: schema */river_job(
args,
created_at,
kind,
max_attempts,
metadata,
priority,
queue,
scheduled_at,
state,
tags,
unique_key,
unique_states
) VALUES (
?1,
coalesce(cast(?2 AS text), datetime('now', 'subsec')),
?3,
?4,
json(cast(?5 AS blob)),
?6,
?7,
coalesce(cast(?8 AS text), datetime('now', 'subsec')),
?9,
json(cast(?10 AS blob)),
CASE WHEN length(cast(?11 AS blob)) = 0 THEN NULL ELSE ?11 END,
?12
)
ON CONFLICT (unique_key)
WHERE unique_key IS NOT NULL
AND unique_states IS NOT NULL
AND CASE state
WHEN 'available' THEN unique_states & (1 << 0)
WHEN 'cancelled' THEN unique_states & (1 << 1)
WHEN 'completed' THEN unique_states & (1 << 2)
WHEN 'discarded' THEN unique_states & (1 << 3)
WHEN 'pending' THEN unique_states & (1 << 4)
WHEN 'retryable' THEN unique_states & (1 << 5)
WHEN 'running' THEN unique_states & (1 << 6)
WHEN 'scheduled' THEN unique_states & (1 << 7)
ELSE 0
END >= 1
-- Something needs to be updated for a row to be returned on a conflict.
DO UPDATE SET kind = EXCLUDED.kind
RETURNING id, args, attempt, attempted_at, attempted_by, created_at, errors, finalized_at, kind, max_attempts, metadata, priority, queue, state, scheduled_at, tags, unique_key, unique_states
`
type JobInsertFastParams struct {
Args []byte
CreatedAt *string
Kind string
MaxAttempts int64
Metadata []byte
Priority int64
Queue string
ScheduledAt *string
State string
Tags []byte
UniqueKey []byte
UniqueStates *int64
}
// Insert a job.
//
// This is supposed to be a batch insert, but various limitations of the
// combined SQLite + sqlc has left me unable to find a way of injecting many
// arguments en masse (like how we slightly abuse arrays to pull it off for the
// Postgres drivers), so we loop over many insert operations instead, with the
// expectation that this may be fixable in the future. Because SQLite targets
// will often be local and therefore with a very minimal round trip compared to
// a network, looping over operations is probably okay performance-wise.
func (q *Queries) JobInsertFast(ctx context.Context, db DBTX, arg *JobInsertFastParams) (*RiverJob, error) {
row := db.QueryRowContext(ctx, jobInsertFast,
arg.Args,
arg.CreatedAt,
arg.Kind,
arg.MaxAttempts,
arg.Metadata,
arg.Priority,
arg.Queue,
arg.ScheduledAt,
arg.State,
arg.Tags,
arg.UniqueKey,
arg.UniqueStates,
)
var i RiverJob
err := row.Scan(
&i.ID,
&i.Args,
&i.Attempt,
&i.AttemptedAt,
&i.AttemptedBy,
&i.CreatedAt,
&i.Errors,
&i.FinalizedAt,
&i.Kind,
&i.MaxAttempts,
&i.Metadata,
&i.Priority,
&i.Queue,
&i.State,
&i.ScheduledAt,
&i.Tags,
&i.UniqueKey,
&i.UniqueStates,
)
return &i, err
}
const jobInsertFastNoReturning = `-- name: JobInsertFastNoReturning :execrows
INSERT INTO /* TEMPLATE: schema */river_job(
args,
created_at,
kind,
max_attempts,
metadata,
priority,
queue,
scheduled_at,
state,
tags,
unique_key,
unique_states
) VALUES (
?1,
coalesce(cast(?2 AS text), datetime('now', 'subsec')),
?3,
?4,
json(cast(?5 AS blob)),
?6,
?7,
coalesce(cast(?8 AS text), datetime('now', 'subsec')),
?9,
json(cast(?10 AS blob)),
CASE WHEN length(cast(?11 AS blob)) = 0 THEN NULL ELSE ?11 END,
?12
)
ON CONFLICT (unique_key)
WHERE unique_key IS NOT NULL
AND unique_states IS NOT NULL
AND CASE state
WHEN 'available' THEN unique_states & (1 << 0)
WHEN 'cancelled' THEN unique_states & (1 << 1)
WHEN 'completed' THEN unique_states & (1 << 2)
WHEN 'discarded' THEN unique_states & (1 << 3)
WHEN 'pending' THEN unique_states & (1 << 4)
WHEN 'retryable' THEN unique_states & (1 << 5)
WHEN 'running' THEN unique_states & (1 << 6)
WHEN 'scheduled' THEN unique_states & (1 << 7)
ELSE 0
END >= 1
DO NOTHING
`
type JobInsertFastNoReturningParams struct {
Args []byte
CreatedAt *string
Kind string
MaxAttempts int64
Metadata []byte
Priority int64
Queue string
ScheduledAt *string
State string
Tags []byte
UniqueKey []byte
UniqueStates *int64
}
func (q *Queries) JobInsertFastNoReturning(ctx context.Context, db DBTX, arg *JobInsertFastNoReturningParams) (int64, error) {
result, err := db.ExecContext(ctx, jobInsertFastNoReturning,
arg.Args,
arg.CreatedAt,
arg.Kind,
arg.MaxAttempts,
arg.Metadata,
arg.Priority,
arg.Queue,
arg.ScheduledAt,
arg.State,
arg.Tags,
arg.UniqueKey,
arg.UniqueStates,
)
if err != nil {
return 0, err
}
return result.RowsAffected()
}
const jobInsertFull = `-- name: JobInsertFull :one
INSERT INTO /* TEMPLATE: schema */river_job(
args,
attempt,
attempted_at,
attempted_by,
created_at,
errors,
finalized_at,
kind,
max_attempts,
metadata,
priority,
queue,
scheduled_at,
state,
tags,
unique_key,
unique_states
) VALUES (
?1,
?2,
cast(?3 as text),
CASE WHEN length(cast(?4 AS blob)) = 0 THEN NULL ELSE json(?4) END,
coalesce(cast(?5 AS text), datetime('now', 'subsec')),
CASE WHEN length(cast(?6 AS blob)) = 0 THEN NULL ELSE ?6 END,
cast(?7 as text),
?8,
?9,
json(cast(?10 AS blob)),
?11,
?12,
coalesce(cast(?13 AS text), datetime('now', 'subsec')),
?14,
json(cast(?15 AS blob)),
CASE WHEN length(cast(?16 AS blob)) = 0 THEN NULL ELSE ?16 END,
?17
) RETURNING id, args, attempt, attempted_at, attempted_by, created_at, errors, finalized_at, kind, max_attempts, metadata, priority, queue, state, scheduled_at, tags, unique_key, unique_states
`
type JobInsertFullParams struct {
Args []byte
Attempt int64
AttemptedAt *string
AttemptedBy []byte
CreatedAt *string
Errors []byte
FinalizedAt *string
Kind string
MaxAttempts int64
Metadata []byte
Priority int64
Queue string
ScheduledAt *string
State string
Tags []byte
UniqueKey []byte
UniqueStates *int64
}
func (q *Queries) JobInsertFull(ctx context.Context, db DBTX, arg *JobInsertFullParams) (*RiverJob, error) {
row := db.QueryRowContext(ctx, jobInsertFull,
arg.Args,
arg.Attempt,
arg.AttemptedAt,
arg.AttemptedBy,
arg.CreatedAt,
arg.Errors,
arg.FinalizedAt,
arg.Kind,
arg.MaxAttempts,
arg.Metadata,
arg.Priority,
arg.Queue,
arg.ScheduledAt,
arg.State,
arg.Tags,
arg.UniqueKey,
arg.UniqueStates,
)
var i RiverJob
err := row.Scan(
&i.ID,
&i.Args,
&i.Attempt,
&i.AttemptedAt,
&i.AttemptedBy,
&i.CreatedAt,
&i.Errors,
&i.FinalizedAt,
&i.Kind,
&i.MaxAttempts,
&i.Metadata,
&i.Priority,
&i.Queue,
&i.State,
&i.ScheduledAt,
&i.Tags,
&i.UniqueKey,
&i.UniqueStates,
)
return &i, err
}
const jobList = `-- name: JobList :many
SELECT id, args, attempt, attempted_at, attempted_by, created_at, errors, finalized_at, kind, max_attempts, metadata, priority, queue, state, scheduled_at, tags, unique_key, unique_states
FROM /* TEMPLATE: schema */river_job
WHERE /* TEMPLATE_BEGIN: where_clause */ 1 /* TEMPLATE_END */
ORDER BY /* TEMPLATE_BEGIN: order_by_clause */ id /* TEMPLATE_END */
LIMIT ?1
`
func (q *Queries) JobList(ctx context.Context, db DBTX, max int64) ([]*RiverJob, error) {
rows, err := db.QueryContext(ctx, jobList, max)
if err != nil {
return nil, err
}
defer rows.Close()
var items []*RiverJob
for rows.Next() {
var i RiverJob
if err := rows.Scan(
&i.ID,
&i.Args,
&i.Attempt,
&i.AttemptedAt,
&i.AttemptedBy,
&i.CreatedAt,
&i.Errors,
&i.FinalizedAt,
&i.Kind,
&i.MaxAttempts,
&i.Metadata,
&i.Priority,
&i.Queue,
&i.State,
&i.ScheduledAt,
&i.Tags,
&i.UniqueKey,
&i.UniqueStates,
); err != nil {
return nil, err
}
items = append(items, &i)
}
if err := rows.Close(); err != nil {
return nil, err
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const jobRescue = `-- name: JobRescue :exec
UPDATE /* TEMPLATE: schema */river_job
SET
errors = json_insert(coalesce(errors, json('[]')), '$[#]', json(cast(?1 AS blob))),
finalized_at = cast(?2 as text),
scheduled_at = ?3,
state = ?4
WHERE id = ?5
`
type JobRescueParams struct {
Error []byte
FinalizedAt *string
ScheduledAt time.Time
State string
ID int64
}
// Rescue a job.
//
// This is supposed to rescue jobs in batches, but various limitations of the
// combined SQLite + sqlc has left me unable to find a way of injecting many
// arguments en masse (like how we slightly abuse arrays to pull it off for the
// Postgres drivers), and SQLite doesn't support `UPDATE` in CTEs, so we loop
// over many insert operations instead, with the expectation that this may be
// fixable in the future. Because SQLite targets will often be local and with a
// very minimal round trip compared to a network, looping over operations is
// probably okay performance-wise.
func (q *Queries) JobRescue(ctx context.Context, db DBTX, arg *JobRescueParams) error {
_, err := db.ExecContext(ctx, jobRescue,
arg.Error,
arg.FinalizedAt,
arg.ScheduledAt,
arg.State,
arg.ID,
)
return err
}
const jobRetry = `-- name: JobRetry :one
UPDATE /* TEMPLATE: schema */river_job
SET
state = 'available',
max_attempts = CASE WHEN attempt = max_attempts THEN max_attempts + 1 ELSE max_attempts END,
finalized_at = NULL,
scheduled_at = coalesce(cast(?1 AS text), datetime('now', 'subsec'))
WHERE id = ?2
-- Do not touch running jobs:
AND state != 'running'
-- If the job is already available with a prior scheduled_at, leave it alone.
--
-- I had to invert the original 'AND NOT' to 'AND'. Something about
-- sqlc's SQLite parser cannot detect a parameter inside an ` + "`" + `AND NOT` + "`" + `. An
-- unfortunate bug that will hopefully be fixed in the future ...
AND (
state <> 'available'
OR scheduled_at > coalesce(cast(?1 AS text), datetime('now', 'subsec'))
)
RETURNING id, args, attempt, attempted_at, attempted_by, created_at, errors, finalized_at, kind, max_attempts, metadata, priority, queue, state, scheduled_at, tags, unique_key, unique_states
`
type JobRetryParams struct {
Now *string
ID int64
}
// Differs by necessity from other drivers because SQLite doesn't support
// `UPDATE` inside CTEs so we can't retry if running but select otherwise.
// Instead, the driver uses a transaction to optimisticaly try an update, but
// perform a subsequent fetch on a not found to return the right status.
//
// I had to invert the last 'AND' expression below (was an 'AND NOT') due to an
// sqlc bug. Something about sqlc's SQLite parser cannot detect a parameter
// inside an `AND NOT`. I'll try to get this fixed upstream at some point so we
// can clean this up and keep it more like the Postgres version.
func (q *Queries) JobRetry(ctx context.Context, db DBTX, arg *JobRetryParams) (*RiverJob, error) {
row := db.QueryRowContext(ctx, jobRetry, arg.Now, arg.ID)
var i RiverJob
err := row.Scan(
&i.ID,
&i.Args,
&i.Attempt,
&i.AttemptedAt,
&i.AttemptedBy,
&i.CreatedAt,
&i.Errors,
&i.FinalizedAt,
&i.Kind,
&i.MaxAttempts,
&i.Metadata,
&i.Priority,
&i.Queue,
&i.State,
&i.ScheduledAt,
&i.Tags,
&i.UniqueKey,
&i.UniqueStates,
)
return &i, err
}
const jobScheduleGetCollision = `-- name: JobScheduleGetCollision :one
SELECT id, args, attempt, attempted_at, attempted_by, created_at, errors, finalized_at, kind, max_attempts, metadata, priority, queue, state, scheduled_at, tags, unique_key, unique_states
FROM /* TEMPLATE: schema */river_job
WHERE id <> ?1
AND unique_key = ?2
AND unique_states IS NOT NULL
AND CASE state
WHEN 'available' THEN unique_states & (1 << 0)
WHEN 'cancelled' THEN unique_states & (1 << 1)
WHEN 'completed' THEN unique_states & (1 << 2)
WHEN 'discarded' THEN unique_states & (1 << 3)
WHEN 'pending' THEN unique_states & (1 << 4)
WHEN 'retryable' THEN unique_states & (1 << 5)
WHEN 'running' THEN unique_states & (1 << 6)
WHEN 'scheduled' THEN unique_states & (1 << 7)
ELSE 0
END >= 1
`
type JobScheduleGetCollisionParams struct {
ID int64
UniqueKey []byte
}
func (q *Queries) JobScheduleGetCollision(ctx context.Context, db DBTX, arg *JobScheduleGetCollisionParams) (*RiverJob, error) {
row := db.QueryRowContext(ctx, jobScheduleGetCollision, arg.ID, arg.UniqueKey)
var i RiverJob
err := row.Scan(
&i.ID,
&i.Args,
&i.Attempt,
&i.AttemptedAt,
&i.AttemptedBy,
&i.CreatedAt,
&i.Errors,
&i.FinalizedAt,
&i.Kind,
&i.MaxAttempts,
&i.Metadata,
&i.Priority,
&i.Queue,
&i.State,
&i.ScheduledAt,
&i.Tags,
&i.UniqueKey,
&i.UniqueStates,
)
return &i, err
}
const jobScheduleGetEligible = `-- name: JobScheduleGetEligible :many
SELECT id, args, attempt, attempted_at, attempted_by, created_at, errors, finalized_at, kind, max_attempts, metadata, priority, queue, state, scheduled_at, tags, unique_key, unique_states
FROM /* TEMPLATE: schema */river_job
WHERE
state IN ('retryable', 'scheduled')
AND scheduled_at <= coalesce(cast(?1 AS text), datetime('now', 'subsec'))
ORDER BY
priority,
scheduled_at,
id
LIMIT ?2
`
type JobScheduleGetEligibleParams struct {
Now *string
Max int64
}
func (q *Queries) JobScheduleGetEligible(ctx context.Context, db DBTX, arg *JobScheduleGetEligibleParams) ([]*RiverJob, error) {
rows, err := db.QueryContext(ctx, jobScheduleGetEligible, arg.Now, arg.Max)
if err != nil {
return nil, err
}
defer rows.Close()
var items []*RiverJob
for rows.Next() {
var i RiverJob
if err := rows.Scan(
&i.ID,
&i.Args,
&i.Attempt,
&i.AttemptedAt,
&i.AttemptedBy,
&i.CreatedAt,
&i.Errors,
&i.FinalizedAt,
&i.Kind,
&i.MaxAttempts,
&i.Metadata,
&i.Priority,
&i.Queue,
&i.State,
&i.ScheduledAt,
&i.Tags,
&i.UniqueKey,
&i.UniqueStates,
); err != nil {
return nil, err
}
items = append(items, &i)
}
if err := rows.Close(); err != nil {
return nil, err
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const jobScheduleSetAvailable = `-- name: JobScheduleSetAvailable :many
UPDATE /* TEMPLATE: schema */river_job
SET
state = 'available'