graphile_worker 0.11.4

High performance Rust/PostgreSQL job queue (also suitable for getting jobs generated by PostgreSQL triggers/functions out into a different work queue)
Documentation
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
use std::sync::Arc;

use crate::sql::add_job::{add_job, add_jobs, JobToAdd, RawJobSpec};
use crate::sql::task_identifiers::{get_tasks_details, SharedTaskDetails};
use crate::tracing::add_tracing_info;
use crate::{errors::GraphileWorkerError, DbJob, Job, JobSpec};
use graphile_worker_lifecycle_hooks::{BeforeJobScheduleContext, HookRegistry, JobScheduleResult};
use graphile_worker_migrations::{migrate, MigrateError};
use graphile_worker_task_handler::TaskHandler;
use indoc::formatdoc;
use serde::Serialize;
use sqlx::{PgExecutor, PgPool};
use tracing::Span;

/// Types of database cleanup tasks that can be performed on the Graphile Worker schema.
///
/// These tasks help maintain database performance by removing unused records and
/// reducing database size over time.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CleanupTask {
    /// Removes task identifier records that are no longer referenced by any jobs.
    /// This helps keep the `_private_tasks` table clean and smaller.
    ///
    /// **Note**: When using `WorkerUtils::cleanup()` from a worker, task identifiers
    /// that the worker knows about will be preserved to support horizontal scaling.
    GcTaskIdentifiers,

    /// Removes job queue records that are no longer referenced by any jobs.
    /// This helps keep the `_private_job_queues` table clean and smaller.
    GcJobQueues,

    /// Removes jobs that have reached their maximum retry attempts and are no longer locked.
    /// This helps clean up permanently failed jobs that will never be processed again.
    DeletePermenantlyFailedJobs,
}

impl CleanupTask {
    pub(crate) async fn execute<'e>(
        &self,
        executor: impl PgExecutor<'e>,
        escaped_schema: &str,
        task_identifiers_to_keep: &[String],
    ) -> Result<(), GraphileWorkerError> {
        match self {
            CleanupTask::DeletePermenantlyFailedJobs => {
                let sql = formatdoc!(
                    r#"
                        delete from {escaped_schema}._private_jobs jobs
                            where attempts = max_attempts
                            and locked_at is null;
                    "#
                );
                sqlx::query(&sql).execute(executor).await?;
            }
            CleanupTask::GcTaskIdentifiers => {
                let sql = formatdoc!(
                    r#"
                        delete from {escaped_schema}._private_tasks tasks
                        where tasks.id not in (
                            select jobs.task_id from {escaped_schema}._private_jobs jobs
                        )
                        and tasks.identifier <> all ($1::text[]);
                    "#
                );
                sqlx::query(&sql)
                    .bind(task_identifiers_to_keep)
                    .execute(executor)
                    .await?;
            }
            CleanupTask::GcJobQueues => {
                let sql = formatdoc!(
                    r#"
                        delete from {escaped_schema}._private_job_queues job_queues
                        where job_queues.id not in (
                            select jobs.job_queue_id from {escaped_schema}._private_jobs jobs
                        );
                    "#
                );
                sqlx::query(&sql).execute(executor).await?;
            }
        }

        Ok(())
    }
}

/// Options for rescheduling jobs.
///
/// This struct allows you to specify various parameters when rescheduling jobs,
/// such as when the job should run, its priority, and how many retry attempts it should have.
/// All fields are optional, and only specified fields will be updated.
#[derive(Default, Debug)]
pub struct RescheduleJobOptions {
    /// When the job should be executed. If not specified, jobs will be scheduled to run immediately.
    pub run_at: Option<chrono::DateTime<chrono::Utc>>,

    /// The job's priority. Higher numbers indicate higher priority (runs sooner).
    /// Default priority is 0.
    pub priority: Option<i16>,

    /// How many times the job has been attempted.
    /// Normally this should not be manually set.
    pub attempts: Option<i16>,

    /// Maximum number of retry attempts before the job is considered permanently failed.
    /// Default is 25 attempts.
    pub max_attempts: Option<i16>,
}

/// The WorkerUtils struct provides a set of utility methods for managing jobs.
///
/// This is the primary interface for adding jobs to the queue, managing existing jobs,
/// performing maintenance tasks, and migrating the database schema.
#[derive(Clone)]
pub struct WorkerUtils {
    /// Database connection pool
    pg_pool: PgPool,

