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
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
use crate::config::Config;
use crate::error::Result;
use crate::store::dblock::DbLock;
use crate::store::{BackendType, ConcurrencyModel};
use crate::store::{
    DbStateTable, DbTables, MessageTable, QueueTable, RunRecordTable, SerializedLock,
    StepRecordTable, Store, Tables, WorkerTable, WorkflowTable,
};
use crate::Worker;

use crate::types::NewQueueRecord;
use async_trait::async_trait;

use std::sync::Arc;
use turso::{Database, Row};

pub(crate) mod dialect;
pub mod tables;

use self::tables::db_state::TursoDbState;
use self::tables::messages::TursoMessageTable;
use self::tables::queues::TursoQueueTable;
use self::tables::runs::TursoRunRecordTable;
use self::tables::steps::TursoStepRecordTable;
use self::tables::workers::TursoWorkerTable;
use self::tables::workflows::TursoWorkflowTable;

#[derive(Debug, Clone)]
pub(crate) struct TursoTables {
    db: Arc<Database>,
    config: Config,
    queues: Arc<TursoQueueTable>,
    messages: Arc<TursoMessageTable>,
    workers: Arc<TursoWorkerTable>,
    db_state: Arc<TursoDbState>,
    workflows: Arc<TursoWorkflowTable>,
    workflow_runs: Arc<TursoRunRecordTable>,
    workflow_steps: Arc<TursoStepRecordTable>,
}

impl TursoTables {
    pub(crate) async fn new(dsn: &str, config: &Config) -> Result<Self> {
        let path = BackendType::TURSO_PREFIXES
            .iter()
            .find_map(|prefix| dsn.strip_prefix(prefix))
            .ok_or_else(|| crate::error::Error::InvalidConfig {
                field: "dsn".to_string(),
                message: "Unsupported DSN format: <redacted>".to_string(),
            })?;
        let builder = turso::Builder::new_local(path);
        let db = builder
            .build()
            .await
            .map_err(|e| crate::error::Error::Internal {
                message: format!("Failed to connect to Turso: {}", e),
            })?;

        let db = Arc::new(db);

        let conn = db.connect().map_err(|e| crate::error::Error::Internal {
            message: format!("Failed to get connection: {}", e),
        })?;

        // Enable WAL mode and busy timeout for better concurrency in local mode
        let mut rows = conn
            .query("PRAGMA journal_mode=WAL;", ())
            .await
            .map_err(|e| crate::error::Error::Internal {
                message: format!("Failed to set WAL mode: {}", e),
            })?;
        while rows
            .next()
            .await
            .map_err(|e| crate::error::Error::Internal {
                message: format!("Failed to consume WAL pragma result: {}", e),
            })?
            .is_some()
        {}

        conn.execute("PRAGMA busy_timeout = 5000;", ())
            .await
            .map_err(|e| crate::error::Error::Internal {
                message: format!("Failed to set busy timeout: {}", e),
            })?;

        // Enable foreign keys
        conn.execute("PRAGMA foreign_keys = ON;", ())
            .await
            .map_err(|e| crate::error::Error::Internal {
                message: format!("Failed to set foreign_keys: {}", e),
            })?;

        Ok(Self {
            db: Arc::clone(&db),
            config: config.clone(),
            queues: Arc::new(TursoQueueTable::new(Arc::clone(&db))),
            messages: Arc::new(TursoMessageTable::new(Arc::clone(&db))),
            workers: Arc::new(TursoWorkerTable::new(Arc::clone(&db))),
            db_state: Arc::new(TursoDbState::new(Arc::clone(&db))),
            workflows: Arc::new(TursoWorkflowTable::new(Arc::clone(&db))),
            workflow_runs: Arc::new(TursoRunRecordTable::new(Arc::clone(&db))),
            workflow_steps: Arc::new(TursoStepRecordTable::new(Arc::clone(&db))),
        })
    }
}

#[derive(Clone)]
pub struct TursoStore {
    db: SerializedLock<TursoTables>,
    tables: Tables<SerializedLock<TursoTables>>,
}

impl std::fmt::Debug for TursoStore {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("TursoStore").finish()
    }
}

