|
11 | 11 | html_favicon_url = "https://github.com/tauri-apps/tauri/raw/dev/app-icon.png"
|
12 | 12 | )]
|
13 | 13 |
|
14 |
| -#[cfg(any( |
15 |
| - all(feature = "sqlite", feature = "mysql"), |
16 |
| - all(feature = "sqlite", feature = "postgres"), |
17 |
| - all(feature = "mysql", feature = "postgres") |
18 |
| -))] |
19 |
| -compile_error!( |
20 |
| - "Only one database driver can be enabled. Set the feature flag for the driver of your choice." |
21 |
| -); |
22 |
| - |
23 |
| -#[cfg(not(any(feature = "sqlite", feature = "mysql", feature = "postgres")))] |
24 |
| -compile_error!( |
25 |
| - "Database driver not defined. Please set the feature flag for the driver of your choice." |
26 |
| -); |
27 |
| - |
| 14 | +mod commands; |
28 | 15 | mod decode;
|
29 |
| -mod plugin; |
30 |
| -pub use plugin::*; |
| 16 | +mod error; |
| 17 | +mod wrapper; |
| 18 | + |
| 19 | +pub use error::Error; |
| 20 | +pub use wrapper::DbPool; |
| 21 | + |
| 22 | +use futures_core::future::BoxFuture; |
| 23 | +use serde::{Deserialize, Serialize}; |
| 24 | +use sqlx::{ |
| 25 | + error::BoxDynError, |
| 26 | + migrate::{Migration as SqlxMigration, MigrationSource, MigrationType, Migrator}, |
| 27 | +}; |
| 28 | +use tauri::{ |
| 29 | + plugin::{Builder as PluginBuilder, TauriPlugin}, |
| 30 | + Manager, RunEvent, Runtime, |
| 31 | +}; |
| 32 | +use tokio::sync::Mutex; |
| 33 | + |
| 34 | +use std::collections::HashMap; |
| 35 | + |
| 36 | +#[derive(Default)] |
| 37 | +pub struct DbInstances(pub Mutex<HashMap<String, DbPool>>); |
| 38 | + |
| 39 | +#[derive(Serialize)] |
| 40 | +#[serde(untagged)] |
| 41 | +pub(crate) enum LastInsertId { |
| 42 | + #[cfg(feature = "sqlite")] |
| 43 | + Sqlite(i64), |
| 44 | + #[cfg(feature = "mysql")] |
| 45 | + MySql(u64), |
| 46 | + #[cfg(feature = "postgres")] |
| 47 | + Postgres(()), |
| 48 | + #[cfg(not(any(feature = "sqlite", feature = "mysql", feature = "postgres")))] |
| 49 | + None, |
| 50 | +} |
| 51 | + |
| 52 | +struct Migrations(Mutex<HashMap<String, MigrationList>>); |
| 53 | + |
| 54 | +#[derive(Default, Clone, Deserialize)] |
| 55 | +pub struct PluginConfig { |
| 56 | + #[serde(default)] |
| 57 | + preload: Vec<String>, |
| 58 | +} |
| 59 | + |
| 60 | +#[derive(Debug)] |
| 61 | +pub enum MigrationKind { |
| 62 | + Up, |
| 63 | + Down, |
| 64 | +} |
| 65 | + |
| 66 | +impl From<MigrationKind> for MigrationType { |
| 67 | + fn from(kind: MigrationKind) -> Self { |
| 68 | + match kind { |
| 69 | + MigrationKind::Up => Self::ReversibleUp, |
| 70 | + MigrationKind::Down => Self::ReversibleDown, |
| 71 | + } |
| 72 | + } |
| 73 | +} |
| 74 | + |
| 75 | +/// A migration definition. |
| 76 | +#[derive(Debug)] |
| 77 | +pub struct Migration { |
| 78 | + pub version: i64, |
| 79 | + pub description: &'static str, |
| 80 | + pub sql: &'static str, |
| 81 | + pub kind: MigrationKind, |
| 82 | +} |
| 83 | + |
| 84 | +#[derive(Debug)] |
| 85 | +struct MigrationList(Vec<Migration>); |
| 86 | + |
| 87 | +impl MigrationSource<'static> for MigrationList { |
| 88 | + fn resolve(self) -> BoxFuture<'static, std::result::Result<Vec<SqlxMigration>, BoxDynError>> { |
| 89 | + Box::pin(async move { |
| 90 | + let mut migrations = Vec::new(); |
| 91 | + for migration in self.0 { |
| 92 | + if matches!(migration.kind, MigrationKind::Up) { |
| 93 | + migrations.push(SqlxMigration::new( |
| 94 | + migration.version, |
| 95 | + migration.description.into(), |
| 96 | + migration.kind.into(), |
| 97 | + migration.sql.into(), |
| 98 | + false, |
| 99 | + )); |
| 100 | + } |
| 101 | + } |
| 102 | + Ok(migrations) |
| 103 | + }) |
| 104 | + } |
| 105 | +} |
| 106 | + |
| 107 | +/// Tauri SQL plugin builder. |
| 108 | +#[derive(Default)] |
| 109 | +pub struct Builder { |
| 110 | + migrations: Option<HashMap<String, MigrationList>>, |
| 111 | +} |
| 112 | + |
| 113 | +impl Builder { |
| 114 | + pub fn new() -> Self { |
| 115 | + #[cfg(not(any(feature = "sqlite", feature = "mysql", feature = "postgres")))] |
| 116 | + eprintln!("No sql driver enabled. Please set at least one of the \"sqlite\", \"mysql\", \"postgres\" feature flags."); |
| 117 | + |
| 118 | + Self::default() |
| 119 | + } |
| 120 | + |
| 121 | + /// Add migrations to a database. |
| 122 | + #[must_use] |
| 123 | + pub fn add_migrations(mut self, db_url: &str, migrations: Vec<Migration>) -> Self { |
| 124 | + self.migrations |
| 125 | + .get_or_insert(Default::default()) |
| 126 | + .insert(db_url.to_string(), MigrationList(migrations)); |
| 127 | + self |
| 128 | + } |
| 129 | + |
| 130 | + pub fn build<R: Runtime>(mut self) -> TauriPlugin<R, Option<PluginConfig>> { |
| 131 | + PluginBuilder::<R, Option<PluginConfig>>::new("sql") |
| 132 | + .invoke_handler(tauri::generate_handler![ |
| 133 | + commands::load, |
| 134 | + commands::execute, |
| 135 | + commands::select, |
| 136 | + commands::close |
| 137 | + ]) |
| 138 | + .setup(|app, api| { |
| 139 | + let config = api.config().clone().unwrap_or_default(); |
| 140 | + |
| 141 | + tauri::async_runtime::block_on(async move { |
| 142 | + let instances = DbInstances::default(); |
| 143 | + let mut lock = instances.0.lock().await; |
| 144 | + |
| 145 | + for db in config.preload { |
| 146 | + let pool = DbPool::connect(&db, app).await?; |
| 147 | + |
| 148 | + if let Some(migrations) = self.migrations.as_mut().unwrap().remove(&db) { |
| 149 | + let migrator = Migrator::new(migrations).await?; |
| 150 | + pool.migrate(&migrator).await?; |
| 151 | + } |
| 152 | + |
| 153 | + lock.insert(db, pool); |
| 154 | + } |
| 155 | + drop(lock); |
| 156 | + |
| 157 | + app.manage(instances); |
| 158 | + app.manage(Migrations(Mutex::new( |
| 159 | + self.migrations.take().unwrap_or_default(), |
| 160 | + ))); |
| 161 | + |
| 162 | + Ok(()) |
| 163 | + }) |
| 164 | + }) |
| 165 | + .on_event(|app, event| { |
| 166 | + if let RunEvent::Exit = event { |
| 167 | + tauri::async_runtime::block_on(async move { |
| 168 | + let instances = &*app.state::<DbInstances>(); |
| 169 | + let instances = instances.0.lock().await; |
| 170 | + for value in instances.values() { |
| 171 | + value.close().await; |
| 172 | + } |
| 173 | + }); |
| 174 | + } |
| 175 | + }) |
| 176 | + .build() |
| 177 | + } |
| 178 | +} |
0 commit comments