pgqrs 0.15.2

A high-performance PostgreSQL-backed job queue for Rust applications
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
//! Workers table CRUD operations for pgqrs.
//!
//! This module provides the [`Workers`] struct which implements pure CRUD operations
//! on the `pgqrs_workers` table.

use crate::error::Result;
use crate::store::dialect::SqlDialect;
use crate::store::postgres::dialect::PostgresDialect;
use crate::types::{WorkerRecord, WorkerStatus};
use async_trait::async_trait;
use chrono::Utc;
use sqlx::PgPool;

// SQL constants for worker table operations
const INSERT_WORKER: &str = r#"
    INSERT INTO pgqrs_workers (name, queue_id, started_at, heartbeat_at, status)
    VALUES ($1, $2, $3, $4, $5)
    RETURNING id
"#;

const GET_WORKER_BY_ID: &str = r#"
    SELECT id, name, queue_id, started_at, heartbeat_at, shutdown_at, status
    FROM pgqrs_workers
    WHERE id = $1
"#;

const LIST_ALL_WORKERS: &str = r#"
    SELECT id, name, queue_id, started_at, heartbeat_at, shutdown_at, status
    FROM pgqrs_workers
    ORDER BY started_at DESC
"#;

const LIST_WORKERS_BY_QUEUE: &str = r#"
    SELECT id, name, queue_id, started_at, heartbeat_at, shutdown_at, status
    FROM pgqrs_workers
    WHERE queue_id = $1
    ORDER BY started_at DESC
"#;

const DELETE_WORKER_BY_ID: &str = r#"
    DELETE FROM pgqrs_workers
    WHERE id = $1
"#;

const DELETE_WORKERS_BY_QUEUE: &str = r#"
    DELETE FROM pgqrs_workers WHERE queue_id = $1
"#;

const COUNT_WORKERS_BY_QUEUE_TX: &str = r#"
    SELECT COUNT(*) FROM pgqrs_workers WHERE queue_id = $1
"#;

const LIST_WORKERS_BY_QUEUE_AND_STATE: &str = r#"
    SELECT id, name, queue_id, started_at, heartbeat_at, shutdown_at, status
    FROM pgqrs_workers
    WHERE queue_id = $1 AND status = $2
    ORDER BY started_at DESC
"#;

const LIST_ZOMBIE_WORKERS: &str = r#"
    SELECT id, name, queue_id, started_at, heartbeat_at, shutdown_at, status
    FROM pgqrs_workers
    WHERE queue_id = $1
    AND status IN ('ready', 'polling', 'suspended', 'interrupted')
    AND heartbeat_at < NOW() - $2
    ORDER BY heartbeat_at ASC
"#;

/// SQL to find existing worker by name
const FIND_WORKER_BY_NAME: &str = r#"
    SELECT id, name, queue_id, started_at, heartbeat_at, shutdown_at, status
    FROM pgqrs_workers
    WHERE name = $1
"#;

/// SQL to reset a stopped worker back to ready state
const RESET_WORKER_TO_READY: &str = r#"
    UPDATE pgqrs_workers
    SET status = 'ready', queue_id = $2, started_at = NOW(), heartbeat_at = NOW(), shutdown_at = NULL
    WHERE id = $1 AND status = 'stopped'
    RETURNING id, name, queue_id, started_at, heartbeat_at, shutdown_at, status
"#;

/// SQL to insert a new ephemeral worker
const INSERT_EPHEMERAL_WORKER: &str = r#"
    INSERT INTO pgqrs_workers (name, queue_id, status)
    VALUES ($1, $2, 'ready')
    RETURNING id, name, queue_id, started_at, heartbeat_at, shutdown_at, status
"#;

/// Workers table CRUD operations for pgqrs.
///
/// Provides pure CRUD operations on the `pgqrs_workers` table.
#[derive(Debug, Clone)]
pub struct Workers {
    pub pool: PgPool,
}

impl Workers {
    /// Create a new Workers instance.
    pub fn new(pool: PgPool) -> Self {
        Self { pool }
    }