impl TursoStore {
    pub async fn new(dsn: &str, config: &Config) -> Result<Self> {
        let db = SerializedLock::new(TursoTables::new(dsn, config).await?);
        let tables = Tables::new(db.clone());
        Ok(Self { db, tables })
    }

    fn any_store(&self) -> crate::store::AnyStore {
        crate::store::AnyStore::Turso(self.clone())
    }
}

/// Re-export consolidated timestamp utilities
pub use crate::store::sqlite_utils::format_timestamp as format_turso_timestamp;
pub use crate::store::sqlite_utils::parse_timestamp as parse_turso_timestamp;

pub trait FromTursoRow: Sized {
    fn from_row(row: &Row, idx: usize) -> Result<Self>;
}

impl FromTursoRow for i64 {
    fn from_row(row: &Row, idx: usize) -> Result<Self> {
        row.get(idx).map_err(|e| crate::error::Error::Internal {
            message: e.to_string(),
        })
    }
}

impl FromTursoRow for String {
    fn from_row(row: &Row, idx: usize) -> Result<Self> {
        row.get(idx).map_err(|e| crate::error::Error::Internal {
            message: e.to_string(),
        })
    }
}

impl FromTursoRow for bool {
    fn from_row(row: &Row, idx: usize) -> Result<Self> {
        let val: i64 = row.get(idx).map_err(|e| crate::error::Error::Internal {
            message: e.to_string(),
        })?;
        Ok(val != 0)
    }
}

pub struct TursoQueryBuilder {
    sql: String,
    params: Vec<turso::Value>,
}

pub async fn connect_db(db: &Database) -> Result<turso::Connection> {
    let conn = db.connect().map_err(|e| crate::error::Error::Internal {
        message: format!("Connect failed: {}", e),
    })?;

    // precise busy_timeout for every connection to handle concurrency
    conn.execute("PRAGMA busy_timeout = 5000;", ())
        .await
        .map_err(|e| crate::error::Error::Internal {
            message: format!("Failed to set busy timeout: {}", e),
        })?;

    conn.execute("PRAGMA foreign_keys = ON;", ())
        .await
        .map_err(|e| crate::error::Error::Internal {
            message: format!("Failed to set foreign_keys: {}", e),
        })?;

    Ok(conn)
}

impl TursoQueryBuilder {
    pub fn new(sql: &str) -> Self {
        Self {
            sql: sql.to_string(),
            params: Vec::new(),
        }
    }

    pub fn bind<T>(mut self, value: T) -> Self
    where
        T: Into<turso::Value>,
    {
        self.params.push(value.into());
        self
    }

    pub async fn execute(self, db: &Database) -> Result<u64> {
        let conn = connect_db(db).await?;
        self.execute_on_connection(&conn).await
    }

    /// Execute once without retry - for DML operations (INSERT/UPDATE/DELETE)
    pub async fn execute_once(self, db: &Database) -> Result<u64> {
        let conn = connect_db(db).await?;
        self.execute_once_on_connection(&conn).await
    }

    pub async fn execute_on_connection(self, conn: &turso::Connection) -> Result<u64> {
        let mut retries = 0;
        const MAX_RETRIES: u32 = 10;
        let mut delay = 50u64; // ms
        const MAX_DELAY: u64 = 5000;

        loop {
            let res = conn.execute(&self.sql, self.params.clone()).await;

            match res {
                Ok(count) => return Ok(count),
                Err(e) => {
                    let msg = e.to_string();
                    let is_locked = msg.contains("database is locked")
                        || msg.contains("SQLITE_BUSY")
                        || msg.contains("snapshot is stale");

                    if is_locked && retries < MAX_RETRIES {
                        retries += 1;

                        // Add jitter: +/- 10%
                        let jitter = (std::time::SystemTime::now()
                            .duration_since(std::time::UNIX_EPOCH)
                            .unwrap_or_default()
                            .subsec_nanos()
                            % 20) as i64
                            - 10;
                        let jittered_delay = (delay as i64 + jitter).max(1) as u64;

                        tracing::warn!(
                            "Database locked, retrying {}/{} in {}ms: {}",
                            retries,
                            MAX_RETRIES,
                            jittered_delay,
                            self.sql
                        );
                        tokio::time::sleep(tokio::time::Duration::from_millis(jittered_delay))
                            .await;
                        delay = delay.saturating_mul(2).min(MAX_DELAY);
                        continue;
                    }

                    return Err(crate::error::Error::QueryFailed {
                        query: self.sql,
                        source: Box::new(e),
                        context: if is_locked {
                            "Execute on conn failed (locked)".into()
                        } else {
                            "Execute on conn failed".into()
                        },
                    });
                }
            }
        }
    }

