fix(deps): update rust crate sqlx to 0.8 [security] (v1) (#1687)

Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
Co-authored-by: FabianLars <fabianlars@fabianlars.de>

Committed via a GitHub action: https://github.com/tauri-apps/plugins-workspace/actions/runs/10678936672

Co-authored-by: FabianLars <FabianLars@users.noreply.github.com>
This commit is contained in:
renovate[bot]
2024-09-03 08:03:10 +00:00
committed by tauri-bot
parent 2807d61f57
commit e848849536
3 changed files with 523 additions and 522 deletions

View File

@@ -6,7 +6,7 @@ authors = { workspace = true }
license = { workspace = true }
edition = { workspace = true }
#rust-version = { workspace = true }
rust-version = "1.65"
rust-version = "1.80"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
@@ -17,7 +17,7 @@ tauri = { workspace = true }
log = { workspace = true }
thiserror = { workspace = true }
futures-core = "0.3"
sqlx = { version = "0.7", features = ["json", "time"] }
sqlx = { version = "0.8", features = ["json", "time"] }
time = "0.3"
tokio = { version = "1", features = ["sync"] }

368
README.md
View File

@@ -1,184 +1,184 @@
![plugin-sql](https://github.com/tauri-apps/plugins-workspace/raw/v1/plugins/sql/banner.png)
Interface with SQL databases through [sqlx](https://github.com/launchbadge/sqlx). It supports the `sqlite`, `mysql` and `postgres` drivers, enabled by a Cargo feature.
## Install
_This plugin requires a Rust version of at least **1.65**_
There are three general methods of installation that we can recommend.
1. Use crates.io and npm (easiest, and requires you to trust that our publishing pipeline worked)
2. Pull sources directly from Github using git tags / revision hashes (most secure)
3. Git submodule install this repo in your tauri project and then use file protocol to ingest the source (most secure, but inconvenient to use)
Install the Core plugin by adding the following to your `Cargo.toml` file:
`src-tauri/Cargo.toml`
```toml
[dependencies.tauri-plugin-sql]
git = "https://github.com/tauri-apps/plugins-workspace"
branch = "v1"
features = ["sqlite"] # or "postgres", or "mysql"
```
You can install the JavaScript Guest bindings using your preferred JavaScript package manager:
> Note: Since most JavaScript package managers are unable to install packages from git monorepos we provide read-only mirrors of each plugin. This makes installation option 2 more ergonomic to use.
```sh
pnpm add https://github.com/tauri-apps/tauri-plugin-sql#v1
# or
npm add https://github.com/tauri-apps/tauri-plugin-sql#v1
# or
yarn add https://github.com/tauri-apps/tauri-plugin-sql#v1
```
## Usage
First you need to register the core plugin with Tauri:
`src-tauri/src/main.rs`
```rust
fn main() {
tauri::Builder::default()
.plugin(tauri_plugin_sql::Builder::default().build())
.run(tauri::generate_context!())
.expect("error while running tauri application");
}
```
Afterwards all the plugin's APIs are available through the JavaScript guest bindings:
```javascript
import Database from "tauri-plugin-sql-api";
// sqlite. The path is relative to `tauri::api::path::BaseDirectory::App`.
const db = await Database.load("sqlite:test.db");
// mysql
const db = await Database.load("mysql://user:pass@host/database");
// postgres
const db = await Database.load("postgres://postgres:password@localhost/test");
await db.execute("INSERT INTO ...");
```
## Syntax
We use sqlx as our underlying library, adopting their query syntax:
- sqlite and postgres use the "$#" syntax when substituting query data
- mysql uses "?" when substituting query data
```javascript
// INSERT and UPDATE examples for sqlite and postgres
const result = await db.execute(
"INSERT into todos (id, title, status) VALUES ($1, $2, $3)",
[todos.id, todos.title, todos.status],
);
const result = await db.execute(
"UPDATE todos SET title = $1, completed = $2 WHERE id = $3",
[todos.title, todos.status, todos.id],
);
// INSERT and UPDATE examples for mysql
const result = await db.execute(
"INSERT into todos (id, title, status) VALUES (?, ?, ?)",
[todos.id, todos.title, todos.status],
);
const result = await db.execute(
"UPDATE todos SET title = ?, completed = ? WHERE id = ?",
[todos.title, todos.status, todos.id],
);
```
## Migrations
This plugin supports database migrations, allowing you to manage database schema evolution over time.
### Defining Migrations
Migrations are defined in Rust using the `Migration` struct. Each migration should include a unique version number, a description, the SQL to be executed, and the type of migration (Up or Down).
Example of a migration:
```rust
use tauri_plugin_sql::{Migration, MigrationKind};
let migration = Migration {
version: 1,
description: "create_initial_tables",
sql: "CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT);",
kind: MigrationKind::Up,
};
```
### Adding Migrations to the Plugin Builder
Migrations are registered with the `Builder` struct provided by the plugin. Use the `add_migrations` method to add your migrations to the plugin for a specific database connection.
Example of adding migrations:
```rust
use tauri_plugin_sql::{Builder, Migration, MigrationKind};
fn main() {
let migrations = vec![
// Define your migrations here
Migration {
version: 1,
description: "create_initial_tables",
sql: "CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT);",
kind: MigrationKind::Up,
}
];
tauri::Builder::default()
.plugin(
tauri_plugin_sql::Builder::default()
.add_migrations("sqlite:mydatabase.db", migrations)
.build(),
)
...
}
```
### Applying Migrations
Migrations are applied automatically when the plugin is initialized. The plugin runs these migrations against the database specified by the connection string. Ensure that the migrations are defined in the correct order and are idempotent (safe to run multiple times).
### Migration Management
- **Version Control**: Each migration must have a unique version number. This is crucial for ensuring the migrations are applied in the correct order.
- **Idempotency**: Write migrations in a way that they can be safely re-run without causing errors or unintended consequences.
- **Testing**: Thoroughly test migrations to ensure they work as expected and do not compromise the integrity of your database.
## Contributing
PRs accepted. Please make sure to read the Contributing Guide before making a pull request.
## Partners
<table>
<tbody>
<tr>
<td align="center" valign="middle">
<a href="https://crabnebula.dev" target="_blank">
<img src="https://github.com/tauri-apps/plugins-workspace/raw/v1/.github/sponsors/crabnebula.svg" alt="CrabNebula" width="283">
</a>
</td>
</tr>
</tbody>
</table>
For the complete list of sponsors please visit our [website](https://tauri.app#sponsors) and [Open Collective](https://opencollective.com/tauri).
## License
Code: (c) 2015 - Present - The Tauri Programme within The Commons Conservancy.
MIT or MIT/Apache 2.0 where applicable.
![plugin-sql](https://github.com/tauri-apps/plugins-workspace/raw/v1/plugins/sql/banner.png)
Interface with SQL databases through [sqlx](https://github.com/launchbadge/sqlx). It supports the `sqlite`, `mysql` and `postgres` drivers, enabled by a Cargo feature.
## Install
_This plugin requires a Rust version of at least **1.80**_
There are three general methods of installation that we can recommend.
1. Use crates.io and npm (easiest, and requires you to trust that our publishing pipeline worked)
2. Pull sources directly from Github using git tags / revision hashes (most secure)
3. Git submodule install this repo in your tauri project and then use file protocol to ingest the source (most secure, but inconvenient to use)
Install the Core plugin by adding the following to your `Cargo.toml` file:
`src-tauri/Cargo.toml`
```toml
[dependencies.tauri-plugin-sql]
git = "https://github.com/tauri-apps/plugins-workspace"
branch = "v1"
features = ["sqlite"] # or "postgres", or "mysql"
```
You can install the JavaScript Guest bindings using your preferred JavaScript package manager:
> Note: Since most JavaScript package managers are unable to install packages from git monorepos we provide read-only mirrors of each plugin. This makes installation option 2 more ergonomic to use.
```sh
pnpm add https://github.com/tauri-apps/tauri-plugin-sql#v1
# or
npm add https://github.com/tauri-apps/tauri-plugin-sql#v1
# or
yarn add https://github.com/tauri-apps/tauri-plugin-sql#v1
```
## Usage
First you need to register the core plugin with Tauri:
`src-tauri/src/main.rs`
```rust
fn main() {
tauri::Builder::default()
.plugin(tauri_plugin_sql::Builder::default().build())
.run(tauri::generate_context!())
.expect("error while running tauri application");
}
```
Afterwards all the plugin's APIs are available through the JavaScript guest bindings:
```javascript
import Database from "tauri-plugin-sql-api";
// sqlite. The path is relative to `tauri::api::path::BaseDirectory::App`.
const db = await Database.load("sqlite:test.db");
// mysql
const db = await Database.load("mysql://user:pass@host/database");
// postgres
const db = await Database.load("postgres://postgres:password@localhost/test");
await db.execute("INSERT INTO ...");
```
## Syntax
We use sqlx as our underlying library, adopting their query syntax:
- sqlite and postgres use the "$#" syntax when substituting query data
- mysql uses "?" when substituting query data
```javascript
// INSERT and UPDATE examples for sqlite and postgres
const result = await db.execute(
"INSERT into todos (id, title, status) VALUES ($1, $2, $3)",
[todos.id, todos.title, todos.status],
);
const result = await db.execute(
"UPDATE todos SET title = $1, completed = $2 WHERE id = $3",
[todos.title, todos.status, todos.id],
);
// INSERT and UPDATE examples for mysql
const result = await db.execute(
"INSERT into todos (id, title, status) VALUES (?, ?, ?)",
[todos.id, todos.title, todos.status],
);
const result = await db.execute(
"UPDATE todos SET title = ?, completed = ? WHERE id = ?",
[todos.title, todos.status, todos.id],
);
```
## Migrations
This plugin supports database migrations, allowing you to manage database schema evolution over time.
### Defining Migrations
Migrations are defined in Rust using the `Migration` struct. Each migration should include a unique version number, a description, the SQL to be executed, and the type of migration (Up or Down).
Example of a migration:
```rust
use tauri_plugin_sql::{Migration, MigrationKind};
let migration = Migration {
version: 1,
description: "create_initial_tables",
sql: "CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT);",
kind: MigrationKind::Up,
};
```
### Adding Migrations to the Plugin Builder
Migrations are registered with the `Builder` struct provided by the plugin. Use the `add_migrations` method to add your migrations to the plugin for a specific database connection.
Example of adding migrations:
```rust
use tauri_plugin_sql::{Builder, Migration, MigrationKind};
fn main() {
let migrations = vec![
// Define your migrations here
Migration {
version: 1,
description: "create_initial_tables",
sql: "CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT);",
kind: MigrationKind::Up,
}
];
tauri::Builder::default()
.plugin(
tauri_plugin_sql::Builder::default()
.add_migrations("sqlite:mydatabase.db", migrations)
.build(),
)
...
}
```
### Applying Migrations
Migrations are applied automatically when the plugin is initialized. The plugin runs these migrations against the database specified by the connection string. Ensure that the migrations are defined in the correct order and are idempotent (safe to run multiple times).
### Migration Management
- **Version Control**: Each migration must have a unique version number. This is crucial for ensuring the migrations are applied in the correct order.
- **Idempotency**: Write migrations in a way that they can be safely re-run without causing errors or unintended consequences.
- **Testing**: Thoroughly test migrations to ensure they work as expected and do not compromise the integrity of your database.
## Contributing
PRs accepted. Please make sure to read the Contributing Guide before making a pull request.
## Partners
<table>
<tbody>
<tr>
<td align="center" valign="middle">
<a href="https://crabnebula.dev" target="_blank">
<img src="https://github.com/tauri-apps/plugins-workspace/raw/v1/.github/sponsors/crabnebula.svg" alt="CrabNebula" width="283">
</a>
</td>
</tr>
</tbody>
</table>
For the complete list of sponsors please visit our [website](https://tauri.app#sponsors) and [Open Collective](https://opencollective.com/tauri).
## License
Code: (c) 2015 - Present - The Tauri Programme within The Commons Conservancy.
MIT or MIT/Apache 2.0 where applicable.

View File

@@ -1,336 +1,337 @@
// Copyright 2021 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use futures_core::future::BoxFuture;
use serde::{ser::Serializer, Deserialize, Serialize};
use serde_json::Value as JsonValue;
use sqlx::{
error::BoxDynError,
migrate::{
MigrateDatabase, Migration as SqlxMigration, MigrationSource, MigrationType, Migrator,
},
Column, Pool, Row,
};
use tauri::{
command,
plugin::{Builder as PluginBuilder, TauriPlugin},
AppHandle, Manager, RunEvent, Runtime, State,
};
use tokio::sync::Mutex;
use std::collections::HashMap;
#[cfg(feature = "sqlite")]
use std::{fs::create_dir_all, path::PathBuf};
#[cfg(feature = "sqlite")]
type Db = sqlx::sqlite::Sqlite;
#[cfg(feature = "mysql")]
type Db = sqlx::mysql::MySql;
#[cfg(feature = "postgres")]
type Db = sqlx::postgres::Postgres;
#[cfg(feature = "sqlite")]
type LastInsertId = i64;
#[cfg(not(feature = "sqlite"))]
type LastInsertId = u64;
#[derive(Debug, thiserror::Error)]
pub enum Error {
#[error(transparent)]
Sql(#[from] sqlx::Error),
#[error(transparent)]
Migration(#[from] sqlx::migrate::MigrateError),
#[error("database {0} not loaded")]
DatabaseNotLoaded(String),
#[error("unsupported datatype: {0}")]
UnsupportedDatatype(String),
}
impl Serialize for Error {
fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.serialize_str(self.to_string().as_ref())
}
}
type Result<T> = std::result::Result<T, Error>;
#[cfg(feature = "sqlite")]
/// Resolves the App's **file path** from the `AppHandle` context
/// object
fn app_path<R: Runtime>(app: &AppHandle<R>) -> PathBuf {
#[allow(deprecated)] // FIXME: Change to non-deprecated function in Tauri v2
app.path_resolver()
.app_dir()
.expect("No App path was found!")
}
#[cfg(feature = "sqlite")]
/// Maps the user supplied DB connection string to a connection string
/// with a fully qualified file path to the App's designed "app_path"
fn path_mapper(mut app_path: PathBuf, connection_string: &str) -> String {
app_path.push(
connection_string
.split_once(':')
.expect("Couldn't parse the connection string for DB!")
.1,
);
format!(
"sqlite:{}",
app_path
.to_str()
.expect("Problem creating fully qualified path to Database file!")
)
}
#[derive(Default)]
struct DbInstances(Mutex<HashMap<String, Pool<Db>>>);
struct Migrations(Mutex<HashMap<String, MigrationList>>);
#[derive(Default, Deserialize)]
pub struct PluginConfig {
#[serde(default)]
preload: Vec<String>,
}
#[derive(Debug)]
pub enum MigrationKind {
Up,
Down,
}
impl From<MigrationKind> for MigrationType {
fn from(kind: MigrationKind) -> Self {
match kind {
MigrationKind::Up => Self::ReversibleUp,
MigrationKind::Down => Self::ReversibleDown,
}
}
}
/// A migration definition.
#[derive(Debug)]
pub struct Migration {
pub version: i64,
pub description: &'static str,
pub sql: &'static str,
pub kind: MigrationKind,
}
#[derive(Debug)]
struct MigrationList(Vec<Migration>);
impl MigrationSource<'static> for MigrationList {
fn resolve(self) -> BoxFuture<'static, std::result::Result<Vec<SqlxMigration>, BoxDynError>> {
Box::pin(async move {
let mut migrations = Vec::new();
for migration in self.0 {
if matches!(migration.kind, MigrationKind::Up) {
migrations.push(SqlxMigration::new(
migration.version,
migration.description.into(),
migration.kind.into(),
migration.sql.into(),
));
}
}
Ok(migrations)
})
}
}
#[command]
async fn load<R: Runtime>(
#[allow(unused_variables)] app: AppHandle<R>,
db_instances: State<'_, DbInstances>,
migrations: State<'_, Migrations>,
db: String,
) -> Result<String> {
#[cfg(feature = "sqlite")]
let fqdb = path_mapper(app_path(&app), &db);
#[cfg(not(feature = "sqlite"))]
let fqdb = db.clone();
#[cfg(feature = "sqlite")]
create_dir_all(app_path(&app)).expect("Problem creating App directory!");
if !Db::database_exists(&fqdb).await.unwrap_or(false) {
Db::create_database(&fqdb).await?;
}
let pool = Pool::connect(&fqdb).await?;
if let Some(migrations) = migrations.0.lock().await.remove(&db) {
let migrator = Migrator::new(migrations).await?;
migrator.run(&pool).await?;
}
db_instances.0.lock().await.insert(db.clone(), pool);
Ok(db)
}
/// Allows the database connection(s) to be closed; if no database
/// name is passed in then _all_ database connection pools will be
/// shut down.
#[command]
async fn close(db_instances: State<'_, DbInstances>, db: Option<String>) -> Result<bool> {
let mut instances = db_instances.0.lock().await;
let pools = if let Some(db) = db {
vec![db]
} else {
instances.keys().cloned().collect()
};
for pool in pools {
let db = instances
.get_mut(&pool) //
.ok_or(Error::DatabaseNotLoaded(pool))?;
db.close().await;
}
Ok(true)
}
/// Execute a command against the database
#[command]
async fn execute(
db_instances: State<'_, DbInstances>,
db: String,
query: String,
values: Vec<JsonValue>,
) -> Result<(u64, LastInsertId)> {
let mut instances = db_instances.0.lock().await;
let db = instances.get_mut(&db).ok_or(Error::DatabaseNotLoaded(db))?;
let mut query = sqlx::query(&query);
for value in values {
if value.is_null() {
query = query.bind(None::<JsonValue>);
} else if value.is_string() {
query = query.bind(value.as_str().unwrap().to_owned())
} else {
query = query.bind(value);
}
}
let result = query.execute(&*db).await?;
#[cfg(feature = "sqlite")]
let r = Ok((result.rows_affected(), result.last_insert_rowid()));
#[cfg(feature = "mysql")]
let r = Ok((result.rows_affected(), result.last_insert_id()));
#[cfg(feature = "postgres")]
let r = Ok((result.rows_affected(), 0));
r
}
#[command]
async fn select(
db_instances: State<'_, DbInstances>,
db: String,
query: String,
values: Vec<JsonValue>,
) -> Result<Vec<HashMap<String, JsonValue>>> {
let mut instances = db_instances.0.lock().await;
let db = instances.get_mut(&db).ok_or(Error::DatabaseNotLoaded(db))?;
let mut query = sqlx::query(&query);
for value in values {
if value.is_null() {
query = query.bind(None::<JsonValue>);
} else if value.is_string() {
query = query.bind(value.as_str().unwrap().to_owned())
} else {
query = query.bind(value);
}
}
let rows = query.fetch_all(&*db).await?;
let mut values = Vec::new();
for row in rows {
let mut value = HashMap::default();
for (i, column) in row.columns().iter().enumerate() {
let v = row.try_get_raw(i)?;
let v = crate::decode::to_json(v)?;
value.insert(column.name().to_string(), v);
}
values.push(value);
}
Ok(values)
}
/// Tauri SQL plugin builder.
#[derive(Default)]
pub struct Builder {
migrations: Option<HashMap<String, MigrationList>>,
}
impl Builder {
/// Add migrations to a database.
#[must_use]
pub fn add_migrations(mut self, db_url: &str, migrations: Vec<Migration>) -> Self {
self.migrations
.get_or_insert(Default::default())
.insert(db_url.to_string(), MigrationList(migrations));
self
}
pub fn build<R: Runtime>(mut self) -> TauriPlugin<R, Option<PluginConfig>> {
PluginBuilder::new("sql")
.invoke_handler(tauri::generate_handler![load, execute, select, close])
.setup_with_config(|app, config: Option<PluginConfig>| {
let config = config.unwrap_or_default();
#[cfg(feature = "sqlite")]
create_dir_all(app_path(app)).expect("problems creating App directory!");
tauri::async_runtime::block_on(async move {
let instances = DbInstances::default();
let mut lock = instances.0.lock().await;
for db in config.preload {
#[cfg(feature = "sqlite")]
let fqdb = path_mapper(app_path(app), &db);
#[cfg(not(feature = "sqlite"))]
let fqdb = db.clone();
if !Db::database_exists(&fqdb).await.unwrap_or(false) {
Db::create_database(&fqdb).await?;
}
let pool = Pool::connect(&fqdb).await?;
if let Some(migrations) = self.migrations.as_mut().unwrap().remove(&db) {
let migrator = Migrator::new(migrations).await?;
migrator.run(&pool).await?;
}
lock.insert(db, pool);
}
drop(lock);
app.manage(instances);
app.manage(Migrations(Mutex::new(
self.migrations.take().unwrap_or_default(),
)));
Ok(())
})
})
.on_event(|app, event| {
if let RunEvent::Exit = event {
tauri::async_runtime::block_on(async move {
let instances = &*app.state::<DbInstances>();
let instances = instances.0.lock().await;
for value in instances.values() {
value.close().await;
}
});
}
})
.build()
}
}
// Copyright 2021 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use futures_core::future::BoxFuture;
use serde::{ser::Serializer, Deserialize, Serialize};
use serde_json::Value as JsonValue;
use sqlx::{
error::BoxDynError,
migrate::{
MigrateDatabase, Migration as SqlxMigration, MigrationSource, MigrationType, Migrator,
},
Column, Pool, Row,
};
use tauri::{
command,
plugin::{Builder as PluginBuilder, TauriPlugin},
AppHandle, Manager, RunEvent, Runtime, State,
};
use tokio::sync::Mutex;
use std::collections::HashMap;
#[cfg(feature = "sqlite")]
use std::{fs::create_dir_all, path::PathBuf};
#[cfg(feature = "sqlite")]
type Db = sqlx::sqlite::Sqlite;
#[cfg(feature = "mysql")]
type Db = sqlx::mysql::MySql;
#[cfg(feature = "postgres")]
type Db = sqlx::postgres::Postgres;
#[cfg(feature = "sqlite")]
type LastInsertId = i64;
#[cfg(not(feature = "sqlite"))]
type LastInsertId = u64;
#[derive(Debug, thiserror::Error)]
pub enum Error {
#[error(transparent)]
Sql(#[from] sqlx::Error),
#[error(transparent)]
Migration(#[from] sqlx::migrate::MigrateError),
#[error("database {0} not loaded")]
DatabaseNotLoaded(String),
#[error("unsupported datatype: {0}")]
UnsupportedDatatype(String),
}
impl Serialize for Error {
fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.serialize_str(self.to_string().as_ref())
}
}
type Result<T> = std::result::Result<T, Error>;
#[cfg(feature = "sqlite")]
/// Resolves the App's **file path** from the `AppHandle` context
/// object
fn app_path<R: Runtime>(app: &AppHandle<R>) -> PathBuf {
#[allow(deprecated)] // FIXME: Change to non-deprecated function in Tauri v2
app.path_resolver()
.app_dir()
.expect("No App path was found!")
}
#[cfg(feature = "sqlite")]
/// Maps the user supplied DB connection string to a connection string
/// with a fully qualified file path to the App's designed "app_path"
fn path_mapper(mut app_path: PathBuf, connection_string: &str) -> String {
app_path.push(
connection_string
.split_once(':')
.expect("Couldn't parse the connection string for DB!")
.1,
);
format!(
"sqlite:{}",
app_path
.to_str()
.expect("Problem creating fully qualified path to Database file!")
)
}
#[derive(Default)]
struct DbInstances(Mutex<HashMap<String, Pool<Db>>>);
struct Migrations(Mutex<HashMap<String, MigrationList>>);
#[derive(Default, Deserialize)]
pub struct PluginConfig {
#[serde(default)]
preload: Vec<String>,
}
#[derive(Debug)]
pub enum MigrationKind {
Up,
Down,
}
impl From<MigrationKind> for MigrationType {
fn from(kind: MigrationKind) -> Self {
match kind {
MigrationKind::Up => Self::ReversibleUp,
MigrationKind::Down => Self::ReversibleDown,
}
}
}
/// A migration definition.
#[derive(Debug)]
pub struct Migration {
pub version: i64,
pub description: &'static str,
pub sql: &'static str,
pub kind: MigrationKind,
}
#[derive(Debug)]
struct MigrationList(Vec<Migration>);
impl MigrationSource<'static> for MigrationList {
fn resolve(self) -> BoxFuture<'static, std::result::Result<Vec<SqlxMigration>, BoxDynError>> {
Box::pin(async move {
let mut migrations = Vec::new();
for migration in self.0 {
if matches!(migration.kind, MigrationKind::Up) {
migrations.push(SqlxMigration::new(
migration.version,
migration.description.into(),
migration.kind.into(),
migration.sql.into(),
false,
));
}
}
Ok(migrations)
})
}
}
#[command]
async fn load<R: Runtime>(
#[allow(unused_variables)] app: AppHandle<R>,
db_instances: State<'_, DbInstances>,
migrations: State<'_, Migrations>,
db: String,
) -> Result<String> {
#[cfg(feature = "sqlite")]
let fqdb = path_mapper(app_path(&app), &db);
#[cfg(not(feature = "sqlite"))]
let fqdb = db.clone();
#[cfg(feature = "sqlite")]
create_dir_all(app_path(&app)).expect("Problem creating App directory!");
if !Db::database_exists(&fqdb).await.unwrap_or(false) {
Db::create_database(&fqdb).await?;
}
let pool = Pool::connect(&fqdb).await?;
if let Some(migrations) = migrations.0.lock().await.remove(&db) {
let migrator = Migrator::new(migrations).await?;
migrator.run(&pool).await?;
}
db_instances.0.lock().await.insert(db.clone(), pool);
Ok(db)
}
/// Allows the database connection(s) to be closed; if no database
/// name is passed in then _all_ database connection pools will be
/// shut down.
#[command]
async fn close(db_instances: State<'_, DbInstances>, db: Option<String>) -> Result<bool> {
let mut instances = db_instances.0.lock().await;
let pools = if let Some(db) = db {
vec![db]
} else {
instances.keys().cloned().collect()
};
for pool in pools {
let db = instances
.get_mut(&pool) //
.ok_or(Error::DatabaseNotLoaded(pool))?;
db.close().await;
}
Ok(true)
}
/// Execute a command against the database
#[command]
async fn execute(
db_instances: State<'_, DbInstances>,
db: String,
query: String,
values: Vec<JsonValue>,
) -> Result<(u64, LastInsertId)> {
let mut instances = db_instances.0.lock().await;
let db = instances.get_mut(&db).ok_or(Error::DatabaseNotLoaded(db))?;
let mut query = sqlx::query(&query);
for value in values {
if value.is_null() {
query = query.bind(None::<JsonValue>);
} else if value.is_string() {
query = query.bind(value.as_str().unwrap().to_owned())
} else {
query = query.bind(value);
}
}
let result = query.execute(&*db).await?;
#[cfg(feature = "sqlite")]
let r = Ok((result.rows_affected(), result.last_insert_rowid()));
#[cfg(feature = "mysql")]
let r = Ok((result.rows_affected(), result.last_insert_id()));
#[cfg(feature = "postgres")]
let r = Ok((result.rows_affected(), 0));
r
}
#[command]
async fn select(
db_instances: State<'_, DbInstances>,
db: String,
query: String,
values: Vec<JsonValue>,
) -> Result<Vec<HashMap<String, JsonValue>>> {
let mut instances = db_instances.0.lock().await;
let db = instances.get_mut(&db).ok_or(Error::DatabaseNotLoaded(db))?;
let mut query = sqlx::query(&query);
for value in values {
if value.is_null() {
query = query.bind(None::<JsonValue>);
} else if value.is_string() {
query = query.bind(value.as_str().unwrap().to_owned())
} else {
query = query.bind(value);
}
}
let rows = query.fetch_all(&*db).await?;
let mut values = Vec::new();
for row in rows {
let mut value = HashMap::default();
for (i, column) in row.columns().iter().enumerate() {
let v = row.try_get_raw(i)?;
let v = crate::decode::to_json(v)?;
value.insert(column.name().to_string(), v);
}
values.push(value);
}
Ok(values)
}
/// Tauri SQL plugin builder.
#[derive(Default)]
pub struct Builder {
migrations: Option<HashMap<String, MigrationList>>,
}
impl Builder {
/// Add migrations to a database.
#[must_use]
pub fn add_migrations(mut self, db_url: &str, migrations: Vec<Migration>) -> Self {
self.migrations
.get_or_insert(Default::default())
.insert(db_url.to_string(), MigrationList(migrations));
self
}
pub fn build<R: Runtime>(mut self) -> TauriPlugin<R, Option<PluginConfig>> {
PluginBuilder::new("sql")
.invoke_handler(tauri::generate_handler![load, execute, select, close])
.setup_with_config(|app, config: Option<PluginConfig>| {
let config = config.unwrap_or_default();
#[cfg(feature = "sqlite")]
create_dir_all(app_path(app)).expect("problems creating App directory!");
tauri::async_runtime::block_on(async move {
let instances = DbInstances::default();
let mut lock = instances.0.lock().await;
for db in config.preload {
#[cfg(feature = "sqlite")]
let fqdb = path_mapper(app_path(app), &db);
#[cfg(not(feature = "sqlite"))]
let fqdb = db.clone();
if !Db::database_exists(&fqdb).await.unwrap_or(false) {
Db::create_database(&fqdb).await?;
}
let pool = Pool::connect(&fqdb).await?;
if let Some(migrations) = self.migrations.as_mut().unwrap().remove(&db) {
let migrator = Migrator::new(migrations).await?;
migrator.run(&pool).await?;
}
lock.insert(db, pool);
}
drop(lock);
app.manage(instances);
app.manage(Migrations(Mutex::new(
self.migrations.take().unwrap_or_default(),
)));
Ok(())
})
})
.on_event(|app, event| {
if let RunEvent::Exit = event {
tauri::async_runtime::block_on(async move {
let instances = &*app.state::<DbInstances>();
let instances = instances.0.lock().await;
for value in instances.values() {
value.close().await;
}
});
}
})
.build()
}
}