forked from silvermine/tauri-plugin-sqlite
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlib.rs
More file actions
489 lines (434 loc) · 17 KB
/
Copy pathlib.rs
File metadata and controls
489 lines (434 loc) · 17 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
use std::collections::HashMap;
use std::sync::Arc;
use serde::Serialize;
use sqlx_sqlite_conn_mgr::Migrator;
use tauri::{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 resolve;
mod subscriptions;
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,
};
/// Database instances managed by the plugin.
///
/// This struct maintains a thread-safe map of database paths to their corresponding
/// connection wrappers.
#[derive(Clone, Default)]
pub struct DbInstances(pub Arc<RwLock<HashMap<String, DatabaseWrapper>>>);
/// 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.
#[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 path (relative, as registered)
pub db_path: String,
/// 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.
///
/// # 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 migrations):
/// tauri::Builder::default()
/// .plugin(Builder::new().build())
/// .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;
///
/// # fn main() {
/// // Setup with migrations:
/// tauri::Builder::default()
/// .plugin(
/// Builder::new()
/// .add_migrations("main.db", sqlx::migrate!("./migrations/main"))
/// .add_migrations("cache.db", sqlx::migrate!("./migrations/cache"))
/// .build()
/// )
/// .run(tauri::generate_context!())
/// .expect("error while running tauri application");
/// # }
/// ```
#[derive(Default)]
pub struct Builder {
/// Migrations registered per database path
migrations: HashMap<String, Arc<Migrator>>,
}
impl Builder {
/// Create a new builder instance.
pub fn new() -> Self {
Self {
migrations: HashMap::new(),
}
}
/// Register migrations for a database path.
///
/// Migrations will be run automatically at plugin initialization.
/// Multiple databases can have their own migrations.
///
/// # Arguments
///
/// * `path` - Database path (relative to app config directory)
/// * `migrator` - Migrator instance, typically from `sqlx::migrate!()`
///
/// # Example
///
/// ```no_run
/// use tauri_plugin_sqlite::Builder;
///
/// # fn example() {
/// Builder::new()
/// .add_migrations("main.db", sqlx::migrate!("./doc-test-fixtures/migrations"))
/// .build::<tauri::Wry>();
/// # }
/// ```
pub fn add_migrations(mut self, path: &str, migrator: Migrator) -> Self {
self.migrations.insert(path.to_string(), Arc::new(migrator));
self
}
/// Build the plugin with command registration and state management.
pub fn build<R: Runtime>(self) -> tauri::plugin::TauriPlugin<R> {
let migrations = Arc::new(self.migrations);
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(DbInstances::default());
app.manage(MigrationStates::default());
app.manage(ActiveInterruptibleTransactions::default());
app.manage(ActiveRegularTransactions::default());
app.manage(subscriptions::ActiveSubscriptions::default());
// Initialize migration states as Pending for all registered databases
let migration_states = app.state::<MigrationStates>();
{
let mut states = migration_states.0.blocking_write();
for path in migrations.keys() {
states.insert(path.clone(), MigrationState::new());
}
}
// Spawn parallel migration tasks for each registered database
if !migrations.is_empty() {
info!("Starting migrations for {} database(s)", migrations.len());
for (path, migrator) in migrations.iter() {
let app_handle = app.clone();
let path = path.clone();
let migrator = Arc::clone(migrator);
tauri::async_runtime::spawn(async move {
run_migrations_for_database(app_handle, path, migrator).await;
});
}
}
debug!("SQLite plugin initialized");
Ok(())
})
.on_event(|app, event| {
match event {
RunEvent::ExitRequested { api, code, .. } => {
// Only intercept user-initiated exits (code is None). Programmatic
// exits via app_handle.exit() have Some(code) — let those through
// to avoid an infinite ExitRequested loop.
if code.is_some() {
return;
}
info!("App exit requested - cleaning up transactions and databases");
// Prevent immediate exit so we can close connections and checkpoint WAL
api.prevent_exit();
let app_handle = app.clone();
let handle = match tokio::runtime::Handle::try_current() {
Ok(h) => h,
Err(_) => {
warn!("No tokio runtime available for cleanup");
app_handle.exit(code.unwrap_or(0));
return;
}
};
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();
// Spawn a blocking thread to abort transactions and close databases
// (block_in_place panics on current_thread runtime)
let cleanup_result = std::thread::spawn(move || {
handle.block_on(async {
// First, abort all subscriptions and transactions
debug!("Aborting active subscriptions and transactions");
active_subs_clone.abort_all().await;
sqlx_sqlite_toolkit::cleanup_all_transactions(&interruptible_txs_clone, ®ular_txs_clone).await;
// Close databases (each wrapper's close() disables its own
// observer at the crate level, unregistering SQLite hooks)
let mut guard = instances_clone.0.write().await;
let wrappers: Vec<DatabaseWrapper> =
guard.drain().map(|(_, v)| v).collect();
// Close databases in parallel with timeout
let mut set = tokio::task::JoinSet::new();
for wrapper in wrappers {
set.spawn(async move { wrapper.close().await });
}
let timeout_result = tokio::time::timeout(
std::time::Duration::from_secs(5),
async {
while let Some(result) = set.join_next().await {
match result {
Ok(Err(e)) => warn!("Error closing database: {:?}", e),
Err(e) => warn!("Database close task panicked: {:?}", e),
Ok(Ok(())) => {}
}
}
},
)
.await;
if timeout_result.is_err() {
warn!("Database cleanup timed out after 5 seconds");
} else {
debug!("Database cleanup complete");
}
})
})
.join();
if let Err(e) = cleanup_result {
error!("Database cleanup thread panicked: {:?}", e);
}
app_handle.exit(code.unwrap_or(0));
}
RunEvent::Exit => {
// ExitRequested should have already closed all databases
// This is just a safety check
let instances = app.state::<DbInstances>();
match instances.0.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::new().build()
}
/// 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>,
path: String,
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(&path) {
state.update_status(MigrationStatus::Running);
}
}
// Emit running event
emit_migration_event(&app, &path, "running", None, None);
// Resolve absolute path and connect
let abs_path = match resolve_migration_path(&path, &app) {
Ok(p) => p,
Err(e) => {
let error_msg = e.to_string();
error!(
"Failed to resolve migration path for {}: {}",
path, error_msg
);
let mut states = migration_states.0.write().await;
if let Some(state) = states.get_mut(&path) {
state.update_status(MigrationStatus::Failed(error_msg.clone()));
}
emit_migration_event(&app, &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 {}: {}", path, error_msg);
let mut states = migration_states.0.write().await;
if let Some(state) = states.get_mut(&path) {
state.update_status(MigrationStatus::Failed(error_msg.clone()));
}
emit_migration_event(&app, &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 {}", path);
match db.run_migrations(&migrator).await {
Ok(()) => {
info!("Migrations completed successfully for {}", path);
let mut states = migration_states.0.write().await;
if let Some(state) = states.get_mut(&path) {
state.update_status(MigrationStatus::Complete);
}
let migration_count = migrator.iter().count();
emit_migration_event(&app, &path, "completed", Some(migration_count), None);
}
Err(e) => {
let error_msg = e.to_string();
error!("Migration failed for {}: {}", path, error_msg);
let mut states = migration_states.0.write().await;
if let Some(state) = states.get_mut(&path) {
state.update_status(MigrationStatus::Failed(error_msg.clone()));
}
emit_migration_event(&app, &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_path: &str,
status: &str,
migration_count: Option<usize>,
error: Option<String>,
) {
let event = MigrationEvent {
db_path: db_path.to_string(),
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_path)
{
state.cache_event(event.clone());
}
if let Err(e) = app.emit("sqlite:migration", &event) {
warn!("Failed to emit migration event: {}", e);
}
}
/// Resolve database path for migrations (similar to wrapper but accessible at init).
fn resolve_migration_path<R: Runtime>(
path: &str,
app: &tauri::AppHandle<R>,
) -> Result<std::path::PathBuf> {
let app_path = app
.path()
.app_config_dir()
.map_err(|_| Error::InvalidPath("No app config path found".to_string()))?;
std::fs::create_dir_all(&app_path)?;
Ok(app_path.join(path))
}