    /// Execute once without retry - for DML operations (INSERT/UPDATE/DELETE)
    /// that should not be retried to prevent data integrity issues.
    pub async fn execute_once_on_connection(self, conn: &turso::Connection) -> Result<u64> {
        conn.execute(&self.sql, self.params.clone())
            .await
            .map_err(|e| crate::error::Error::QueryFailed {
                query: self.sql,
                source: Box::new(e),
                context: "Execute once failed (DML - no retry)".into(),
            })
    }

    pub async fn fetch_all(self, db: &Database) -> Result<Vec<Row>> {
        let conn = connect_db(db).await?;
        self.fetch_all_on_connection(&conn).await
    }

    /// Fetch all rows once without retry - for DML operations with RETURNING clause
    pub async fn fetch_all_once(self, db: &Database) -> Result<Vec<Row>> {
        let conn = connect_db(db).await?;
        self.fetch_all_once_on_connection(&conn).await
    }

    pub async fn fetch_all_on_connection(self, conn: &turso::Connection) -> Result<Vec<Row>> {
        let mut retries = 0;
        const MAX_RETRIES: u32 = 10;
        let mut delay = 50u64; // ms
        const MAX_DELAY: u64 = 5000;

        loop {
            let res = conn.query(&self.sql, self.params.clone()).await;

            match res {
                Ok(mut rows) => {
                    let mut result = Vec::new();
                    let mut loop_err = None;

                    loop {
                        match rows.next().await {
                            Ok(Some(row)) => result.push(row),
                            Ok(None) => break,
                            Err(e) => {
                                loop_err = Some(e);
                                break;
                            }
                        }
                    }

                    if let Some(e) = loop_err {
                        let msg = e.to_string();
                        let is_locked = msg.contains("database is locked")
                            || msg.contains("SQLITE_BUSY")
                            || msg.contains("snapshot is stale");

                        if is_locked && retries < MAX_RETRIES {
                            retries += 1;

                            // Add jitter: +/- 10%
                            let jitter = (std::time::SystemTime::now()
                                .duration_since(std::time::UNIX_EPOCH)
                                .unwrap_or_default()
                                .subsec_nanos()
                                % 20) as i64
                                - 10;
                            let jittered_delay = (delay as i64 + jitter).max(1) as u64;

                            tracing::warn!(
                                "Database locked during fetch, retrying {}/{} in {}ms: {}",
                                retries,
                                MAX_RETRIES,
                                jittered_delay,
                                self.sql
                            );
                            tokio::time::sleep(tokio::time::Duration::from_millis(jittered_delay))
                                .await;
                            delay = delay.saturating_mul(2).min(MAX_DELAY);
                            continue;
                        }

                        return Err(crate::error::Error::QueryFailed {
                            query: self.sql.clone(),
                            source: Box::new(e),
                            context: "Next row failed".into(),
                        });
                    }

                    return Ok(result);
                }
                Err(e) => {
                    let msg = e.to_string();
                    let is_locked = msg.contains("database is locked")
                        || msg.contains("SQLITE_BUSY")
                        || msg.contains("snapshot is stale");

                    if is_locked && retries < MAX_RETRIES {
                        retries += 1;

                        // Add jitter: +/- 10%
                        let jitter = (std::time::SystemTime::now()
                            .duration_since(std::time::UNIX_EPOCH)
                            .unwrap_or_default()
                            .subsec_nanos()
                            % 20) as i64
                            - 10;
                        let jittered_delay = (delay as i64 + jitter).max(1) as u64;

                        tracing::warn!(
                            "Database locked query start, retrying {}/{} in {}ms: {}",
                            retries,
                            MAX_RETRIES,
                            jittered_delay,
                            self.sql
                        );
                        tokio::time::sleep(tokio::time::Duration::from_millis(jittered_delay))
                            .await;
                        delay = delay.saturating_mul(2).min(MAX_DELAY);
                        continue;
                    }

                    return Err(crate::error::Error::QueryFailed {
                        query: self.sql.clone(),
                        source: Box::new(e),
                        context: "Query on conn failed".into(),
                    });
                }
            }
        }
    }

