pgqrs 0.15.0

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
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
use crate::error::Result;
use crate::store::dialect::SqlDialect;
use crate::store::turso::dialect::TursoDialect;
use crate::store::turso::{format_turso_timestamp, parse_turso_timestamp};
use crate::types::QueueMessage;
use async_trait::async_trait;
use serde_json::Value as JsonValue;
use std::collections::HashSet;
use std::sync::Arc;
use turso::{Database, Value as TursoValue};

const INSERT_MESSAGE: &str = r#"
    INSERT INTO pgqrs_messages (queue_id, payload, read_ct, enqueued_at, vt, producer_worker_id, consumer_worker_id)
    VALUES (?, ?, ?, ?, ?, ?, ?)
    RETURNING id, queue_id, payload, vt, enqueued_at, read_ct, dequeued_at, producer_worker_id, consumer_worker_id, archived_at;
"#;

const GET_MESSAGE_BY_ID: &str = r#"
    SELECT id, queue_id, payload, vt, enqueued_at, read_ct, dequeued_at, producer_worker_id, consumer_worker_id, archived_at
    FROM pgqrs_messages
    WHERE id = ?;
"#;

const LIST_ALL_MESSAGES: &str = r#"
    SELECT id, queue_id, payload, vt, enqueued_at, read_ct, dequeued_at, producer_worker_id, consumer_worker_id, archived_at
    FROM pgqrs_messages
    WHERE archived_at IS NULL
    ORDER BY enqueued_at DESC;
"#;

const DELETE_MESSAGE_BY_ID: &str = r#"
    DELETE FROM pgqrs_messages
    WHERE id = ?;
"#;

const LIST_MESSAGES_BY_QUEUE: &str = r#"
    SELECT id, queue_id, payload, vt, enqueued_at, read_ct, dequeued_at, producer_worker_id, consumer_worker_id, archived_at
    FROM pgqrs_messages
    WHERE queue_id = ? AND archived_at IS NULL
    ORDER BY enqueued_at DESC
    LIMIT 1000;
"#;

#[derive(Debug, Clone)]
pub struct TursoMessageTable {
    db: Arc<Database>,
}

impl TursoMessageTable {
    pub fn new(db: Arc<Database>) -> Self {
        Self { db }
    }

    pub fn map_row(row: &turso::Row) -> Result<QueueMessage> {
        let id: i64 = row.get(0)?;
        let queue_id: i64 = row.get(1)?;

        let payload_str: String = row.get(2)?;
        let payload: JsonValue = serde_json::from_str(&payload_str)?;

        let vt_str: Option<String> = row.get(3)?;
        let vt = match vt_str {
            Some(s) => Some(parse_turso_timestamp(&s)?),
            None => None,
        };

        let enqueued_at_str: String = row.get(4)?;
        let enqueued_at = parse_turso_timestamp(&enqueued_at_str)?;

        let read_ct: i32 = row.get(5)?;

        let dequeued_at_str: Option<String> = row.get(6)?;
        let dequeued_at = match dequeued_at_str {
            Some(s) => Some(parse_turso_timestamp(&s)?),
            None => None,
        };

        let producer_worker_id: Option<i64> = row.get(7)?;
        let consumer_worker_id: Option<i64> = row.get(8)?;

        let archived_at_str: Option<String> = row.get(9)?;
        let archived_at = match archived_at_str {
            Some(s) => Some(parse_turso_timestamp(&s)?),
            None => None,
        };

        Ok(QueueMessage {
            id,
            queue_id,
            payload,
            vt: vt.unwrap_or(enqueued_at),
            enqueued_at,
            read_ct,
            dequeued_at,
            producer_worker_id,
            consumer_worker_id,
            archived_at,
        })
    }
}