    /// SQL-escaped schema name where Graphile Worker tables are located
    escaped_schema: String,

    /// Optional lifecycle hooks for intercepting job scheduling
    hooks: Option<Arc<HookRegistry>>,

    /// Shared task details for refreshing after GcTaskIdentifiers cleanup
    task_details: SharedTaskDetails,

    /// Whether to use local application time (true) or database time (false) for timestamps
    use_local_time: bool,
}

impl WorkerUtils {
    /// Creates a new instance of WorkerUtils.
    ///
    /// # Arguments
    /// * `pg_pool` - PostgreSQL connection pool
    /// * `escaped_schema` - The escaped name of the schema where Graphile Worker tables are stored
    ///
    /// # Returns
    /// A new WorkerUtils instance
    pub fn new(pg_pool: PgPool, escaped_schema: String) -> Self {
        Self {
            pg_pool,
            escaped_schema,
            hooks: None,
            task_details: SharedTaskDetails::default(),
            use_local_time: false,
        }
    }

    /// Adds lifecycle hooks to this WorkerUtils instance.
    pub fn with_hooks(mut self, hooks: Arc<HookRegistry>) -> Self {
        self.hooks = Some(hooks);
        self
    }

    /// Adds task details to this WorkerUtils instance.
    ///
    /// When task_details is provided, cleanup operations that include `GcTaskIdentifiers`
    /// will automatically refresh the task details to ensure the worker can still pick
    /// up jobs after task identifiers are garbage collected.
    pub fn with_task_details(mut self, task_details: SharedTaskDetails) -> Self {
        self.task_details = task_details;
        self
    }

    /// Sets whether to use local application time or database time for timestamps.
    ///
    /// When `use_local_time` is true, the application's `Utc::now()` is used for timestamps,
    /// which can help handle clock drift between the application server and database server.
    /// When false (default), PostgreSQL's `now()` is used instead.
    pub fn with_use_local_time(mut self, use_local_time: bool) -> Self {
        self.use_local_time = use_local_time;
        self
    }

    async fn invoke_before_job_schedule(
        &self,
        identifier: &str,
        payload: serde_json::Value,
        spec: &JobSpec,
    ) -> Result<serde_json::Value, GraphileWorkerError> {
        let Some(hooks) = &self.hooks else {
            return Ok(payload);
        };

        let ctx = BeforeJobScheduleContext {
            identifier: identifier.to_string(),
            payload,
            spec: spec.clone(),
        };

        match hooks.intercept(ctx).await {
            JobScheduleResult::Continue(payload) => Ok(payload),
            JobScheduleResult::Skip => Err(GraphileWorkerError::JobScheduleSkipped),
            JobScheduleResult::Fail(msg) => Err(GraphileWorkerError::JobScheduleFailed(msg)),
        }
    }

