bdk_turso 0.3.1

Turso persistence backend for BDK
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
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
//! Async Turso storage for BDK wallet and chain changesets.
//!
//! [`Store`] owns a Turso database connection pool and exposes methods to migrate the schema and
//! read or write persisted changesets.

use std::{fmt, sync::Arc, time::Duration};

use bdk_chain::{
    BlockId, ConfirmationBlockTime, DescriptorId, bitcoin, keychain_txout, local_chain, tx_graph,
};
use bitcoin::hex::DisplayHex;
use bitcoin::{Amount, BlockHash, OutPoint, ScriptBuf, Transaction, TxOut, Txid, consensus};
pub use turso::EncryptionOpts;
#[cfg(feature = "remote")]
pub use turso::sync::RemoteEncryptionCipher;
pub use turso::transaction::TransactionBehavior;
use turso::{
    Builder, Connection, Database as LocalDatabase, Value,
    transaction::Transaction as DatabaseTransaction,
};

use crate::Error;

/// A column as reported by `PRAGMA table_info`: name, declared type, not-null flag, default value,
/// and primary-key position.
type TableColumn = (String, String, i64, Value, i64);

/// How long a connection waits for a contended database lock before returning an error.
///
/// Turso leaves its busy handler unset by default, so a concurrent writer otherwise fails
/// immediately with `Busy`. This matches the 5-second default used by `sqlx`'s SQLite driver.
const BUSY_TIMEOUT: Duration = Duration::from_secs(5);

/// Switch a local database to MVCC journal mode.
///
/// `BEGIN CONCURRENT` is only accepted when MVCC is enabled. The setting is persisted in the
/// database header, so this is a no-op after the first call.
async fn enable_mvcc(database: &LocalDatabase) -> Result<(), Error> {
    let connection = database.connect()?;
    let mut rows = connection.query("PRAGMA journal_mode = 'mvcc'", ()).await?;
    while rows.next().await?.is_some() {}
    Ok(())
}

/// Opt-in Turso features applied when opening a [`Store`].
///
/// All experimental features are disabled by default. Configure an `Options` value before opening
/// the database; these settings cannot be changed on an already-open database.
///
/// These builders are pass-through engine settings: they change what SQL an application may run or
/// how Turso executes it, but they do not change the crate's schema or persistence queries. The
/// exceptions are [`Options::with_transaction_behavior`], which applies to every transaction the
/// store opens, and the default B-tree indexes created by [`Store::migrate`], which do not depend
/// on any option. `with_generated_columns` and `with_without_rowid` affect only application SQL,
/// and `with_index_method` enables alternative index methods rather than ordinary B-tree indexes.
#[derive(Clone, Default)]
pub struct Options {
    /// Enables Turso's experimental index-method support.
    index_method: bool,
    /// Enables opening the database from multiple processes.
    multiprocess_wal: bool,
    /// Enables the experimental `VACUUM` command.
    vacuum: bool,
    /// Enables `ATTACH DATABASE` and `DETACH DATABASE`.
    attach: bool,
    /// Enables generated columns.
    generated_columns: bool,
    /// Enables `WITHOUT ROWID` tables.
    without_rowid: bool,
    /// Enables the MVCC passive checkpoint option.
    mvcc_passive_checkpoint: bool,
    /// Transaction behavior applied to every connection opened by the store.
    transaction_behavior: Option<TransactionBehavior>,
    /// Enables local at-rest encryption and supplies its cipher and key.
    encryption: Option<EncryptionOpts>,
    #[cfg(feature = "remote")]
    /// Enables Turso Cloud encryption; this does not encrypt the local sync cache.
    remote_encryption: Option<(String, RemoteEncryptionCipher)>,
}

impl Options {
    /// Create options with every experimental feature disabled.
    ///
    /// Enable only the capabilities needed by the application by chaining the relevant `with_*`
    /// methods before passing the options to a store constructor.
    pub fn new() -> Self {
        Self::default()
    }

    /// Enable Turso's experimental index-method support for the opened database.
    ///
    /// This allows application SQL to create indexes with a non-default method, such as
    /// `CREATE INDEX ... USING toy_vector_sparse_ivf (...)`. It does not enable ordinary B-tree
    /// indexes, which are always available; [`Store::migrate`] already creates B-tree indexes for
    /// the crate's lookup columns. The crate's own queries do not use alternative index methods, so
    /// this option only affects application-level SQL. Turso's full-text `fts` method is not
    /// compiled into this crate's default dependency build. It must be enabled before opening the
    /// database and only affects databases opened with the returned options.
    pub fn with_index_method(mut self) -> Self {
        self.index_method = true;
        self
    }

    /// Enable multi-process access to the database through Turso's WAL coordinator.
    ///
    /// Use this only when the same database file must be shared between operating-system
    /// processes. It changes locking and coordination at the engine level; it does not change the
    /// crate's schema or queries. Multiple [`Store`] clones in one process already share the same
    /// database handle and do not need this option. It cannot be combined with
    /// [`TransactionBehavior::Concurrent`], because Turso's MVCC mode does not support multi-process
    /// access; that combination returns [`Error::ConflictingOptions`]. Disabled by default.
    pub fn with_multiprocess_wal(mut self) -> Self {
        self.multiprocess_wal = true;
        self
    }

    /// Enable Turso's experimental `VACUUM` support for the opened database.
    ///
    /// Use it when application SQL needs to reclaim space after large deletions or migrations. It
    /// makes the command available; it does not run vacuuming automatically, and the crate never
    /// runs `VACUUM` itself. Query behavior is otherwise unchanged.
    pub fn with_vacuum(mut self) -> Self {
        self.vacuum = true;
        self
    }

    /// Enable SQL `ATTACH DATABASE` and `DETACH DATABASE` statements.
    ///
    /// Use it for application SQL that reads or joins another SQLite-compatible file. It does not
    /// change the crate's schema or queries; [`Store::migrate_to`] copies tables without
    /// `ATTACH`. Disabled by default and applied only when the database is opened.
    pub fn with_attach(mut self) -> Self {
        self.attach = true;
        self
    }

    /// Enable Turso's experimental generated-column support for SQL schemas.
    ///
    /// Use it for application tables that declare `GENERATED ALWAYS AS` columns. It does not alter
    /// the crate's wallet schema, and the crate's `INSERT` and `SELECT` statements name columns
    /// explicitly, so generated columns only affect application-level SQL.
    pub fn with_generated_columns(mut self) -> Self {
        self.generated_columns = true;
        self
    }

    /// Enable `WITHOUT ROWID` table definitions in the opened database.
    ///
    /// Use it for application tables with composite primary keys that do not need an implicit
    /// rowid. `WITHOUT ROWID` stores rows in primary-key order: primary-key lookups avoid a second
    /// index, but there is no implicit rowid and `INTEGER PRIMARY KEY` no longer aliases one. The
    /// crate's schema does not use `WITHOUT ROWID`, so its tables and queries are unchanged.
    pub fn with_without_rowid(mut self) -> Self {
        self.without_rowid = true;
        self
    }

