Skip to content
Merged
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
4 changes: 4 additions & 0 deletions .github/workflows/tauri-ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,10 @@ jobs:
working-directory: apps/tauri/src-tauri
run: cargo check --locked

- name: cargo clippy
working-directory: apps/tauri/src-tauri
run: cargo clippy --locked --all-targets -- -D warnings

- name: cargo test
working-directory: apps/tauri/src-tauri
run: cargo test --locked
27 changes: 6 additions & 21 deletions apps/tauri/src-tauri/src/commands.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use crate::connection::{
ConnectionConfig, ConnectionError, ConnectionId, ConnectionManager, ConnectionRegistry,
QueryEvent, SchemaObject, TableSchema,
SchemaObject, TableSchema,
};
use tauri::ipc::Channel;
use tauri::State;
Expand Down Expand Up @@ -51,35 +51,20 @@ pub fn db_list_columns(
registry.with_sqlite(&id, |s| s.list_columns(&table))
}

/// Execute SQL and stream `QueryEvent` batches over `on_event` (not one giant IPC payload).
/// Execute SQL and stream `QueryEvent` batches over `on_event`.
/// Failures return as the invoke `Err` only (no dual channel `Error` event).
#[tauri::command]
pub fn db_execute_query(
id: ConnectionId,
sql: String,
limit: Option<u32>,
on_event: Channel<QueryEvent>,
on_event: Channel<crate::connection::QueryEvent>,
registry: State<'_, ConnectionRegistry>,
) -> Result<(), ConnectionError> {
let conn_arc = registry.sqlite_connection_arc(&id)?;
let guard = conn_arc
.lock()
.map_err(|_| ConnectionError::io("sqlite connection lock poisoned"))?;
let conn = guard
.as_ref()
.ok_or_else(|| ConnectionError::Disconnected { id: id.clone() })?;

let limit = limit.map(|n| n as usize);
match crate::connection::sqlite_query::execute_streaming(conn, &sql, limit, None, |ev| {
registry.execute_sqlite_query(&id, &sql, limit, |ev| {
on_event
.send(ev)
.map_err(|e| ConnectionError::io(format!("query channel closed: {e}")))
}) {
Ok(()) => Ok(()),
Err(e) => {
let _ = on_event.send(QueryEvent::Error {
message: e.to_string(),
});
Err(e)
}
}
})
}
18 changes: 18 additions & 0 deletions apps/tauri/src-tauri/src/connection/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,12 @@ impl fmt::Display for ConnectionError {

impl std::error::Error for ConnectionError {}

impl From<rusqlite::Error> for ConnectionError {
fn from(value: rusqlite::Error) -> Self {
Self::driver(DriverKind::Sqlite, value.to_string())
}
}

/// IPC-friendly result alias.
pub type ConnectionResult<T> = Result<T, ConnectionError>;

Expand All @@ -79,4 +85,16 @@ mod tests {
let err = ConnectionError::driver(DriverKind::Sqlite, "no such table");
assert_eq!(err.to_string(), "sqlite error: no such table");
}

#[test]
fn from_rusqlite() {
let err: ConnectionError = rusqlite::Error::InvalidQuery.into();
assert!(matches!(
err,
ConnectionError::Driver {
driver: DriverKind::Sqlite,
..
}
));
}
}
6 changes: 1 addition & 5 deletions apps/tauri/src-tauri/src/connection/id.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,15 +41,13 @@ impl From<&str> for ConnectionId {
}
}

/// Driver family — mirrors Flutter connection `type` strings.
/// Driver family wired (or stubbed) in this crate. Redis/Mongo land with their epics.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum DriverKind {
Sqlite,
Postgres,
Mysql,
Redis,
Mongodb,
}

impl DriverKind {
Expand All @@ -58,8 +56,6 @@ impl DriverKind {
Self::Sqlite => "sqlite",
Self::Postgres => "postgres",
Self::Mysql => "mysql",
Self::Redis => "redis",
Self::Mongodb => "mongodb",
}
}
}
Expand Down
103 changes: 72 additions & 31 deletions apps/tauri/src-tauri/src/connection/manager.rs
Original file line number Diff line number Diff line change
@@ -1,33 +1,34 @@
use super::error::{ConnectionError, ConnectionResult};
use super::id::{ConnectionId, DriverKind};
use super::query::QueryEvent;
use super::sqlite::SqliteSession;
use serde::{Deserialize, Serialize};
use std::any::Any;
use std::collections::HashMap;
use std::sync::{Arc, Mutex};

