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
1 change: 1 addition & 0 deletions apps/tauri/src-tauri/Cargo.lock

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

1 change: 1 addition & 0 deletions apps/tauri/src-tauri/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ tauri = { version = "2", features = [] }
tauri-plugin-opener = "2"
serde = { version = "1", features = ["derive"] }
serde_json = "1"
uuid = { version = "1", features = ["v4", "serde"] }

[profile.release]
codegen-units = 1
Expand Down
82 changes: 82 additions & 0 deletions apps/tauri/src-tauri/src/connection/error.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
use super::id::{ConnectionId, DriverKind};
use serde::Serialize;
use std::fmt;

/// Typed connection failures exposed over Tauri IPC.
#[derive(Debug, Clone, Serialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum ConnectionError {
NotFound { id: ConnectionId },
AlreadyConnected { id: ConnectionId },
Disconnected { id: ConnectionId },
InvalidConfig { message: String },
UnsupportedDriver { driver: DriverKind },
Io { message: String },
Driver { driver: DriverKind, message: String },
}

impl ConnectionError {
pub fn invalid_config(message: impl Into<String>) -> Self {
Self::InvalidConfig {
message: message.into(),
}
}

pub fn io(message: impl Into<String>) -> Self {
Self::Io {
message: message.into(),
}
}

pub fn driver(driver: DriverKind, message: impl Into<String>) -> Self {
Self::Driver {
driver,
message: message.into(),
}
}
}

impl fmt::Display for ConnectionError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::NotFound { id } => write!(f, "connection not found: {id}"),
Self::AlreadyConnected { id } => write!(f, "already connected: {id}"),
Self::Disconnected { id } => write!(f, "connection closed: {id}"),
Self::InvalidConfig { message } => write!(f, "invalid config: {message}"),
Self::UnsupportedDriver { driver } => {
write!(f, "unsupported driver: {driver}")
}
Self::Io { message } => write!(f, "io error: {message}"),
Self::Driver { driver, message } => {
write!(f, "{driver} error: {message}")
}
}
}
}

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

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

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn display_and_serde_not_found() {
let err = ConnectionError::NotFound {
id: ConnectionId::from("c1"),
};
assert_eq!(err.to_string(), "connection not found: c1");
let json = serde_json::to_value(&err).unwrap();
assert_eq!(json["kind"], "not_found");
assert_eq!(json["id"], "c1");
}

#[test]
fn display_driver() {
let err = ConnectionError::driver(DriverKind::Sqlite, "no such table");
assert_eq!(err.to_string(), "sqlite error: no such table");
}
}
91 changes: 91 additions & 0 deletions apps/tauri/src-tauri/src/connection/id.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
use serde::{Deserialize, Serialize};
use std::fmt;
use uuid::Uuid;

/// Opaque live-connection handle shared across IPC and drivers.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(transparent)]
pub struct ConnectionId(String);

impl ConnectionId {
pub fn new() -> Self {
Self(Uuid::new_v4().to_string())
}

pub fn as_str(&self) -> &str {
&self.0
}
}

impl Default for ConnectionId {
fn default() -> Self {
Self::new()
}
}

impl fmt::Display for ConnectionId {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.0)
}
}

impl From<String> for ConnectionId {
fn from(value: String) -> Self {
Self(value)
}
}

impl From<&str> for ConnectionId {
fn from(value: &str) -> Self {
Self(value.to_owned())
}
}

/// Driver family — mirrors Flutter connection `type` strings.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum DriverKind {
Sqlite,
Postgres,
Mysql,
Redis,
Mongodb,
}

impl DriverKind {
pub fn as_str(self) -> &'static str {
match self {
Self::Sqlite => "sqlite",
Self::Postgres => "postgres",
Self::Mysql => "mysql",
Self::Redis => "redis",
Self::Mongodb => "mongodb",
}
}
}

impl fmt::Display for DriverKind {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn connection_id_round_trips_json() {
let id = ConnectionId::from("abc-123");
let json = serde_json::to_string(&id).unwrap();
assert_eq!(json, "\"abc-123\"");
let back: ConnectionId = serde_json::from_str(&json).unwrap();
assert_eq!(back, id);
}

#[test]
fn driver_kind_serde() {
let json = serde_json::to_string(&DriverKind::Sqlite).unwrap();
assert_eq!(json, "\"sqlite\"");
}
}
190 changes: 190 additions & 0 deletions apps/tauri/src-tauri/src/connection/manager.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,190 @@
use super::error::{ConnectionError, ConnectionResult};
use super::id::{ConnectionId, DriverKind};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::sync::{Arc, Mutex};