    /// Enable Turso's experimental passive-checkpoint behavior for MVCC databases.
    ///
    /// Use it for long-running MVCC workloads that need checkpointing to run alongside readers and
    /// writers. The database must already be in MVCC journal mode; selecting
    /// [`TransactionBehavior::Concurrent`] through [`Options::with_transaction_behavior`] enables
    /// MVCC for local stores. This option only enables the behavior and does not start a
    /// checkpoint. It is rejected by remote sync stores, and the crate's schema and queries are
    /// unchanged.
    pub fn with_mvcc_passive_checkpoint(mut self) -> Self {
        self.mvcc_passive_checkpoint = true;
        self
    }

    /// Set the behavior used by every transaction opened through this store.
    ///
    /// Turso stores one [`TransactionBehavior`] per connection, and a later call replaces the
    /// earlier value, so the four behaviors are mutually exclusive rather than composable. Calling
    /// this method more than once is allowed and the last call wins.
    ///
    /// - [`TransactionBehavior::Deferred`] (the default) starts the transaction on first access.
    /// - [`TransactionBehavior::Immediate`] acquires the write lock at `BEGIN`.
    /// - [`TransactionBehavior::Exclusive`] prevents other connections from reading while the
    ///   transaction is open.
    /// - [`TransactionBehavior::Concurrent`] allows parallel writers with conflicts detected at
    ///   commit.
    ///
    /// Selecting `Concurrent` switches a local database to MVCC journal mode when the store is
    /// opened. Turso rejects DDL inside `BEGIN CONCURRENT`, so [`Store::migrate`] and
    /// [`Store::migrate_to`] still use a `Deferred` transaction for schema changes. `Concurrent` is
    /// rejected by remote sync stores and cannot be combined with
    /// [`Options::with_multiprocess_wal`] (MVCC does not support multi-process access); those
    /// combinations return `Error::UnsupportedOption` or [`Error::ConflictingOptions`]
    /// respectively. The crate's read and write queries otherwise run under the selected behavior.
    pub fn with_transaction_behavior(mut self, behavior: TransactionBehavior) -> Self {
        self.transaction_behavior = Some(behavior);
        self
    }

    /// Configure local at-rest encryption using Turso's cipher name and hexadecimal key.
    ///
    /// Keep the key secret and use the same settings whenever reopening the database. Encrypted
    /// local files cannot be opened by SQLite-compatible backends. Remote sync stores cannot use
    /// local at-rest encryption; use `with_remote_encryption` for Turso Cloud encryption instead.
    /// Cloud encryption does not encrypt the local sync cache.
    pub fn with_encryption(mut self, encryption: EncryptionOpts) -> Self {
        self.encryption = Some(encryption);
        self
    }

    /// Configure Turso Cloud encryption with a base64-encoded key and cipher.
    ///
    /// This setting is available with the `remote` feature and only applies to remote stores. It
    /// enables Turso Cloud database encryption; the local sync cache remains unencrypted.
    #[cfg(feature = "remote")]
    pub fn with_remote_encryption(
        mut self,
        base64_key: impl Into<String>,
        cipher: RemoteEncryptionCipher,
    ) -> Self {
        self.remote_encryption = Some((base64_key.into(), cipher));
        self
    }
}

/// Generate local encryption options with a random 32-byte key and the `aes256gcm` cipher.
///
/// Save the returned `hexkey` in a secret manager before opening the database, and reuse these
/// options to reopen it; losing the key makes the data inaccessible.
///
/// ```
/// use bdk_turso::{Options, generate_encryption_opts};
///
/// let encryption = generate_encryption_opts();
/// assert_eq!(encryption.cipher, "aes256gcm");
/// assert_eq!(encryption.hexkey.len(), 64);
/// let options = Options::new().with_encryption(encryption);
/// ```
pub fn generate_encryption_opts() -> EncryptionOpts {
    let key: [u8; 32] = rand::random();
    EncryptionOpts {
        cipher: "aes256gcm".to_owned(),
        hexkey: key.as_slice().to_lower_hex_string(),
    }
}

impl fmt::Debug for Options {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Options")
            .field("index_method", &self.index_method)
            .field("multiprocess_wal", &self.multiprocess_wal)
            .field("vacuum", &self.vacuum)
            .field("attach", &self.attach)
            .field("generated_columns", &self.generated_columns)
            .field("without_rowid", &self.without_rowid)
            .field("mvcc_passive_checkpoint", &self.mvcc_passive_checkpoint)
            .field(
                "transaction_behavior",
                &match self.transaction_behavior {
                    None | Some(TransactionBehavior::Deferred) => "deferred",
                    Some(TransactionBehavior::Immediate) => "immediate",
                    Some(TransactionBehavior::Exclusive) => "exclusive",
                    Some(TransactionBehavior::Concurrent) => "concurrent",
                    Some(_) => "unknown",
                },
            )
            .field("encryption_enabled", &self.encryption.is_some())
            .field("remote_encryption_enabled", &{
                #[cfg(feature = "remote")]
                {
                    self.remote_encryption.is_some()
                }
                #[cfg(not(feature = "remote"))]
                {
                    false
                }
            })
            .finish()
    }
}

/// An asynchronous store for BDK wallet changesets backed by Turso.
///
/// Local stores use Turso in process. With the `remote` feature, remote stores keep a local sync
/// cache and synchronize changes with Turso Cloud. Call [`Store::migrate`] before using low-level
/// read/write methods; `AsyncWalletPersister` initialization performs migration automatically.
///
/// Do not run `bdk_sqlite::Store::migrate()` on this database. Since it has no SQLx migration
/// history, `bdk_sqlite` will run migrations containing `DROP TABLE IF EXISTS` statements and
/// erase the existing wallet state.
#[derive(Clone)]
pub struct Store {
    pub(crate) database: StoreDatabase,
    options: Option<Options>,
}

#[derive(Clone)]
pub(crate) enum StoreDatabase {
    Local(LocalDatabase),
    #[cfg(feature = "remote")]
    Remote(turso::sync::Database),
}

impl fmt::Debug for Store {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Store")
            .field(
                "backend",
                &match &self.database {
                    StoreDatabase::Local(_) => "local",
                    #[cfg(feature = "remote")]
                    StoreDatabase::Remote(_) => "remote",
                },
            )
            .field("options", &self.options)
            .finish()
    }
}

impl Store {
    /// Create an in-memory database with all experimental options disabled.
    ///
    /// The database exists for the lifetime of the returned store and is not persisted to a file.
    /// Use [`Store::new_memory_with_options`] when an in-memory database needs experimental
    /// features.
    pub async fn new_memory() -> Result<Self, Error> {
        Self::new_memory_with_options(Options::default()).await
    }

    /// Create an in-memory database using the supplied experimental options.
    ///
    /// The options are applied while Turso opens the database. The database remains in memory for
    /// the lifetime of the store and is not persisted to disk.
    pub async fn new_memory_with_options(options: Options) -> Result<Self, Error> {
        Self::new_with_options(":memory:", options).await
    }

    /// Create or open a local database using default options.
    ///
    /// This constructor leaves all experimental options disabled. It does not create the BDK
    /// schema; call [`Store::migrate`] before using the persistence methods, unless the store is
    /// initialized through `AsyncWalletPersister`.
    pub async fn new(path: &str) -> Result<Self, Error> {
        Self::new_with_options(path, Options::default()).await
    }