    async fn prepare_batch_jobs<'a, I>(
        &self,
        jobs: I,
    ) -> Result<(Vec<JobToAdd<'a>>, bool), GraphileWorkerError>
    where
        I: IntoIterator<Item = (&'a str, serde_json::Value, &'a JobSpec)>,
    {
        let jobs: Vec<_> = jobs.into_iter().collect();
        let mut jobs_to_add = Vec::with_capacity(jobs.len());

        for (identifier, mut payload, spec) in jobs {
            add_tracing_info(&mut payload);

            let payload = self
                .invoke_before_job_schedule(identifier, payload, spec)
                .await?;

            jobs_to_add.push(JobToAdd {
                identifier,
                payload,
                spec,
            });
        }

        let job_key_preserve_run_at = jobs_to_add.iter().any(|j| {
            j.spec
                .job_key_mode()
                .as_ref()
                .is_some_and(|m| matches!(m, crate::JobKeyMode::PreserveRunAt))
        });

        Ok((jobs_to_add, job_key_preserve_run_at))
    }

    /// Adds a job to the queue with type safety.
    ///
    /// Uses the TaskHandler trait to ensure that the job identifier
    /// and payload type match, providing compile-time type safety.
    ///
    /// # Arguments
    /// * `payload` - The job payload, which must match the type specified in the task handler
    /// * `spec` - Job specification (priority, queue, etc.)
    ///
    /// # Returns
    /// * `Result<Job, GraphileWorkerError>` - The created job or an error
    ///
    /// # Example
    /// ```
    /// # use graphile_worker::{WorkerUtils, JobSpec, TaskHandler, WorkerContext, IntoTaskHandlerResult};
    /// # use graphile_worker::errors::GraphileWorkerError;
    /// # use serde::{Deserialize, Serialize};
    /// # #[derive(Deserialize, Serialize)]
    /// # struct MyTask { data: String }
    /// # impl TaskHandler for MyTask {
    /// #     const IDENTIFIER: &'static str = "my_task";
    /// #     async fn run(self, _ctx: WorkerContext) -> impl IntoTaskHandlerResult { Ok::<(), String>(()) }
    /// # }
    /// # async fn example(utils: &WorkerUtils) -> Result<(), GraphileWorkerError> {
    /// let job = utils.add_job(
    ///     MyTask { data: "hello".to_string() },
    ///     JobSpec::default()
    /// ).await?;
    /// # Ok(())
    /// # }
    /// ```
    #[tracing::instrument(
        "add_job",
        skip_all,
        fields(
            messaging.system = "graphile-worker",
            messaging.operation.name = "add_job",
            messaging.destination.name = tracing::field::Empty,
            otel.name = tracing::field::Empty
        )
    )]
    pub async fn add_job<T: TaskHandler>(
        &self,
        payload: T,
        spec: JobSpec,
    ) -> Result<Job, GraphileWorkerError> {
        let identifier = T::IDENTIFIER;
        let mut payload = serde_json::to_value(payload)?;
        add_tracing_info(&mut payload);

        let span = Span::current();
        span.record("otel.name", identifier);
        span.record("messaging.destination.name", identifier);

        let payload = self
            .invoke_before_job_schedule(identifier, payload, &spec)
            .await?;
        add_job(
            &self.pg_pool,
            &self.escaped_schema,
            identifier,
            payload,
            spec,
            self.use_local_time,
        )
        .await
    }

    /// Adds a job to the queue with a raw identifier and payload.
    ///
    /// Doesn't require the task handler to be defined at compile time,
    /// allowing for dynamic job creation. However, lacks the compile-time type safety
    /// of `add_job`.
    ///
    /// # Arguments
    /// * `identifier` - The task identifier string
    /// * `payload` - The job payload (any serializable type)
    /// * `spec` - Job specification (priority, queue, etc.)
    ///
    /// # Returns
    /// * `Result<Job, GraphileWorkerError>` - The created job or an error
    ///
    /// # Example
    /// ```
    /// # use graphile_worker::{WorkerUtils, JobSpec};
    /// # use graphile_worker::errors::GraphileWorkerError;
    /// # use serde_json::json;
    /// # async fn example(utils: &WorkerUtils) -> Result<(), GraphileWorkerError> {
    /// let job = utils.add_raw_job(
    ///     "send_email",
    ///     json!({ "to": "user@example.com", "subject": "Hello" }),
    ///     JobSpec::default()
    /// ).await?;
    /// # Ok(())
    /// # }
    /// ```
    #[tracing::instrument(
        "add_raw_job",
        skip_all,
        fields(
            messaging.system = "graphile-worker",
            messaging.operation.name = "add_job",
            messaging.destination.name = identifier,
            otel.name = identifier
        )
    )]
    pub async fn add_raw_job<P>(
        &self,
        identifier: &str,
        payload: P,
        spec: JobSpec,
    ) -> Result<Job, GraphileWorkerError>
    where
        P: Serialize,
    {
        let mut payload = serde_json::to_value(payload)?;
        add_tracing_info(&mut payload);

        let payload = self
            .invoke_before_job_schedule(identifier, payload, &spec)
            .await?;
        add_job(
            &self.pg_pool,
            &self.escaped_schema,
            identifier,
            payload,
            spec,
            self.use_local_time,
        )
        .await
    }

    /// Adds multiple jobs of the same type to the queue in a single batch operation.
    ///
    /// This is more efficient than calling `add_job` multiple times when you need to
    /// add many jobs of the same type, as it uses a single database round trip.
    ///
    /// # Arguments
    /// * `jobs` - Slice of tuples containing payloads and job specifications
    ///
    /// # Returns
    /// * `Result<Vec<Job>, GraphileWorkerError>` - The created jobs or an error
    ///
    /// # Limitations
    /// * `job_key_mode: UnsafeDedupe` is not supported in batch operations
    /// * `job_key_mode` is applied uniformly: if any job uses `PreserveRunAt`, it applies
    ///   to all jobs in the batch. For per-job `job_key_mode` control, use `add_job` individually.
    ///
    /// # Hook Failure Behavior
    /// If the `before_job_schedule` hook fails for any job in the batch, the entire
    /// batch operation fails and no jobs are added. For partial success semantics,
    /// use `add_job` individually in a loop with your own error handling.
    ///
    /// # Example
    /// ```
    /// # use graphile_worker::{WorkerUtils, JobSpec, TaskHandler, WorkerContext, IntoTaskHandlerResult};
    /// # use graphile_worker::errors::GraphileWorkerError;
    /// # use serde::{Deserialize, Serialize};
    /// # #[derive(Clone, Deserialize, Serialize)]
    /// # struct SendEmail { to: String }
    /// # impl TaskHandler for SendEmail {
    /// #     const IDENTIFIER: &'static str = "send_email";
    /// #     async fn run(self, _ctx: WorkerContext) -> impl IntoTaskHandlerResult { Ok::<(), String>(()) }
    /// # }
    /// # async fn example(utils: &WorkerUtils) -> Result<(), GraphileWorkerError> {
    /// let spec = JobSpec::default();
    /// let jobs = utils.add_jobs::<SendEmail>(&[
    ///     (SendEmail { to: "user1@example.com".into() }, &spec),
    ///     (SendEmail { to: "user2@example.com".into() }, &spec),
    /// ]).await?;
    /// # Ok(())
    /// # }
    /// ```
    #[tracing::instrument(
        "add_jobs",
        skip_all,
        fields(
            messaging.system = "graphile-worker",
            messaging.operation.name = "add_jobs",
            messaging.batch.message_count = jobs.len()
        )
    )]
    pub async fn add_jobs<T: TaskHandler + Clone>(
        &self,
        jobs: &[(T, &JobSpec)],
    ) -> Result<Vec<Job>, GraphileWorkerError> {
        if jobs.is_empty() {
            return Ok(vec![]);
        }

        let identifier = T::IDENTIFIER;
        let job_inputs = jobs.iter().map(|(payload, spec)| {
            let payload_value = serde_json::to_value(payload.clone())?;
            Ok((identifier, payload_value, *spec))
        });
        let job_inputs: Result<Vec<_>, GraphileWorkerError> = job_inputs.collect();

        let (jobs_to_add, job_key_preserve_run_at) = self.prepare_batch_jobs(job_inputs?).await?;

        let task_details = self.task_details.read().await;

        add_jobs(
            &self.pg_pool,
            &self.escaped_schema,
            &jobs_to_add,
            &task_details,
            job_key_preserve_run_at,
            self.use_local_time,
        )
        .await
    }

    /// Adds multiple jobs with raw identifiers and payloads in a single batch operation.
    ///
    /// This allows adding jobs of different types in a single batch, but without
    /// compile-time type safety. More efficient than multiple `add_raw_job` calls.
    ///
    /// # Arguments
    /// * `jobs` - Slice of `RawJobSpec` containing identifiers, payloads, and specifications
    ///
    /// # Returns
    /// * `Result<Vec<Job>, GraphileWorkerError>` - The created jobs or an error
    ///
    /// # Limitations
    /// * `job_key_mode: UnsafeDedupe` is not supported in batch operations
    /// * `job_key_mode` is applied uniformly: if any job uses `PreserveRunAt`, it applies
    ///   to all jobs in the batch. For per-job `job_key_mode` control, use `add_raw_job` individually.
    ///
    /// # Hook Failure Behavior
    /// If the `before_job_schedule` hook fails for any job in the batch, the entire
    /// batch operation fails and no jobs are added. For partial success semantics,
    /// use `add_raw_job` individually in a loop with your own error handling.
    ///
    /// # Example
    /// ```
    /// # use graphile_worker::{WorkerUtils, JobSpec, RawJobSpec};
    /// # use graphile_worker::errors::GraphileWorkerError;
    /// # use serde_json::json;
    /// # async fn example(utils: &WorkerUtils) -> Result<(), GraphileWorkerError> {
    /// let jobs = utils.add_raw_jobs(&[
    ///     RawJobSpec {
    ///         identifier: "send_email".into(),
    ///         payload: json!({ "to": "user@example.com" }),
    ///         spec: JobSpec::default(),
    ///     },
    ///     RawJobSpec {
    ///         identifier: "process_payment".into(),
    ///         payload: json!({ "amount": 100 }),
    ///         spec: JobSpec::default(),
    ///     },
    /// ]).await?;
    /// # Ok(())
    /// # }
    /// ```
    #[tracing::instrument(
        "add_raw_jobs",
        skip_all,
        fields(
            messaging.system = "graphile-worker",
            messaging.operation.name = "add_jobs",
            messaging.batch.message_count = jobs.len()
        )
    )]
    pub async fn add_raw_jobs(&self, jobs: &[RawJobSpec]) -> Result<Vec<Job>, GraphileWorkerError> {
        if jobs.is_empty() {
            return Ok(vec![]);
        }

        let job_inputs = jobs
            .iter()
            .map(|job| (job.identifier.as_str(), job.payload.clone(), &job.spec));

        let (jobs_to_add, job_key_preserve_run_at) = self.prepare_batch_jobs(job_inputs).await?;

        let unique_identifiers: Vec<String> = jobs
            .iter()
            .map(|j| j.identifier.clone())
            .collect::<std::collections::HashSet<_>>()
            .into_iter()
            .collect();

        let task_details =
            get_tasks_details(&self.pg_pool, &self.escaped_schema, unique_identifiers).await?;

        add_jobs(
            &self.pg_pool,
            &self.escaped_schema,
            &jobs_to_add,
            &task_details,
            job_key_preserve_run_at,
            self.use_local_time,
        )
        .await
    }

    /// Removes a job from the queue by its job key.
    ///
    /// Useful for cancelling scheduled jobs that haven't run yet.
    ///
    /// # Arguments
    /// * `job_key` - The unique job key that was assigned when the job was created
    ///
    /// # Returns
    /// * `Result<(), GraphileWorkerError>` - Ok if the job was removed successfully
    pub async fn remove_job(&self, job_key: &str) -> Result<(), GraphileWorkerError> {
        let sql = formatdoc!(
            r#"
                select * from {escaped_schema}.remove_job($1::text);
            "#,
            escaped_schema = self.escaped_schema
        );

        sqlx::query(&sql)
            .bind(job_key)
            .execute(&self.pg_pool)
            .await?;

        Ok(())
    }

    /// Marks multiple jobs as completed.
    ///
    /// # Arguments
    /// * `ids` - Array of job IDs to mark as completed
    ///
    /// # Returns
    /// * `Result<Vec<DbJob>, GraphileWorkerError>` - The updated job records
    pub async fn complete_jobs(&self, ids: &[i64]) -> Result<Vec<DbJob>, GraphileWorkerError> {
        let sql = formatdoc!(
            r#"
                select * from {escaped_schema}.complete_jobs($1::bigint[]);
            "#,
            escaped_schema = self.escaped_schema
        );

        let jobs = sqlx::query_as(&sql)
            .bind(ids)
            .fetch_all(&self.pg_pool)
            .await?;

        Ok(jobs)
    }

    /// Marks multiple jobs as permanently failed with a reason.
    ///
    /// # Arguments
    /// * `ids` - Array of job IDs to mark as permanently failed
    /// * `reason` - The reason for the failure, which will be recorded in the error field
    ///
    /// # Returns
    /// * `Result<Vec<DbJob>, GraphileWorkerError>` - The updated job records
    pub async fn permanently_fail_jobs(
        &self,
        ids: &[i64],
        reason: &str,
    ) -> Result<Vec<DbJob>, GraphileWorkerError> {
        let sql = formatdoc!(
            r#"
                select * from {escaped_schema}.permanently_fail_jobs($1::bigint[], $2::text);
            "#,
            escaped_schema = self.escaped_schema
        );

        let jobs = sqlx::query_as(&sql)
            .bind(ids)
            .bind(reason)
            .fetch_all(&self.pg_pool)
            .await?;

        Ok(jobs)
    }

    /// Reschedules multiple jobs with new parameters.
    ///
    /// This allows changing when jobs will run next, their priority,
    /// and their retry behavior.
    ///
    /// # Arguments
    /// * `ids` - Array of job IDs to reschedule
    /// * `options` - Options for rescheduling (run_at, priority, attempts, max_attempts)
    ///
    /// # Returns
    /// * `Result<Vec<DbJob>, GraphileWorkerError>` - The updated job records
    pub async fn reschedule_jobs(
        &self,
        ids: &[i64],
        options: RescheduleJobOptions,
    ) -> Result<Vec<DbJob>, GraphileWorkerError> {
        let sql = formatdoc!(
            r#"
                select * from {escaped_schema}.reschedule_jobs(
                    $1::bigint[],
                    run_at := $2::timestamptz,
                    priority := $3::int,
                    attempts := $4::int,
                    max_attempts := $5::int
                );
            "#,
            escaped_schema = self.escaped_schema
        );

        let jobs = sqlx::query_as(&sql)
            .bind(ids)
            .bind(options.run_at)
            .bind(options.priority)
            .bind(options.attempts)
            .bind(options.max_attempts)
            .fetch_all(&self.pg_pool)
            .await?;

        Ok(jobs)
    }

    /// Force unlocks worker records in the database.
    ///
    /// Useful for recovering from situations where workers crashed without
    /// properly releasing their locks, allowing their jobs to be picked up by other workers.
    ///
    /// # Arguments
    /// * `worker_ids` - Array of worker IDs to force unlock
    ///
    /// # Returns
    /// * `Result<(), GraphileWorkerError>` - Ok if workers were successfully unlocked
    pub async fn force_unlock_workers(
        &self,
        worker_ids: &[&str],
    ) -> Result<(), GraphileWorkerError> {
        let sql = formatdoc!(
            r#"
                select * from {escaped_schema}.force_unlock_workers($1::text[]);
            "#,
            escaped_schema = self.escaped_schema
        );

        sqlx::query(&sql)
            .bind(worker_ids)
            .execute(&self.pg_pool)
            .await?;

        Ok(())
    }

    /// Runs database cleanup tasks to maintain performance.
    ///
    /// Executes the specified cleanup tasks, which helps keep
    /// the database size manageable and improves query performance.
    ///
    /// When `GcTaskIdentifiers` is included in the tasks and this `WorkerUtils` instance
    /// was created with task details (via `with_task_details`), the task identifiers
    /// known to this worker will be preserved (not deleted), supporting horizontal scaling.
    /// Additionally, task details will be refreshed after cleanup.
    ///
    /// # Arguments
    /// * `tasks` - Array of cleanup tasks to perform
    ///
    /// # Returns
    /// * `Result<(), GraphileWorkerError>` - Ok if all cleanup tasks completed successfully
    ///
    /// # Example
    /// ```
    /// # use graphile_worker::WorkerUtils;
    /// # use graphile_worker::worker_utils::CleanupTask;
    /// # use graphile_worker::errors::GraphileWorkerError;
    /// # async fn example(utils: &WorkerUtils) -> Result<(), GraphileWorkerError> {
    /// utils.cleanup(&[
    ///     CleanupTask::DeletePermenantlyFailedJobs,
    ///     CleanupTask::GcTaskIdentifiers,
    ///     CleanupTask::GcJobQueues,
    /// ]).await?;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn cleanup(&self, tasks: &[CleanupTask]) -> Result<(), GraphileWorkerError> {
        let should_refresh_task_identifiers = tasks
            .iter()
            .any(|t| matches!(t, CleanupTask::GcTaskIdentifiers));

        if should_refresh_task_identifiers {
            let mut guard = self.task_details.write().await;
            let task_names = guard.task_names();

            for task in tasks {
                task.execute(&self.pg_pool, &self.escaped_schema, &task_names)
                    .await?;
            }

            let refreshed =
                get_tasks_details(&self.pg_pool, &self.escaped_schema, task_names).await?;
            *guard = refreshed;
            return Ok(());
        }

        for task in tasks {
            task.execute(&self.pg_pool, &self.escaped_schema, &[])
                .await?;
        }

        Ok(())
    }

    /// Runs database migrations to ensure the schema is up to date.
    ///
    /// Automatically called when initializing a worker, but can
    /// also be called manually if needed.
    ///
    /// # Returns
    /// * `Result<(), MigrateError>` - Ok if migrations completed successfully
    pub async fn migrate(&self) -> Result<(), MigrateError> {
        migrate(&self.pg_pool, &self.escaped_schema).await?;
        Ok(())
    }
}