    pub async fn count_for_fk<'a, 'b: 'a>(
        &self,
        foreign_key_value: i64,
        tx: &'a mut sqlx::Transaction<'b, sqlx::Postgres>,
    ) -> Result<i64> {
        let count: i64 = sqlx::query_scalar(COUNT_WORKERS_BY_QUEUE_TX)
            .bind(foreign_key_value)
            .fetch_one(&mut **tx)
            .await
            .map_err(|e| crate::error::Error::QueryFailed {
                query: "COUNT_WORKERS_BY_QUEUE_TX".into(),
                source: Box::new(e),
                context: format!("Failed to count workers for queue {}", foreign_key_value),
            })?;
        Ok(count)
    }

    pub async fn delete_by_fk<'a, 'b: 'a>(
        &self,
        foreign_key_value: i64,
        tx: &'a mut sqlx::Transaction<'b, sqlx::Postgres>,
    ) -> Result<u64> {
        let result = sqlx::query(DELETE_WORKERS_BY_QUEUE)
            .bind(foreign_key_value)
            .execute(&mut **tx)
            .await
            .map_err(|e| crate::error::Error::QueryFailed {
                query: "DELETE_WORKERS_BY_QUEUE".into(),
                source: Box::new(e),
                context: format!("Failed to delete workers for queue {}", foreign_key_value),
            })?;
        Ok(result.rows_affected())
    }

    pub async fn list_zombies_for_queue_tx<'a, 'b: 'a>(
        &self,
        queue_id: i64,
        older_than: chrono::Duration,
        tx: &'a mut sqlx::Transaction<'b, sqlx::Postgres>,
    ) -> Result<Vec<WorkerRecord>> {
        let workers = sqlx::query_as::<_, WorkerRecord>(LIST_ZOMBIE_WORKERS)
            .bind(queue_id)
            .bind(older_than)
            .fetch_all(&mut **tx)
            .await
            .map_err(|e| crate::error::Error::QueryFailed {
                query: "LIST_ZOMBIE_WORKERS".into(),
                source: Box::new(e),
                context: format!("Failed to list zombie workers for queue {}", queue_id),
            })?;
        Ok(workers)
    }

    /// Get the current status of a worker.
    pub async fn get_status(&self, worker_id: i64) -> Result<WorkerStatus> {
        const GET_WORKER_STATUS: &str = "SELECT status FROM pgqrs_workers WHERE id = $1";
        let status: WorkerStatus = sqlx::query_scalar(GET_WORKER_STATUS)
            .bind(worker_id)
            .fetch_one(&self.pool)
            .await
            .map_err(|e| crate::error::Error::QueryFailed {
                query: "GET_WORKER_STATUS".into(),
                source: Box::new(e),
                context: format!("Failed to get worker {} status", worker_id),
            })?;

        Ok(status)
    }

    /// Update worker heartbeat timestamp.
    pub async fn heartbeat(&self, worker_id: i64) -> Result<()> {
        const UPDATE_HEARTBEAT: &str = r#"
            UPDATE pgqrs_workers
            SET heartbeat_at = $1
            WHERE id = $2
        "#;
        let now = Utc::now();
        sqlx::query(UPDATE_HEARTBEAT)
            .bind(now)
            .bind(worker_id)
            .execute(&self.pool)
            .await
            .map_err(|e| crate::error::Error::QueryFailed {
                query: "UPDATE_HEARTBEAT".into(),
                source: Box::new(e),
                context: format!("Failed to update heartbeat for worker {}", worker_id),
            })?;

        Ok(())
    }

    /// Check if this worker is healthy based on heartbeat age
    pub async fn is_healthy(&self, worker_id: i64, max_age: chrono::Duration) -> Result<bool> {
        let threshold = Utc::now() - max_age;

        // Query returns true if heartbeat_at >= threshold (i.e., within max_age)
        let is_healthy: bool =
            sqlx::query_scalar("SELECT heartbeat_at >= $2 FROM pgqrs_workers WHERE id = $1")
                .bind(worker_id)
                .bind(threshold)
                .fetch_one(&self.pool)
                .await
                .map_err(|e| crate::error::Error::QueryFailed {
                    query: "CHECK_WORKER_HEALTH".into(),
                    source: Box::new(e),
                    context: format!("Failed to check health for worker {}", worker_id),
                })?;

        Ok(is_healthy)
    }

    /// Transition worker to Suspended.
    pub async fn suspend(&self, worker_id: i64) -> Result<()> {
        const TRANSITION_TO_SUSPENDED: &str = r#"
            UPDATE pgqrs_workers
            SET status = 'suspended'
            WHERE id = $1 AND status IN ('ready', 'polling', 'interrupted')
            RETURNING id
        "#;
        let result: Option<i64> = sqlx::query_scalar(TRANSITION_TO_SUSPENDED)
            .bind(worker_id)
            .fetch_optional(&self.pool)
            .await
            .map_err(|e| crate::error::Error::QueryFailed {
                query: "TRANSITION_TO_SUSPENDED".into(),
                source: Box::new(e),
                context: format!("Failed to suspend worker {}", worker_id),
            })?;

        match result {
            Some(_) => Ok(()),
            None => {
                let current_status = self.get_status(worker_id).await?;
                Err(crate::error::Error::InvalidStateTransition {
                    from: current_status.to_string(),
                    to: "suspended".to_string(),
                    reason: "Worker must be Ready, Polling, or Interrupted to suspend".to_string(),
                })
            }
        }
    }

    /// Transition worker from Suspended to Ready.
    pub async fn resume(&self, worker_id: i64) -> Result<()> {
        const TRANSITION_SUSPENDED_TO_READY: &str = r#"
            UPDATE pgqrs_workers
            SET status = 'ready'
            WHERE id = $1 AND status = 'suspended'
            RETURNING id
        "#;
        let result: Option<i64> = sqlx::query_scalar(TRANSITION_SUSPENDED_TO_READY)
            .bind(worker_id)
            .fetch_optional(&self.pool)
            .await
            .map_err(|e| crate::error::Error::QueryFailed {
                query: format!("TRANSITION_SUSPENDED_TO_READY ({})", worker_id),
                source: Box::new(e),
                context: format!("Failed to resume worker {}", worker_id),
            })?;

        match result {
            Some(_) => Ok(()),
            None => {
                let current_status = self.get_status(worker_id).await?;
                Err(crate::error::Error::InvalidStateTransition {
                    from: current_status.to_string(),
                    to: "ready".to_string(),
                    reason: "Worker must be in Suspended state to resume".to_string(),
                })
            }
        }
    }

    /// Transition worker from Ready to Polling.
    pub async fn poll(&self, worker_id: i64) -> Result<()> {
        const TRANSITION_READY_OR_INTERRUPTED_TO_POLLING: &str = r#"
            UPDATE pgqrs_workers
            SET status = 'polling'
            WHERE id = $1 AND status IN ('ready', 'polling')
            RETURNING id
        "#;
        let result: Option<i64> = sqlx::query_scalar(TRANSITION_READY_OR_INTERRUPTED_TO_POLLING)
            .bind(worker_id)
            .fetch_optional(&self.pool)
            .await
            .map_err(|e| crate::error::Error::QueryFailed {
                query: "TRANSITION_READY_TO_POLLING".into(),
                source: Box::new(e),
                context: format!("Failed to set worker {} to polling", worker_id),
            })?;

        if result.is_some() {
            return Ok(());
        }

        let current_status = self.get_status(worker_id).await?;
        Err(crate::error::Error::InvalidStateTransition {
            from: current_status.to_string(),
            to: "polling".to_string(),
            reason: "Worker must be Ready to start polling".to_string(),
        })
    }

    /// Transition worker from Polling to Interrupted.
    pub async fn interrupt(&self, worker_id: i64) -> Result<()> {
        const TRANSITION_POLLING_TO_INTERRUPTED: &str = r#"
            UPDATE pgqrs_workers
            SET status = 'interrupted'
            WHERE id = $1 AND status = 'polling'
            RETURNING id
        "#;
        let result: Option<i64> = sqlx::query_scalar(TRANSITION_POLLING_TO_INTERRUPTED)
            .bind(worker_id)
            .fetch_optional(&self.pool)
            .await
            .map_err(|e| crate::error::Error::QueryFailed {
                query: "TRANSITION_POLLING_TO_INTERRUPTED".into(),
                source: Box::new(e),
                context: format!("Failed to interrupt worker {}", worker_id),
            })?;

        if result.is_some() {
            return Ok(());
        }

        let current_status = self.get_status(worker_id).await?;
        Err(crate::error::Error::InvalidStateTransition {
            from: current_status.to_string(),
            to: "interrupted".to_string(),
            reason: "Worker must be in Polling state to be interrupted".to_string(),
        })
    }

    /// Shutdown worker: transition from Suspended to Stopped.
    pub async fn shutdown(&self, worker_id: i64) -> Result<()> {
        const TRANSITION_SUSPENDED_TO_STOPPED: &str = r#"
            UPDATE pgqrs_workers
            SET status = 'stopped', shutdown_at = $2
            WHERE id = $1 AND status = 'suspended'
            RETURNING id
        "#;
        let now = Utc::now();
        let result: Option<i64> = sqlx::query_scalar(TRANSITION_SUSPENDED_TO_STOPPED)
            .bind(worker_id)
            .bind(now)
            .fetch_optional(&self.pool)
            .await
            .map_err(|e| crate::error::Error::QueryFailed {
                query: format!("TRANSITION_SUSPENDED_TO_STOPPED ({})", worker_id),
                source: Box::new(e),
                context: format!("Failed to shutdown worker {}", worker_id),
            })?;

        match result {
            Some(_) => Ok(()),
            None => {
                let current_status = self.get_status(worker_id).await?;
                Err(crate::error::Error::InvalidStateTransition {
                    from: current_status.to_string(),
                    to: "stopped".to_string(),
                    reason: "Worker must be in Suspended state to shutdown".to_string(),
                })
            }
        }
    }
}