    /// Create or open a local database with the supplied Turso options.
    ///
    /// The options are applied only while opening the database. All experimental features remain
    /// disabled unless explicitly enabled on `options`. This constructor does not run the BDK
    /// schema migration; call [`Store::migrate`] before using the persistence methods.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use bdk_turso::{Options, Store};
    ///
    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// let options = Options::new().with_attach().with_generated_columns();
    /// let store = Store::new_with_options("wallet.sqlite", options).await?;
    /// store.migrate().await?;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn new_with_options(path: &str, options: Options) -> Result<Self, Error> {
        if options.multiprocess_wal
            && matches!(
                options.transaction_behavior,
                Some(TransactionBehavior::Concurrent)
            )
        {
            return Err(Error::ConflictingOptions(
                "`with_multiprocess_wal` cannot be combined with `TransactionBehavior::Concurrent`: Turso's MVCC mode does not support multi-process access".into(),
            ));
        }

        #[cfg(feature = "remote")]
        if options.remote_encryption.is_some() {
            return Err(Error::UnsupportedOption(
                "remote encryption can only be used with Store::new_remote_with_options".into(),
            ));
        }

        let mut builder = Builder::new_local(path)
            .experimental_index_method(options.index_method)
            .experimental_multiprocess_wal(options.multiprocess_wal)
            .experimental_vacuum(options.vacuum)
            .experimental_attach(options.attach)
            .experimental_generated_columns(options.generated_columns)
            .experimental_without_rowid(options.without_rowid)
            .experimental_mvcc_passive_checkpoint(options.mvcc_passive_checkpoint);

        if let Some(encryption) = &options.encryption {
            builder = builder
                .experimental_encryption(true)
                .with_encryption(encryption.clone());
        }