    /// Fetch all rows once without retry - for DML operations with RETURNING clause
    /// that should not be retried to prevent data integrity issues.
    pub async fn fetch_all_once_on_connection(self, conn: &turso::Connection) -> Result<Vec<Row>> {
        let mut rows = conn
            .query(&self.sql, self.params.clone())
            .await
            .map_err(|e| crate::error::Error::QueryFailed {
                query: self.sql.clone(),
                source: Box::new(e),
                context: "Query once failed (DML - no retry)".into(),
            })?;

        let mut result = Vec::new();
        loop {
            match rows.next().await {
                Ok(Some(row)) => result.push(row),
                Ok(None) => break,
                Err(e) => {
                    return Err(crate::error::Error::QueryFailed {
                        query: self.sql.clone(),
                        source: Box::new(e),
                        context: "Fetch row once failed (DML - no retry)".into(),
                    })
                }
            }
        }
        Ok(result)
    }

    pub async fn fetch_one(self, db: &Database) -> Result<Row> {
        let conn = connect_db(db).await?;
        self.fetch_one_on_connection(&conn).await
    }

    /// Fetch one row once without retry - for DML operations with RETURNING clause
    pub async fn fetch_one_once(self, db: &Database) -> Result<Row> {
        let conn = connect_db(db).await?;
        self.fetch_one_once_on_connection(&conn).await
    }

    pub async fn fetch_one_on_connection(self, conn: &turso::Connection) -> Result<Row> {
        let rows = self.fetch_all_on_connection(conn).await?;
        if rows.is_empty() {
            Err(crate::error::Error::NotFound {
                entity: "Row".into(),
                id: "None".into(),
            })
        } else {
            Ok(rows.into_iter().next().unwrap())
        }
    }

    /// Fetch one row once without retry - for DML operations with RETURNING clause
    pub async fn fetch_one_once_on_connection(self, conn: &turso::Connection) -> Result<Row> {
        let rows = self.fetch_all_once_on_connection(conn).await?;
        if rows.is_empty() {
            Err(crate::error::Error::NotFound {
                entity: "Row".into(),
                id: "None".into(),
            })
        } else {
            Ok(rows.into_iter().next().unwrap())
        }
    }

    pub async fn fetch_optional(self, db: &Database) -> Result<Option<Row>> {
        let conn = connect_db(db).await?;
        self.fetch_optional_on_connection(&conn).await
    }

    /// Fetch optional row once without retry - for DML operations with RETURNING clause
    pub async fn fetch_optional_once(self, db: &Database) -> Result<Option<Row>> {
        let conn = connect_db(db).await?;
        self.fetch_optional_once_on_connection(&conn).await
    }

    pub async fn fetch_optional_on_connection(
        self,
        conn: &turso::Connection,
    ) -> Result<Option<Row>> {
        let rows = self.fetch_all_on_connection(conn).await?;
        Ok(rows.into_iter().next())
    }

    /// Fetch optional row once without retry - for DML operations with RETURNING clause
    pub async fn fetch_optional_once_on_connection(
        self,
        conn: &turso::Connection,
    ) -> Result<Option<Row>> {
        let rows = self.fetch_all_once_on_connection(conn).await?;
        Ok(rows.into_iter().next())
    }
}

pub fn query(sql: &str) -> TursoQueryBuilder {
    TursoQueryBuilder::new(sql)
}

pub struct GenericScalarBuilder {
    builder: TursoQueryBuilder,
}

impl GenericScalarBuilder {
    pub fn bind<V: Into<turso::Value>>(mut self, value: V) -> Self {
        self.builder = self.builder.bind(value);
        self
    }

    pub async fn fetch_one<T>(self, db: &Database) -> Result<T>
    where
        T: FromTursoRow,
    {
        let row = self.builder.fetch_one(db).await?;
        T::from_row(&row, 0)
    }

    /// Fetch one scalar value once without retry - for DML operations with RETURNING clause
    pub async fn fetch_one_once<T>(self, db: &Database) -> Result<T>
    where
        T: FromTursoRow,
    {
        let row = self.builder.fetch_one_once(db).await?;
        T::from_row(&row, 0)
    }