// Implement the public WorkerTable trait by delegating to inherent methods
#[async_trait]
impl crate::store::WorkerTable for Workers {
    async fn insert(&self, data: crate::types::NewWorkerRecord) -> Result<WorkerRecord> {
        let now = Utc::now();

        let worker_id: i64 = sqlx::query_scalar(INSERT_WORKER)
            .bind(&data.name)
            .bind(data.queue_id)
            .bind(now)
            .bind(now)
            .bind(WorkerStatus::Ready)
            .fetch_one(&self.pool)
            .await
            .map_err(|e| crate::error::Error::QueryFailed {
                query: "INSERT_WORKER".into(),
                source: Box::new(e),
                context: format!("Failed to insert worker {}", data.name),
            })?;

        Ok(WorkerRecord {
            id: worker_id,
            name: data.name,
            queue_id: data.queue_id,
            started_at: now,
            heartbeat_at: now,
            shutdown_at: None,
            status: WorkerStatus::Ready,
        })
    }

    async fn get(&self, id: i64) -> Result<WorkerRecord> {
        let worker = sqlx::query_as::<_, WorkerRecord>(GET_WORKER_BY_ID)
            .bind(id)
            .fetch_one(&self.pool)
            .await
            .map_err(|e| crate::error::Error::QueryFailed {
                query: format!("GET_WORKER_BY_ID ({})", id),
                source: Box::new(e),
                context: format!("Failed to get worker {}", id),
            })?;

        Ok(worker)
    }