        let database = builder.build().await?;
        if matches!(
            options.transaction_behavior,
            Some(TransactionBehavior::Concurrent)
        ) {
            enable_mvcc(&database).await?;
        }
        Ok(Self {
            database: StoreDatabase::Local(database),
            options: Some(options),
        })
    }

    /// Connect to a Turso Cloud database using a local sync cache.
    ///
    /// This constructor requires the `remote` feature. `local_path` is the on-device cache file,
    /// while `remote_url` and `auth_token` are supplied by the caller. Reads pull remote changes
    /// before accessing the cache, and committed writes are pushed to Turso Cloud. If a push fails
    /// after a local commit, the method returns an error but the cache may contain the write; retry
    /// the same persistence operation to retry its upload. Use a disposable remote database for
    /// integration testing.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # #[cfg(feature = "remote")]
    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// use bdk_turso::Store;
    ///
    /// let store = Store::new_remote(
    ///     "wallet-cache.db",
    ///     "libsql://your-database.turso.io",
    ///     "your-auth-token",
    /// ).await?;
    /// store.migrate().await?;
    /// # Ok(())
    /// # }
    /// ```
    #[cfg(feature = "remote")]
    pub async fn new_remote(
        local_path: &str,
        remote_url: &str,
        auth_token: &str,
    ) -> Result<Self, Error> {
        Self::new_remote_with_options(local_path, remote_url, auth_token, Options::default()).await
    }

    /// Connect to Turso Cloud using a local cache and the supplied database options.
    ///
    /// Local at-rest encryption and MVCC passive checkpointing are unsupported in sync mode and
    /// return an error. Use [`Options::with_remote_encryption`] for Turso Cloud encryption; this
    /// does not encrypt the local cache. The remaining experimental engine options are forwarded to
    /// Turso's sync builder.
    #[cfg(feature = "remote")]
    pub async fn new_remote_with_options(
        local_path: &str,
        remote_url: &str,
        auth_token: &str,
        options: Options,
    ) -> Result<Self, Error> {
        if options.encryption.is_some() {
            return Err(Error::UnsupportedOption(
                "local at-rest encryption is unsupported in remote sync mode; use `with_remote_encryption` for Turso Cloud encryption (the local cache remains unencrypted)".into(),
            ));
        }
        if options.mvcc_passive_checkpoint {
            return Err(Error::UnsupportedOption(
                "MVCC passive checkpointing is not supported by Turso's remote sync builder".into(),
            ));
        }
        if matches!(
            options.transaction_behavior,
            Some(TransactionBehavior::Concurrent)
        ) {
            return Err(Error::UnsupportedOption(
                "Concurrent transaction behavior requires MVCC and is not supported by Turso's remote sync builder".into(),
            ));
        }

        let mut builder = turso::sync::Builder::new_remote(local_path)
            .with_remote_url(remote_url)
            .with_auth_token(auth_token)
            .experimental_index_method(options.index_method)
            .experimental_multiprocess_wal(options.multiprocess_wal)
            .experimental_vacuum(options.vacuum)
            .experimental_attach(options.attach)
            .experimental_generated_columns(options.generated_columns)
            .experimental_without_rowid(options.without_rowid);

        if let Some((key, cipher)) = &options.remote_encryption {
            builder = builder.with_remote_encryption(key.clone(), *cipher);
        }

        let database = builder.build().await?;
        Ok(Self {
            database: StoreDatabase::Remote(database),
            options: Some(options),
        })
    }

    /// Wrap an already-open local Turso database in a `Store`.
    ///
    /// This does not open a path or run the BDK schema migration. Call [`Store::migrate`] before
    /// using persistence methods. Because the database was created externally, its opening options
    /// are not inferred by the store.
    pub fn from_database(database: LocalDatabase) -> Self {
        Self {
            database: StoreDatabase::Local(database),
            options: None,
        }
    }

    /// Return the options retained by this store, if they are known.
    ///
    /// Stores created with a constructor retain the configuration passed to Turso. Stores wrapped
    /// with [`Store::from_database`] return `None` because the database's original settings cannot
    /// be inferred.
    pub fn options(&self) -> Option<&Options> {
        self.options.as_ref()
    }

    pub(crate) async fn connect(&self) -> Result<Connection, Error> {
        self.connect_with_behavior(self.configured_transaction_behavior())
            .await
    }

    fn configured_transaction_behavior(&self) -> TransactionBehavior {
        self.options
            .as_ref()
            .and_then(|options| options.transaction_behavior)
            .unwrap_or(TransactionBehavior::Deferred)
    }

    async fn connect_with_behavior(
        &self,
        transaction_behavior: TransactionBehavior,
    ) -> Result<Connection, Error> {
        match &self.database {
            StoreDatabase::Local(database) => {
                let mut connection = database.connect()?;
                connection.busy_timeout(BUSY_TIMEOUT)?;
                connection.set_transaction_behavior(transaction_behavior);
                Ok(connection)
            }
            #[cfg(feature = "remote")]
            StoreDatabase::Remote(database) => {
                database.pull().await?;
                let mut connection = database.connect().await?;
                connection.busy_timeout(BUSY_TIMEOUT)?;
                connection.set_transaction_behavior(transaction_behavior);
                Ok(connection)
            }
        }
    }

    /// Push locally committed changes from the cache to Turso Cloud.
    ///
    /// Remote persistence methods call this after committing local changes. If an upload fails,
    /// call `push` to retry it without reapplying the changeset. This is a no-op for local stores
    /// and does not pull remote changes.
    pub async fn push(&self) -> Result<(), Error> {
        match &self.database {
            StoreDatabase::Local(_) => Ok(()),
            #[cfg(feature = "remote")]
            StoreDatabase::Remote(database) => database.push().await.map_err(Error::RemotePush),
        }
    }

    /// Apply the default schema and schemas for enabled features in a transaction.
    ///
    /// Core chain and transaction tables are always created. Wallet-specific tables are created
    /// only with the `wallet` feature, and the PSBT table only with `psbt`. This migration is safe
    /// to run repeatedly; `AsyncWalletPersister::initialize` runs it for you when enabled.
    ///
    /// DDL runs in a `Deferred` transaction even when the store uses another transaction behavior,
    /// because Turso rejects DDL inside `BEGIN CONCURRENT`.
    pub async fn migrate(&self) -> Result<(), Error> {
        let mut conn = self
            .connect_with_behavior(TransactionBehavior::Deferred)
            .await?;
        let txn = conn.transaction().await?;
        txn.execute_batch(include_str!("../migrations/0001_default_schema.up.sql"))
            .await?;
        #[cfg(feature = "wallet")]
        txn.execute_batch(include_str!("../migrations/0002_wallet_schema.up.sql"))
            .await?;
        #[cfg(feature = "psbt")]
        txn.execute_batch(include_str!("../migrations/0003_psbt.up.sql"))
            .await?;
        txn.commit().await?;
        drop(conn);
        self.push().await?;
        Ok(())
    }

    /// Copy tables, indexes, and rows present in this store to `destination` without running schema
    /// migrations.
    ///
    /// Existing tables must have compatible column definitions. Source rows replace destination
    /// rows on key conflicts, while destination-only rows and tables remain. Indexes are copied
    /// after rows are transferred; an index that already exists in the destination must have the
    /// same definition. The destination is expected to be empty, though merging into an existing
    /// store is supported. The transfer is atomic on the destination; the source is unchanged.
    /// Feature-gated tables are discovered from the database itself, so this also works when the
    /// stores were opened with different features or wrapped with [`Store::from_database`].
    /// Internal SQLite and Turso tables are not copied. Both the source and destination are read
    /// through their own transactions, and remote stores pull before access. The destination is
    /// pushed after the local transaction commits; a failed remote push may leave the destination's
    /// local cache updated.
    ///
    /// Both connections use a `Deferred` transaction behavior, because Turso rejects DDL inside
    /// `BEGIN CONCURRENT` and this method creates tables and indexes on the destination.
    pub async fn migrate_to(&self, destination: &Store) -> Result<(), Error> {
        let mut source_conn = self
            .connect_with_behavior(TransactionBehavior::Deferred)
            .await?;
        let mut destination_conn = destination
            .connect_with_behavior(TransactionBehavior::Deferred)
            .await?;
        let (source_tables, source_columns, source_indexes) = {
            let source_txn = source_conn.transaction().await?;
            let source_tables = Self::user_tables(&source_txn).await?;
            let source_table_names = source_tables
                .iter()
                .map(|(name, _)| name.to_ascii_lowercase())
                .collect::<std::collections::HashSet<_>>();
            let mut source_columns: std::collections::HashMap<String, Vec<TableColumn>> =
                std::collections::HashMap::new();
            for (name, _) in &source_tables {
                let columns = Self::table_columns(&source_txn, name).await?;
                source_columns.insert(name.to_ascii_lowercase(), columns);
            }
            let source_indexes = Self::user_indexes(&source_txn)
                .await?
                .into_iter()
                .filter(|(_, table, _)| source_table_names.contains(&table.to_ascii_lowercase()))
                .collect::<Vec<_>>();
            source_txn.commit().await?;
            (source_tables, source_columns, source_indexes)
        };
        let destination_tables = Self::user_tables(&destination_conn).await?;
        let destination_names = destination_tables
            .iter()
            .map(|(name, _)| name.to_ascii_lowercase())
            .collect::<std::collections::HashSet<_>>();
        let mut destination_columns: std::collections::HashMap<String, Vec<TableColumn>> =
            std::collections::HashMap::new();
        for (name, _) in &destination_tables {
            let columns = Self::table_columns(&destination_conn, name).await?;
            destination_columns.insert(name.to_ascii_lowercase(), columns);
        }
        let destination_indexes = Self::user_indexes(&destination_conn)
            .await?
            .into_iter()
            .map(|(name, _, sql)| (name.to_ascii_lowercase(), sql))
            .collect::<std::collections::HashMap<_, _>>();

        let source_txn = source_conn.transaction().await?;
        let destination_txn = destination_conn.transaction().await?;
        for (table, create_sql) in source_tables {
            if create_sql
                .trim_start()
                .to_ascii_lowercase()
                .starts_with("create virtual table")
            {
                return Err(Error::Migration(format!(
                    "virtual table `{table}` is outside the supported SQLite-compatible subset"
                )));
            }

            let columns = source_columns
                .get(&table.to_ascii_lowercase())
                .cloned()
                .ok_or_else(|| {
                    Error::Migration(format!("missing column metadata for `{table}`"))
                })?;
            if columns.is_empty() {
                return Err(Error::Migration(format!(
                    "table `{table}` has no transferable columns"
                )));
            }

            if destination_names.contains(&table.to_ascii_lowercase()) {
                if let Some(destination_columns) =
                    destination_columns.get(&table.to_ascii_lowercase())
                    && columns != *destination_columns
                {
                    return Err(Error::Migration(format!(
                        "table `{table}` has incompatible column definitions in the destination"
                    )));
                }
            } else {
                destination_txn.execute_batch(&create_sql).await?;
            }

            let quoted_table = Self::quote_identifier(&table);
            let quoted_columns = columns
                .iter()
                .map(|(name, _, _, _, _)| Self::quote_identifier(name))
                .collect::<Vec<_>>();
            let select_sql = format!("SELECT {} FROM {quoted_table}", quoted_columns.join(", "));
            let insert_sql = format!(
                "INSERT OR REPLACE INTO {quoted_table} ({}) VALUES ({})",
                quoted_columns.join(", "),
                (1..=columns.len())
                    .map(|index| format!("?{index}"))
                    .collect::<Vec<_>>()
                    .join(", ")
            );
            let mut rows = source_txn.query(select_sql, ()).await?;
            while let Some(row) = rows.next().await? {
                let values = (0..columns.len())
                    .map(|index| row.get_value(index))
                    .collect::<turso::Result<Vec<_>>>()?;
                destination_txn.execute(&insert_sql, values).await?;
            }
        }

        for (index, table, create_sql) in source_indexes {
            match destination_indexes.get(&index.to_ascii_lowercase()) {
                Some(existing) if existing != &create_sql => {
                    return Err(Error::Migration(format!(
                        "index `{index}` on `{table}` has an incompatible definition in the destination"
                    )));
                }
                Some(_) => {}
                None => destination_txn.execute_batch(&create_sql).await?,
            }
        }

        destination_txn.commit().await?;
        source_txn.commit().await?;
        drop(destination_conn);
        destination.push().await?;
        Ok(())
    }

    async fn user_tables(conn: &Connection) -> Result<Vec<(String, String)>, Error> {
        let mut rows = conn
            .query(
                "SELECT name, sql FROM sqlite_master WHERE type = 'table' AND sql IS NOT NULL AND lower(substr(name, 1, 7)) != 'sqlite_' AND lower(substr(name, 1, 6)) != 'turso_' AND lower(substr(name, 1, 8)) != '__turso_' ORDER BY name",
                (),
            )
            .await?;
        let mut tables = Vec::new();
        while let Some(row) = rows.next().await? {
            tables.push((row.get(0)?, row.get(1)?));
        }
        Ok(tables)
    }

    async fn user_indexes(conn: &Connection) -> Result<Vec<(String, String, String)>, Error> {
        let mut rows = conn
            .query(
                "SELECT name, tbl_name, sql FROM sqlite_master WHERE type = 'index' AND sql IS NOT NULL ORDER BY name",
                (),
            )
            .await?;
        let mut indexes = Vec::new();
        while let Some(row) = rows.next().await? {
            indexes.push((row.get(0)?, row.get(1)?, row.get(2)?));
        }
        Ok(indexes)
    }

    async fn table_columns(conn: &Connection, table: &str) -> Result<Vec<TableColumn>, Error> {
        let mut rows = conn
            .query(
                format!("PRAGMA table_info({})", Self::quote_identifier(table)),
                (),
            )
            .await?;
        let mut columns = Vec::new();
        while let Some(row) = rows.next().await? {
            columns.push((
                row.get(1)?,
                row.get(2)?,
                row.get::<i64>(3)?,
                row.get_value(4)?,
                row.get::<i64>(5)?,
            ));
        }
        Ok(columns)
    }

    fn quote_identifier(identifier: &str) -> String {
        format!("\"{}\"", identifier.replace('"', "\"\""))
    }

    /// Persist transaction-graph changes in a transaction owned by this store.
    ///
    /// Transactions, timestamps, outputs, and anchors are written together. For an atomic write of
    /// the complete wallet state, use the wallet changeset persister instead.
    pub async fn write_tx_graph(
        &self,
        tx_graph: &tx_graph::ChangeSet<ConfirmationBlockTime>,
    ) -> Result<(), Error> {
        let mut conn = self.connect().await?;
        let txn = conn.transaction().await?;
        Self::write_tx_graph_in_transaction(&txn, tx_graph).await?;
        txn.commit().await?;
        drop(conn);
        self.push().await?;
        Ok(())
    }

    pub(crate) async fn write_tx_graph_in_transaction(
        conn: &DatabaseTransaction<'_>,
        tx_graph: &tx_graph::ChangeSet<ConfirmationBlockTime>,
    ) -> Result<(), Error> {
        for tx in &tx_graph.txs {
            let txid = tx.compute_txid();
            conn.execute(
                "INSERT INTO tx(txid, tx) VALUES(?1, ?2) ON CONFLICT DO UPDATE SET tx = ?2",
                (txid.to_string(), consensus::encode::serialize(tx)),
            )
            .await?;
        }
        for (txid, time) in &tx_graph.first_seen {
            conn.execute(
                "INSERT INTO tx(txid, first_seen) VALUES(?1, ?2) ON CONFLICT DO UPDATE SET first_seen = ?2",
                (txid.to_string(), i64::try_from(*time)?),
            )
            .await?;
        }
        for (txid, time) in &tx_graph.last_seen {
            conn.execute(
                "INSERT INTO tx(txid, last_seen) VALUES(?1, ?2) ON CONFLICT DO UPDATE SET last_seen = ?2",
                (txid.to_string(), i64::try_from(*time)?),
            )
            .await?;
        }
        for (txid, time) in &tx_graph.last_evicted {
            conn.execute(
                "INSERT INTO tx(txid, last_evicted) VALUES(?1, ?2) ON CONFLICT DO UPDATE SET last_evicted = ?2",
                (txid.to_string(), i64::try_from(*time)?),
            )
            .await?;
        }
        for (outpoint, txout) in &tx_graph.txouts {
            let OutPoint { txid, vout } = outpoint;
            let TxOut {
                value,
                script_pubkey,
            } = txout;
            conn.execute(
                "INSERT INTO txout(txid, vout, value, script) VALUES(?1, ?2, ?3, ?4) ON CONFLICT DO UPDATE SET value = ?3, script = ?4",
                (
                    txid.to_string(),
                    i64::from(*vout),
                    i64::try_from(value.to_sat())?,
                    script_pubkey.to_bytes(),
                ),
            )
            .await?;
        }
        for (anchor, txid) in &tx_graph.anchors {
            let BlockId { height, hash } = anchor.block_id;
            conn.execute(
                "INSERT INTO anchor(block_height, block_hash, txid, confirmation_time) VALUES(?1, ?2, ?3, ?4) ON CONFLICT DO UPDATE SET confirmation_time = ?4",
                (
                    i64::from(height),
                    hash.to_string(),
                    txid.to_string(),
                    i64::try_from(anchor.confirmation_time)?,
                ),
            )
            .await?;
        }

        Ok(())
    }

    /// Apply local-chain block changes in a transaction owned by this store.
    ///
    /// A block with a hash is inserted at its height if that height is not already present; a block
    /// with no hash removes the row at that height.
    pub async fn write_local_chain(
        &self,
        local_chain: &local_chain::ChangeSet,
    ) -> Result<(), Error> {
        let mut conn = self.connect().await?;
        let txn = conn.transaction().await?;
        Self::write_local_chain_in_transaction(&txn, local_chain).await?;
        txn.commit().await?;
        drop(conn);
        self.push().await?;
        Ok(())
    }

    pub(crate) async fn write_local_chain_in_transaction(
        conn: &DatabaseTransaction<'_>,
        local_chain: &local_chain::ChangeSet,
    ) -> Result<(), Error> {
        for (&height, hash) in &local_chain.blocks {
            match hash {
                Some(hash) => {
                    conn.execute(
                        "INSERT INTO block(height, hash) VALUES(?1, ?2) ON CONFLICT(height) DO UPDATE SET hash = ?2",
                        (i64::from(height), hash.to_string()),
                    )
                    .await?;
                }
                None => {
                    conn.execute("DELETE FROM block WHERE height = ?1", [i64::from(height)])
                        .await?;
                }
            }
        }

        Ok(())
    }

    /// Persist keychain reveal indices and cached scripts in a store-owned transaction.
    ///
    /// Reveal indices and cached scripts are updated when present in the changeset.
    pub async fn write_keychain_txout(
        &self,
        keychain_txout: &keychain_txout::ChangeSet,
    ) -> Result<(), Error> {
        let mut conn = self.connect().await?;
        let txn = conn.transaction().await?;
        Self::write_keychain_txout_in_transaction(&txn, keychain_txout).await?;
        txn.commit().await?;
        drop(conn);
        self.push().await?;
        Ok(())
    }

    pub(crate) async fn write_keychain_txout_in_transaction(
        conn: &DatabaseTransaction<'_>,
        keychain_txout: &keychain_txout::ChangeSet,
    ) -> Result<(), Error> {
        for (descriptor_id, last_revealed) in &keychain_txout.last_revealed {
            conn.execute(
                "INSERT INTO keychain_last_revealed(descriptor_id, last_revealed) VALUES(?1, ?2) ON CONFLICT DO UPDATE SET last_revealed = ?2",
                (descriptor_id.to_string(), i64::from(*last_revealed)),
            )
            .await?;
        }
        for (descriptor_id, spk_cache) in &keychain_txout.spk_cache {
            for (derivation_index, script) in spk_cache {
                conn.execute(
                    "INSERT INTO keychain_script_pubkey(descriptor_id, derivation_index, script) VALUES(?1, ?2, ?3) ON CONFLICT(descriptor_id, derivation_index) DO UPDATE SET script = ?3",
                    (
                        descriptor_id.to_string(),
                        i64::from(*derivation_index),
                        script.to_bytes(),
                    ),
                )
                .await?;
            }
        }

        Ok(())
    }

    /// Read transaction-graph changes through a transaction owned by this store.
    ///
    /// Returns the persisted transactions, timestamps, outputs, and confirmation anchors.
    pub async fn read_tx_graph(&self) -> Result<tx_graph::ChangeSet<ConfirmationBlockTime>, Error> {
        let mut conn = self.connect().await?;
        let txn = conn.transaction().await?;
        let changeset = Self::read_tx_graph_in_transaction(&txn).await?;
        txn.commit().await?;
        Ok(changeset)
    }

    pub(crate) async fn read_tx_graph_in_transaction(
        conn: &DatabaseTransaction<'_>,
    ) -> Result<tx_graph::ChangeSet<ConfirmationBlockTime>, Error> {
        let mut changeset = tx_graph::ChangeSet::default();

        let mut rows = conn
            .query(
                "SELECT txid, tx, first_seen, last_seen, last_evicted FROM tx",
                (),
            )
            .await?;
        while let Some(row) = rows.next().await? {
            let txid: Txid = row.get::<String>(0)?.parse()?;
            let tx: Option<Vec<u8>> = row.get(1)?;
            let first_seen: Option<i64> = row.get(2)?;
            let last_seen: Option<i64> = row.get(3)?;
            let last_evicted: Option<i64> = row.get(4)?;
            if let Some(data) = tx {
                let tx: Transaction = consensus::encode::deserialize(&data)?;
                changeset.txs.insert(Arc::new(tx));
            }
            if let Some(first_seen) = first_seen {
                changeset.first_seen.insert(txid, first_seen.try_into()?);
            }
            if let Some(last_seen) = last_seen {
                changeset.last_seen.insert(txid, last_seen.try_into()?);
            }
            if let Some(last_evicted) = last_evicted {
                changeset
                    .last_evicted
                    .insert(txid, last_evicted.try_into()?);
            }
        }

        let mut rows = conn
            .query("SELECT txid, vout, value, script FROM txout", ())
            .await?;
        while let Some(row) = rows.next().await? {
            let txid: Txid = row.get::<String>(0)?.parse()?;
            let vout = u32::try_from(row.get::<i64>(1)?)?;
            let value = Amount::from_sat(u64::try_from(row.get::<i64>(2)?)?);
            let script_pubkey = ScriptBuf::from_bytes(row.get::<Vec<u8>>(3)?);
            changeset.txouts.insert(
                OutPoint { txid, vout },
                TxOut {
                    value,
                    script_pubkey,
                },
            );
        }

        let mut rows = conn
            .query(
                "SELECT block_height, block_hash, txid, confirmation_time FROM anchor",
                (),
            )
            .await?;
        while let Some(row) = rows.next().await? {
            let height = u32::try_from(row.get::<i64>(0)?)?;
            let hash: BlockHash = row.get::<String>(1)?.parse()?;
            let txid: Txid = row.get::<String>(2)?.parse()?;
            let confirmation_time = u64::try_from(row.get::<i64>(3)?)?;
            changeset.anchors.insert((
                ConfirmationBlockTime {
                    block_id: BlockId { height, hash },
                    confirmation_time,
                },
                txid,
            ));
        }

        Ok(changeset)
    }

    /// Read persisted local-chain blocks through a transaction owned by this store.
    ///
    /// Each stored height and hash is returned as a block entry with a hash.
    pub async fn read_local_chain(&self) -> Result<local_chain::ChangeSet, Error> {
        let mut conn = self.connect().await?;
        let txn = conn.transaction().await?;
        let changeset = Self::read_local_chain_in_transaction(&txn).await?;
        txn.commit().await?;
        Ok(changeset)
    }

    pub(crate) async fn read_local_chain_in_transaction(
        conn: &DatabaseTransaction<'_>,
    ) -> Result<local_chain::ChangeSet, Error> {
        let mut changeset = local_chain::ChangeSet::default();
        let mut rows = conn.query("SELECT height, hash FROM block", ()).await?;
        while let Some(row) = rows.next().await? {
            let height = u32::try_from(row.get::<i64>(0)?)?;
            let hash: BlockHash = row.get::<String>(1)?.parse()?;
            changeset.blocks.insert(height, Some(hash));
        }

        Ok(changeset)
    }

    /// Read persisted reveal indices and cached scripts through a store-owned transaction.
    ///
    /// The returned changeset includes entries present in the database; an empty database yields
    /// empty maps.
    pub async fn read_keychain_txout(&self) -> Result<keychain_txout::ChangeSet, Error> {
        let mut conn = self.connect().await?;
        let txn = conn.transaction().await?;
        let changeset = Self::read_keychain_txout_in_transaction(&txn).await?;
        txn.commit().await?;
        Ok(changeset)
    }

    pub(crate) async fn read_keychain_txout_in_transaction(
        conn: &DatabaseTransaction<'_>,
    ) -> Result<keychain_txout::ChangeSet, Error> {
        let mut changeset = keychain_txout::ChangeSet::default();

        let mut rows = conn
            .query(
                "SELECT descriptor_id, last_revealed FROM keychain_last_revealed",
                (),
            )
            .await?;
        while let Some(row) = rows.next().await? {
            let descriptor_id: DescriptorId = row.get::<String>(0)?.parse()?;
            let last_revealed = u32::try_from(row.get::<i64>(1)?)?;
            changeset.last_revealed.insert(descriptor_id, last_revealed);
        }

        let mut rows = conn
            .query(
                "SELECT descriptor_id, derivation_index, script FROM keychain_script_pubkey",
                (),
            )
            .await?;
        while let Some(row) = rows.next().await? {
            let descriptor_id: DescriptorId = row.get::<String>(0)?.parse()?;
            let derivation_index = u32::try_from(row.get::<i64>(1)?)?;
            let script = ScriptBuf::from_bytes(row.get::<Vec<u8>>(2)?);
            changeset
                .spk_cache
                .entry(descriptor_id)
                .or_default()
                .insert(derivation_index, script);
        }

        Ok(changeset)
    }

    /// Store a PSBT under the txid of its unsigned transaction.
    ///
    /// Writing another PSBT with the same unsigned transaction ID replaces the previous one. The
    /// complete PSBT, including signing metadata, is serialized. Run [`Store::migrate`] first.
    ///
    /// PSBTs can contain partial signatures, so persistence requires a database opened with local
    /// at-rest encryption. Remote sync stores are an exception: their local cache is not encrypted
    /// by Turso Cloud settings, so PSBT persistence is permitted there without local encryption.
    /// Stores created without `Options::with_encryption`, stores created by
    /// [`Store::from_database`] whose opening options are unknown, and local stores without
    /// encryption return [`Error::PsbtRequiresEncryption`].
    #[cfg(feature = "psbt")]
    pub async fn write_psbt(&self, psbt: &bitcoin::Psbt) -> Result<bitcoin::Txid, Error> {
        self.require_encryption()?;
        let txid = psbt.unsigned_tx.compute_txid();
        let mut conn = self.connect().await?;
        let txn = conn.transaction().await?;
        txn.execute(
            "INSERT INTO psbt(unsigned_txid, data) VALUES(?1, ?2) ON CONFLICT(unsigned_txid) DO UPDATE SET data = ?2",
            (txid.to_string(), psbt.serialize()),
        )
        .await?;
        txn.commit().await?;
        drop(conn);
        self.push().await?;
        Ok(txid)
    }

    /// Load the PSBT stored for an unsigned transaction ID.
    ///
    /// Returns `Ok(None)` when no PSBT is stored for `txid`. This method opens and commits its own
    /// read transaction. Run [`Store::migrate`] first. Like [`Store::write_psbt`], this requires a
    /// store opened with local at-rest encryption, except for remote sync stores whose local cache
    /// is not encrypted by Turso Cloud settings.
    #[cfg(feature = "psbt")]
    pub async fn read_psbt(&self, txid: bitcoin::Txid) -> Result<Option<bitcoin::Psbt>, Error> {
        self.require_encryption()?;
        let mut conn = self.connect().await?;
        let txn = conn.transaction().await?;
        let mut rows = txn
            .query(
                "SELECT data FROM psbt WHERE unsigned_txid = ?1",
                [txid.to_string()],
            )
            .await?;
        let data = rows
            .next()
            .await?
            .map(|row| row.get::<Vec<u8>>(0))
            .transpose()?;
        let psbt = data
            .map(|data| bitcoin::Psbt::deserialize(&data))
            .transpose()?;
        txn.commit().await?;
        Ok(psbt)
    }

    /// PSBT persistence requires local at-rest encryption, except for remote sync stores whose
    /// local cache is not encrypted by Turso Cloud settings.
    #[cfg(feature = "psbt")]
    fn require_encryption(&self) -> Result<(), Error> {
        #[cfg(feature = "remote")]
        {
            if matches!(&self.database, StoreDatabase::Remote(_)) {
                return Ok(());
            }
        }
        match self.options.as_ref() {
            Some(options) if options.encryption.is_some() => Ok(()),
            _ => Err(Error::PsbtRequiresEncryption),
        }
    }
}