    pub async fn fetch_optional<T>(self, db: &Database) -> Result<Option<T>>
    where
        T: FromTursoRow,
    {
        let row = self.builder.fetch_optional(db).await?;
        if let Some(r) = row {
            Ok(Some(T::from_row(&r, 0)?))
        } else {
            Ok(None)
        }
    }

    /// Fetch optional scalar value once without retry - for DML operations with RETURNING clause
    pub async fn fetch_optional_once<T>(self, db: &Database) -> Result<Option<T>>
    where
        T: FromTursoRow,
    {
        let row = self.builder.fetch_optional_once(db).await?;
        if let Some(r) = row {
            Ok(Some(T::from_row(&r, 0)?))
        } else {
            Ok(None)
        }
    }

    pub async fn fetch_optional_on_connection<T>(
        self,
        conn: &turso::Connection,
    ) -> Result<Option<T>>
    where
        T: FromTursoRow,
    {
        let row = self.builder.fetch_optional_on_connection(conn).await?;
        if let Some(r) = row {
            Ok(Some(T::from_row(&r, 0)?))
        } else {
            Ok(None)
        }
    }
}

pub fn query_scalar(sql: &str) -> GenericScalarBuilder {
    GenericScalarBuilder {
        builder: TursoQueryBuilder::new(sql),
    }
}

#[async_trait]
impl DbTables for TursoTables {
    async fn execute_raw(&self, sql: &str) -> Result<()> {
        query(sql).execute_once(&self.db).await?;
        Ok(())
    }

    async fn execute_raw_with_i64(&self, sql: &str, param: i64) -> Result<()> {
        query(sql).bind(param).execute_once(&self.db).await?;
        Ok(())
    }

    async fn execute_raw_with_two_i64(&self, sql: &str, param1: i64, param2: i64) -> Result<()> {
        query(sql)
            .bind(param1)
            .bind(param2)
            .execute_once(&self.db)
            .await?;
        Ok(())
    }

    async fn query_int(&self, sql: &str) -> Result<i64> {
        query_scalar(sql).fetch_one(&self.db).await
    }

    async fn query_string(&self, sql: &str) -> Result<String> {
        query_scalar(sql).fetch_one(&self.db).await
    }

    async fn query_bool(&self, sql: &str) -> Result<bool> {
        query_scalar(sql).fetch_one(&self.db).await
    }

    fn config(&self) -> &Config {
        &self.config
    }

    fn concurrency_model(&self) -> ConcurrencyModel {
        ConcurrencyModel::SingleProcess
    }

    fn queues(&self) -> &dyn QueueTable {
        self.queues.as_ref()
    }

    fn messages(&self) -> &dyn MessageTable {
        self.messages.as_ref()
    }

    fn workers(&self) -> &dyn WorkerTable {
        self.workers.as_ref()
    }

    fn db_state(&self) -> &dyn DbStateTable {
        self.db_state.as_ref()
    }

    fn workflows(&self) -> &dyn WorkflowTable {
        self.workflows.as_ref()
    }

    fn workflow_runs(&self) -> &dyn RunRecordTable {
        self.workflow_runs.as_ref()
    }

    fn workflow_steps(&self) -> &dyn StepRecordTable {
        self.workflow_steps.as_ref()
    }