#[async_trait]
impl crate::store::MessageTable for TursoMessageTable {
    async fn insert(&self, data: crate::types::NewQueueMessage) -> Result<QueueMessage> {
        let payload_str = data.payload.to_string();
        let enqueued_at_str = format_turso_timestamp(&data.enqueued_at);
        let vt_str = format_turso_timestamp(&data.vt);

        let row = crate::store::turso::query(INSERT_MESSAGE)
            .bind(TursoValue::Integer(data.queue_id))
            .bind(TursoValue::Text(payload_str))
            .bind(TursoValue::Integer(data.read_ct as i64))
            .bind(TursoValue::Text(enqueued_at_str))
            .bind(TursoValue::Text(vt_str))
            .bind(match data.producer_worker_id {
                Some(id) => TursoValue::Integer(id),
                None => TursoValue::Null,
            })
            .bind(match data.consumer_worker_id {
                Some(id) => TursoValue::Integer(id),
                None => TursoValue::Null,
            })
            .fetch_one_once(&self.db)
            .await?;

        Self::map_row(&row)
    }

    async fn get(&self, id: i64) -> Result<QueueMessage> {
        let row = crate::store::turso::query(GET_MESSAGE_BY_ID)
            .bind(id)
            .fetch_one(&self.db)
            .await?;

        Self::map_row(&row)
    }

    async fn list(&self) -> Result<Vec<QueueMessage>> {
        let rows = crate::store::turso::query(LIST_ALL_MESSAGES)
            .fetch_all(&self.db)
            .await?;

        let mut messages = Vec::with_capacity(rows.len());
        for row in rows {
            messages.push(Self::map_row(&row)?);
        }
        Ok(messages)
    }

    async fn count(&self) -> Result<i64> {
        let count: i64 = crate::store::turso::query_scalar(
            "SELECT COUNT(*) FROM pgqrs_messages WHERE archived_at IS NULL",
        )
        .fetch_one(&self.db)
        .await?;
        Ok(count)
    }

    async fn delete(&self, id: i64) -> Result<u64> {
        let rows = crate::store::turso::query(DELETE_MESSAGE_BY_ID)
            .bind(id)
            .execute_once(&self.db)
            .await?;
        Ok(rows)
    }

    async fn filter_by_fk(&self, queue_id: i64) -> Result<Vec<QueueMessage>> {
        let rows = crate::store::turso::query(LIST_MESSAGES_BY_QUEUE)
            .bind(queue_id)
            .fetch_all(&self.db)
            .await?;

        let mut messages = Vec::with_capacity(rows.len());
        for row in rows {
            messages.push(Self::map_row(&row)?);
        }
        Ok(messages)
    }

    async fn list_by_consumer_worker(&self, worker_id: i64) -> Result<Vec<QueueMessage>> {
        let rows = crate::store::turso::query(TursoDialect::MESSAGE.list_by_consumer_worker)
            .bind(worker_id)
            .fetch_all(&self.db)
            .await?;

        let mut messages = Vec::with_capacity(rows.len());
        for row in rows {
            messages.push(Self::map_row(&row)?);
        }
        Ok(messages)
    }

    async fn count_by_consumer_worker(&self, worker_id: i64) -> Result<i64> {
        crate::store::turso::query_scalar(TursoDialect::MESSAGE.count_by_consumer_worker)
            .bind(worker_id)
            .fetch_one(&self.db)
            .await
    }

    async fn count_worker_references(&self, worker_id: i64) -> Result<i64> {
        crate::store::turso::query_scalar(TursoDialect::MESSAGE.count_worker_references)
            .bind(worker_id)
            .bind(worker_id)
            .fetch_one(&self.db)
            .await
    }

    async fn move_to_dlq(&self, max_read_ct: i32) -> Result<Vec<i64>> {
        let rows = crate::store::turso::query(TursoDialect::MESSAGE.move_to_dlq)
            .bind(max_read_ct)
            .fetch_all(&self.db)
            .await?;

        let mut ids = Vec::with_capacity(rows.len());
        for row in rows {
            ids.push(row.get(0)?);
        }
        Ok(ids)
    }