#[cfg(test)]
mod test {
    use super::*;
    use bitcoin::hashes::Hash;

    #[test]
    fn options_default_to_disabled() {
        let options = Options::new();

        assert!(!options.index_method);
        assert!(!options.multiprocess_wal);
        assert!(!options.vacuum);
        assert!(!options.attach);
        assert!(!options.generated_columns);
        assert!(!options.without_rowid);
        assert!(!options.mvcc_passive_checkpoint);
        assert!(options.transaction_behavior.is_none());
        assert!(options.encryption.is_none());
        #[cfg(feature = "remote")]
        assert!(options.remote_encryption.is_none());
    }

    #[test]
    fn generated_encryption_opts_use_a_random_aes256gcm_key() {
        let first = generate_encryption_opts();
        let second = generate_encryption_opts();

        assert_eq!(first.cipher, "aes256gcm");
        assert_eq!(first.hexkey.len(), 64);
        assert!(first.hexkey.bytes().all(|byte| byte.is_ascii_hexdigit()));
        assert_ne!(first.hexkey, second.hexkey);
    }

    #[cfg(feature = "remote")]
    #[tokio::test]
    async fn unsupported_remote_options_return_actionable_errors() -> anyhow::Result<()> {
        let local_encryption = Options::new().with_encryption(EncryptionOpts {
            cipher: "aes256gcm".to_owned(),
            hexkey: "00".repeat(32),
        });
        let error = Store::new_remote_with_options(
            ":memory:",
            "libsql://unused.turso.io",
            "unused-token",
            local_encryption,
        )
        .await
        .unwrap_err();
        assert!(
            matches!(error, Error::UnsupportedOption(message) if message.contains("local at-rest encryption"))
        );

        let error = Store::new_remote_with_options(
            ":memory:",
            "libsql://unused.turso.io",
            "unused-token",
            Options::new().with_mvcc_passive_checkpoint(),
        )
        .await
        .unwrap_err();
        assert!(
            matches!(error, Error::UnsupportedOption(message) if message.contains("MVCC passive checkpointing"))
        );

        let error = Store::new_remote_with_options(
            ":memory:",
            "libsql://unused.turso.io",
            "unused-token",
            Options::new().with_transaction_behavior(TransactionBehavior::Concurrent),
        )
        .await
        .unwrap_err();
        assert!(
            matches!(error, Error::UnsupportedOption(message) if message.contains("Concurrent transaction behavior"))
        );

        let remote_encryption = Options::new()
            .with_remote_encryption("unused-key", turso::sync::RemoteEncryptionCipher::Aes256Gcm);
        let error = Store::new_with_options(":memory:", remote_encryption)
            .await
            .unwrap_err();
        assert!(
            matches!(error, Error::UnsupportedOption(message) if message.contains("remote encryption"))
        );
        Ok(())
    }