/// Driver-agnostic connect parameters (tagged for IPC).
/// Secrets are not part of this enum — keyring lands with #1847.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "driver", rename_all = "snake_case")]
pub enum ConnectionConfig {
Sqlite {
/// Absolute or relative path to a `.db` / `.sqlite` file.
path: String,
},
/// Stub until the Postgres adapter epic wires connect.
Postgres {
host: String,
port: u16,
database: String,
user: String,
/// Secret is resolved via keyring later; optional here for stubs.
password: Option<String>,
},
/// Stub until the MySQL adapter epic wires connect.
Mysql {
host: String,
port: u16,
database: String,
user: String,
password: Option<String>,
},
}

Expand All @@ -45,7 +46,8 @@ impl ConnectionConfig {
pub trait ConnectionSession: Send + Sync {
fn id(&self) -> &ConnectionId;
fn driver(&self) -> DriverKind;
fn disconnect(&mut self) -> ConnectionResult<()>;
/// Close the underlying driver connection (interior mutability OK).
fn disconnect(&self) -> ConnectionResult<()>;
/// Downcast hook for driver-specific APIs (introspection, query).
fn as_any(&self) -> &dyn Any;
}
Expand All @@ -58,13 +60,12 @@ pub trait ConnectionManager: Send + Sync {
fn driver_of(&self, id: &ConnectionId) -> Option<DriverKind>;
}

type SessionBox = Box<dyn ConnectionSession>;
type SessionArc = Arc<dyn ConnectionSession>;

/// In-memory registry used by Tauri commands. Drivers register factories later.
/// In-memory registry used by Tauri commands.
pub struct ConnectionRegistry {
sessions: Mutex<HashMap<ConnectionId, SessionBox>>,
/// Optional opener for tests / driver wiring. Returns a live session.
opener: Option<Arc<dyn Fn(ConnectionConfig) -> ConnectionResult<SessionBox> + Send + Sync>>,
sessions: Mutex<HashMap<ConnectionId, SessionArc>>,
opener: Option<Arc<dyn Fn(ConnectionConfig) -> ConnectionResult<SessionArc> + Send + Sync>>,
}

impl Default for ConnectionRegistry {
Expand All @@ -81,7 +82,10 @@ impl ConnectionRegistry {
/// Registry with SQLite opener wired (PG/MySQL return UnsupportedDriver).
pub fn with_builtin_drivers() -> Self {
Self::with_opener(|config| match config {
ConnectionConfig::Sqlite { path } => super::sqlite::open_sqlite(path),
ConnectionConfig::Sqlite { path } => {
let session = super::sqlite::open_sqlite(path)?;
Ok(Arc::new(session) as SessionArc)
}
other => Err(ConnectionError::UnsupportedDriver {
driver: other.driver_kind(),
}),
Expand All @@ -90,7 +94,7 @@ impl ConnectionRegistry {

pub fn with_opener<F>(opener: F) -> Self
where
F: Fn(ConnectionConfig) -> ConnectionResult<SessionBox> + Send + Sync + 'static,
F: Fn(ConnectionConfig) -> ConnectionResult<SessionArc> + Send + Sync + 'static,
{
Self {
sessions: Mutex::new(HashMap::new()),
Expand All @@ -100,22 +104,27 @@ impl ConnectionRegistry {

fn lock(
&self,
) -> ConnectionResult<std::sync::MutexGuard<'_, HashMap<ConnectionId, SessionBox>>> {
) -> ConnectionResult<std::sync::MutexGuard<'_, HashMap<ConnectionId, SessionArc>>> {
self.sessions
.lock()
.map_err(|_| ConnectionError::io("connection registry lock poisoned"))
}

/// Run a closure against a live [`SqliteSession`].
/// Clone a session Arc under a brief map lock.
fn session_arc(&self, id: &ConnectionId) -> ConnectionResult<SessionArc> {
let map = self.lock()?;
map.get(id)
.cloned()
.ok_or_else(|| ConnectionError::NotFound { id: id.clone() })
}

/// Run a closure against a live [`SqliteSession`] **outside** the registry map lock.
pub fn with_sqlite<T>(
&self,
id: &ConnectionId,
f: impl FnOnce(&SqliteSession) -> ConnectionResult<T>,
) -> ConnectionResult<T> {
let map = self.lock()?;
let session = map
.get(id)
.ok_or_else(|| ConnectionError::NotFound { id: id.clone() })?;
let session = self.session_arc(id)?;
let sqlite = session
.as_any()
.downcast_ref::<SqliteSession>()
Expand All @@ -125,12 +134,15 @@ impl ConnectionRegistry {
f(sqlite)
}

/// Clone the SQLite connection Arc so callers can drop the registry lock.
pub fn sqlite_connection_arc(
/// Stream a query through the SQLite session API (commands stay thin).
pub fn execute_sqlite_query(
&self,
id: &ConnectionId,
) -> ConnectionResult<std::sync::Arc<std::sync::Mutex<Option<rusqlite::Connection>>>> {
self.with_sqlite(id, |s| Ok(s.connection_arc()))
sql: &str,
limit: Option<usize>,
emit: impl FnMut(QueryEvent) -> ConnectionResult<()>,
) -> ConnectionResult<()> {
self.with_sqlite(id, |s| s.execute_streaming(sql, limit, emit))
}
}

Expand All @@ -142,6 +154,7 @@ impl ConnectionManager for ConnectionRegistry {
.ok_or(ConnectionError::UnsupportedDriver {
driver: config.driver_kind(),
})?;
// Open outside the map lock (disk I/O).
let session = opener(config)?;
let id = session.id().clone();
let mut map = self.lock()?;
Expand All @@ -154,11 +167,11 @@ impl ConnectionManager for ConnectionRegistry {

fn disconnect(&self, id: &ConnectionId) -> ConnectionResult<()> {
let mut map = self.lock()?;
let mut session = map
let session = map
.remove(id)
.ok_or_else(|| ConnectionError::NotFound { id: id.clone() })?;
session.disconnect()?;
Ok(())
drop(map);
session.disconnect()
}

fn is_connected(&self, id: &ConnectionId) -> bool {
Expand All @@ -177,7 +190,6 @@ mod tests {
struct FakeSession {
id: ConnectionId,
driver: DriverKind,
closed: bool,
}

impl ConnectionSession for FakeSession {
Expand All @@ -187,8 +199,7 @@ mod tests {
fn driver(&self) -> DriverKind {
self.driver
}
fn disconnect(&mut self) -> ConnectionResult<()> {
self.closed = true;
fn disconnect(&self) -> ConnectionResult<()> {
Ok(())
}
fn as_any(&self) -> &dyn Any {
Expand All @@ -200,11 +211,10 @@ mod tests {
fn registry_connect_disconnect() {
let reg = ConnectionRegistry::with_opener(|cfg| {
assert!(matches!(cfg, ConnectionConfig::Sqlite { .. }));
Ok(Box::new(FakeSession {
Ok(Arc::new(FakeSession {
id: ConnectionId::from("s1"),
driver: DriverKind::Sqlite,
closed: false,
}))
}) as SessionArc)
});

let id = reg
Expand All @@ -230,7 +240,6 @@ mod tests {
port: 5432,
database: "db".into(),
user: "u".into(),
password: None,
})
.unwrap_err();
assert!(matches!(
Expand All @@ -240,4 +249,36 @@ mod tests {
}
));
}

#[test]
fn execute_sqlite_query_streams_via_session() {
let path = std::env::temp_dir().join(format!(
"querya_reg_query_{}.db",
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_nanos()
));
{
let conn = rusqlite::Connection::open(&path).unwrap();
conn.execute_batch("CREATE TABLE t(n INTEGER); INSERT INTO t VALUES (1),(2),(3);")
.unwrap();
}
let reg = ConnectionRegistry::with_builtin_drivers();
let id = reg
.connect(ConnectionConfig::Sqlite {
path: path.to_string_lossy().into(),
})
.unwrap();
let mut events = Vec::new();
reg.execute_sqlite_query(&id, "SELECT n FROM t ORDER BY n", Some(10), |ev| {
events.push(ev);
Ok(())
})
.unwrap();
assert!(matches!(events.first(), Some(QueryEvent::Columns { .. })));
assert!(matches!(events.last(), Some(QueryEvent::Done { row_count: 3, .. })));
reg.disconnect(&id).unwrap();
let _ = std::fs::remove_file(&path);
}
}
4 changes: 0 additions & 4 deletions apps/tauri/src-tauri/src/connection/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,4 @@ pub use error::ConnectionError;
pub use id::{ConnectionId, DriverKind};
pub use introspect::{ColumnMeta, SchemaObject, SchemaObjectKind, TableSchema};
pub use manager::{ConnectionConfig, ConnectionManager, ConnectionRegistry};
#[allow(unused_imports)] // public API for later IPC / frontend issues
pub use manager::ConnectionSession;
pub use query::QueryEvent;
#[allow(unused_imports)] // public API for later IPC / frontend issues
pub use sqlite::{open_sqlite, SqliteSession};
Loading
Loading