    async fn release_by_consumer_worker(&self, worker_id: i64) -> Result<u64> {
        crate::store::turso::query(TursoDialect::MESSAGE.release_by_consumer_worker)
            .bind(worker_id)
            .execute_once(&self.db)
            .await
    }

    async fn batch_insert(
        &self,
        queue_id: i64,
        payloads: &[JsonValue],
        params: crate::types::BatchInsertParams,
    ) -> Result<Vec<i64>> {
        if payloads.is_empty() {
            return Ok(vec![]);
        }

        let conn = self
            .db
            .connect()
            .map_err(|e| crate::error::Error::Internal {
                message: e.to_string(),
            })?;

        conn.execute("BEGIN", ())
            .await
            .map_err(|e| crate::error::Error::QueryFailed {
                query: "BEGIN".into(),
                source: Box::new(e),
                context: "Begin batch".into(),
            })?;

        let mut ids = Vec::with_capacity(payloads.len());
        let enqueued_at_str = format_turso_timestamp(&params.enqueued_at);
        let vt_str = format_turso_timestamp(&params.vt);

        for payload in payloads {
            let res = async {
                crate::store::turso::query(
                    r#"
                    INSERT INTO pgqrs_messages (queue_id, payload, read_ct, enqueued_at, vt, producer_worker_id, consumer_worker_id)
                    VALUES (?, ?, ?, ?, ?, ?, ?)
                    RETURNING id
                    "#,
                )
                .bind(TursoValue::Integer(queue_id))
                .bind(TursoValue::Text(payload.to_string()))
                .bind(TursoValue::Integer(params.read_ct as i64))
                .bind(TursoValue::Text(enqueued_at_str.as_str().to_string()))
                .bind(TursoValue::Text(vt_str.as_str().to_string()))
                .bind(match params.producer_worker_id {
                    Some(id) => TursoValue::Integer(id),
                    None => TursoValue::Null,
                })
                .bind(match params.consumer_worker_id {
                    Some(id) => TursoValue::Integer(id),
                    None => TursoValue::Null,
                })
                .fetch_one_once_on_connection(&conn)
                .await
             }.await;

            match res {
                Ok(row) => {
                    let id: i64 = row.get(0)?;
                    ids.push(id);
                }
                Err(e) => {
                    let _ = conn.execute("ROLLBACK", ()).await;
                    return Err(e);
                }
            }
        }

        conn.execute("COMMIT", ())
            .await
            .map_err(|e| crate::error::Error::QueryFailed {
                query: "COMMIT".into(),
                source: Box::new(e),
                context: "Commit batch".into(),
            })?;

        Ok(ids)
    }

    async fn get_by_ids(&self, ids: &[i64]) -> Result<Vec<QueueMessage>> {
        if ids.is_empty() {
            return Ok(vec![]);
        }

        let placeholders: Vec<String> = ids.iter().map(|_| "?".to_string()).collect();
        let sql = format!(
            "SELECT id, queue_id, payload, vt, enqueued_at, read_ct, dequeued_at, producer_worker_id, consumer_worker_id, archived_at FROM pgqrs_messages WHERE id IN ({}) ORDER BY id",
            placeholders.join(", ")
        );

        let mut query = crate::store::turso::query(&sql);
        for id in ids {
            query = query.bind(*id);
        }

        let rows = query.fetch_all(&self.db).await?;

        let mut messages = Vec::with_capacity(rows.len());
        for row in rows {
            messages.push(Self::map_row(&row)?);
        }
        Ok(messages)
    }

    async fn update_payload(&self, id: i64, payload: JsonValue) -> Result<u64> {
        let payload_str = payload.to_string();
        let sql = "UPDATE pgqrs_messages SET payload = ? WHERE id = ?";
        let rows = crate::store::turso::query(sql)
            .bind(payload_str)
            .bind(id)
            .execute_once(&self.db)
            .await?;
        Ok(rows)
    }