    #[tokio::test]
    async fn wrapped_database_options_are_unknown() -> anyhow::Result<()> {
        let store = Store::new_memory().await?;
        assert!(store.options().is_some());

        let database = Builder::new_local(":memory:").build().await?;
        let wrapped = Store::from_database(database);
        assert!(wrapped.options().is_none());
        Ok(())
    }

    #[tokio::test]
    async fn migrate_creates_default_and_feature_enabled_schemas() -> anyhow::Result<()> {
        let store = Store::new_memory().await?;
        store.migrate().await?;

        let conn = store.connect().await?;
        let mut rows = conn
            .query(
                "SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'block'",
                (),
            )
            .await?;
        assert!(rows.next().await?.is_some());

        let mut rows = conn
            .query(
                "SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'network'",
                (),
            )
            .await?;
        assert_eq!(rows.next().await?.is_some(), cfg!(feature = "wallet"));

        let mut rows = conn
            .query(
                "SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'psbt'",
                (),
            )
            .await?;
        assert_eq!(rows.next().await?.is_some(), cfg!(feature = "psbt"));
        Ok(())
    }

    #[tokio::test]
    async fn migrate_creates_lookup_indexes() -> anyhow::Result<()> {
        let store = Store::new_memory().await?;
        store.migrate().await?;

        let names = index_names(&store).await?;
        for expected in [
            "anchor_block_hash_idx",
            "anchor_txid_idx",
            "block_hash_idx",
            "txout_script_idx",
        ] {
            assert!(
                names.contains(&expected.to_owned()),
                "missing index `{expected}`; found {names:?}"
            );
        }
        #[cfg(feature = "wallet")]
        assert!(
            names.contains(&"keychain_script_pubkey_script_idx".to_owned()),
            "missing wallet script index; found {names:?}"
        );
        Ok(())
    }