    async fn bootstrap(&self) -> Result<()> {
        let conn = connect_db(&self.db).await?;
        let scripts = [
            (
                "00_create_schema_version",
                include_str!("../../../migrations/turso/00_create_schema_version.sql"),
            ),
            (
                "01_create_queues",
                include_str!("../../../migrations/turso/01_create_queues.sql"),
            ),
            (
                "02_create_workers",
                include_str!("../../../migrations/turso/02_create_workers.sql"),
            ),
            (
                "03_create_messages",
                include_str!("../../../migrations/turso/03_create_messages.sql"),
            ),
            (
                "05_create_workflows",
                include_str!("../../../migrations/turso/05_create_workflows.sql"),
            ),
        ];

        for (name, script) in scripts {
            // Check if migration already applied
            if name != "00_create_schema_version" {
                let applied: Option<i64> = crate::store::turso::query_scalar(
                    "SELECT 1 FROM pgqrs_schema_version WHERE version = ?",
                )
                .bind(name.to_string())
                .fetch_optional_on_connection(&conn)
                .await?;

                if applied.is_some() {
                    continue;
                }
            }

            for statement in script.split(';') {
                let s = statement.trim();
                if !s.is_empty() {
                    conn.execute(s, ())
                        .await
                        .map_err(|e| crate::error::Error::Internal {
                            message: format!("Bootstrap failed on {}: {}", name, e),
                        })?;
                }
            }
            if name != "00_create_schema_version" {
                let sql = "INSERT OR IGNORE INTO pgqrs_schema_version (version, applied_at, description) VALUES (?, datetime('now'), ?)";
                conn.execute(sql, (name, format!("Applied {}", name)))
                    .await
                    .map_err(|e| crate::error::Error::Internal {
                        message: format!("Failed to record migration {}: {}", name, e),
                    })?;
            }
        }
        Ok(())
    }
}

#[async_trait]
impl Store for TursoStore {
    async fn execute_raw(&self, sql: &str) -> Result<()> {
        let sql = sql.to_string();
        self.db
            .with_write(|db| Box::pin(async move { db.execute_raw(&sql).await }))
            .await
    }

    async fn execute_raw_with_i64(&self, sql: &str, param: i64) -> Result<()> {
        let sql = sql.to_string();
        self.db
            .with_write(|db| Box::pin(async move { db.execute_raw_with_i64(&sql, param).await }))
            .await
    }

    async fn execute_raw_with_two_i64(&self, sql: &str, param1: i64, param2: i64) -> Result<()> {
        let sql = sql.to_string();
        self.db
            .with_write(|db| {
                Box::pin(async move { db.execute_raw_with_two_i64(&sql, param1, param2).await })
            })
            .await
    }

    async fn query_int(&self, sql: &str) -> Result<i64> {
        let sql = sql.to_string();
        self.db
            .with_read(|db| Box::pin(async move { db.query_int(&sql).await }))
            .await
    }

    async fn query_string(&self, sql: &str) -> Result<String> {
        let sql = sql.to_string();
        self.db
            .with_read(|db| Box::pin(async move { db.query_string(&sql).await }))
            .await
    }

    async fn query_bool(&self, sql: &str) -> Result<bool> {
        let sql = sql.to_string();
        self.db
            .with_read(|db| Box::pin(async move { db.query_bool(&sql).await }))
            .await
    }

    fn config(&self) -> &Config {
        self.db.config()
    }

    fn queues(&self) -> &dyn QueueTable {
        &self.tables
    }

    fn messages(&self) -> &dyn MessageTable {
        &self.tables
    }

    fn workers(&self) -> &dyn WorkerTable {
        &self.tables
    }

    fn db_state(&self) -> &dyn DbStateTable {
        &self.tables
    }

    fn workflows(&self) -> &dyn WorkflowTable {
        &self.tables
    }

    fn workflow_runs(&self) -> &dyn RunRecordTable {
        &self.tables
    }

    fn workflow_steps(&self) -> &dyn StepRecordTable {
        &self.tables
    }

    async fn bootstrap(&self) -> Result<()> {
        self.db
            .with_write(|db| Box::pin(async move { db.bootstrap().await }))
            .await
    }

    async fn admin(&self, name: &str, config: &Config) -> Result<crate::workers::Admin> {
        let _ = config;
        crate::workers::Admin::new(self.any_store(), name).await
    }

    async fn admin_ephemeral(&self, config: &Config) -> Result<crate::workers::Admin> {
        let _ = config;
        crate::workers::Admin::new_ephemeral(self.any_store()).await
    }

    async fn producer(
        &self,
        queue_name: &str,
        name: &str,
        config: &Config,
    ) -> Result<crate::workers::Producer> {
        let queue_info = QueueTable::get_by_name(&self.tables, queue_name).await?;
        let worker_record = WorkerTable::register(&self.tables, Some(queue_info.id), name).await?;

        Ok(crate::workers::Producer::new(
            self.any_store(),
            queue_info,
            worker_record,
            config.validation_config.clone(),
        ))
    }