    async fn extend_visibility(
        &self,
        id: i64,
        worker_id: i64,
        additional_seconds: u32,
    ) -> Result<u64> {
        let sql = r#"
            UPDATE pgqrs_messages
            SET vt = datetime(vt, '+' || ? || ' seconds')
            WHERE id = ? AND consumer_worker_id = ?;
        "#;

        let rows = crate::store::turso::query(sql)
            .bind(additional_seconds as i32)
            .bind(id)
            .bind(worker_id)
            .execute_once(&self.db)
            .await?;

        Ok(rows)
    }

    async fn extend_visibility_batch(
        &self,
        message_ids: &[i64],
        worker_id: i64,
        additional_seconds: u32,
    ) -> Result<Vec<bool>> {
        if message_ids.is_empty() {
            return Ok(vec![]);
        }

        let conn = self
            .db
            .connect()
            .map_err(|e| crate::error::Error::Internal {
                message: e.to_string(),
            })?;
        conn.execute("BEGIN", ())
            .await
            .map_err(|e| crate::error::Error::QueryFailed {
                query: "BEGIN".into(),
                source: Box::new(e),
                context: "Begin extend batch".into(),
            })?;

        let mut extended_set = HashSet::new();
        let sql = r#"
            UPDATE pgqrs_messages
            SET vt = datetime(vt, '+' || ? || ' seconds')
            WHERE id = ? AND consumer_worker_id = ?
        "#;

        for id in message_ids {
            let res = async {
                crate::store::turso::query(sql)
                    .bind(additional_seconds as i32)
                    .bind(*id)
                    .bind(worker_id)
                    .execute_once_on_connection(&conn)
                    .await
            }
            .await;

            match res {
                Ok(rows) => {
                    if rows > 0 {
                        extended_set.insert(*id);
                    }
                }
                Err(e) => {
                    let _ = conn.execute("ROLLBACK", ()).await;
                    return Err(e);
                }
            }
        }

        conn.execute("COMMIT", ())
            .await
            .map_err(|e| crate::error::Error::QueryFailed {
                query: "COMMIT".into(),
                source: Box::new(e),
                context: "Commit extend batch".into(),
            })?;

        let result = message_ids
            .iter()
            .map(|id| extended_set.contains(id))
            .collect();

        Ok(result)
    }

    async fn release_messages_by_ids(
        &self,
        message_ids: &[i64],
        worker_id: i64,
    ) -> Result<Vec<bool>> {
        if message_ids.is_empty() {
            return Ok(vec![]);
        }

        let conn = self
            .db
            .connect()
            .map_err(|e| crate::error::Error::Internal {
                message: e.to_string(),
            })?;
        conn.execute("BEGIN", ())
            .await
            .map_err(|e| crate::error::Error::QueryFailed {
                query: "BEGIN".into(),
                source: Box::new(e),
                context: "Begin release batch".into(),
            })?;

        let mut released_set = HashSet::new();
        let sql = r#"
            UPDATE pgqrs_messages
            SET vt = datetime('now'), consumer_worker_id = NULL
            WHERE id = ? AND consumer_worker_id = ?
        "#;

        for id in message_ids {
            let res = async {
                crate::store::turso::query(sql)
                    .bind(*id)
                    .bind(worker_id)
                    .execute_once_on_connection(&conn)
                    .await
            }
            .await;

            match res {
                Ok(rows) => {
                    if rows > 0 {
                        released_set.insert(*id);
                    }
                }
                Err(e) => {
                    let _ = conn.execute("ROLLBACK", ()).await;
                    return Err(e);
                }
            }
        }

        conn.execute("COMMIT", ())
            .await
            .map_err(|e| crate::error::Error::QueryFailed {
                query: "COMMIT".into(),
                source: Box::new(e),
                context: "Commit release batch".into(),
            })?;

        let result = message_ids
            .iter()
            .map(|id| released_set.contains(id))
            .collect();

        Ok(result)
    }