    #[tokio::test]
    async fn migrate_to_copies_indexes() -> anyhow::Result<()> {
        let source = Store::new_memory().await?;
        source.migrate().await?;

        let destination = Store::new_memory().await?;
        source.migrate_to(&destination).await?;

        assert_eq!(
            index_names(&source).await?,
            index_names(&destination).await?
        );
        Ok(())
    }

    async fn index_names(store: &Store) -> anyhow::Result<Vec<String>> {
        let conn = store.connect().await?;
        let mut rows = conn
            .query(
                "SELECT name FROM sqlite_master WHERE type = 'index' AND sql IS NOT NULL ORDER BY name",
                (),
            )
            .await?;
        let mut names = Vec::new();
        while let Some(row) = rows.next().await? {
            names.push(row.get::<String>(0)?);
        }
        Ok(names)
    }

    #[test]
    fn transaction_behavior_last_call_wins() {
        let options = Options::new()
            .with_transaction_behavior(TransactionBehavior::Immediate)
            .with_transaction_behavior(TransactionBehavior::Exclusive);

        assert!(matches!(
            options.transaction_behavior,
            Some(TransactionBehavior::Exclusive)
        ));
    }

    #[tokio::test]
    async fn multiprocess_wal_conflicts_with_concurrent() -> anyhow::Result<()> {
        let error = Store::new_memory_with_options(
            Options::new()
                .with_multiprocess_wal()
                .with_transaction_behavior(TransactionBehavior::Concurrent),
        )
        .await
        .unwrap_err();

        assert!(
            matches!(error, Error::ConflictingOptions(message) if message.contains("multiprocess"))
        );
        Ok(())
    }

