-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathlib.rs
More file actions
2026 lines (1812 loc) · 71.2 KB
/
Copy pathlib.rs
File metadata and controls
2026 lines (1812 loc) · 71.2 KB
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
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::sync::atomic::{AtomicU8, Ordering};
use serde::Serialize;
use sqlx_sqlite_conn_mgr::Migrator;
use tauri::{AppHandle, Emitter, Manager, RunEvent, Runtime, plugin::Builder as PluginBuilder};
use tokio::sync::{Notify, RwLock};
use tracing::{debug, error, info, trace, warn};
mod commands;
mod error;
mod subscriptions;
mod validate;
pub use error::{Error, Result};
pub use sqlx_sqlite_conn_mgr::{
AttachedMode, AttachedSpec, Migrator as SqliteMigrator, SqliteDatabaseConfig,
};
pub use sqlx_sqlite_toolkit::{
ActiveInterruptibleTransactions, ActiveRegularTransactions, DatabaseWrapper,
InterruptibleTransaction, InterruptibleTransactionBuilder, Statement,
TransactionExecutionBuilder, WriteQueryResult,
};
use crate::subscriptions::ActiveSubscriptions;
/// Default maximum number of concurrently loaded databases.
const DEFAULT_MAX_DATABASES: usize = 50;
/// Upper bound on how long close/cleanup may run before returning a timeout error.
const CLOSE_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(5);
/// Tracks cleanup progress during app exit: 0 = not started, 1 = running, 2 = complete.
static CLEANUP_STATE: AtomicU8 = AtomicU8::new(0);
/// Guarantees `CLEANUP_STATE` reaches `2` and `app_handle.exit(..)` fires even if the
/// cleanup task panics. Without this, a panic would leave the state at `1` and subsequent
/// user exit attempts would call `prevent_exit()` indefinitely.
///
/// The exit code carried through is whatever the triggering `ExitRequested` carried —
/// `None` (user-initiated close) becomes `0`, `Some(n)` (programmatic
/// `app_handle.exit(n)`) is preserved so application-level exit codes survive the
/// cleanup detour.
struct ExitGuard<R: Runtime> {
app_handle: tauri::AppHandle<R>,
exit_code: i32,
}
impl<R: Runtime> Drop for ExitGuard<R> {
fn drop(&mut self) {
CLEANUP_STATE.store(2, Ordering::SeqCst);
self.app_handle.exit(self.exit_code);
}
}
/// Database instances managed by the plugin.
///
/// This struct maintains a thread-safe map of database paths to their corresponding
/// connection wrappers, with a configurable upper limit on how many databases can be
/// loaded simultaneously.
///
/// The string key is the registered database key.
#[derive(Clone)]
pub struct DbInstances {
pub(crate) inner: Arc<RwLock<HashMap<String, DatabaseWrapper>>>,
pub(crate) max: usize,
}
impl Default for DbInstances {
fn default() -> Self {
Self {
inner: Arc::new(RwLock::new(HashMap::new())),
max: DEFAULT_MAX_DATABASES,
}
}
}
impl DbInstances {
/// Create a new instance with the given maximum database count.
pub fn new(max: usize) -> Self {
Self {
inner: Arc::new(RwLock::new(HashMap::new())),
max,
}
}
}
/// Tracks the paths of all registered databases.
/// The String value of the key is the database identifier, not the path.
/// For example, the value of the key `MAIN` would be something like
/// `/var/lib/myapp/main.db`.
///
/// This key value is what will be used by the caller to interact with the database.
/// For example, when calling `load()` or `execute()`, the caller will pass the key value
/// to identify the database to which they want to connect.
#[derive(Clone, Default)]
pub struct RegisteredDatabases {
pub(crate) database_path_by_key: Arc<HashMap<String, PathBuf>>,
}
/// Contains the information required for registering a database.
///
/// When initializing or setting up the plugin, the caller will pass the path to the database
/// file and the migrator to use for the database.
///
/// This information is then stored in the `RegisteredDatabases` struct, which is used to
/// track the paths of all registered databases.
///
/// The `migrator` is not held by the app state, but rather is only used after
/// initialization to run the migrations for the database.
#[derive(Debug, Clone)]
struct DatabaseInfo {
path: PathBuf,
migrator: Option<Arc<Migrator>>,
}
fn validated_database_info(
path: impl Into<PathBuf>,
migrator: Option<Migrator>,
) -> Result<DatabaseInfo> {
let path = path.into();
Ok(DatabaseInfo {
path: validate::validate_database_path(&path)?,
migrator: migrator.map(Arc::new),
})
}
/// Ensure each registration key maps to a distinct database path.
fn ensure_distinct_database_paths(
database_info_by_key: &HashMap<String, DatabaseInfo>,
) -> Result<()> {
let mut path_to_key = HashMap::new();
for (key, info) in database_info_by_key {
if let Some(existing_key) = path_to_key.insert(info.path.clone(), key.as_str()) {
return Err(Error::InvalidConfig(format!(
"database keys {existing_key} and {key} both register the same path: {}",
info.path.display()
)));
}
}
Ok(())
}
/// Migration status for a database.
#[derive(Debug, Clone)]
pub enum MigrationStatus {
/// Migrations are pending (not yet started)
Pending,
/// Migrations are currently running
Running,
/// Migrations completed successfully
Complete,
/// Migrations failed with an error
Failed(String),
}
/// Tracks migration state for a single database with notification support.
pub struct MigrationState {
pub(crate) status: MigrationStatus,
pub(crate) notify: Arc<Notify>,
pub(crate) events: Vec<MigrationEvent>,
}
impl MigrationState {
fn new() -> Self {
Self {
status: MigrationStatus::Pending,
notify: Arc::new(Notify::new()),
events: Vec::new(),
}
}
fn update_status(&mut self, status: MigrationStatus) {
self.status = status;
self.notify.notify_waiters();
}
fn cache_event(&mut self, event: MigrationEvent) {
self.events.push(event);
}
}
/// Tracks migration state for all databases.
/// The String value of the key is the database identifier, not the path.
#[derive(Default)]
pub struct MigrationStates(pub RwLock<HashMap<String, MigrationState>>);
/// Event payload emitted during migration operations.
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct MigrationEvent {
/// Database key, meant to be human readable (such as `MAIN`).
/// This is what is to be used by the client to interact with the database.
pub db_key: String,
/// Database path, the absolute path to the database file, such as
/// `/var/lib/myapp/main.db`.
pub db_path: PathBuf,
/// Status: "running", "completed", "failed"
pub status: String,
/// Total number of migrations defined in the migrator (on "completed"), not just newly applied
#[serde(skip_serializing_if = "Option::is_none")]
pub migration_count: Option<usize>,
/// Error message (on "failed")
#[serde(skip_serializing_if = "Option::is_none")]
pub error: Option<String>,
}
/// Builder for the SQLite plugin.
///
/// Use this to configure the plugin and build the plugin instance.
///
/// # Database registration
///
/// Every database must be **registered** with a stable key and filesystem path (or
/// in-memory URI) before it can be opened. The frontend and Rust callers open databases
/// by **key** via `load()` / [`Connection::connect`]. Paths are validated and
/// canonicalized at registration time.
///
/// Because legitimate paths usually depend on runtime values (for example
/// `app.path().app_data_dir()`), registration normally happens in the [`Builder::on_setup`]
/// hook. Static paths can be registered up front with [`Builder::register_database`].
///
/// # Example
///
/// ```ignore
/// // Note: This example uses `ignore` instead of `no_run` because
/// // tauri::generate_context!() requires tauri.conf.json at compile time,
/// // which cannot be provided in doc test environments.
/// use tauri_plugin_sqlite::Builder;
///
/// # fn main() {
/// // Basic setup (no databases registered yet — register them in `on_setup`):
/// tauri::Builder::default()
/// .plugin(Builder::new().build().expect("failed to build sqlite plugin"))
/// .run(tauri::generate_context!())
/// .expect("error while running tauri application");
/// # }
/// ```
///
/// # Example with migrations
///
/// ```ignore
/// // Note: This example uses `ignore` instead of `no_run` because
/// // tauri::generate_context!() requires tauri.conf.json at compile time,
/// // which cannot be provided in doc test environments.
/// use tauri_plugin_sqlite::Builder;
/// use tauri::Manager;
///
/// # fn main() {
/// // Resolve the database path from the app instance and register it with migrations.
/// // The frontend then calls `Database.load("MAIN")` with the registration key.
/// tauri::Builder::default()
/// .plugin(
/// Builder::new()
/// .on_setup(|app, reg| {
/// let db = app.path().app_data_dir()?.join("main.db");
/// reg.register_database(
/// "MAIN",
/// db,
/// Some(sqlx::migrate!("./migrations/main")),
/// )?;
/// Ok(())
/// })
/// .build()
/// .expect("failed to build sqlite plugin")
/// )
/// .run(tauri::generate_context!())
/// .expect("error while running tauri application");
/// # }
/// ```
///
/// Collects database registrations from the [`Builder::on_setup`] hook.
///
/// Passed to the `on_setup` closure during plugin setup, where the `app` instance is
/// available. Use it to register values that can only be computed at runtime (for example,
/// paths derived from `app.path().app_data_dir()`).
#[derive(Default)]
pub struct SetupRegistrar {
database_info_by_key: HashMap<String, DatabaseInfo>,
}
impl SetupRegistrar {
/// Register a database path, optionally with migrations. See [`Builder::register_database`].
///
/// This invocation is to be used when the database path is known at runtime (such as
/// a path dependent on `app.path().app_data_dir()`).
///
/// For a path that is known at compile time, use [`Builder::register_database`]
/// instead.
///
/// The `key` is the identifier for the database. It is used to identify the database
/// when calling `load()` or `execute()`.
///
/// The `path` is the absolute filesystem path or in-memory URI. It is validated and
/// canonicalized at registration time.
///
/// Returns `Err` if the path fails validation (relative, traversal, or canonicalization).
///
/// The `migrator` runs automatically at plugin initialization when provided.
///
/// If the same key is registered more than once, the last registration will override
/// all previous ones.
///
/// Distinct keys must map to distinct database paths. Duplicate paths are rejected
/// when the plugin initializes (see [`Builder::build`]).
pub fn register_database(
&mut self,
key: &str,
path: impl Into<PathBuf>,
migrator: Option<Migrator>,
) -> Result<()> {
self
.database_info_by_key
.insert(key.to_string(), validated_database_info(path, migrator)?);
Ok(())
}
}
/// Closure type for the deferred [`Builder::on_setup`] hook.
type OnSetupHook<R> = Box<dyn FnOnce(&AppHandle<R>, &mut SetupRegistrar) -> Result<()> + Send>;
pub struct Builder<R: Runtime> {
/// Migrations registered per database path, keyed by the database key.
database_info_by_key: HashMap<String, DatabaseInfo>,
/// Timeout for interruptible transactions. Defaults to 5 minutes.
transaction_timeout: Option<std::time::Duration>,
/// Maximum number of concurrently loaded databases. Defaults to 50.
max_databases: Option<usize>,
/// Deferred hook run during plugin setup with the app handle. Lets callers register
/// paths/migrations computed from `app`. Returning `Err` aborts app startup.
on_setup: Option<OnSetupHook<R>>,
}
impl<R: Runtime> Default for Builder<R> {
fn default() -> Self {
Self::new()
}
}
impl<R: Runtime> std::fmt::Debug for Builder<R> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Builder")
.field("database_info_by_key", &self.database_info_by_key)
.field("transaction_timeout", &self.transaction_timeout)
.field("max_databases", &self.max_databases)
.field("on_setup", &self.on_setup.is_some())
.finish()
}
}
impl<R: Runtime> Builder<R> {
/// Create a new builder instance.
pub fn new() -> Self {
Self {
database_info_by_key: HashMap::new(),
transaction_timeout: None,
max_databases: None,
on_setup: None,
}
}
/// Register a database by key and path, optionally with migrations.
///
/// Pass `None` for `migrator` when the database has no migrations. Migrations run
/// automatically at plugin initialization when provided.
///
/// Use this when the path is known at compile time. For paths derived from the `app`
/// instance (for example `app.path().app_data_dir()`), use [`on_setup`](Self::on_setup)
/// and [`SetupRegistrar::register_database`] instead.
///
/// The frontend must call `load()` with the registration **key**.
///
/// # Example
///
/// ```no_run
/// use tauri_plugin_sqlite::Builder;
/// use std::path::PathBuf;
///
/// const MAIN_DB_KEY: &str = "MAIN";
///
/// # fn example() -> tauri_plugin_sqlite::Result<()> {
/// Builder::<tauri::Wry>::new()
/// .register_database(
/// MAIN_DB_KEY,
/// PathBuf::from("/var/lib/myapp/main.db"),
/// Some(sqlx::migrate!("./doc-test-fixtures/migrations")),
/// )?
/// .build()?;
/// # Ok(())
/// # }
/// ```
///
/// If the same key is registered more than once, the last registration will override
/// all previous ones.
///
/// Distinct keys must map to distinct database paths. If two distinct keys register
/// the same path, plugin initialization returns [`Error::InvalidConfig`]. Registrations
/// from [`on_setup`](Self::on_setup) are validated when the merged map is initialized.
pub fn register_database(
mut self,
key: &str,
path: impl Into<PathBuf>,
migrator: Option<Migrator>,
) -> Result<Self> {
self
.database_info_by_key
.insert(key.to_string(), validated_database_info(path, migrator)?);
Ok(self)
}
/// Set the timeout for interruptible transactions.
///
/// If an interruptible transaction exceeds this duration, it will be automatically
/// rolled back on the next access attempt. Defaults to 5 minutes.
///
/// Returns `Err(Error::InvalidConfig)` if `timeout` is zero.
pub fn transaction_timeout(mut self, timeout: std::time::Duration) -> Result<Self> {
if timeout.is_zero() {
return Err(Error::InvalidConfig(
"transaction_timeout must be greater than zero".to_string(),
));
}
self.transaction_timeout = Some(timeout);
Ok(self)
}
/// Set the maximum number of databases that can be loaded simultaneously.
///
/// Prevents unbounded memory growth from connection pool proliferation.
/// Defaults to 50.
///
/// Returns `Err(Error::InvalidConfig)` if `max` is zero.
pub fn max_databases(mut self, max: usize) -> Result<Self> {
if max == 0 {
return Err(Error::InvalidConfig(
"max_databases must be greater than zero".to_string(),
));
}
self.max_databases = Some(max);
Ok(self)
}
/// Register a hook that runs during plugin setup, once the `app` instance exists.
///
/// This is the primary way to register database paths, because the legitimate absolute
/// paths usually depend on runtime values — for example paths derived from
/// `app.path().app_data_dir()`. The closure receives the app handle and a
/// [`SetupRegistrar`] on which you call [`register_database`](SetupRegistrar::register_database).
///
/// Entries registered here are merged with those registered statically via
/// [`register_database`](Self::register_database); a later registration for the same
/// key overrides an earlier one.
///
/// Returning `Err` from the hook aborts app startup (fail-fast).
///
/// # Example
///
/// ```no_run
/// use tauri_plugin_sqlite::Builder;
/// use tauri::Manager;
///
/// const MAIN_DB_KEY: &str = "MAIN";
///
/// # fn example() -> tauri_plugin_sqlite::Result<()> {
/// Builder::<tauri::Wry>::new()
/// .on_setup(|app, reg| {
/// let dir = app.path().app_data_dir().map_err(|e| tauri_plugin_sqlite::Error::InvalidConfig(e.to_string()))?;
/// let db = dir.join("main.db");
/// reg.register_database(
/// MAIN_DB_KEY,
/// db,
/// Some(sqlx::migrate!("./doc-test-fixtures/migrations"))
/// )?;
/// Ok(())
/// })
/// .build()?;
/// # Ok(())
/// # }
/// ```
pub fn on_setup(
mut self,
f: impl FnOnce(&AppHandle<R>, &mut SetupRegistrar) -> Result<()> + Send + 'static,
) -> Self {
self.on_setup = Some(Box::new(f));
self
}
/// Build the plugin with command registration and state management.
///
/// Duplicate paths across distinct registration keys are rejected during plugin
/// initialization (the setup hook), after [`on_setup`](Self::on_setup) registrations
/// are merged with static ones.
pub fn build(self) -> Result<tauri::plugin::TauriPlugin<R>> {
let database_info_by_key = self.database_info_by_key;
let transaction_timeout = self.transaction_timeout;
let max_databases = self.max_databases;
let on_setup = self.on_setup;
Ok(PluginBuilder::<R>::new("sqlite")
.invoke_handler(tauri::generate_handler![
commands::load,
commands::execute,
commands::execute_transaction,
commands::begin_interruptible_transaction,
commands::transaction_continue,
commands::transaction_read,
commands::fetch_all,
commands::fetch_one,
commands::fetch_page,
commands::close,
commands::close_all,
commands::remove,
commands::get_migration_events,
commands::observe,
commands::subscribe,
commands::unsubscribe,
commands::unobserve,
])
.setup(move |app, _api| {
app.manage(match max_databases {
Some(max) => DbInstances::new(max),
None => DbInstances::default(),
});
app.manage(MigrationStates::default());
app.manage(match transaction_timeout {
Some(timeout) => ActiveInterruptibleTransactions::new(timeout),
None => ActiveInterruptibleTransactions::default(),
});
app.manage(ActiveRegularTransactions::default());
app.manage(subscriptions::ActiveSubscriptions::default());
// Run the deferred setup hook (if any), merge with static registrations.
// Paths are validated and canonicalized at registration time. Hook errors
// abort startup (fail-fast).
let mut database_info_by_key = database_info_by_key;
if let Some(on_setup_action) = on_setup {
let mut registrar = SetupRegistrar::default();
on_setup_action(app, &mut registrar)?;
database_info_by_key.extend(registrar.database_info_by_key);
}
ensure_distinct_database_paths(&database_info_by_key)?;
app.manage(RegisteredDatabases {
database_path_by_key: Arc::new(database_info_by_key.iter().map(|(key, info)| (key.clone(), info.path.clone())).collect()),
});
let migration_states = app.state::<MigrationStates>();
{
let mut states = migration_states.0.blocking_write();
// Only track migration state for databases that have a migrator.
// Keys without migrations are omitted so `await_migrations` returns
// immediately instead of waiting on a Pending state that never runs.
for (key, info) in &database_info_by_key {
if info.migrator.is_some() {
states.insert(key.clone(), MigrationState::new());
}
}
}
for (key, info) in &database_info_by_key {
if let Some(migrator) = &info.migrator {
info!("Starting migrations for database {}", key);
let key = key.clone();
let migrator = migrator.clone();
let path = info.path.clone();
let app_handle = app.clone();
tauri::async_runtime::spawn(async move {
run_migrations_for_database(app_handle, &key, &path, &migrator).await;
});
}
}
debug!("SQLite plugin initialized");
Ok(())
})
.on_event(|app, event| {
match event {
RunEvent::ExitRequested { api, code, .. } => {
// Claim cleanup ownership once. Three possible CLEANUP_STATE values:
// 0 → claim it, run cleanup
// 1 → cleanup already in progress (another invocation won the
// race). Keep exit prevented while it finishes.
// 2 → cleanup already complete; this ExitRequested is the
// re-exit fired by ExitGuard. Let it through unchanged.
//
// We deliberately do not skip programmatic exits (code.is_some()).
// A user-space app_handle.exit(N) — fatal-error handler, updater,
// Ctrl+C handler — would otherwise tear down plugin state with
// interruptible transactions still live in the map, and the
// captured-runtime Drop path on the toolkit side still relies on
// the runtime being up when it spawns the rollback. Running
// cleanup here is the clean path.
match CLEANUP_STATE.compare_exchange(
0,
1,
Ordering::SeqCst,
Ordering::SeqCst,
) {
Ok(_) => {}
Err(2) => return,
Err(_) => {
api.prevent_exit();
debug!("Exit requested while database cleanup is in progress");
return;
}
}
let exit_code = code.unwrap_or(0);
info!(
"App exit requested (code={}) - cleaning up transactions and databases",
exit_code
);
// Prevent immediate exit so we can close connections and checkpoint WAL
api.prevent_exit();
let app_handle = app.clone();
let instances_clone = app.state::<DbInstances>().inner().clone();
let interruptible_txs_clone = app.state::<ActiveInterruptibleTransactions>().inner().clone();
let regular_txs_clone = app.state::<ActiveRegularTransactions>().inner().clone();
let active_subs_clone = app.state::<subscriptions::ActiveSubscriptions>().inner().clone();
// Run cleanup on the async runtime (without blocking the event loop),
// then trigger a programmatic exit when done. ExitGuard ensures
// CLEANUP_STATE reaches 2 and exit() fires even on panic.
tauri::async_runtime::spawn(async move {
let _guard = ExitGuard { app_handle, exit_code };
// Scope block: drops the RwLock write guard (from instances_clone)
// before _guard fires exit(), whose RunEvent::Exit handler calls
// try_read() on the same lock.
{
let timeout_result = tokio::time::timeout(
CLOSE_TIMEOUT,
async {
debug!("Aborting active subscriptions and transactions");
active_subs_clone.abort_all().await;
if let Err(e) = sqlx_sqlite_toolkit::cleanup_all_transactions(
&interruptible_txs_clone,
®ular_txs_clone,
)
.await
{
warn!("Transaction cleanup failed during exit: {e}");
}
if let Err(e) =
close_all_wrappers(&instances_clone).await
{
warn!("Error closing databases during exit: {e:?}");
}
},
)
.await;
if timeout_result.is_err() {
warn!("Database cleanup timed out after 5 seconds");
} else {
debug!("Database cleanup complete");
}
}
});
}
RunEvent::Exit => {
// ExitRequested should have already closed all databases
// This is just a safety check
let instances = app.state::<DbInstances>();
match instances.inner.try_read() {
Ok(guard) => {
if !guard.is_empty() {
warn!(
"Exit event fired with {} database(s) still open - cleanup may have been skipped",
guard.len()
);
} else {
debug!("Exit event: all databases already closed");
}
}
Err(_) => {
warn!("Exit event: could not check database state (lock held - cleanup may still be in progress)");
}
}
}
_ => {
// Other events don't require action
}
}
})
.build())
}
}
/// Initializes the plugin with default configuration.
pub fn init<R: Runtime>() -> tauri::plugin::TauriPlugin<R> {
Builder::<R>::new()
.build()
.expect("failed to build sqlite plugin")
}
/// Run migrations for a single database and emit events.
///
/// This function is spawned as a task for each database with registered migrations.
/// It runs during plugin setup, before the frontend calls `load`.
///
/// # Timing & Caching
///
/// 1. Plugin setup spawns this task (async, non-blocking)
/// 2. This task connects via `SqliteDatabase::connect()`, which caches the instance
/// 3. When frontend later calls `load`, it awaits migration completion first
/// 4. Then `load` calls `connect()` again, which returns the **same cached instance**
///
/// The `DatabaseWrapper` created here is temporary and dropped after migrations complete,
/// but the underlying `SqliteDatabase` (with its connection pools) remains cached in the
/// global registry and is reused when `load` creates its own wrapper.
async fn run_migrations_for_database<R: Runtime>(
app: tauri::AppHandle<R>,
key: &str,
path: &Path,
migrator: &Arc<Migrator>,
) {
let migration_states = app.state::<MigrationStates>();
// Update state to Running
{
let mut states = migration_states.0.write().await;
if let Some(state) = states.get_mut(key) {
state.update_status(MigrationStatus::Running);
}
}
// Emit running event
emit_migration_event(&app, key, path, "running", None, None);
// Resolve absolute path and connect
let abs_path = match resolve_database_path(key, &app) {
Ok(p) => p,
Err(e) => {
let error_msg = e.to_string();
error!(
"Failed to resolve migration path for {}: {}",
key, error_msg
);
let mut states = migration_states.0.write().await;
if let Some(state) = states.get_mut(key) {
state.update_status(MigrationStatus::Failed(error_msg.clone()));
}
emit_migration_event(&app, key, path, "failed", None, Some(error_msg));
return;
}
};
// Connect to database
let db = match DatabaseWrapper::connect(&abs_path, None).await {
Ok(wrapper) => wrapper,
Err(e) => {
let error_msg = e.to_string();
error!("Failed to connect for migrations {}: {}", key, error_msg);
let mut states = migration_states.0.write().await;
if let Some(state) = states.get_mut(key) {
state.update_status(MigrationStatus::Failed(error_msg.clone()));
}
emit_migration_event(&app, key, path, "failed", None, Some(error_msg));
return;
}
};
// Run migrations
// Note: SQLx's migrator.run() doesn't provide per-migration callbacks,
// so we can only report start and finish. For detailed per-migration events,
// we would need to iterate migrations manually.
trace!("Running migrations for {}", key);
match db.run_migrations(migrator).await {
Ok(()) => {
info!("Migrations completed successfully for {}", key);
let mut states = migration_states.0.write().await;
if let Some(state) = states.get_mut(key) {
state.update_status(MigrationStatus::Complete);
}
let migration_count = migrator.iter().count();
emit_migration_event(&app, key, path, "completed", Some(migration_count), None);
}
Err(e) => {
let error_msg = e.to_string();
error!("Migration failed for {}: {}", key, error_msg);
let mut states = migration_states.0.write().await;
if let Some(state) = states.get_mut(key) {
state.update_status(MigrationStatus::Failed(error_msg.clone()));
}
emit_migration_event(&app, key, path, "failed", None, Some(error_msg));
}
}
}
/// Emit a migration event to the frontend and cache it.
fn emit_migration_event<R: Runtime>(
app: &tauri::AppHandle<R>,
db_key: &str,
db_path: &Path,
status: &str,
migration_count: Option<usize>,
error: Option<String>,
) {
let event = MigrationEvent {
db_key: db_key.to_string(),
db_path: db_path.to_path_buf(),
status: status.to_string(),
migration_count,
error,
};
// Cache event in migration state
let migration_states = app.state::<MigrationStates>();
if let Ok(mut states) = migration_states.0.try_write()
&& let Some(state) = states.get_mut(db_key)
{
state.cache_event(event.clone());
}
if let Err(e) = app.emit("sqlite:migration", &event) {
warn!("Failed to emit migration event: {}", e);
}
}
/// Connect to a registered database by its registration key.
///
/// Opens the database through the same path as the frontend `load` IPC command
/// ([`connect_to_database`]): awaits migrations, enforces max-database limits, and
/// stores the wrapper in [`DbInstances`]. Returns a [`DatabaseWrapper`] for direct
/// toolkit use.
///
/// The `database_key` must match a key registered via
/// [`Builder::register_database`] or [`SetupRegistrar::register_database`].
///
/// # Why use a key?
///
/// Database paths are usually resolved once during plugin setup — for example
/// `app.path().app_data_dir()?.join("main.db")` in [`Builder::on_setup`]. Without
/// registration keys, every call site would repeat that path discovery or keep its own
/// `PathBuf`. Registration stores the key-to-path mapping once; `connect` reuses the key
/// so callers do not supply a filesystem path on every open.
///
/// On mobile, path discovery is not a cheap string join. Resolvers such as
/// [tauri-plugin-fs-resolver](https://github.com/silvermine/tauri-plugin-fs-resolver)
/// call platform-native APIs so paths match OS sandbox rules. On Android that means a
/// JNI call into Kotlin `Context` (e.g. `getFilesDir()`) on each resolve — noticeably
/// more expensive than a local HashMap lookup, and a different kind of boundary than
/// TypeScript-to-Rust IPC (in-process JNI vs webview bridge). Register the resolved
/// `PathBuf` once in `on_setup`; every later `connect(database_key)` only looks up that
/// key in [`RegisteredDatabases`] — no repeat native or JNI work.
///
/// For webview/frontend access, use `Database.load(dbKey)` instead.
///
/// # Example
///
/// ```ignore
/// use tauri::{Manager, Runtime};
/// use tauri_plugin_sqlite::Connection;
///
/// // During setup (on_setup):
/// // reg.register_database("MAIN", app.path().app_data_dir()?.join("main.db"), None);
///
/// async fn read_users<R: Runtime>(app: tauri::AppHandle<R>) -> tauri_plugin_sqlite::Result<()> {
/// let db = app.connect("MAIN").await?;
/// let rows = db.fetch_all("SELECT * FROM users".into(), vec![]).execute().await?;
/// Ok(())
/// }
/// ```
pub trait Connection<R: Runtime> {
/// Connect with default pool configuration.
fn connect(&self, database_key: &str) -> impl Future<Output = Result<DatabaseWrapper>> + Send;
/// Connect with custom [`SqliteDatabaseConfig`] (pool sizes, idle timeout).
fn connect_with_config(
&self,
database_key: &str,
config: SqliteDatabaseConfig,
) -> impl Future<Output = Result<DatabaseWrapper>> + Send;
/// Close the loaded instance for a registered database key.
///
/// Returns `true` if the database was loaded and successfully closed.
/// Returns `false` if the database was not loaded (nothing to close).
/// Returns `Err` if transaction cleanup or pool close fails (database file
/// may not be safe to delete or recreate).
///
/// On success (`Ok(true)`), connections are closed and WAL is truncated via
/// `wal_checkpoint(TRUNCATE)`. The main `.db` file is safe to delete or recreate.
/// `-wal` / `-shm` sidecar files may remain as empty artifacts and are harmless.
///
/// If close returns `Err`, the database file may still be locked — do not delete it.
///
/// Close is bounded by a 5-second timeout; hung pool teardown returns an error
/// rather than blocking indefinitely.
///
/// Active subscriptions for this key are aborted, and in-flight transactions
/// are cleaned up (interruptible transactions rolled back; regular transaction
/// tasks aborted and awaited) before the connection pool is closed.
fn close(&self, database_key: &str) -> impl Future<Output = Result<bool>> + Send;
}
/// Delegates to [`connect_to_database`]: same open path as the `load` IPC command.
impl<R: Runtime> Connection<R> for AppHandle<R> {
async fn connect(&self, database_key: &str) -> Result<DatabaseWrapper> {
let response = connect_to_database(self, database_key, None).await?;
Ok(response.wrapper)
}
async fn connect_with_config(
&self,
database_key: &str,
config: SqliteDatabaseConfig,
) -> Result<DatabaseWrapper> {
let response = connect_to_database(self, database_key, Some(config)).await?;
Ok(response.wrapper)
}
async fn close(&self, database_key: &str) -> Result<bool> {
let instances = self
.try_state::<DbInstances>()
.ok_or(Error::MissingState("DbInstances".into()))?;
let subs = self
.try_state::<ActiveSubscriptions>()
.ok_or(Error::MissingState("ActiveSubscriptions".into()))?;
let interruptible_txs =
self
.try_state::<ActiveInterruptibleTransactions>()
.ok_or(Error::MissingState(
"ActiveInterruptibleTransactions".into(),
))?;
let regular_txs = self
.try_state::<ActiveRegularTransactions>()
.ok_or(Error::MissingState("ActiveRegularTransactions".into()))?;
close_database(
database_key,
&instances,
&subs,
&interruptible_txs,
®ular_txs,
)
.await
}
}
struct ConnectionResponse {
path: PathBuf,
wrapper: DatabaseWrapper,
}
async fn connect_to_database<R: Runtime>(
app: &AppHandle<R>,
db_key: &str,
custom_config: Option<SqliteDatabaseConfig>,
) -> Result<ConnectionResponse> {
let migration_states = app.state::<MigrationStates>();
let db_instances = app.state::<DbInstances>();
// Wait for migrations to complete if registered for this database
await_migrations(&migration_states, db_key).await?;
let path = resolve_database_path(db_key, app)?;
let instances = db_instances.inner.read().await;
// Return cached if db was already loaded
if let Some(wrapper) = instances.get(db_key) {
return Ok(ConnectionResponse {
path,
wrapper: wrapper.clone(),
});
}
drop(instances); // Release read lock before acquiring write lock
let mut instances = db_instances.inner.write().await;
// Check database count limit before creating a new connection.
// This check is before entry() to avoid borrow conflicts, and the write lock
// prevents races between the len() check and the insert.
if !instances.contains_key(db_key) && instances.len() >= db_instances.max {
return Err(Error::TooManyDatabases(db_instances.max));
}
// Use entry API to atomically check and insert, avoiding race conditions