    async fn release_with_visibility(
        &self,
        id: i64,
        worker_id: i64,
        vt: chrono::DateTime<chrono::Utc>,
    ) -> Result<u64> {
        let vt_str = format_turso_timestamp(&vt);
        let sql = r#"
            UPDATE pgqrs_messages
            SET vt = ?, consumer_worker_id = NULL
            WHERE id = ? AND consumer_worker_id = ?
        "#;

        let rows = crate::store::turso::query(sql)
            .bind(vt_str)
            .bind(id)
            .bind(worker_id)
            .execute_once(&self.db)
            .await?;

        Ok(rows)
    }

    async fn count_pending_for_queue(&self, queue_id: i64) -> Result<i64> {
        let now_str = format_turso_timestamp(&chrono::Utc::now());
        let count: i64 = crate::store::turso::query_scalar(
            r#"
            SELECT COUNT(*)
            FROM pgqrs_messages
            WHERE queue_id = ? AND (vt IS NULL OR vt <= ?) AND consumer_worker_id IS NULL AND archived_at IS NULL
            "#,
        )
        .bind(queue_id)
        .bind(now_str)
        .fetch_one(&self.db)
        .await?;
        Ok(count)
    }

    async fn count_pending_for_queue_and_worker(
        &self,
        queue_id: i64,
        worker_id: i64,
    ) -> Result<i64> {
        let count: i64 = crate::store::turso::query_scalar(
            r#"
            SELECT COUNT(*)
            FROM pgqrs_messages
            WHERE queue_id = ? AND consumer_worker_id = ? AND archived_at IS NULL
            "#,
        )
        .bind(queue_id)
        .bind(worker_id)
        .fetch_one(&self.db)
        .await?;

        Ok(count)
    }

    async fn dequeue_at(
        &self,
        queue_id: i64,
        limit: usize,
        vt: u32,
        worker_id: i64,
        now: chrono::DateTime<chrono::Utc>,
        max_read_ct: i32,
    ) -> Result<Vec<QueueMessage>> {
        let now_str = format_turso_timestamp(&now);
        let conn = crate::store::turso::connect_db(&self.db).await?;

        conn.execute("BEGIN IMMEDIATE", ()).await.map_err(|e| {
            crate::error::Error::QueryFailed {
                query: "BEGIN IMMEDIATE".into(),
                source: Box::new(e),
                context: "Dequeue start".into(),
            }
        })?;

        // 1. Select candidates
        let sql_select = r#"
            SELECT id
            FROM pgqrs_messages
            WHERE queue_id = ? AND (vt IS NULL OR vt <= ?) AND consumer_worker_id IS NULL AND archived_at IS NULL AND read_ct < ?
            ORDER BY enqueued_at ASC
            LIMIT ?
        "#;

        let mut grabbed_ids = Vec::new();

        let rows = crate::store::turso::query(sql_select)
            .bind(queue_id)
            .bind(now_str.clone())
            .bind(max_read_ct as i64)
            .bind(limit as i64)
            .fetch_all_on_connection(&conn)
            .await;

        let rows = match rows {
            Ok(res) => res,
            Err(e) => {
                let _ = conn.execute("ROLLBACK", ()).await;
                return Err(e);
            }
        };

        for row in rows {
            let id: i64 = row.get(0)?;
            grabbed_ids.push(id);
        }

        if grabbed_ids.is_empty() {
            conn.execute("ROLLBACK", ())
                .await
                .map_err(|e| crate::error::Error::QueryFailed {
                    query: "ROLLBACK".into(),
                    source: Box::new(e),
                    context: "Dequeue empty".into(),
                })?;
            return Ok(vec![]);
        }

        // 2. Update them
        let new_vt = now + chrono::Duration::seconds(vt as i64);
        let new_vt_str = format_turso_timestamp(&new_vt);

        let mut messages = Vec::with_capacity(grabbed_ids.len());

        for id in &grabbed_ids {
            let update_res = crate::store::turso::query("UPDATE pgqrs_messages SET consumer_worker_id = ?, vt = ?, read_ct = read_ct + 1, dequeued_at = COALESCE(dequeued_at, ?) WHERE id = ? RETURNING id, queue_id, payload, vt, enqueued_at, read_ct, dequeued_at, producer_worker_id, consumer_worker_id, archived_at")
                .bind(worker_id)
                .bind(new_vt_str.clone())
                .bind(now_str.clone())
                .bind(*id)
                .fetch_one_once_on_connection(&conn)
                .await;

            match update_res {
                Ok(row) => {
                    messages.push(Self::map_row(&row)?);
                }
                Err(e) => {
                    let _ = conn.execute("ROLLBACK", ()).await;
                    return Err(e);
                }
            }
        }

        conn.execute("COMMIT", ())
            .await
            .map_err(|e| crate::error::Error::QueryFailed {
                query: "COMMIT".into(),
                source: Box::new(e),
                context: "Dequeue commit".into(),
            })?;

        Ok(messages)
    }