    #[tokio::test]
    async fn concurrent_transaction_behavior_enables_mvcc() -> anyhow::Result<()> {
        let store = Store::new_memory_with_options(
            Options::new().with_transaction_behavior(TransactionBehavior::Concurrent),
        )
        .await?;
        store.migrate().await?;

        let conn = store.connect().await?;
        let mut rows = conn.query("PRAGMA journal_mode", ()).await?;
        let row = rows
            .next()
            .await?
            .expect("journal_mode should return a row");
        assert_eq!(row.get::<String>(0)?, "mvcc");

        let mut changeset = local_chain::ChangeSet::default();
        changeset.blocks.insert(7, Some(Hash::hash(b"concurrent")));
        store.write_local_chain(&changeset).await?;
        assert_eq!(store.read_local_chain().await?, changeset);
        Ok(())
    }

    #[tokio::test]
    async fn each_transaction_behavior_can_write() -> anyhow::Result<()> {
        for behavior in [
            TransactionBehavior::Deferred,
            TransactionBehavior::Immediate,
            TransactionBehavior::Exclusive,
        ] {
            let store =
                Store::new_memory_with_options(Options::new().with_transaction_behavior(behavior))
                    .await?;
            store.migrate().await?;

            let mut changeset = local_chain::ChangeSet::default();
            changeset.blocks.insert(1, Some(Hash::hash(b"behavior")));
            store.write_local_chain(&changeset).await?;
            assert_eq!(store.read_local_chain().await?, changeset);
        }
        Ok(())
    }

    #[tokio::test]
    async fn lookup_queries_use_default_indexes() -> anyhow::Result<()> {
        let store = Store::new_memory().await?;
        store.migrate().await?;
        let conn = store.connect().await?;

        let mut lookups = vec![
            (
                "EXPLAIN QUERY PLAN SELECT height FROM block WHERE hash = 'x'",
                "block_hash_idx",
            ),
            (
                "EXPLAIN QUERY PLAN SELECT txid FROM txout WHERE script = x'00'",
                "txout_script_idx",
            ),
            (
                "EXPLAIN QUERY PLAN SELECT block_height FROM anchor WHERE txid = 'x'",
                "anchor_txid_idx",
            ),
            (
                "EXPLAIN QUERY PLAN SELECT txid FROM anchor WHERE block_hash = 'x'",
                "anchor_block_hash_idx",
            ),
        ];
        #[cfg(feature = "wallet")]
        lookups.push((
            "EXPLAIN QUERY PLAN SELECT descriptor_id FROM keychain_script_pubkey WHERE script = x'00'",
            "keychain_script_pubkey_script_idx",
        ));

        for (sql, index) in lookups {
            let mut rows = conn.query(sql, ()).await?;
            let mut plan = String::new();
            while let Some(row) = rows.next().await? {
                plan.push_str(&row.get::<String>(3)?);
                plan.push('\n');
            }
            assert!(
                plan.contains(index),
                "`{sql}` did not use `{index}`:\n{plan}"
            );
        }
        Ok(())
    }

    #[tokio::test]
    async fn index_method_option_enables_application_index_methods() -> anyhow::Result<()> {
        let store = Store::new_memory_with_options(Options::new().with_index_method()).await?;
        store.migrate().await?;
        let conn = store.connect().await?;
        conn.execute(
            "CREATE TABLE vectors (id INTEGER PRIMARY KEY, embedding)",
            (),
        )
        .await?;
        conn.execute_batch(
            "INSERT INTO vectors VALUES (1, vector32_sparse('[1, 0, 1]'));
             INSERT INTO vectors VALUES (2, vector32_sparse('[2, 0, 1]'));
             INSERT INTO vectors VALUES (3, vector32_sparse('[3, 0, 1]'));",
        )
        .await?;
        conn.execute(
            "CREATE INDEX vectors_idx ON vectors USING toy_vector_sparse_ivf (embedding)",
            (),
        )
        .await?;

        let mut rows = conn
            .query(
                "SELECT id FROM vectors ORDER BY vector_distance_jaccard(embedding, vector32_sparse('[3, 0, 1]')) LIMIT 1",
                (),
            )
            .await?;
        let row = rows
            .next()
            .await?
            .expect("index method should return a row");
        assert_eq!(row.get::<i64>(0)?, 3);
        Ok(())
    }

    #[tokio::test]
    async fn block_table_height_rebases_reorgs() -> anyhow::Result<()> {
        let mut changeset = local_chain::ChangeSet::default();
        changeset.blocks.insert(0, Some(Hash::hash(b"0")));
        changeset.blocks.insert(1, Some(Hash::hash(b"1")));

        let store = Store::new_memory().await?;
        store.migrate().await?;
        store.write_local_chain(&changeset).await?;

        changeset.blocks.insert(1, Some(Hash::hash(b"1a")));
        store.write_local_chain(&changeset).await?;

        let conn = store.connect().await?;
        let mut rows = conn
            .query("SELECT height, hash FROM block WHERE height = 1", ())
            .await?;
        let row = rows.next().await?.expect("expected block row");
        let row_hash: String = row.get(1)?;
        let expected_hash = BlockHash::hash(b"1a").to_string();
        assert_eq!(row_hash, expected_hash);

        let mut changeset = local_chain::ChangeSet::default();
        changeset.blocks.insert(1, None);
        store.write_local_chain(&changeset).await?;

        changeset.blocks.insert(1, Some(Hash::hash(b"1a")));
        store.write_local_chain(&changeset).await?;

        let conn = store.connect().await?;
        let mut rows = conn
            .query("SELECT height, hash FROM block WHERE height = 1", ())
            .await?;
        let row = rows.next().await?.expect("expected block row");
        let row_hash: String = row.get(1)?;
        let expected_hash = BlockHash::hash(b"1a").to_string();
        assert_eq!(row_hash, expected_hash);

        Ok(())
    }
}