/// Driver-agnostic connect parameters (tagged for IPC).
#[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,
},
Postgres {
host: String,
port: u16,
database: String,
user: String,
/// Secret is resolved via keyring later; optional here for stubs.
password: Option<String>,
},
Mysql {
host: String,
port: u16,
database: String,
user: String,
password: Option<String>,
},
}

impl ConnectionConfig {
pub fn driver_kind(&self) -> DriverKind {
match self {
Self::Sqlite { .. } => DriverKind::Sqlite,
Self::Postgres { .. } => DriverKind::Postgres,
Self::Mysql { .. } => DriverKind::Mysql,
}
}
}

/// Live session handle — drivers implement this behind the registry.
pub trait ConnectionSession: Send + Sync {
fn id(&self) -> &ConnectionId;
fn driver(&self) -> DriverKind;
fn disconnect(&mut self) -> ConnectionResult<()>;
}

/// Opens and tracks live DB sessions.
pub trait ConnectionManager: Send + Sync {
fn connect(&self, config: ConnectionConfig) -> ConnectionResult<ConnectionId>;
fn disconnect(&self, id: &ConnectionId) -> ConnectionResult<()>;
fn is_connected(&self, id: &ConnectionId) -> bool;
fn driver_of(&self, id: &ConnectionId) -> Option<DriverKind>;
}

type SessionBox = Box<dyn ConnectionSession>;

/// In-memory registry used by Tauri commands. Drivers register factories later.
#[derive(Default)]
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>>,
}

impl ConnectionRegistry {
pub fn new() -> Self {
Self::default()
}

pub fn with_opener<F>(opener: F) -> Self
where
F: Fn(ConnectionConfig) -> ConnectionResult<SessionBox> + Send + Sync + 'static,
{
Self {
sessions: Mutex::new(HashMap::new()),
opener: Some(Arc::new(opener)),
}
}

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

impl ConnectionManager for ConnectionRegistry {
fn connect(&self, config: ConnectionConfig) -> ConnectionResult<ConnectionId> {
let opener = self
.opener
.as_ref()
.ok_or(ConnectionError::UnsupportedDriver {
driver: config.driver_kind(),
})?;
let session = opener(config)?;
let id = session.id().clone();
let mut map = self.lock()?;
if map.contains_key(&id) {
return Err(ConnectionError::AlreadyConnected { id });
}
map.insert(id.clone(), session);
Ok(id)
}

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

fn is_connected(&self, id: &ConnectionId) -> bool {
self.lock().map(|m| m.contains_key(id)).unwrap_or(false)
}

fn driver_of(&self, id: &ConnectionId) -> Option<DriverKind> {
self.lock().ok()?.get(id).map(|s| s.driver())
}
}

#[cfg(test)]
mod tests {
use super::*;

struct FakeSession {
id: ConnectionId,
driver: DriverKind,
closed: bool,
}

impl ConnectionSession for FakeSession {
fn id(&self) -> &ConnectionId {
&self.id
}
fn driver(&self) -> DriverKind {
self.driver
}
fn disconnect(&mut self) -> ConnectionResult<()> {
self.closed = true;
Ok(())
}
}

#[test]
fn registry_connect_disconnect() {
let reg = ConnectionRegistry::with_opener(|cfg| {
assert!(matches!(cfg, ConnectionConfig::Sqlite { .. }));
Ok(Box::new(FakeSession {
id: ConnectionId::from("s1"),
driver: DriverKind::Sqlite,
closed: false,
}))
});

let id = reg
.connect(ConnectionConfig::Sqlite {
path: "/tmp/x.db".into(),
})
.unwrap();
assert_eq!(id.as_str(), "s1");
assert!(reg.is_connected(&id));
assert_eq!(reg.driver_of(&id), Some(DriverKind::Sqlite));
reg.disconnect(&id).unwrap();
assert!(!reg.is_connected(&id));
let err = reg.disconnect(&id).unwrap_err();
assert!(matches!(err, ConnectionError::NotFound { .. }));
}

#[test]
fn registry_without_opener_is_unsupported() {
let reg = ConnectionRegistry::new();
let err = reg
.connect(ConnectionConfig::Sqlite {
path: "a.db".into(),
})
.unwrap_err();
assert!(matches!(
err,
ConnectionError::UnsupportedDriver {
driver: DriverKind::Sqlite
}
));
}
}
9 changes: 9 additions & 0 deletions apps/tauri/src-tauri/src/connection/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
//! Shared connection layer for Querya drivers (SQLite first, then PG/MySQL/…).

mod error;
mod id;
mod manager;

pub use error::ConnectionError;
pub use id::{ConnectionId, DriverKind};
pub use manager::{ConnectionConfig, ConnectionManager, ConnectionRegistry};
Loading
Loading