    async fn consumer(
        &self,
        queue_name: &str,
        name: &str,
        config: &Config,
    ) -> Result<crate::workers::Consumer> {
        let _ = config;
        let queue_info = QueueTable::get_by_name(&self.tables, queue_name).await?;
        let worker_record = WorkerTable::register(&self.tables, Some(queue_info.id), name).await?;

        Ok(crate::workers::Consumer::new(
            self.any_store(),
            queue_info,
            worker_record,
        ))
    }

    async fn queue(&self, name: &str) -> Result<crate::types::QueueRecord> {
        let queue_exists = QueueTable::exists(&self.tables, name).await?;
        if queue_exists {
            return Err(crate::error::Error::QueueAlreadyExists {
                name: name.to_string(),
            });
        }

        QueueTable::insert(
            &self.tables,
            NewQueueRecord {
                queue_name: name.to_string(),
            },
        )
        .await
    }

    async fn producer_ephemeral(
        &self,
        queue_name: &str,
        config: &Config,
    ) -> Result<crate::workers::Producer> {
        let queue_info = QueueTable::get_by_name(&self.tables, queue_name).await?;
        let worker_record =
            WorkerTable::register_ephemeral(&self.tables, Some(queue_info.id)).await?;

        Ok(crate::workers::Producer::new(
            self.any_store(),
            queue_info,
            worker_record,
            config.validation_config.clone(),
        ))
    }

    async fn consumer_ephemeral(
        &self,
        queue_name: &str,
        config: &Config,
    ) -> Result<crate::workers::Consumer> {
        let _ = config;
        let queue_info = QueueTable::get_by_name(&self.tables, queue_name).await?;
        let worker_record =
            WorkerTable::register_ephemeral(&self.tables, Some(queue_info.id)).await?;

        Ok(crate::workers::Consumer::new(
            self.any_store(),
            queue_info,
            worker_record,
        ))
    }

    async fn workflow(&self, name: &str) -> Result<crate::types::WorkflowRecord> {
        let queue_exists = QueueTable::exists(&self.tables, name).await?;
        if !queue_exists {
            let _queue = QueueTable::insert(
                &self.tables,
                NewQueueRecord {
                    queue_name: name.to_string(),
                },
            )
            .await?;
        }

        let queue = QueueTable::get_by_name(&self.tables, name).await?;

        let workflow_record = WorkflowTable::insert(
            &self.tables,
            crate::types::NewWorkflowRecord {
                name: name.to_string(),
                queue_id: queue.id,
            },
        )
        .await
        .map_err(|e| {
            let msg = e.to_string();
            if msg.contains("UNIQUE constraint failed") || msg.contains("constraint failed") {
                return crate::error::Error::WorkflowAlreadyExists {
                    name: name.to_string(),
                };
            }
            e
        })?;

        Ok(workflow_record)
    }

    async fn run(&self, message: crate::types::QueueMessage) -> Result<crate::workers::Run> {
        // Try to find existing run by message_id
        match RunRecordTable::get_by_message_id(&self.tables, message.id).await {
            Ok(record) => {
                return Ok(crate::workers::Run::new(self.any_store(), record));
            }
            Err(crate::error::Error::NotFound { .. }) => {
                // Not found, continue to create new run
            }
            Err(e) => return Err(e),
        }

        // Otherwise, it's a new trigger. Create run record.
        let queue = QueueTable::get(&self.tables, message.queue_id).await?;
        let workflow = WorkflowTable::get_by_name(&self.tables, &queue.queue_name).await?;

        let run_rec = RunRecordTable::insert(
            &self.tables,
            crate::types::NewRunRecord {
                workflow_id: workflow.id,
                message_id: message.id,
                input: Some(message.payload.clone()),
            },
        )
        .await?;

        Ok(crate::workers::Run::new(self.any_store(), run_rec))
    }

    async fn worker(&self, id: i64) -> Result<Box<dyn Worker>> {
        let worker_record = WorkerTable::get(&self.tables, id).await?;
        Ok(Box::new(crate::workers::WorkerHandle::new(
            self.any_store(),
            worker_record,
        )))
    }

    fn concurrency_model(&self) -> ConcurrencyModel {
        self.db.concurrency_model()
    }

    fn backend_name(&self) -> &'static str {
        "turso"
    }
}