Skip to content

feat(sql): support for SQLite pragma and encryption pragmas #2553

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 4 commits into
base: v2
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 3 additions & 0 deletions plugins/sql/.vscode/settings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"rust-analyzer.cargo.features": ["mysql", "postgres", "sqlite"]
}
3 changes: 2 additions & 1 deletion plugins/sql/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -36,8 +36,9 @@ time = "0.3"
tokio = { version = "1", features = ["sync"] }
indexmap = { version = "2", features = ["serde"] }

libsqlite3-sys = { version = "0.30.1", features = ["bundled-sqlcipher"] }

[features]
sqlite = ["sqlx/sqlite", "sqlx/runtime-tokio"]
mysql = ["sqlx/mysql", "sqlx/runtime-tokio-rustls"]
postgres = ["sqlx/postgres", "sqlx/runtime-tokio-rustls"]
# TODO: bundled-cipher etc
2 changes: 1 addition & 1 deletion plugins/sql/api-iife.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

23 changes: 21 additions & 2 deletions plugins/sql/guest-js/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,12 +42,31 @@ export default class Database {
*
* @example
* ```ts
* // Basic connection to a SQLite database
* const db = await Database.load("sqlite:test.db");
*
* // Connecting with an encryption key for added security
* const db = await Database.load("sqlite:encrypted.db", {
* sqlite: { pragmas: { "key": "encryption_key" } }
* });
*
* // Connecting with specific pragmas for configuration
* const db = await Database.load("sqlite:test.db", {
* sqlite: { pragmas: { "journal_mode": "WAL", "foreign_keys": "ON" } }
* });
* ```
*/
static async load(path: string): Promise<Database> {
static async load(
path: string,
options?: {
sqlite?: {
pragmas?: Record<string, string>
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Since you are already adding options. Could you add support for extensions, to fix #1705

extensions?: Record<string, Option<string>>  // extension, entry_point

}
}
): Promise<Database> {
const _path = await invoke<string>('plugin:sql|load', {
db: path
db: path,
options
})

return new Database(_path)
Expand Down
7 changes: 3 additions & 4 deletions plugins/sql/src/commands.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,22 +2,21 @@
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT

use crate::{wrapper::ConnectionOptions, DbInstances, DbPool, Error, LastInsertId, Migrations};
use indexmap::IndexMap;
use serde_json::Value as JsonValue;
use sqlx::migrate::Migrator;
use tauri::{command, AppHandle, Runtime, State};

use crate::{DbInstances, DbPool, Error, LastInsertId, Migrations};

#[command]
pub(crate) async fn load<R: Runtime>(
app: AppHandle<R>,
db_instances: State<'_, DbInstances>,
migrations: State<'_, Migrations>,
db: String,
options: Option<ConnectionOptions>,
) -> Result<String, crate::Error> {
let pool = DbPool::connect(&db, &app).await?;

let pool = DbPool::connect(&db, &app, options).await?;
if let Some(migrations) = migrations.0.lock().await.remove(&db) {
let migrator = Migrator::new(migrations).await?;
pool.migrate(&migrator).await?;
Expand Down
5 changes: 4 additions & 1 deletion plugins/sql/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,9 @@ mod wrapper;

pub use error::Error;
pub use wrapper::DbPool;
#[cfg(feature = "sqlite")]
pub use wrapper::SqliteOptions;
pub use wrapper::ConnectionOptions;

use futures_core::future::BoxFuture;
use serde::{Deserialize, Serialize};
Expand Down Expand Up @@ -150,7 +153,7 @@ impl Builder {
let mut lock = instances.0.write().await;

for db in config.preload {
let pool = DbPool::connect(&db, app).await?;
let pool = DbPool::connect(&db, app, None).await?;

if let Some(migrations) =
self.migrations.as_mut().and_then(|mm| mm.remove(&db))
Expand Down
57 changes: 53 additions & 4 deletions plugins/sql/src/wrapper.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,15 @@
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT

#[cfg(feature = "sqlite")]
use std::collections::HashMap;
#[cfg(feature = "sqlite")]
use std::fs::create_dir_all;

use indexmap::IndexMap;
use serde_json::Value as JsonValue;
#[cfg(feature = "sqlite")]
use sqlx::sqlite::SqliteConnectOptions;
#[cfg(any(feature = "sqlite", feature = "mysql", feature = "postgres"))]
use sqlx::{migrate::MigrateDatabase, Column, Executor, Pool, Row};
#[cfg(any(feature = "sqlite", feature = "mysql", feature = "postgres"))]
Expand All @@ -33,6 +37,40 @@ pub enum DbPool {
None,
}

#[cfg(feature = "sqlite")]
#[derive(serde::Serialize, serde::Deserialize, Debug)]
pub struct SqliteOptions {
pub pragmas: HashMap<String, String>,
}

#[cfg(feature = "sqlite")]
impl Default for SqliteOptions {
fn default() -> Self {
Self {
pragmas: HashMap::new(),
}
}
}

#[derive(serde::Serialize, serde::Deserialize, Debug)]
pub struct ConnectionOptions {
#[cfg(feature = "sqlite")]
pub sqlite: Option<SqliteOptions>,
// #[cfg(feature = "mysql")]
// mysql: Option<MySqlOptions>,
// #[cfg(feature = "postgres")]
// postgres: Option<PostgresOptions>,
}

impl Default for ConnectionOptions {
fn default() -> Self {
Self {
#[cfg(feature = "sqlite")]
sqlite: None,
}
}
}

// public methods
/* impl DbPool {
/// Get the inner Sqlite Pool. Returns None for MySql and Postgres pools.
Expand Down Expand Up @@ -68,6 +106,7 @@ impl DbPool {
pub(crate) async fn connect<R: Runtime>(
conn_url: &str,
_app: &AppHandle<R>,
options: Option<ConnectionOptions>,
) -> Result<Self, crate::Error> {
match conn_url
.split_once(':')
Expand All @@ -82,13 +121,23 @@ impl DbPool {
.expect("No App config path was found!");

create_dir_all(&app_path).expect("Couldn't create app config dir");

let conn_url = &path_mapper(app_path, conn_url);
let filename = conn_url.split_once(':').unwrap().1;

if !Sqlite::database_exists(conn_url).await.unwrap_or(false) {
Sqlite::create_database(conn_url).await?;
let mut sqlite_options = SqliteConnectOptions::new()
.filename(filename)
.create_if_missing(true);
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Load extensions with entry points.

// Apply pragmas if provided
if let Some(conn_opts) = options {
if let Some(sqlite_opts) = conn_opts.sqlite {
for (pragma_name, pragma_value) in sqlite_opts.pragmas {
sqlite_options = sqlite_options.pragma(pragma_name, pragma_value);
}
}
}
Ok(Self::Sqlite(Pool::connect(conn_url).await?))

// Connect with options (which includes create_if_missing)
Ok(Self::Sqlite(Pool::connect_with(sqlite_options).await?))
}
#[cfg(feature = "mysql")]
"mysql" => {
Expand Down