    async fn list(&self) -> Result<Vec<WorkerRecord>> {
        let workers = sqlx::query_as::<_, WorkerRecord>(LIST_ALL_WORKERS)
            .fetch_all(&self.pool)
            .await
            .map_err(|e| crate::error::Error::QueryFailed {
                query: "LIST_ALL_WORKERS".into(),
                source: Box::new(e),
                context: "Failed to list all workers".into(),
            })?;

        Ok(workers)
    }

    async fn count(&self) -> Result<i64> {
        let query = "SELECT COUNT(*) FROM pgqrs_workers";
        let row = sqlx::query_scalar(query)
            .fetch_one(&self.pool)
            .await
            .map_err(|e| crate::error::Error::QueryFailed {
                query: "SELECT COUNT(*) FROM pgqrs_workers".into(),
                source: Box::new(e),
                context: "Failed to count workers".into(),
            })?;
        Ok(row)
    }

    async fn delete(&self, id: i64) -> Result<u64> {
        let result = sqlx::query(DELETE_WORKER_BY_ID)
            .bind(id)
            .execute(&self.pool)
            .await
            .map_err(|e| crate::error::Error::QueryFailed {
                query: format!("DELETE_WORKER_BY_ID ({})", id),
                source: Box::new(e),
                context: format!("Failed to delete worker {}", id),
            })?;

        Ok(result.rows_affected())
    }

    async fn filter_by_fk(&self, queue_id: i64) -> Result<Vec<WorkerRecord>> {
        let workers = sqlx::query_as::<_, WorkerRecord>(LIST_WORKERS_BY_QUEUE)
            .bind(queue_id)
            .fetch_all(&self.pool)
            .await
            .map_err(|e| crate::error::Error::QueryFailed {
                query: format!("LIST_WORKERS_BY_QUEUE (queue_id={})", queue_id),
                source: Box::new(e),
                context: format!("Failed to filter workers by queue ID {}", queue_id),
            })?;
        Ok(workers)
    }

