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
209 changes: 105 additions & 104 deletions src-tauri/src/commands.rs

Large diffs are not rendered by default.

9 changes: 5 additions & 4 deletions src-tauri/src/db/backup.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ Speed notes (why the code is shaped the way it is):
- Progress is a per-table event, throttled while a table is being copied.
*/

use crate::db::connection::Db;
use std::fs::File;
use std::io::{self, BufWriter, Read, Write};
use std::path::{Path, PathBuf};
Expand All @@ -29,9 +30,9 @@ use std::time::{Duration, Instant};
use futures::{StreamExt, TryStreamExt};
use serde::{Deserialize, Serialize};
use sqlx::{Column, Executor, Row, TypeInfo};
use tauri::{AppHandle, Emitter, State};
use tauri::{AppHandle, Emitter};

use super::connection::{require_conn, ActiveConnection, DbState};
use super::connection::{require_conn, ActiveConnection};

/// Cooperative cancel flag for the in-flight backup/restore. The frontend sets
/// it via `backup_cancel`; the export/import loops poll it and stop early.
Expand Down Expand Up @@ -446,7 +447,7 @@ fn partial_path(path: &Path) -> PathBuf {
#[tauri::command]
pub async fn backup_export(
app: AppHandle,
state: State<'_, DbState>,
state: Db<'_>,
schema: Option<String>,
tables: Option<Vec<String>>,
options: Option<ExportOptions>,
Expand Down Expand Up @@ -583,7 +584,7 @@ async fn export_into(
#[tauri::command]
pub async fn backup_import(
app: AppHandle,
state: State<'_, DbState>,
state: Db<'_>,
sql: Option<String>,
path: Option<String>,
) -> Result<ImportResult, String> {
Expand Down
115 changes: 90 additions & 25 deletions src-tauri/src/db/connection.rs
Original file line number Diff line number Diff line change
Expand Up @@ -404,6 +404,9 @@ pub struct DbState {
/// connection key the page chose, oldest first. Switching back resumes one
/// without connecting again. Capped (see `parked`).
pub parked: Arc<Mutex<Vec<(String, ActiveConnection)>>>,
/// The page's key for the open (front) pool, when it has said. A call routed
/// to another key is served from `parked`; see `require_conn`.
pub active_key: Arc<Mutex<Option<String>>>,
/// Cancel handles for the queries currently in flight, keyed by the id the
/// caller sent. Keyed rather than a single slot because the UI runs several
/// queries at once (one per editor tab) - with one slot, the second run
Expand All @@ -417,28 +420,88 @@ impl Default for DbState {
Self {
conn: Arc::new(Mutex::new(None)),
parked: Arc::new(Mutex::new(Vec::new())),
active_key: Arc::new(Mutex::new(None)),
cancels: Arc::new(Mutex::new(std::collections::HashMap::new())),
}
}
}

/// Register a cancel handle for `id`, replacing (and dropping) any handle already
/// stored under it.
pub fn register_cancel(state: &State<'_, DbState>, id: &str, tx: oneshot::Sender<()>) {
pub fn register_cancel(state: &Db<'_>, id: &str, tx: oneshot::Sender<()>) {
if let Ok(mut map) = state.cancels.lock() {
map.insert(id.to_string(), tx);
}
}

/// Drop the cancel handle for `id` (query finished, cancelling it is meaningless).
pub fn unregister_cancel(state: &State<'_, DbState>, id: &str) {
pub fn unregister_cancel(state: &Db<'_>, id: &str) {
if let Ok(mut map) = state.cancels.lock() {
map.remove(id);
}
}

/// Returns a clone of the active connection, or an error if disconnected.
pub fn require_conn(state: &State<'_, DbState>) -> Result<ActiveConnection, String> {
/// `State<DbState>` plus the database the call is for.
///
/// Labs, several connections at once: tabs from several databases are open
/// together, and each call the page makes names its database in a `__conn`
/// argument (src/lib/api.js). The key is read from the request itself, so a
/// call sent just before a switch still reaches the database it was made for,
/// whichever pool is in front by the time it runs. Without one, the call goes
/// to the front pool, as before.
#[derive(Clone)]
pub struct Db<'r> {
state: State<'r, DbState>,
/// The `__conn` key the page sent, if any.
pub route: Option<String>,
}

impl<'r> Db<'r> {
/// For code that has the managed state but no request (MCP, background work):
/// it always means the front pool.
pub fn front(state: State<'r, DbState>) -> Self {
Self { state, route: None }
}
pub fn inner(&self) -> &'r DbState {
self.state.inner()
}
}

impl std::ops::Deref for Db<'_> {
type Target = DbState;
fn deref(&self) -> &DbState {
self.state.inner()
}
}

impl<'r, 'de: 'r, R: tauri::Runtime> tauri::ipc::CommandArg<'de, R> for Db<'r> {
fn from_command(command: tauri::ipc::CommandItem<'de, R>) -> Result<Self, tauri::ipc::InvokeError> {
let route = match command.message.payload() {
tauri::ipc::InvokeBody::Json(v) => v.get("__conn").and_then(|k| k.as_str()).filter(|k| !k.is_empty()).map(str::to_string),
_ => None,
};
let state = <State<'r, DbState> as tauri::ipc::CommandArg<'de, R>>::from_command(command)?;
Ok(Self { state, route })
}
}

/// Returns a clone of the connection the call is for, or an error if there is
/// none. A routed call (see `Db`) gets its own database's pool: the front one
/// when that is its key, else the one kept aside for it. A key whose pool was
/// closed (pushed out by the cap, or its connection edited) is an error rather
/// than a quiet run on whatever database happens to be in front.
pub fn require_conn(state: &Db<'_>) -> Result<ActiveConnection, String> {
if let Some(key) = state.route.as_deref() {
let front = state.active_key.lock().map_err(|e| e.to_string())?.clone();
if front.as_deref() != Some(key) {
if let Some((_, c)) = state.parked.lock().map_err(|e| e.to_string())?.iter().find(|(k, _)| k == key) {
return Ok(c.clone());
}
if front.is_some() {
return Err("That database's connection was closed. Click its tab to open it again.".to_string());
}
}
}
state
.conn
.lock()
Expand All @@ -448,7 +511,7 @@ pub fn require_conn(state: &State<'_, DbState>) -> Result<ActiveConnection, Stri
}

/// Convenience helper kept for all existing PostgreSQL-specific code.
pub fn require_pool(state: &State<'_, DbState>) -> Result<PgPool, String> {
pub fn require_pool(state: &Db<'_>) -> Result<PgPool, String> {
match require_conn(state)? {
ActiveConnection::Postgres(pool) => Ok(pool),
other => Err(format!(
Expand Down Expand Up @@ -480,12 +543,14 @@ pub fn update_d1_token(token: &str) {
}
}

fn set_conn(state: &State<'_, DbState>, conn: Option<ActiveConnection>) -> Result<(), String> {
fn set_conn(state: &Db<'_>, conn: Option<ActiveConnection>) -> Result<(), String> {
*state.conn.lock().map_err(|e| e.to_string())? = conn;
// A fresh pool: the page names its key once it knows it (set_active_conn_key).
*state.active_key.lock().map_err(|e| e.to_string())? = None;
Ok(())
}

async fn close_existing(state: &State<'_, DbState>) {
async fn close_existing(state: &Db<'_>) {
let old = state.conn.lock().ok().and_then(|mut g| g.take());
let Some(conn) = old else { return };
close_in_background(conn);
Expand Down Expand Up @@ -1279,7 +1344,7 @@ pub async fn test_connection(config: PgConfig) -> Result<(), String> {
}

pub async fn connect(
state: State<'_, DbState>,
state: Db<'_>,
tunnel_state: State<'_, TunnelState>,
config: PgConfig,
) -> Result<(), String> {
Expand Down Expand Up @@ -1357,7 +1422,7 @@ pub async fn test_sqlite_connection(config: SqliteConfig) -> Result<(), String>
Ok(())
}

pub async fn connect_sqlite(state: State<'_, DbState>, config: SqliteConfig) -> Result<(), String> {
pub async fn connect_sqlite(state: Db<'_>, config: SqliteConfig) -> Result<(), String> {
let pool = open_sqlite(&config).await?;
close_existing(&state).await;
set_conn(&state, Some(ActiveConnection::Sqlite(pool)))
Expand Down Expand Up @@ -1458,7 +1523,7 @@ pub async fn test_mysql_connection(config: MysqlConfig) -> Result<(), String> {
}

pub async fn connect_mysql(
state: State<'_, DbState>,
state: Db<'_>,
tunnel_state: State<'_, TunnelState>,
config: MysqlConfig,
) -> Result<(), String> {
Expand Down Expand Up @@ -1492,7 +1557,7 @@ pub async fn test_d1_connection(config: D1Config) -> Result<(), String> {
Ok(())
}

pub async fn connect_d1(state: State<'_, DbState>, config: D1Config) -> Result<(), String> {
pub async fn connect_d1(state: Db<'_>, config: D1Config) -> Result<(), String> {
// Validate credentials before storing
test_d1_connection(config.clone()).await?;
close_existing(&state).await;
Expand All @@ -1506,7 +1571,7 @@ pub async fn test_libsql_connection(config: LibSqlConfig) -> Result<(), String>
Ok(())
}

pub async fn connect_libsql(state: State<'_, DbState>, config: LibSqlConfig) -> Result<(), String> {
pub async fn connect_libsql(state: Db<'_>, config: LibSqlConfig) -> Result<(), String> {
test_libsql_connection(config.clone()).await?;
close_existing(&state).await;
set_conn(&state, Some(ActiveConnection::LibSql(config)))
Expand All @@ -1523,7 +1588,7 @@ pub async fn test_clickhouse_connection(config: ClickhouseConfig) -> Result<(),
.await
}

pub async fn connect_clickhouse(state: State<'_, DbState>, config: ClickhouseConfig) -> Result<(), String> {
pub async fn connect_clickhouse(state: Db<'_>, config: ClickhouseConfig) -> Result<(), String> {
// Validate credentials/reachability before storing.
test_clickhouse_connection(config.clone()).await?;
close_existing(&state).await;
Expand All @@ -1536,42 +1601,42 @@ pub async fn test_posthog_connection(config: PosthogConfig) -> Result<(), String
crate::db::posthog::query(&config, "SELECT 1").await.map(|_| ())
}

pub async fn connect_posthog(state: State<'_, DbState>, config: PosthogConfig) -> Result<(), String> {
pub async fn connect_posthog(state: Db<'_>, config: PosthogConfig) -> Result<(), String> {
test_posthog_connection(config.clone()).await?;
close_existing(&state).await;
set_conn(&state, Some(ActiveConnection::Posthog(config)))
}

// ── DynamoDB connect / test ───────────────────────────────────────────────────

pub async fn connect_dynamodb(state: State<'_, DbState>, config: crate::db::dynamodb::DynamoConfig) -> Result<(), String> {
pub async fn connect_dynamodb(state: Db<'_>, config: crate::db::dynamodb::DynamoConfig) -> Result<(), String> {
crate::db::dynamodb::ping(&config).await?;
set_conn(&state, Some(ActiveConnection::Dynamodb(config)))
}

// ── Document engines connect ──────────────────────────────────────────────────

pub async fn connect_cassandra(state: State<'_, DbState>, config: crate::db::cassandra::CassandraConfig) -> Result<(), String> {
pub async fn connect_cassandra(state: Db<'_>, config: crate::db::cassandra::CassandraConfig) -> Result<(), String> {
let session = crate::db::cassandra::connect(&config).await?;
set_conn(&state, Some(ActiveConnection::Doc(crate::db::docdb::DocConn::Cassandra(session))))
}

pub async fn connect_mongo(state: State<'_, DbState>, config: crate::db::mongo::MongoConfig) -> Result<(), String> {
pub async fn connect_mongo(state: Db<'_>, config: crate::db::mongo::MongoConfig) -> Result<(), String> {
let handle = crate::db::mongo::connect(&config).await?;
set_conn(&state, Some(ActiveConnection::Doc(crate::db::docdb::DocConn::Mongo(handle))))
}

pub async fn connect_firestore(state: State<'_, DbState>, config: crate::db::firestore::FirestoreConfig) -> Result<(), String> {
pub async fn connect_firestore(state: Db<'_>, config: crate::db::firestore::FirestoreConfig) -> Result<(), String> {
crate::db::firestore::ping(&config).await?;
set_conn(&state, Some(ActiveConnection::Doc(crate::db::docdb::DocConn::Firestore(config))))
}

pub async fn connect_couchdb(state: State<'_, DbState>, config: crate::db::couchdb::CouchConfig) -> Result<(), String> {
pub async fn connect_couchdb(state: Db<'_>, config: crate::db::couchdb::CouchConfig) -> Result<(), String> {
crate::db::couchdb::ping(&config).await?;
set_conn(&state, Some(ActiveConnection::Doc(crate::db::docdb::DocConn::Couch(config))))
}

pub async fn connect_elastic(state: State<'_, DbState>, config: crate::db::elastic::EsConfig) -> Result<(), String> {
pub async fn connect_elastic(state: Db<'_>, config: crate::db::elastic::EsConfig) -> Result<(), String> {
let config = crate::db::elastic::connect(config).await?;
set_conn(&state, Some(ActiveConnection::Doc(crate::db::docdb::DocConn::Elastic(config))))
}
Expand All @@ -1583,7 +1648,7 @@ pub async fn test_redis_connection(config: RedisConfig) -> Result<(), String> {
connect_racing_probe(&host, port, None, crate::db::redis::ping(&config)).await
}

pub async fn connect_redis(state: State<'_, DbState>, config: RedisConfig) -> Result<(), String> {
pub async fn connect_redis(state: Db<'_>, config: RedisConfig) -> Result<(), String> {
// Validate credentials/reachability before storing.
test_redis_connection(config.clone()).await?;
close_existing(&state).await;
Expand Down Expand Up @@ -1619,7 +1684,7 @@ pub async fn test_duckdb_connection(config: DuckdbConfig) -> Result<(), String>
crate::db::duckdb::ping(&handle).await
}

pub async fn connect_duckdb(state: State<'_, DbState>, config: DuckdbConfig) -> Result<(), String> {
pub async fn connect_duckdb(state: Db<'_>, config: DuckdbConfig) -> Result<(), String> {
let handle = open_duckdb(&config).await?;
crate::db::duckdb::ping(&handle).await?;
close_existing(&state).await;
Expand All @@ -1639,7 +1704,7 @@ pub async fn test_mssql_connection(config: MssqlConfig) -> Result<(), String> {
crate::db::mssql::ping(&handle).await
}

pub async fn connect_mssql(state: State<'_, DbState>, config: MssqlConfig) -> Result<(), String> {
pub async fn connect_mssql(state: Db<'_>, config: MssqlConfig) -> Result<(), String> {
let handle = open_mssql(&config).await?;
close_existing(&state).await;
set_conn(&state, Some(ActiveConnection::Mssql(handle)))
Expand All @@ -1663,7 +1728,7 @@ pub async fn test_oracle_connection(config: OracleConfig) -> Result<(), String>
crate::db::oracle::ping(&handle).await
}

pub async fn connect_oracle(state: State<'_, DbState>, config: OracleConfig) -> Result<(), String> {
pub async fn connect_oracle(state: Db<'_>, config: OracleConfig) -> Result<(), String> {
let handle = open_oracle(&config).await?;
close_existing(&state).await;
set_conn(&state, Some(ActiveConnection::Oracle(handle)))
Expand All @@ -1672,7 +1737,7 @@ pub async fn connect_oracle(state: State<'_, DbState>, config: OracleConfig) ->
// ── Disconnect ────────────────────────────────────────────────────────────────

pub async fn disconnect(
state: State<'_, DbState>,
state: Db<'_>,
tunnel_state: State<'_, TunnelState>,
) -> Result<(), String> {
// close_existing already sets state to None atomically via take() before
Expand Down
10 changes: 5 additions & 5 deletions src-tauri/src/db/geo.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,12 +16,12 @@
//! so the GiST index still answers it. Reprojection to WGS84 happens only on
//! the rows that survive.

use super::connection::{require_conn, ActiveConnection, DbState};
use crate::db::connection::Db;
use super::connection::{require_conn, ActiveConnection};
use super::query::{build_where, RowFilter};
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
use sqlx::{PgPool, Row};
use tauri::State;

/// Hard ceiling on features returned in one fetch, whatever the caller asks for.
/// Above this the canvas is drawing more points than the viewport has pixels and
Expand Down Expand Up @@ -91,7 +91,7 @@ pub struct GeoFeatures {
/// PostGIS puts its own tables in these schemas; they are plumbing, not data.
const HIDDEN_SCHEMAS: &str = "('information_schema', 'pg_catalog', 'topology', 'tiger', 'tiger_data')";

fn pg_pool(state: &State<'_, DbState>) -> Result<Option<PgPool>, String> {
fn pg_pool(state: &Db<'_>) -> Result<Option<PgPool>, String> {
match require_conn(state)? {
ActiveConnection::Postgres(pool) => Ok(Some(pool)),
_ => Ok(None),
Expand Down Expand Up @@ -122,7 +122,7 @@ fn unavailable() -> GeoOverview {
/// Is PostGIS installed, and what can be mapped? Safe to call on any connection:
/// a non-Postgres engine, or a Postgres without the extension, reports
/// `available: false` rather than failing.
pub async fn geo_overview(state: State<'_, DbState>) -> Result<GeoOverview, String> {
pub async fn geo_overview(state: Db<'_>) -> Result<GeoOverview, String> {
let Some(pool) = pg_pool(&state)? else { return Ok(unavailable()) };

let version: Option<String> =
Expand Down Expand Up @@ -372,7 +372,7 @@ async fn layer_extent(
/// holds more than `limit` rows.
#[allow(clippy::too_many_arguments)]
pub async fn geo_features(
state: State<'_, DbState>,
state: Db<'_>,
schema: String,
table: String,
column: String,
Expand Down
7 changes: 4 additions & 3 deletions src-tauri/src/db/import.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,14 +10,15 @@ keep going, the batch is replayed one row at a time so the report can name the
rows that were actually bad instead of blaming all 500.
*/

use crate::db::connection::Db;
use std::collections::HashMap;
use std::sync::atomic::{AtomicBool, Ordering};

use serde::{Deserialize, Serialize};
use serde_json::Value;
use tauri::{AppHandle, Emitter, State};
use tauri::{AppHandle, Emitter};

use super::connection::{require_conn, ActiveConnection, DbState};
use super::connection::{require_conn, ActiveConnection};
use super::query::{bind_typed_value, is_bytea_type, pg_insert_meta, validate_typed_value};
use super::schema::validate_ident;

Expand Down Expand Up @@ -123,7 +124,7 @@ fn emit_log(app: &AppHandle, level: &'static str, message: impl Into<String>) {
#[tauri::command]
pub async fn import_rows(
app: AppHandle,
state: State<'_, DbState>,
state: Db<'_>,
schema: Option<String>,
table: String,
columns: Vec<String>,
Expand Down
Loading
Loading