    async fn archive(&self, id: i64, worker_id: i64) -> Result<Option<QueueMessage>> {
        let now = chrono::Utc::now();
        let now_str = format_turso_timestamp(&now);

        let row = crate::store::turso::query(
            "UPDATE pgqrs_messages SET archived_at = ? WHERE id = ? AND consumer_worker_id = ? AND archived_at IS NULL RETURNING id, queue_id, payload, vt, enqueued_at, read_ct, dequeued_at, producer_worker_id, consumer_worker_id, archived_at",
        )
        .bind(now_str)
        .bind(id)
        .bind(worker_id)
        .fetch_optional(&self.db)
        .await?;

        if let Some(r) = row {
            Ok(Some(Self::map_row(&r)?))
        } else {
            Ok(None)
        }
    }

    async fn archive_many(&self, ids: &[i64], worker_id: i64) -> Result<Vec<bool>> {
        if ids.is_empty() {
            return Ok(vec![]);
        }

        let conn = self
            .db
            .connect()
            .map_err(|e| crate::error::Error::Internal {
                message: e.to_string(),
            })?;
        conn.execute("BEGIN", ())
            .await
            .map_err(|e| crate::error::Error::QueryFailed {
                query: "BEGIN".into(),
                source: Box::new(e),
                context: "Begin archive batch".into(),
            })?;

        let mut archived_set = HashSet::new();
        let now = chrono::Utc::now();
        let now_str = format_turso_timestamp(&now);

        for id in ids {
            let res = async {
                crate::store::turso::query("UPDATE pgqrs_messages SET archived_at = ? WHERE id = ? AND consumer_worker_id = ? AND archived_at IS NULL RETURNING id")
                    .bind(now_str.clone())
                    .bind(*id)
                    .bind(worker_id)
                    .fetch_optional_on_connection(&conn)
                    .await
            }
            .await;

            match res {
                Ok(Some(row)) => {
                    let id: i64 = row.get(0)?;
                    archived_set.insert(id);
                }
                Ok(None) => {}
                Err(e) => {
                    let _ = conn.execute("ROLLBACK", ()).await;
                    return Err(e);
                }
            }
        }

        conn.execute("COMMIT", ())
            .await
            .map_err(|e| crate::error::Error::QueryFailed {
                query: "COMMIT".into(),
                source: Box::new(e),
                context: "Commit archive batch".into(),
            })?;

        let result = ids.iter().map(|id| archived_set.contains(id)).collect();
        Ok(result)
    }