    async fn count_by_fk(&self, queue_id: i64) -> Result<i64> {
        let count: i64 = sqlx::query_scalar(COUNT_WORKERS_BY_QUEUE_TX)
            .bind(queue_id)
            .fetch_one(&self.pool)
            .await
            .map_err(|e| crate::error::Error::QueryFailed {
                query: "COUNT_WORKERS_BY_QUEUE".into(),
                source: Box::new(e),
                context: format!("Failed to count workers for queue {}", queue_id),
            })?;
        Ok(count)
    }

    async fn mark_stopped(&self, id: i64) -> Result<()> {
        sqlx::query(PostgresDialect::WORKER.mark_stopped)
            .bind(id)
            .execute(&self.pool)
            .await
            .map_err(|e| crate::error::Error::QueryFailed {
                query: "MARK_WORKER_STOPPED".into(),
                source: Box::new(e),
                context: format!("Failed to mark worker {} as stopped", id),
            })?;
        Ok(())
    }

    async fn count_for_queue(
        &self,
        queue_id: i64,
        state: crate::types::WorkerStatus,
    ) -> Result<i64> {
        const COUNT_WORKERS_BY_STATE: &str = r#"
            SELECT COUNT(*)
            FROM pgqrs_workers
            WHERE queue_id = $1 AND status = $2
        "#;

        let count: i64 = sqlx::query_scalar(COUNT_WORKERS_BY_STATE)
            .bind(queue_id)
            .bind(&state)
            .fetch_one(&self.pool)
            .await
            .map_err(|e| crate::error::Error::QueryFailed {
                query: format!(
                    "COUNT_WORKERS_BY_STATE (queue_id={}, state={:?})",
                    queue_id, state
                ),
                source: Box::new(e),
                context: format!(
                    "Failed to count workers for queue {} with state {:?}",
                    queue_id, state
                ),
            })?;

        Ok(count)
    }

    async fn count_zombies_for_queue(
        &self,
        queue_id: i64,
        older_than: chrono::Duration,
    ) -> Result<i64> {
        const COUNT_ZOMBIE_WORKERS: &str = r#"
            SELECT COUNT(*)
            FROM pgqrs_workers
            WHERE queue_id = $1
            AND status IN ('ready', 'polling', 'suspended', 'interrupted')
            AND heartbeat_at < NOW() - $2
        "#;

        let count: i64 = sqlx::query_scalar(COUNT_ZOMBIE_WORKERS)
            .bind(queue_id)
            .bind(older_than)
            .fetch_one(&self.pool)
            .await
            .map_err(|e| crate::error::Error::QueryFailed {
                query: format!("COUNT_ZOMBIE_WORKERS (queue_id={})", queue_id),
                source: Box::new(e),
                context: format!("Failed to count zombie workers for queue {}", queue_id),
            })?;

        Ok(count)
    }

    async fn list_for_queue(
        &self,
        queue_id: i64,
        state: crate::types::WorkerStatus,
    ) -> Result<Vec<WorkerRecord>> {
        let workers = sqlx::query_as::<_, WorkerRecord>(LIST_WORKERS_BY_QUEUE_AND_STATE)
            .bind(queue_id)
            .bind(&state)
            .fetch_all(&self.pool)
            .await
            .map_err(|e| crate::error::Error::QueryFailed {
                query: format!(
                    "LIST_WORKERS_BY_QUEUE_AND_STATE (queue_id={}, state={:?})",
                    queue_id, state
                ),
                source: Box::new(e),
                context: format!(
                    "Failed to list workers for queue {} with state {:?}",
                    queue_id, state
                ),
            })?;

        Ok(workers)
    }

    async fn list_zombies_for_queue(
        &self,
        queue_id: i64,
        older_than: chrono::Duration,
    ) -> Result<Vec<WorkerRecord>> {
        let workers = sqlx::query_as::<_, WorkerRecord>(LIST_ZOMBIE_WORKERS)
            .bind(queue_id)
            .bind(older_than)
            .fetch_all(&self.pool)
            .await
            .map_err(|e| crate::error::Error::QueryFailed {
                query: format!("LIST_ZOMBIE_WORKERS (queue_id={})", queue_id),
                source: Box::new(e),
                context: format!("Failed to list zombie workers for queue {}", queue_id),
            })?;
        Ok(workers)
    }

    async fn register(&self, queue_id: Option<i64>, name: &str) -> Result<WorkerRecord> {
        let existing_worker: Option<WorkerRecord> = sqlx::query_as(FIND_WORKER_BY_NAME)
            .bind(name)
            .fetch_optional(&self.pool)
            .await
            .map_err(|e| crate::error::Error::QueryFailed {
                query: format!("FIND_WORKER_BY_NAME ({})", name),
                source: Box::new(e),
                context: format!("Failed to find worker {}", name),
            })?;

        let worker_info = match existing_worker {
            Some(worker) => {
                match worker.status {
                    WorkerStatus::Stopped => {
                        // Reset stopped worker to ready
                        sqlx::query_as::<_, WorkerRecord>(RESET_WORKER_TO_READY)
                            .bind(worker.id)
                            .bind(queue_id)
                            .fetch_one(&self.pool)
                            .await
                            .map_err(|e| crate::error::Error::QueryFailed {
                                query: format!("RESET_WORKER_TO_READY ({})", worker.id),
                                source: Box::new(e),
                                context: format!("Failed to reset worker {}", name),
                            })?
                    }
                    WorkerStatus::Ready => {
                        return Err(crate::error::Error::ValidationFailed {
                            reason: format!(
                                "Worker {} is already active. Cannot register duplicate.",
                                name
                            ),
                        });
                    }
                    WorkerStatus::Suspended => {
                        return Err(crate::error::Error::ValidationFailed {
                            reason: format!(
                                "Worker {} is suspended. Use resume() to reactivate.",
                                name
                            ),
                        });
                    }
                    WorkerStatus::Polling | WorkerStatus::Interrupted => {
                        return Err(crate::error::Error::ValidationFailed {
                            reason: format!(
                                "Worker {} is already active. Cannot register duplicate.",
                                name
                            ),
                        });
                    }
                }
            }
            None => {
                // Create new worker
                let now = Utc::now();
                let inserted_id: i64 = sqlx::query_scalar(INSERT_WORKER)
                    .bind(name)
                    .bind(queue_id)
                    .bind(now)
                    .bind(now)
                    .bind(WorkerStatus::Ready)
                    .fetch_one(&self.pool)
                    .await
                    .map_err(|e| crate::error::Error::QueryFailed {
                        query: "INSERT_WORKER".into(),
                        source: Box::new(e),
                        context: format!("Failed to insert new worker {}", name),
                    })?;

                WorkerRecord {
                    id: inserted_id,
                    name: name.to_string(),
                    queue_id,
                    started_at: now,
                    heartbeat_at: now,
                    shutdown_at: None,
                    status: WorkerStatus::Ready,
                }
            }
        };
        Ok(worker_info)
    }

    async fn register_ephemeral(&self, queue_id: Option<i64>) -> Result<WorkerRecord> {
        let name = format!("__ephemeral__{}", uuid::Uuid::new_v4());

        let worker_info = sqlx::query_as::<_, WorkerRecord>(INSERT_EPHEMERAL_WORKER)
            .bind(&name)
            .bind(queue_id)
            .fetch_one(&self.pool)
            .await
            .map_err(|e| crate::error::Error::QueryFailed {
                query: "INSERT_EPHEMERAL_WORKER".into(),
                source: Box::new(e),
                context: "Failed to create ephemeral worker".into(),
            })?;

        Ok(worker_info)
    }

    async fn get_status(&self, id: i64) -> Result<WorkerStatus> {
        self.get_status(id).await
    }

    async fn suspend(&self, id: i64) -> Result<()> {
        self.suspend(id).await
    }

    async fn resume(&self, id: i64) -> Result<()> {
        self.resume(id).await
    }

    async fn shutdown(&self, id: i64) -> Result<()> {
        self.shutdown(id).await
    }

    async fn poll(&self, id: i64) -> Result<()> {
        self.poll(id).await
    }

    async fn interrupt(&self, id: i64) -> Result<()> {
        self.interrupt(id).await
    }

    async fn heartbeat(&self, id: i64) -> Result<()> {
        self.heartbeat(id).await
    }

    async fn is_healthy(&self, id: i64, max_age: chrono::Duration) -> Result<bool> {
        self.is_healthy(id, max_age).await
    }
}