    async fn replay_dlq(&self, id: i64) -> Result<Option<QueueMessage>> {
        let conn = self
            .db
            .connect()
            .map_err(|e| crate::error::Error::Internal {
                message: e.to_string(),
            })?;

        conn.execute("BEGIN", ())
            .await
            .map_err(|e| crate::error::Error::QueryFailed {
                query: "BEGIN".into(),
                source: Box::new(e),
                context: "Begin replay".into(),
            })?;

        let now_str = format_turso_timestamp(&chrono::Utc::now());

        let msg_row_opt = crate::store::turso::query(
            r#"
            UPDATE pgqrs_messages
            SET archived_at = NULL,
                read_ct = 0,
                vt = ?,
                enqueued_at = ?,
                consumer_worker_id = NULL,
                dequeued_at = NULL
            WHERE id = ? AND archived_at IS NOT NULL
            RETURNING id, queue_id, payload, vt, enqueued_at, read_ct, dequeued_at, producer_worker_id, consumer_worker_id, archived_at;
            "#,
        )
        .bind(now_str.clone())
        .bind(now_str)
        .bind(id)
        .fetch_optional_on_connection(&conn)
        .await;

        let msg_row_opt = match msg_row_opt {
            Ok(res) => res,
            Err(e) => {
                let _ = conn.execute("ROLLBACK", ()).await;
                return Err(e);
            }
        };

        if let Some(msg_row) = msg_row_opt {
            conn.execute("COMMIT", ())
                .await
                .map_err(|e| crate::error::Error::QueryFailed {
                    query: "COMMIT".into(),
                    source: Box::new(e),
                    context: "Commit replay".into(),
                })?;

            let msg = Self::map_row(&msg_row)?;
            Ok(Some(msg))
        } else {
            let _ = conn.execute("ROLLBACK", ()).await;
            Ok(None)
        }
    }

    async fn list_archived_by_queue(&self, queue_id: i64) -> Result<Vec<QueueMessage>> {
        let rows = crate::store::turso::query(
            r#"
            SELECT id, queue_id, payload, vt, enqueued_at, read_ct, dequeued_at, producer_worker_id, consumer_worker_id, archived_at
            FROM pgqrs_messages
            WHERE queue_id = ? AND archived_at IS NOT NULL
            ORDER BY archived_at DESC
            "#,
        )
        .bind(queue_id)
        .fetch_all(&self.db)
        .await?;

        let mut messages = Vec::with_capacity(rows.len());
        for row in rows {
            messages.push(Self::map_row(&row)?);
        }
        Ok(messages)
    }

    async fn count_by_fk(&self, queue_id: i64) -> Result<i64> {
        let count: i64 = crate::store::turso::query_scalar(
            "SELECT COUNT(*) FROM pgqrs_messages WHERE queue_id = ?",
        )
        .bind(queue_id)
        .fetch_one(&self.db)
        .await?;
        Ok(count)
    }

    async fn delete_by_ids(&self, ids: &[i64]) -> Result<Vec<bool>> {
        let mut results = Vec::with_capacity(ids.len());

        if ids.is_empty() {
            return Ok(vec![]);
        }

        for &id in ids {
            let rows = crate::store::turso::query(DELETE_MESSAGE_BY_ID)
                .bind(id)
                .execute_once(&self.db)
                .await?;
            results.push(rows > 0);
        }

        Ok(results)
    }

    async fn delete_owned(&self, id: i64, worker_id: i64) -> Result<u64> {
        let rows = crate::store::turso::query(
            "DELETE FROM pgqrs_messages WHERE id = ? AND consumer_worker_id = ?",
        )
        .bind(id)
        .bind(worker_id)
        .execute_once(&self.db)
        .await?;
        Ok(rows)
    }

    async fn delete_many_owned(&self, ids: &[i64], worker_id: i64) -> Result<Vec<bool>> {
        if ids.is_empty() {
            return Ok(vec![]);
        }

        let placeholders: Vec<String> = ids.iter().map(|_| "?".to_string()).collect();
        let sql = format!(
            "DELETE FROM pgqrs_messages WHERE id IN ({}) AND consumer_worker_id = ? RETURNING id",
            placeholders.join(", ")
        );

        let mut query = crate::store::turso::query(&sql);
        for id in ids {
            query = query.bind(*id);
        }
        query = query.bind(worker_id);

        let rows = query.fetch_all_once(&self.db).await?;

        let mut deleted_ids = HashSet::new();
        for row in rows {
            let id: i64 = row.get(0)?;
            deleted_ids.insert(id);
        }

        let mut results = Vec::with_capacity(ids.len());
        for id in ids {
            results.push(deleted_ids.contains(id));
        }
        Ok(results)
    }
}