diff --git a/src-tauri/src/commands.rs b/src-tauri/src/commands.rs index 1f8f595d..cb95a412 100644 --- a/src-tauri/src/commands.rs +++ b/src-tauri/src/commands.rs @@ -1,3 +1,4 @@ +use crate::db::connection::Db; use std::sync::OnceLock; use tauri::Emitter; @@ -364,7 +365,7 @@ use crate::db::{ list_schemas, list_tables, list_indexes_for, list_enums, list_functions, list_triggers, list_sequences, ping_connection, table_row_counts, truncate_table, drop_table, get_table_column_structure, get_schema_column_structure, get_incoming_foreign_keys, get_table_ddl as db_get_table_ddl, test_clickhouse_connection, test_connection, test_d1_connection, test_duckdb_connection, test_libsql_connection, test_mssql_connection, test_mysql_connection, test_oracle_connection, test_redis_connection, test_sqlite_connection, - update_table_cell, fetch_cell_value, ConnectionConfig, D1Config, DbState, EnumInfo, FunctionInfo, ExplainResult, IndexInfo, LibSqlConfig, + update_table_cell, fetch_cell_value, ConnectionConfig, D1Config, EnumInfo, FunctionInfo, ExplainResult, IndexInfo, LibSqlConfig, SqlResult, SqliteConfig, TableInfo, TableRowCount, TableRows, TriggerInfo, SequenceInfo, ColumnStructureRow, TableColumnStructure, IncomingForeignKey, InsertRowResult, TunnelState, apply_table_changes, ApplyChangesResult, RowUpdate, @@ -385,7 +386,7 @@ pub async fn test_postgres_connection(config: ConnectionConfig) -> Result<(), St #[tauri::command] pub async fn connect_postgres( - state: State<'_, DbState>, + state: Db<'_>, tunnel_state: State<'_, TunnelState>, config: ConnectionConfig, ) -> Result<(), String> { @@ -401,7 +402,7 @@ pub async fn test_sqlite(config: SqliteConfig) -> Result<(), String> { #[tauri::command] pub async fn connect_sqlite_db( - state: State<'_, DbState>, + state: Db<'_>, config: SqliteConfig, ) -> Result<(), String> { connect_sqlite(state, config).await @@ -416,7 +417,7 @@ pub async fn test_mysql(config: MysqlConfig) -> Result<(), String> { #[tauri::command] pub async fn connect_mysql_db( - state: State<'_, DbState>, + state: Db<'_>, tunnel_state: State<'_, TunnelState>, config: MysqlConfig, ) -> Result<(), String> { @@ -432,7 +433,7 @@ pub async fn test_d1(config: D1Config) -> Result<(), String> { #[tauri::command] pub async fn connect_d1_db( - state: State<'_, DbState>, + state: Db<'_>, config: D1Config, ) -> Result<(), String> { connect_d1(state, config).await @@ -446,7 +447,7 @@ pub async fn test_libsql(config: LibSqlConfig) -> Result<(), String> { } #[tauri::command] -pub async fn connect_libsql_db(state: State<'_, DbState>, config: LibSqlConfig) -> Result<(), String> { +pub async fn connect_libsql_db(state: Db<'_>, config: LibSqlConfig) -> Result<(), String> { connect_libsql(state, config).await } @@ -459,7 +460,7 @@ pub async fn test_posthog(config: crate::db::connection::PosthogConfig) -> Resul #[tauri::command] pub async fn connect_posthog_db( - state: State<'_, DbState>, + state: Db<'_>, config: crate::db::connection::PosthogConfig, ) -> Result<(), String> { crate::db::connection::connect_posthog(state, config).await @@ -473,7 +474,7 @@ pub async fn test_clickhouse(config: ClickhouseConfig) -> Result<(), String> { } #[tauri::command] -pub async fn connect_clickhouse_db(state: State<'_, DbState>, config: ClickhouseConfig) -> Result<(), String> { +pub async fn connect_clickhouse_db(state: Db<'_>, config: ClickhouseConfig) -> Result<(), String> { connect_clickhouse(state, config).await } @@ -485,7 +486,7 @@ pub async fn test_redis(config: RedisConfig) -> Result<(), String> { } #[tauri::command] -pub async fn connect_redis_db(state: State<'_, DbState>, config: RedisConfig) -> Result<(), String> { +pub async fn connect_redis_db(state: Db<'_>, config: RedisConfig) -> Result<(), String> { connect_redis(state, config).await } @@ -493,7 +494,7 @@ pub async fn connect_redis_db(state: State<'_, DbState>, config: RedisConfig) -> /// SCAN page (next cursor + keys); the frontend loops until the cursor is "0". #[tauri::command] pub async fn redis_scan( - state: State<'_, DbState>, + state: Db<'_>, cursor: String, pattern: Option, count: u32, @@ -504,7 +505,7 @@ pub async fn redis_scan( } } -fn require_redis(state: &State<'_, DbState>) -> Result { +fn require_redis(state: &Db<'_>) -> Result { match require_conn(state)? { ActiveConnection::Redis(cfg) => Ok(cfg), _ => Err("Not connected to a Redis database".into()), @@ -514,7 +515,7 @@ fn require_redis(state: &State<'_, DbState>) -> Result { /// One page of the Redis keys table (keys with type, TTL, size and preview). #[tauri::command] pub async fn redis_key_page( - state: State<'_, DbState>, + state: Db<'_>, cursor: String, pattern: Option, key_type: Option, @@ -527,7 +528,7 @@ pub async fn redis_key_page( /// Fresh keys-table rows for specific keys. #[tauri::command] pub async fn redis_key_rows( - state: State<'_, DbState>, + state: Db<'_>, keys: Vec, ) -> Result, String> { let cfg = require_redis(&state)?; @@ -537,7 +538,7 @@ pub async fn redis_key_rows( /// A key's value, paged for collections. #[tauri::command] pub async fn redis_key_value( - state: State<'_, DbState>, + state: Db<'_>, key: crate::db::redis::KeyRef, cursor: Option, count: u32, @@ -548,7 +549,7 @@ pub async fn redis_key_value( /// One Redis command as structured JSON, for the insight views. #[tauri::command] -pub async fn redis_command(state: State<'_, DbState>, args: Vec) -> Result { +pub async fn redis_command(state: Db<'_>, args: Vec) -> Result { let cfg = require_redis(&state)?; crate::db::redis::command_json(&cfg, args).await } @@ -557,7 +558,7 @@ pub async fn redis_command(state: State<'_, DbState>, args: Vec) -> Resu #[tauri::command] pub async fn redis_subscribe( app: tauri::AppHandle, - state: State<'_, DbState>, + state: Db<'_>, id: String, channels: Vec, patterns: Vec, @@ -580,7 +581,7 @@ pub fn redis_unsubscribe(id: String) { /// Apply staged Redis writes in one MULTI/EXEC transaction. #[tauri::command] pub async fn redis_apply( - state: State<'_, DbState>, + state: Db<'_>, ops: Vec, ) -> Result, String> { let cfg = require_redis(&state)?; @@ -596,7 +597,7 @@ pub async fn test_dynamodb(config: crate::db::dynamodb::DynamoConfig) -> Result< #[tauri::command] pub async fn connect_dynamodb_db( - state: State<'_, DbState>, + state: Db<'_>, config: crate::db::dynamodb::DynamoConfig, ) -> Result<(), String> { crate::db::connection::connect_dynamodb(state, config).await @@ -611,7 +612,7 @@ pub fn dynamodb_profiles() -> Vec { /// One DynamoDB API call (`op` from an allowlist) on the active connection. #[tauri::command] pub async fn dynamodb_request( - state: State<'_, DbState>, + state: Db<'_>, op: String, body: serde_json::Value, ) -> Result { @@ -630,14 +631,14 @@ pub async fn test_couchdb(config: crate::db::couchdb::CouchConfig) -> Result<(), } #[tauri::command] -pub async fn connect_couchdb_db(state: State<'_, DbState>, config: crate::db::couchdb::CouchConfig) -> Result<(), String> { +pub async fn connect_couchdb_db(state: Db<'_>, config: crate::db::couchdb::CouchConfig) -> Result<(), String> { crate::db::connection::connect_couchdb(state, config).await } /// One CouchDB HTTP call (path allowlisted) on the active connection. #[tauri::command] pub async fn couchdb_request( - state: State<'_, DbState>, + state: Db<'_>, method: String, path: String, body: Option, @@ -658,14 +659,14 @@ pub async fn test_elastic(config: crate::db::elastic::EsConfig) -> Result, config: crate::db::elastic::EsConfig) -> Result<(), String> { +pub async fn connect_elastic_db(state: Db<'_>, config: crate::db::elastic::EsConfig) -> Result<(), String> { crate::db::connection::connect_elastic(state, config).await } /// One REST call (path allowlisted) on the active connection. #[tauri::command] pub async fn elastic_request( - state: State<'_, DbState>, + state: Db<'_>, method: String, path: String, body: Option, @@ -680,7 +681,7 @@ pub async fn elastic_request( /// Import a file into an index (the preview reuses `mongo_import_preview`). #[tauri::command] pub async fn elastic_import( - state: State<'_, DbState>, + state: Db<'_>, index: String, path: String, format: Option, @@ -701,11 +702,11 @@ pub async fn test_mongo(config: crate::db::mongo::MongoConfig) -> Result<(), Str } #[tauri::command] -pub async fn connect_mongo_db(state: State<'_, DbState>, config: crate::db::mongo::MongoConfig) -> Result<(), String> { +pub async fn connect_mongo_db(state: Db<'_>, config: crate::db::mongo::MongoConfig) -> Result<(), String> { crate::db::connection::connect_mongo(state, config).await } -fn require_mongo(state: &State<'_, DbState>) -> Result { +fn require_mongo(state: &Db<'_>) -> Result { match require_conn(state)? { ActiveConnection::Doc(crate::db::docdb::DocConn::Mongo(m)) => Ok(m), _ => Err("Not connected to MongoDB".into()), @@ -715,7 +716,7 @@ fn require_mongo(state: &State<'_, DbState>) -> Result, schema: String) -> Result<(), String> { +pub async fn doc_use_schema(state: Db<'_>, schema: String) -> Result<(), String> { match require_conn(&state)? { ActiveConnection::Doc(d) => crate::db::docdb::use_schema(&d, &schema).await, _ => Ok(()), @@ -723,20 +724,20 @@ pub async fn doc_use_schema(state: State<'_, DbState>, schema: String) -> Result } #[tauri::command] -pub async fn mongo_collections(state: State<'_, DbState>) -> Result, String> { +pub async fn mongo_collections(state: Db<'_>) -> Result, String> { let m = require_mongo(&state)?; crate::db::mongo::list_collections(&m).await } #[tauri::command] -pub async fn mongo_describe(state: State<'_, DbState>, collection: String) -> Result { +pub async fn mongo_describe(state: Db<'_>, collection: String) -> Result { let m = require_mongo(&state)?; crate::db::mongo::describe(&m, &collection).await } #[tauri::command] pub async fn mongo_find( - state: State<'_, DbState>, + state: Db<'_>, collection: String, filter: String, sort: Option, @@ -758,14 +759,14 @@ pub async fn mongo_find( } #[tauri::command] -pub async fn mongo_count(state: State<'_, DbState>, collection: String, filter: String) -> Result { +pub async fn mongo_count(state: Db<'_>, collection: String, filter: String) -> Result { let m = require_mongo(&state)?; crate::db::mongo::count(&m, &collection, &filter).await } #[tauri::command] pub async fn mongo_save( - state: State<'_, DbState>, + state: Db<'_>, collection: String, doc: serde_json::Value, prev_id: Option, @@ -775,14 +776,14 @@ pub async fn mongo_save( } #[tauri::command] -pub async fn mongo_delete(state: State<'_, DbState>, collection: String, id: serde_json::Value) -> Result<(), String> { +pub async fn mongo_delete(state: Db<'_>, collection: String, id: serde_json::Value) -> Result<(), String> { let m = require_mongo(&state)?; crate::db::mongo::delete(&m, &collection, &id).await } #[tauri::command] pub async fn mongo_explain( - state: State<'_, DbState>, + state: Db<'_>, collection: String, filter: String, sort: Option, @@ -793,20 +794,20 @@ pub async fn mongo_explain( } #[tauri::command] -pub async fn mongo_schema(state: State<'_, DbState>, collection: String, filter: String, size: Option) -> Result { +pub async fn mongo_schema(state: Db<'_>, collection: String, filter: String, size: Option) -> Result { let m = require_mongo(&state)?; crate::db::mongo::schema_sample(&m, &collection, &filter, size.unwrap_or(1000)).await } #[tauri::command] -pub async fn mongo_indexes(state: State<'_, DbState>, collection: String) -> Result, String> { +pub async fn mongo_indexes(state: Db<'_>, collection: String) -> Result, String> { let m = require_mongo(&state)?; crate::db::mongo::index_details(&m, &collection).await } #[tauri::command] pub async fn mongo_create_index( - state: State<'_, DbState>, + state: Db<'_>, collection: String, keys: String, options: Option, @@ -816,7 +817,7 @@ pub async fn mongo_create_index( } #[tauri::command] -pub async fn mongo_drop_index(state: State<'_, DbState>, collection: String, name: String) -> Result<(), String> { +pub async fn mongo_drop_index(state: Db<'_>, collection: String, name: String) -> Result<(), String> { let m = require_mongo(&state)?; crate::db::mongo::drop_index(&m, &collection, &name).await } @@ -824,7 +825,7 @@ pub async fn mongo_drop_index(state: State<'_, DbState>, collection: String, nam #[tauri::command] #[allow(clippy::too_many_arguments)] pub async fn mongo_update_field( - state: State<'_, DbState>, + state: Db<'_>, collection: String, id: serde_json::Value, path: String, @@ -837,7 +838,7 @@ pub async fn mongo_update_field( } #[tauri::command] -pub async fn mongo_aggregate(state: State<'_, DbState>, collection: String, pipeline: String, limit: Option) -> Result, String> { +pub async fn mongo_aggregate(state: Db<'_>, collection: String, pipeline: String, limit: Option) -> Result, String> { let m = require_mongo(&state)?; crate::db::mongo::aggregate_preview(&m, &collection, &pipeline, limit.unwrap_or(10)).await } @@ -852,7 +853,7 @@ pub async fn mongo_import_preview(path: String, format: Option, infer: O #[tauri::command] pub async fn mongo_import( - state: State<'_, DbState>, + state: Db<'_>, collection: String, path: String, format: Option, @@ -870,14 +871,14 @@ pub async fn test_firestore(config: crate::db::firestore::FirestoreConfig) -> Re } #[tauri::command] -pub async fn connect_firestore_db(state: State<'_, DbState>, config: crate::db::firestore::FirestoreConfig) -> Result<(), String> { +pub async fn connect_firestore_db(state: Db<'_>, config: crate::db::firestore::FirestoreConfig) -> Result<(), String> { crate::db::connection::connect_firestore(state, config).await } /// One Firestore REST call (document paths of this database only). #[tauri::command] pub async fn firestore_request( - state: State<'_, DbState>, + state: Db<'_>, method: String, path: String, body: Option, @@ -897,11 +898,11 @@ pub async fn test_cassandra(config: crate::db::cassandra::CassandraConfig) -> Re } #[tauri::command] -pub async fn connect_cassandra_db(state: State<'_, DbState>, config: crate::db::cassandra::CassandraConfig) -> Result<(), String> { +pub async fn connect_cassandra_db(state: Db<'_>, config: crate::db::cassandra::CassandraConfig) -> Result<(), String> { crate::db::connection::connect_cassandra(state, config).await } -fn require_cassandra(state: &State<'_, DbState>) -> Result { +fn require_cassandra(state: &Db<'_>) -> Result { match require_conn(state)? { ActiveConnection::Doc(crate::db::docdb::DocConn::Cassandra(s)) => Ok(s), _ => Err("Not connected to Cassandra".into()), @@ -909,20 +910,20 @@ fn require_cassandra(state: &State<'_, DbState>) -> Result) -> Result, String> { +pub async fn cassandra_tables(state: Db<'_>) -> Result, String> { let s = require_cassandra(&state)?; crate::db::cassandra::list_tables(&s).await } #[tauri::command] -pub async fn cassandra_describe(state: State<'_, DbState>, table: String) -> Result { +pub async fn cassandra_describe(state: Db<'_>, table: String) -> Result { let s = require_cassandra(&state)?; crate::db::cassandra::describe(&s, &table).await } #[tauri::command] pub async fn cassandra_page( - state: State<'_, DbState>, + state: Db<'_>, table: String, filter: String, cursor: Option, @@ -934,7 +935,7 @@ pub async fn cassandra_page( #[tauri::command] pub async fn cassandra_save( - state: State<'_, DbState>, + state: Db<'_>, table: String, row: serde_json::Value, prev: Option, @@ -944,7 +945,7 @@ pub async fn cassandra_save( } #[tauri::command] -pub async fn cassandra_delete(state: State<'_, DbState>, table: String, row: serde_json::Value) -> Result<(), String> { +pub async fn cassandra_delete(state: Db<'_>, table: String, row: serde_json::Value) -> Result<(), String> { let s = require_cassandra(&state)?; crate::db::cassandra::delete(&s, &table, &row).await } @@ -957,7 +958,7 @@ pub async fn test_duckdb(config: DuckdbConfig) -> Result<(), String> { } #[tauri::command] -pub async fn connect_duckdb_db(state: State<'_, DbState>, config: DuckdbConfig) -> Result<(), String> { +pub async fn connect_duckdb_db(state: Db<'_>, config: DuckdbConfig) -> Result<(), String> { connect_duckdb(state, config).await } @@ -969,7 +970,7 @@ pub async fn test_mssql(config: MssqlConfig) -> Result<(), String> { } #[tauri::command] -pub async fn connect_mssql_db(state: State<'_, DbState>, config: MssqlConfig) -> Result<(), String> { +pub async fn connect_mssql_db(state: Db<'_>, config: MssqlConfig) -> Result<(), String> { connect_mssql(state, config).await } @@ -981,13 +982,13 @@ pub async fn test_oracle(config: OracleConfig) -> Result<(), String> { } #[tauri::command] -pub async fn connect_oracle_db(state: State<'_, DbState>, config: OracleConfig) -> Result<(), String> { +pub async fn connect_oracle_db(state: Db<'_>, config: OracleConfig) -> Result<(), String> { connect_oracle(state, config).await } /// The Oracle container the active connection is in (FREEPDB1, CDB$ROOT). #[tauri::command] -pub async fn oracle_container_name(state: State<'_, DbState>) -> Result { +pub async fn oracle_container_name(state: Db<'_>) -> Result { match crate::db::connection::require_conn(&state)? { ActiveConnection::Oracle(h) => crate::db::oracle::container_name(&h).await, _ => Err("Not connected to Oracle".into()), @@ -1002,7 +1003,7 @@ use crate::db::live::{self, LiveState}; #[tauri::command] pub async fn live_start( app: tauri::AppHandle, - state: State<'_, DbState>, + state: Db<'_>, live_state: State<'_, LiveState>, schema: String, table: String, @@ -1022,7 +1023,7 @@ pub async fn live_stop(live_state: State<'_, LiveState>) -> Result<(), String> { #[tauri::command] pub async fn disconnect_postgres( - state: State<'_, DbState>, + state: Db<'_>, tunnel_state: State<'_, TunnelState>, live_state: State<'_, LiveState>, ) -> Result<(), String> { @@ -1092,7 +1093,7 @@ fn mssql_plan_lines(xml: &str) -> Vec { #[tauri::command] pub async fn pg_explain_sql( - state: State<'_, DbState>, + state: Db<'_>, sql: String, analyze: Option, ) -> Result { @@ -1179,13 +1180,13 @@ pub async fn pg_explain_sql( // ── DB-agnostic query commands ──────────────────────────────────────────────── #[tauri::command] -pub async fn pg_list_schemas(state: State<'_, DbState>) -> Result, String> { +pub async fn pg_list_schemas(state: Db<'_>) -> Result, String> { list_schemas(state).await } #[tauri::command] pub async fn pg_list_tables( - state: State<'_, DbState>, + state: Db<'_>, schema: String, ) -> Result, String> { list_tables(state, schema).await @@ -1195,7 +1196,7 @@ pub async fn pg_list_tables( /// unknown (-1) row count. See `db::schema::table_row_counts`. #[tauri::command] pub async fn pg_table_row_counts( - state: State<'_, DbState>, + state: Db<'_>, schema: String, tables: Vec, ) -> Result, String> { @@ -1204,7 +1205,7 @@ pub async fn pg_table_row_counts( #[tauri::command] pub async fn pg_list_indexes( - state: State<'_, DbState>, + state: Db<'_>, schema: String, table: Option, ) -> Result, String> { @@ -1213,7 +1214,7 @@ pub async fn pg_list_indexes( #[tauri::command] pub async fn pg_get_table_column_structure( - state: State<'_, DbState>, + state: Db<'_>, schema: String, table: String, ) -> Result, String> { @@ -1224,7 +1225,7 @@ pub async fn pg_get_table_column_structure( /// table. Used by the ER diagram, which needs the whole schema up front. #[tauri::command] pub async fn pg_get_schema_column_structure( - state: State<'_, DbState>, + state: Db<'_>, schema: String, ) -> Result, String> { get_schema_column_structure(state, schema).await @@ -1232,7 +1233,7 @@ pub async fn pg_get_schema_column_structure( #[tauri::command] pub async fn pg_get_incoming_foreign_keys( - state: State<'_, DbState>, + state: Db<'_>, schema: String, table: String, ) -> Result, String> { @@ -1241,7 +1242,7 @@ pub async fn pg_get_incoming_foreign_keys( #[tauri::command] pub async fn pg_list_enums( - state: State<'_, DbState>, + state: Db<'_>, schema: String, ) -> Result, String> { list_enums(state, schema).await @@ -1249,7 +1250,7 @@ pub async fn pg_list_enums( #[tauri::command] pub async fn pg_list_triggers( - state: State<'_, DbState>, + state: Db<'_>, schema: String, ) -> Result, String> { list_triggers(state, schema).await @@ -1257,7 +1258,7 @@ pub async fn pg_list_triggers( #[tauri::command] pub async fn pg_list_sequences( - state: State<'_, DbState>, + state: Db<'_>, schema: String, ) -> Result, String> { list_sequences(state, schema).await @@ -1265,7 +1266,7 @@ pub async fn pg_list_sequences( #[tauri::command] pub async fn pg_list_functions( - state: State<'_, DbState>, + state: Db<'_>, schema: String, ) -> Result, String> { list_functions(state, schema).await @@ -1275,7 +1276,7 @@ pub async fn pg_list_functions( /// and which of those kinds the engine has (the sidebar's Objects tab). #[tauri::command] pub async fn list_db_objects( - state: State<'_, DbState>, + state: Db<'_>, schema: String, ) -> Result { crate::db::objects::list_db_objects(state, schema).await @@ -1283,7 +1284,7 @@ pub async fn list_db_objects( #[tauri::command] pub async fn get_object_definition( - state: State<'_, DbState>, + state: Db<'_>, kind: String, schema: String, name: String, @@ -1296,7 +1297,7 @@ pub async fn get_object_definition( #[tauri::command] #[allow(clippy::too_many_arguments)] pub async fn drop_db_object( - state: State<'_, DbState>, + state: Db<'_>, kind: String, schema: String, name: String, @@ -1321,20 +1322,20 @@ pub async fn drop_db_object( /// Table and view comments for one schema (the sidebar's comments setting). #[tauri::command] pub async fn list_object_comments( - state: State<'_, DbState>, + state: Db<'_>, schema: String, ) -> Result, String> { crate::db::objects::list_object_comments(state, schema).await } #[tauri::command] -pub async fn ping_db_connection(state: State<'_, DbState>) -> Result<(), String> { +pub async fn ping_db_connection(state: Db<'_>) -> Result<(), String> { ping_connection(state).await } #[tauri::command] pub async fn pg_truncate_table( - state: State<'_, DbState>, + state: Db<'_>, schema: String, table: String, ) -> Result<(), String> { @@ -1343,7 +1344,7 @@ pub async fn pg_truncate_table( #[tauri::command] pub async fn pg_drop_table( - state: State<'_, DbState>, + state: Db<'_>, schema: String, table: String, cascade: bool, @@ -1356,7 +1357,7 @@ pub async fn pg_drop_table( /// Copy a database on the current server under a new name, structure and rows. #[tauri::command] pub async fn pg_clone_database( - state: State<'_, DbState>, + state: Db<'_>, source: String, target: String, ) -> Result { @@ -1366,7 +1367,7 @@ pub async fn pg_clone_database( #[tauri::command] pub async fn get_table_ddl( - state: State<'_, DbState>, + state: Db<'_>, schema: String, table: String, ) -> Result { @@ -1384,7 +1385,7 @@ pub async fn get_table_ddl_on_connection( #[tauri::command] pub async fn pg_get_table_rows( - state: State<'_, DbState>, + state: Db<'_>, schema: String, table: String, limit: i64, @@ -1440,7 +1441,7 @@ pub async fn pg_get_table_rows( /// total streams in without blocking the initial paint. #[tauri::command] pub async fn pg_count_table_rows( - state: State<'_, DbState>, + state: Db<'_>, schema: String, table: String, search: Option, @@ -1473,7 +1474,7 @@ pub async fn pg_count_table_rows( /// Which text columns a search index would cover, and which have one. #[tauri::command] pub async fn pg_search_index_status( - state: State<'_, DbState>, + state: Db<'_>, schema: String, table: String, ) -> Result { @@ -1483,7 +1484,7 @@ pub async fn pg_search_index_status( /// Create trigram indexes so the grid's search is an index scan. #[tauri::command] pub async fn pg_create_search_index( - state: State<'_, DbState>, + state: Db<'_>, schema: String, table: String, ) -> Result, String> { @@ -1492,7 +1493,7 @@ pub async fn pg_create_search_index( #[tauri::command] pub async fn pg_get_column_stats( - state: State<'_, DbState>, + state: Db<'_>, schema: String, table: String, column: String, @@ -1504,7 +1505,7 @@ pub async fn pg_get_column_stats( #[tauri::command] pub async fn geo_overview( - state: State<'_, DbState>, + state: Db<'_>, ) -> Result { crate::db::geo_overview(state).await } @@ -1512,7 +1513,7 @@ pub async fn geo_overview( #[tauri::command] #[allow(clippy::too_many_arguments)] pub async fn geo_features( - state: State<'_, DbState>, + state: Db<'_>, schema: String, table: String, column: String, @@ -1537,28 +1538,28 @@ pub async fn geo_features( #[tauri::command] pub async fn instance_version( - state: State<'_, DbState>, + state: Db<'_>, ) -> Result { crate::db::instance_version(state).await } #[tauri::command] pub async fn instance_activity( - state: State<'_, DbState>, + state: Db<'_>, ) -> Result { crate::db::instance_activity(state).await } #[tauri::command] pub async fn instance_state( - state: State<'_, DbState>, + state: Db<'_>, ) -> Result { crate::db::instance_state(state).await } #[tauri::command] pub async fn instance_config( - state: State<'_, DbState>, + state: Db<'_>, ) -> Result, String> { crate::db::instance_config(state).await } @@ -1567,7 +1568,7 @@ pub async fn instance_config( /// `value = None` resets it to the server default. #[tauri::command] pub async fn instance_set_config( - state: State<'_, DbState>, + state: Db<'_>, name: String, value: Option, ) -> Result { @@ -1578,7 +1579,7 @@ pub async fn instance_set_config( /// only - it never reads user rows and never writes. #[tauri::command] pub async fn advisor_scan( - state: State<'_, DbState>, + state: Db<'_>, ) -> Result { let conn = crate::db::connection::require_conn(&state)?; crate::db::advisor::scan(&conn).await @@ -1586,7 +1587,7 @@ pub async fn advisor_scan( #[tauri::command] pub async fn instance_replication( - state: State<'_, DbState>, + state: Db<'_>, ) -> Result { crate::db::instance_replication(state).await } @@ -1595,7 +1596,7 @@ pub async fn instance_replication( /// it keeps the single-slot behaviour older callers relied on. #[tauri::command] pub async fn pg_execute_sql( - state: State<'_, DbState>, + state: Db<'_>, sql: String, query_id: Option, ) -> Result { @@ -1604,7 +1605,7 @@ pub async fn pg_execute_sql( #[tauri::command] pub async fn pg_execute_sql_multi( - state: State<'_, DbState>, + state: Db<'_>, sql: String, query_id: Option, ) -> Result, String> { @@ -1621,7 +1622,7 @@ pub async fn pg_execute_sql_multi( /// Stream results). The window reads them with `result_window`. #[tauri::command] pub async fn pg_execute_sql_stream( - state: State<'_, DbState>, + state: Db<'_>, store: State<'_, crate::db::result_store::ResultStore>, sql: String, query_id: Option, @@ -1720,13 +1721,13 @@ pub async fn list_tables_on_connection( /// Run a DDL statement outside a transaction (required for CREATE/DROP DATABASE etc.). #[tauri::command] -pub async fn pg_execute_ddl(state: State<'_, DbState>, sql: String) -> Result<(), String> { +pub async fn pg_execute_ddl(state: Db<'_>, sql: String) -> Result<(), String> { execute_ddl(state, sql).await } #[tauri::command] pub async fn pg_update_table_cell( - state: State<'_, DbState>, + state: Db<'_>, schema: String, table: String, primary_key: HashMap, @@ -1739,7 +1740,7 @@ pub async fn pg_update_table_cell( /// Load one cell in full - the value a browse page deliberately did not fetch. #[tauri::command] pub async fn pg_fetch_cell_value( - state: State<'_, DbState>, + state: Db<'_>, schema: String, table: String, primary_key: HashMap, @@ -1751,7 +1752,7 @@ pub async fn pg_fetch_cell_value( #[tauri::command] pub async fn pg_delete_table_row( - state: State<'_, DbState>, + state: Db<'_>, schema: String, table: String, primary_key: HashMap, @@ -1761,7 +1762,7 @@ pub async fn pg_delete_table_row( #[tauri::command] pub async fn pg_delete_table_rows( - state: State<'_, DbState>, + state: Db<'_>, schema: String, table: String, primary_keys: Vec>, @@ -1772,7 +1773,7 @@ pub async fn pg_delete_table_rows( /// Staged grid changes as one transaction (Postgres, MySQL, SQLite) - see `apply_table_changes`. #[tauri::command] pub async fn pg_apply_table_changes( - state: State<'_, DbState>, + state: Db<'_>, schema: String, table: String, updates: Vec, @@ -1784,7 +1785,7 @@ pub async fn pg_apply_table_changes( #[tauri::command] pub async fn pg_insert_table_row( - state: State<'_, DbState>, + state: Db<'_>, schema: String, table: String, values: HashMap, @@ -1798,7 +1799,7 @@ pub async fn pg_insert_table_row( /// cancels every query in flight (the old whole-app "stop" behaviour). #[tauri::command] pub async fn cancel_query( - state: State<'_, DbState>, + state: Db<'_>, query_id: Option, ) -> Result<(), String> { if let Ok(mut map) = state.cancels.lock() { @@ -2246,7 +2247,7 @@ pub fn set_window_glass(window: tauri::WebviewWindow, enabled: bool, dark: bool) /// D1 Time Travel: the bookmark for now, or for the moment nearest `timestamp`. #[tauri::command] -pub async fn d1_bookmark(state: State<'_, DbState>, timestamp: Option) -> Result { +pub async fn d1_bookmark(state: Db<'_>, timestamp: Option) -> Result { match require_conn(&state)? { ActiveConnection::D1(cfg) => crate::db::d1::bookmark(&cfg, timestamp.as_deref()).await, _ => Err("Time Travel is a Cloudflare D1 feature.".into()), @@ -2255,7 +2256,7 @@ pub async fn d1_bookmark(state: State<'_, DbState>, timestamp: Option) - /// D1 Time Travel: rewind the database to a bookmark; returns the previous one. #[tauri::command] -pub async fn d1_restore(state: State<'_, DbState>, bookmark: String) -> Result { +pub async fn d1_restore(state: Db<'_>, bookmark: String) -> Result { match require_conn(&state)? { ActiveConnection::D1(cfg) => crate::db::d1::restore(&cfg, &bookmark).await, _ => Err("Time Travel is a Cloudflare D1 feature.".into()), diff --git a/src-tauri/src/db/backup.rs b/src-tauri/src/db/backup.rs index 47506558..7a27821c 100644 --- a/src-tauri/src/db/backup.rs +++ b/src-tauri/src/db/backup.rs @@ -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}; @@ -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. @@ -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, tables: Option>, options: Option, @@ -583,7 +584,7 @@ async fn export_into( #[tauri::command] pub async fn backup_import( app: AppHandle, - state: State<'_, DbState>, + state: Db<'_>, sql: Option, path: Option, ) -> Result { diff --git a/src-tauri/src/db/connection.rs b/src-tauri/src/db/connection.rs index e6421d98..a58e12ea 100644 --- a/src-tauri/src/db/connection.rs +++ b/src-tauri/src/db/connection.rs @@ -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>>, + /// 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>>, /// 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 @@ -417,6 +420,7 @@ 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())), } } @@ -424,21 +428,80 @@ impl Default for DbState { /// 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 { +/// `State` 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, +} + +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 { + 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 = 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 { + 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() @@ -448,7 +511,7 @@ pub fn require_conn(state: &State<'_, DbState>) -> Result) -> Result { +pub fn require_pool(state: &Db<'_>) -> Result { match require_conn(state)? { ActiveConnection::Postgres(pool) => Ok(pool), other => Err(format!( @@ -480,12 +543,14 @@ pub fn update_d1_token(token: &str) { } } -fn set_conn(state: &State<'_, DbState>, conn: Option) -> Result<(), String> { +fn set_conn(state: &Db<'_>, conn: Option) -> 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); @@ -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> { @@ -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))) @@ -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> { @@ -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; @@ -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))) @@ -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; @@ -1536,7 +1601,7 @@ 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))) @@ -1544,34 +1609,34 @@ pub async fn connect_posthog(state: State<'_, DbState>, config: PosthogConfig) - // ── 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)))) } @@ -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; @@ -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; @@ -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))) @@ -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))) @@ -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 diff --git a/src-tauri/src/db/geo.rs b/src-tauri/src/db/geo.rs index f8993e8a..8e20b718 100644 --- a/src-tauri/src/db/geo.rs +++ b/src-tauri/src/db/geo.rs @@ -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 @@ -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, String> { +fn pg_pool(state: &Db<'_>) -> Result, String> { match require_conn(state)? { ActiveConnection::Postgres(pool) => Ok(Some(pool)), _ => Ok(None), @@ -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 { +pub async fn geo_overview(state: Db<'_>) -> Result { let Some(pool) = pg_pool(&state)? else { return Ok(unavailable()) }; let version: Option = @@ -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, diff --git a/src-tauri/src/db/import.rs b/src-tauri/src/db/import.rs index d0940577..cb9978f4 100644 --- a/src-tauri/src/db/import.rs +++ b/src-tauri/src/db/import.rs @@ -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; @@ -123,7 +124,7 @@ fn emit_log(app: &AppHandle, level: &'static str, message: impl Into) { #[tauri::command] pub async fn import_rows( app: AppHandle, - state: State<'_, DbState>, + state: Db<'_>, schema: Option, table: String, columns: Vec, diff --git a/src-tauri/src/db/insights.rs b/src-tauri/src/db/insights.rs index eb93e26e..2a189807 100644 --- a/src-tauri/src/db/insights.rs +++ b/src-tauri/src/db/insights.rs @@ -13,13 +13,13 @@ //! than failing the whole command. The dashboard must never hard-fail because, //! e.g., `pg_stat_replication` requires a privileged role. -use super::connection::{require_conn, ActiveConnection, ClickhouseConfig, DbState}; +use crate::db::connection::Db; +use super::connection::{require_conn, ActiveConnection, ClickhouseConfig}; use super::query::SqlResult; use serde::Serialize; use serde_json::{Map, Value}; use sqlx::{Column, MySqlPool, PgPool, Row, SqlitePool}; use std::collections::HashMap; -use tauri::State; /// Returned when Instance Insights is requested on an unsupported engine. const UNSUPPORTED: &str = @@ -265,7 +265,7 @@ pub struct InstanceVersion { } /// Cheap engine + version lookup so the dashboard header can render immediately. -pub async fn instance_version(state: State<'_, DbState>) -> Result { +pub async fn instance_version(state: Db<'_>) -> Result { match require_conn(&state)? { ActiveConnection::Postgres(pool) => { let version = sqlx::query("SHOW server_version") @@ -369,7 +369,7 @@ fn usage_pct(total: i64, max: i64) -> f64 { } } -pub async fn instance_activity(state: State<'_, DbState>) -> Result { +pub async fn instance_activity(state: Db<'_>) -> Result { match require_conn(&state)? { ActiveConnection::Postgres(pool) => Ok(pg_activity(&pool).await), ActiveConnection::Mysql(pool) => Ok(mysql_activity(&pool).await), @@ -566,7 +566,7 @@ pub struct InstanceState { pub prepared_transactions: Vec, } -pub async fn instance_state(state: State<'_, DbState>) -> Result { +pub async fn instance_state(state: Db<'_>) -> Result { match require_conn(&state)? { ActiveConnection::Postgres(pool) => { let sessions = pg_query_objects( @@ -692,7 +692,7 @@ pub struct ConfigSetting { pub editable: bool, } -pub async fn instance_config(state: State<'_, DbState>) -> Result, String> { +pub async fn instance_config(state: Db<'_>) -> Result, String> { match require_conn(&state)? { ActiveConnection::Postgres(pool) => { let rows = sqlx::query( @@ -863,7 +863,7 @@ fn sql_literal(value: &str) -> String { /// hold `pg_write_all_settings`) - the server's own error is passed straight /// through when it is not. pub async fn instance_set_config( - state: State<'_, DbState>, + state: Db<'_>, name: String, value: Option, ) -> Result { @@ -983,7 +983,7 @@ pub struct InstanceReplication { pub slots: Vec, } -pub async fn instance_replication(state: State<'_, DbState>) -> Result { +pub async fn instance_replication(state: Db<'_>) -> Result { match require_conn(&state)? { ActiveConnection::Postgres(pool) => { let stats = pg_query_objects( diff --git a/src-tauri/src/db/objects.rs b/src-tauri/src/db/objects.rs index eabb0b6f..4f3d7cc4 100644 --- a/src-tauri/src/db/objects.rs +++ b/src-tauri/src/db/objects.rs @@ -11,12 +11,12 @@ //! Postgres routine's argument list for DROP is read back from the catalog //! rather than taken from the caller. +use crate::db::connection::Db; use serde::Serialize; use serde_json::Value; use sqlx::{MySqlPool, PgPool, Row, SqlitePool}; -use tauri::State; -use super::connection::{require_conn, ActiveConnection, D1Config, DbState, LibSqlConfig}; +use super::connection::{require_conn, ActiveConnection, D1Config, LibSqlConfig}; use super::mysql::my_text_named; use super::query::SqlResult; use super::sql_util::{esc_backslash_quote, esc_single_quote, quote_backtick, quote_bracket, quote_double}; @@ -232,7 +232,7 @@ fn trigger_row(name: String, table: String, detail: String, comment: Option, schema: String) -> Result { +pub async fn list_db_objects(state: Db<'_>, schema: String) -> Result { let conn = require_conn(&state)?; let kinds: Vec = kinds_for(&conn).iter().map(|k| k.to_string()).collect(); let cascade = matches!(conn, ActiveConnection::Postgres(_)); @@ -654,7 +654,7 @@ async fn list_clickhouse(cfg: &super::connection::ClickhouseConfig) -> Result, + state: Db<'_>, kind: String, schema: String, name: String, @@ -1041,7 +1041,7 @@ async fn def_clickhouse(cfg: &super::connection::ClickhouseConfig, kind: &str, d /// Drop one object. Returns the statement that ran, for the log. #[allow(clippy::too_many_arguments)] pub async fn drop_object( - state: State<'_, DbState>, + state: Db<'_>, kind: String, schema: String, name: String, @@ -1155,7 +1155,7 @@ pub async fn drop_object( /// Table and view comments for one schema, in one query. Engines that keep /// none (SQLite and its relatives) return an empty list. -pub async fn list_object_comments(state: State<'_, DbState>, schema: String) -> Result, String> { +pub async fn list_object_comments(state: Db<'_>, schema: String) -> Result, String> { let pairs = |r: SqlResult| -> Vec { r.rows .iter() diff --git a/src-tauri/src/db/parked.rs b/src-tauri/src/db/parked.rs index 13b46f93..0238cb31 100644 --- a/src-tauri/src/db/parked.rs +++ b/src-tauri/src/db/parked.rs @@ -3,18 +3,18 @@ //! database costs nothing. Only the pool handle moves (it is an Arc inside), //! so this never touches the network. -use super::connection::{close_in_background, DbState}; -use tauri::State; +use super::connection::{close_in_background, Db}; /// More than this many set-aside pools and the oldest is closed. -const MAX_PARKED: usize = 6; +const MAX_PARKED: usize = 8; /// Set the open connection aside under `key`. Nothing open: nothing to do. #[tauri::command] -pub fn park_connection(state: State<'_, DbState>, key: String) -> Result<(), String> { +pub fn park_connection(state: Db<'_>, key: String) -> Result<(), String> { let Some(conn) = state.conn.lock().map_err(|e| e.to_string())?.take() else { return Ok(()); }; + *state.active_key.lock().map_err(|e| e.to_string())? = None; let mut parked = state.parked.lock().map_err(|e| e.to_string())?; parked.retain(|(k, _)| k != &key); parked.push((key, conn)); @@ -28,13 +28,14 @@ pub fn park_connection(state: State<'_, DbState>, key: String) -> Result<(), Str /// Make the pool set aside under `key` the open one. False when there is none /// (the page then connects as usual). #[tauri::command] -pub fn resume_connection(state: State<'_, DbState>, key: String) -> Result { +pub fn resume_connection(state: Db<'_>, key: String) -> Result { let found = { let mut parked = state.parked.lock().map_err(|e| e.to_string())?; parked.iter().position(|(k, _)| k == &key).map(|i| parked.remove(i).1) }; let Some(conn) = found else { return Ok(false) }; let previous = state.conn.lock().map_err(|e| e.to_string())?.replace(conn); + *state.active_key.lock().map_err(|e| e.to_string())? = Some(key); if let Some(prev) = previous { close_in_background(prev); } @@ -46,7 +47,7 @@ pub fn resume_connection(state: State<'_, DbState>, key: String) -> Result, + state: Db<'_>, key: Option, connection: Option, ) -> Result<(), String> { @@ -66,6 +67,14 @@ pub fn close_parked( /// Which connections are set aside, oldest first. #[tauri::command] -pub fn parked_connections(state: State<'_, DbState>) -> Result, String> { +pub fn parked_connections(state: Db<'_>) -> Result, String> { Ok(state.parked.lock().map_err(|e| e.to_string())?.iter().map(|(k, _)| k.clone()).collect()) } + +/// The page's key for the pool now in front, after it connects fresh (a +/// resume sets it itself). Routed calls compare against it. +#[tauri::command] +pub fn set_active_conn_key(state: Db<'_>, key: Option) -> Result<(), String> { + *state.active_key.lock().map_err(|e| e.to_string())? = key.filter(|k| !k.is_empty()); + Ok(()) +} diff --git a/src-tauri/src/db/query.rs b/src-tauri/src/db/query.rs index a1e2d18c..3edeb457 100644 --- a/src-tauri/src/db/query.rs +++ b/src-tauri/src/db/query.rs @@ -1,4 +1,5 @@ -use super::connection::{require_conn, require_pool, ActiveConnection, DbState}; +use crate::db::connection::Db; +use super::connection::{require_conn, require_pool, ActiveConnection}; use super::schema::validate_ident; use chrono::{DateTime, NaiveDate, NaiveDateTime, NaiveTime, Utc}; use futures::TryStreamExt; @@ -9,7 +10,6 @@ use sqlx::{Column, Decode, Postgres, Row, TypeInfo, ValueRef}; use std::collections::HashMap; use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; use std::sync::Arc; -use tauri::State; use uuid::Uuid; #[derive(Debug, Clone, Serialize)] @@ -1958,7 +1958,7 @@ pub(crate) fn validate_raw_filters(conn: &ActiveConnection, filters: Option<&[Ro } pub async fn get_table_rows( - state: State<'_, DbState>, + state: Db<'_>, schema: String, table: String, limit: i64, @@ -2580,7 +2580,7 @@ static SUPERSEDED: std::sync::LazyLock = std::sync::LazyLock::new(|| /// (the WHERE clause bounds the scan). Non-Postgres engines return -1 - their /// `get_table_rows` already carries a real total, so the UI keeps that. pub async fn count_table_rows( - state: State<'_, DbState>, + state: Db<'_>, schema: String, table: String, search: Option, @@ -2689,7 +2689,7 @@ pub async fn count_table_rows( } pub async fn update_table_cell( - state: State<'_, DbState>, + state: Db<'_>, schema: String, table: String, primary_key: HashMap, @@ -2908,7 +2908,7 @@ pub(crate) async fn pg_insert_meta( } pub async fn insert_table_row( - state: State<'_, DbState>, + state: Db<'_>, schema: String, table: String, values: HashMap, @@ -3034,7 +3034,7 @@ pub async fn insert_table_row( } pub async fn delete_table_row( - state: State<'_, DbState>, + state: Db<'_>, schema: String, table: String, primary_key: HashMap, @@ -3047,7 +3047,7 @@ pub async fn delete_table_row( } pub async fn delete_table_rows( - state: State<'_, DbState>, + state: Db<'_>, schema: String, table: String, primary_keys: Vec>, @@ -3263,7 +3263,7 @@ pub(crate) fn describe_pk(pk_columns: &[String], primary_key: &HashMap, + state: Db<'_>, schema: String, table: String, updates: Vec, @@ -3514,7 +3514,7 @@ pub(crate) fn is_row_returning_sql(sql: &str) -> bool { /// Execute a single DDL statement that must run outside a transaction (e.g. /// CREATE DATABASE), directly on the connection, on any engine that has DDL. -pub async fn execute_ddl(state: State<'_, DbState>, sql: String) -> Result<(), String> { +pub async fn execute_ddl(state: Db<'_>, sql: String) -> Result<(), String> { let sql_str = sql.trim(); if sql_str.is_empty() { return Err("Statement is empty".into()); @@ -3523,7 +3523,7 @@ pub async fn execute_ddl(state: State<'_, DbState>, sql: String) -> Result<(), S } pub async fn execute_sql( - state: State<'_, DbState>, + state: Db<'_>, sql: String, query_id: Option, ) -> Result { @@ -4479,7 +4479,7 @@ async fn run_sql_multi_pg( } pub async fn execute_sql_multi( - state: State<'_, DbState>, + state: Db<'_>, sql: String, query_id: Option, ) -> Result, String> { @@ -4594,7 +4594,7 @@ impl StatementOutcome { /// A single Postgres statement streams through `sink` (into the result store, /// in store mode). A script's results come back in the reply. pub async fn execute_sql_script( - state: State<'_, DbState>, + state: Db<'_>, sql: String, query_id: Option, sink: Option<&mut RowSink>, @@ -5146,7 +5146,7 @@ const CELL_FETCH_HARD_MAX: i64 = 64 * 1024 * 1024; const CELL_FETCH_DEFAULT_MAX: i64 = 32 * 1024 * 1024; pub async fn fetch_cell_value( - state: State<'_, DbState>, + state: Db<'_>, schema: String, table: String, primary_key: HashMap, @@ -5260,7 +5260,7 @@ pub async fn fetch_cell_value( } pub async fn get_column_stats( - state: State<'_, DbState>, + state: Db<'_>, schema: String, table: String, column: String, @@ -5354,7 +5354,7 @@ pub async fn get_column_stats( /// MIN/MAX/DISTINCT on the column type (e.g. JSON/BLOB), so the panel still shows /// total + null counts instead of erroring. async fn column_stats_generic( - state: State<'_, DbState>, + state: Db<'_>, schema: String, table: String, column: String, @@ -5457,7 +5457,7 @@ async fn dispatch_stats_sql(conn: &ActiveConnection, sql: &str) -> Result) -> Result<(), String> { +pub async fn ping_connection(state: Db<'_>) -> Result<(), String> { let conn = require_conn(&state)?; match conn { // Remote pools: touch every idle connection, not just one (see keepalive_idle). @@ -5940,7 +5940,7 @@ fn search_index_name(table: &str, column: &str) -> String { } pub async fn search_index_status( - state: State<'_, DbState>, + state: Db<'_>, schema: String, table: String, ) -> Result { @@ -5987,7 +5987,7 @@ pub async fn search_index_status( /// Create the missing trigram indexes. CONCURRENTLY, so the table stays /// readable and writable while they build; returns the indexes created. pub async fn create_search_index( - state: State<'_, DbState>, + state: Db<'_>, schema: String, table: String, ) -> Result, String> { diff --git a/src-tauri/src/db/schema.rs b/src-tauri/src/db/schema.rs index 3d0128be..3495ccc2 100644 --- a/src-tauri/src/db/schema.rs +++ b/src-tauri/src/db/schema.rs @@ -1,7 +1,7 @@ -use super::connection::{require_conn, ActiveConnection, AnyConnectionConfig, DbState}; +use crate::db::connection::Db; +use super::connection::{require_conn, ActiveConnection, AnyConnectionConfig}; use serde::Serialize; use sqlx::{MySqlPool, PgPool, Row}; -use tauri::State; use super::mysql::{my_int, my_text, my_text_named}; @@ -219,7 +219,7 @@ pub struct TableRowCount { /// `list_tables` already returns exact counts inline (SQLite/D1/libSQL/…) /// never report -1, so they return an empty list here. pub async fn table_row_counts( - state: State<'_, DbState>, + state: Db<'_>, schema: String, tables: Vec, ) -> Result, String> { @@ -1138,7 +1138,7 @@ async fn list_sequences_pg(pool: &PgPool, schema: &str) -> Result) -> Result, String> { +pub async fn list_schemas(state: Db<'_>) -> Result, String> { match require_conn(&state)? { ActiveConnection::Postgres(pool) => list_schemas_pg(&pool).await, ActiveConnection::Mysql(pool) => list_schemas_mysql(&pool).await, @@ -1153,7 +1153,7 @@ pub async fn list_schemas(state: State<'_, DbState>) -> Result, Stri } } -pub async fn list_tables(state: State<'_, DbState>, schema: String) -> Result, String> { +pub async fn list_tables(state: Db<'_>, schema: String) -> Result, String> { match require_conn(&state)? { ActiveConnection::Postgres(pool) => { validate_ident(&schema)?; @@ -1197,7 +1197,7 @@ pub async fn list_tables(state: State<'_, DbState>, schema: String) -> Result, + state: Db<'_>, schema: String, table: Option, ) -> Result, String> { @@ -1295,7 +1295,7 @@ async fn list_functions_mysql(pool: &sqlx::MySqlPool, schema: &str) -> Result, schema: String) -> Result, String> { +pub async fn list_functions(state: Db<'_>, schema: String) -> Result, String> { match require_conn(&state)? { ActiveConnection::Postgres(pool) => { validate_ident(&schema)?; @@ -1309,7 +1309,7 @@ pub async fn list_functions(state: State<'_, DbState>, schema: String) -> Result } } -pub async fn list_enums(state: State<'_, DbState>, schema: String) -> Result, String> { +pub async fn list_enums(state: Db<'_>, schema: String) -> Result, String> { match require_conn(&state)? { ActiveConnection::Postgres(pool) => { validate_ident(&schema)?; @@ -1319,7 +1319,7 @@ pub async fn list_enums(state: State<'_, DbState>, schema: String) -> Result, schema: String) -> Result, String> { +pub async fn list_triggers(state: Db<'_>, schema: String) -> Result, String> { match require_conn(&state)? { ActiveConnection::Postgres(pool) => { validate_ident(&schema)?; @@ -1334,7 +1334,7 @@ pub async fn list_triggers(state: State<'_, DbState>, schema: String) -> Result< } } -pub async fn list_sequences(state: State<'_, DbState>, schema: String) -> Result, String> { +pub async fn list_sequences(state: Db<'_>, schema: String) -> Result, String> { match require_conn(&state)? { ActiveConnection::Postgres(pool) => { validate_ident(&schema)?; @@ -1349,19 +1349,19 @@ pub async fn list_sequences(state: State<'_, DbState>, schema: String) -> Result // Both spell the statement per engine in `admin`; this used to know Postgres // and SQLite only and told every other engine it was unsupported. -pub async fn truncate_table(state: State<'_, DbState>, schema: String, table: String) -> Result<(), String> { +pub async fn truncate_table(state: Db<'_>, schema: String, table: String) -> Result<(), String> { let conn = require_conn(&state)?; super::admin::truncate_table(&conn, &schema, &table).await } -pub async fn drop_table(state: State<'_, DbState>, schema: String, table: String, cascade: bool, kind: Option) -> Result<(), String> { +pub async fn drop_table(state: Db<'_>, schema: String, table: String, cascade: bool, kind: Option) -> Result<(), String> { let kind = super::admin::ObjectKind::parse(kind.as_deref())?; let conn = require_conn(&state)?; super::admin::drop_object(&conn, &schema, &table, kind, cascade).await } pub async fn get_table_column_structure( - state: State<'_, DbState>, + state: Db<'_>, schema: String, table: String, ) -> Result, String> { @@ -1720,7 +1720,7 @@ async fn get_column_structure_pg( /// MongoDB, CouchDB, Firestore, DynamoDB and Redis have no schema-wide column /// catalog: they answer empty at once, and the caller reads per table. pub async fn get_schema_column_structure( - state: State<'_, DbState>, + state: Db<'_>, schema: String, ) -> Result, String> { match require_conn(&state)? { @@ -2502,7 +2502,7 @@ async fn get_incoming_fks_mssql(handle: &super::connection::MssqlHandle, schema: } pub async fn get_incoming_foreign_keys( - state: State<'_, DbState>, + state: Db<'_>, schema: String, table: String, ) -> Result, String> { @@ -2677,7 +2677,7 @@ async fn get_ddl_libsql( } pub async fn get_table_ddl( - state: State<'_, DbState>, + state: Db<'_>, schema: String, table: String, ) -> Result { diff --git a/src-tauri/src/db/tx.rs b/src-tauri/src/db/tx.rs index 845394e4..b03fab1d 100644 --- a/src-tauri/src/db/tx.rs +++ b/src-tauri/src/db/tx.rs @@ -11,6 +11,7 @@ as it stays open, so a session that is left behind is closed automatically after `IDLE_TIMEOUT` - see `sweep_idle`. */ +use crate::db::connection::Db; use std::collections::HashMap; use std::sync::Mutex; use std::time::{Duration, Instant}; @@ -21,7 +22,7 @@ use serde_json::Value; use sqlx::{Column, Row, TypeInfo}; use tauri::State; -use super::connection::{require_conn, ActiveConnection, DbState}; +use super::connection::{require_conn, ActiveConnection}; use super::query::{ cell_to_json, is_row_returning_sql, pg_type_label, split_sql_statements, ColumnInfo, SqlResult, EXECUTE_SQL_TIMEOUT_MS, @@ -122,7 +123,7 @@ fn no_session(id: &str) -> String { /// Open a transaction and hold its connection until commit or rollback. #[tauri::command] pub async fn tx_begin( - db: State<'_, DbState>, + db: Db<'_>, tx: State<'_, TxState>, session_id: String, ) -> Result { diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index 570ed49d..b29a7c37 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -452,6 +452,7 @@ pub fn run() { let db_state = DbState { conn: Arc::clone(&db_conn), parked: Arc::new(Mutex::new(Vec::new())), + active_key: Arc::new(Mutex::new(None)), cancels: Arc::new(std::sync::Mutex::new(std::collections::HashMap::new())), }; let db_conn_for_setup = Arc::clone(&db_conn); @@ -912,6 +913,7 @@ pub fn run() { quit::cancel_quit, quit::set_quit_guard, db::parked::park_connection, + db::parked::set_active_conn_key, db::parked::resume_connection, db::parked::close_parked, db::parked::parked_connections, diff --git a/src/lib/api.js b/src/lib/api.js index a267cd75..689c9d63 100644 --- a/src/lib/api.js +++ b/src/lib/api.js @@ -77,8 +77,21 @@ async function healD1Auth(msg) { } } +/** + * Labs, several connections at once: the key of the database the page is on. + * Every call carries it as `__conn` (read by the Rust `Db` extractor), so a + * call sent just before a switch still runs on the database it was made for, + * whichever pool is in front by the time it lands. Empty: no routing. + */ +let _connRoute = '' +/** @param {string} key */ +export function setConnRoute(key) { + _connRoute = key || '' +} + async function inv(command, args = {}) { const t0 = performance.now() + if (_connRoute && args && typeof args === 'object' && !('__conn' in args)) args = { ...args, __conn: _connRoute } try { const r = await invoke(command, args) traceIpc(command, performance.now() - t0, true) diff --git a/src/lib/components/StudioShell.svelte b/src/lib/components/StudioShell.svelte index 2a1f3841..affcba64 100644 --- a/src/lib/components/StudioShell.svelte +++ b/src/lib/components/StudioShell.svelte @@ -149,7 +149,7 @@ import WifiOff from '@lucide/svelte/icons/wifi-off' import Unplug from '@lucide/svelte/icons/unplug' import RefreshCw from '@lucide/svelte/icons/refresh-cw' - import { + import { setConnRoute, disconnectPostgres, prewarmDns, listSchemas, @@ -7633,6 +7633,10 @@ let rowSearch = $state('') } async function onConnected(conn, savedId) { + // A fresh pool is in front and unnamed: no routing until the switch that + // opened it names it (handleSwitchDatabase), or a call meant for this + // database could be sent to a kept one for the database just left. + setConnRoute('') connectedSavedId = savedId ?? '' // Labels belong to the database they were read from. void import('$lib/plugins/extensions/fk-labels.js').then((m) => m.clearFkLabels()) @@ -8316,6 +8320,7 @@ let rowSearch = $state('') if (!forget && persistConnectionId && activeSchema) setLastSchema(persistConnectionId, activeSchema) recordActivity({ type: 'disconnect', title: `Disconnected from ${connection?.name ?? 'database'}`, success: true }) setWasDisconnected(true) + setConnRoute('') try { await disconnectPostgres() } catch { /* ignore */ } try { await mcpStop() } catch { /* ignore */ } mcpRunning = false @@ -8334,6 +8339,7 @@ let rowSearch = $state('') savedConnections = loadSavedConnections() // Labs: its kept tabs go with it (its pools are closed by removeConnection). for (const key of [..._sessions.keys()]) if (key.startsWith(`${id}|`)) _sessions.delete(key) + sessionsTick++ if (connection && id && (id === persistConnectionId || id === connection.id)) { void handleDisconnect({ forget: true }) } @@ -8426,27 +8432,55 @@ let rowSearch = $state('') // their rows (marked evicted) and refetch when shown, so a kept session // costs a tab list, not its data. SSH-tunnelled connections share one // tunnel slot, so they still connect each time. - /** @type {Map} */ + /** + * @typedef {{ conn: any, label: string, tabs: StudioTab[], activeTabId: string | null, + * activeSchema: string, activeTable: string | null, schemas: string[], tables: any[] }} KeptSession + */ + /** @type {Map} */ const _sessions = new Map() + /** Bumped on every change to _sessions, so the tab bar re-reads it. */ + let sessionsTick = $state(0) + /** Databases in the order they were first opened: the tab bar groups by it, so tabs don't jump around on a switch. */ + let sessionOrder = $state(/** @type {string[]} */ ([])) const multiConnection = () => loadSettings().multiConnection === true /** One key per database, not per saved connection: a server holds several. @param {any} c */ const sessionKey = (c) => (c ? [c.id ?? '', c.type, c.databaseId ?? c.database ?? c.filePath ?? ''].join('|') : '') /** @param {any} c */ const keepable = (c) => !!c && !c.ssh?.host + /** A database's short name for its tabs. @param {any} c */ + const sessionLabel = (c) => String(c?.database || c?.name || c?.filePath?.split(/[\\/]/).pop() || c?.host || 'database') + /** @param {string} key */ + function noteSession(key) { + if (key && !sessionOrder.includes(key)) sessionOrder = [...sessionOrder, key] + } - /** Put the open connection's tabs aside under its key. */ + /** Put the open connection's tabs (and its sidebar) aside under its key. */ function keepSession() { if (!connection) return saveActiveTabState() + flushSqlTabs() const key = sessionKey(connection) + noteSession(key) // Newest last, so the cap drops the one used longest ago (as db/parked.rs does). _sessions.delete(key) _sessions.set(key, { - tabs: tabs.map((t) => (t.kind === 'table' && t.state ? { ...t, state: { ...t.state, rows: [], evicted: true } } : t)), + conn: connection, + label: sessionLabel(connection), + // The tab on screen keeps its rows, so coming back to it is instant; + // the others refetch when shown, so a kept database costs little. + tabs: tabs.map((t) => (t.kind === 'table' && t.state && t.id !== activeTabId ? { ...t, state: { ...t.state, rows: [], evicted: true } } : t)), activeTabId, activeSchema, + activeTable, + schemas, + tables, }) - while (_sessions.size > 6) _sessions.delete(/** @type {string} */ (_sessions.keys().next().value)) + while (_sessions.size > 8) { + const old = /** @type {string} */ (_sessions.keys().next().value) + _sessions.delete(old) + sessionOrder = sessionOrder.filter((k) => k !== old) + } + sessionsTick++ } /** Bring a kept session's tabs back over the fresh connection's default tab. @param {any} conn */ @@ -8455,6 +8489,7 @@ let rowSearch = $state('') const s = _sessions.get(key) if (!s || !s.tabs.length) return _sessions.delete(key) + sessionsTick++ tabs = s.tabs // Its editor tabs are already here: don't add the stored copies again. if (tabs.some((t) => t.kind === 'sql')) _sqlTabsRestoredFor = sqlDraftKey @@ -8467,8 +8502,108 @@ let rowSearch = $state('') await applyTabToEditor(front) } - /** @param {import('$lib/stores/connections.js').SavedConnection} conn */ - async function handleSwitchDatabase(conn) { + /** + * Switch to a kept database in place: its pool is already open (resumed in + * Rust), so nothing is torn down and nothing reconnects. The connection, + * sidebar and tabs are swapped in one go and refreshed quietly behind, so + * the switch shows no welcome screen, no empty sidebar and no spinner. + * @param {any} conn @param {KeptSession} s @param {string | null} [focusTab] + */ + async function resumeSession(conn, s, focusTab = null) { + connectedSavedId = conn.id ?? '' + connection = conn + savedConnections = loadSavedConnections() + tableReadonly = savedConnections.find((c) => c.id === conn.id)?.readOnly ?? conn.readOnly ?? false + if (conn.id) setLastConnectionId(conn.id) + error = '' + connectionLost = false + tableColumnsCache = new Map() + resetIncomingFkCache() + _catalog.clear() + _sqlHintsLoadedFor = '' + indexes = [] + enums = [] + triggers = [] + sequences = [] + tableFilter = '' + structureColumns = [] + structureSearch = '' + schemas = s.schemas + activeSchema = s.activeSchema + tables = s.tables + activeTable = s.activeTable + // The list on screen is this database's: a refresh keeps it up (no dots). + _tablesKey = catalogKey(persistConnectionId, 'tables', activeSchema) + loadingTables = false + tabs = s.tabs + if (tabs.some((t) => t.kind === 'sql')) _sqlTabsRestoredFor = sqlDraftKey + const front = tabs.find((t) => t.id === focusTab) ?? tabs.find((t) => t.id === s.activeTabId) ?? tabs[0] + activeTabId = front?.id ?? null + if (front) await applyTabToEditor(front) + void refreshQueryStores().catch(() => {}) + // Catch up quietly: the kept lists can be a little behind. + void (async () => { + const at = persistConnectionId + try { await loadSchemas() } catch { /* the table list still refreshes */ } + if (!connectionMoved(at)) await loadTables({ force: true, quiet: true }) + })() + } + + /** The kept session holding a tab, if any. @param {string} id */ + function sessionOfTab(id) { + for (const [key, s] of _sessions) if (s.tabs.some((t) => t.id === id)) return { key, s } + return null + } + + /** A tab of another open database: switch to that database, on that tab. @param {string} id */ + async function activateForeignTab(id) { + const hit = sessionOfTab(id) + if (!hit) return + await handleSwitchDatabase(hit.s.conn, { focusTab: id }) + } + + /** Close a tab of another open database without switching to it. @param {string} id */ + function closeForeignTab(id) { + const hit = sessionOfTab(id) + if (!hit) return + const left = hit.s.tabs.filter((t) => t.id !== id) + if (left.length) _sessions.set(hit.key, { ...hit.s, tabs: left, activeTabId: hit.s.activeTabId === id ? left[0].id : hit.s.activeTabId }) + else _sessions.set(hit.key, { ...hit.s, tabs: [] }) + sessionsTick++ + } + + /** + * Labs: one tab bar for every open database. This database's tabs and the + * kept ones, grouped in the order the databases were opened, each labelled + * with its database once more than one is open. + */ + const barTabs = $derived.by(() => { + void sessionsTick + const own = $appAiInTab ? tabs : tabs.filter((t) => t.kind !== 'ai') + if (!connection || _sessions.size === 0) return own + const here = sessionKey(connection) + const kept = [..._sessions].filter(([k, s]) => k !== here && s.tabs.some((t) => t.kind !== 'welcome')) + if (!kept.length) return own + const label = sessionLabel(connection) + const order = sessionOrder.includes(here) ? sessionOrder : [...sessionOrder, here] + /** @type {any[]} */ + const out = [] + for (const k of order) { + if (k === here) out.push(...own.map((t) => ({ ...t, connLabel: label }))) + else { + const s = _sessions.get(k) + if (!s) continue + for (const t of s.tabs) if (t.kind !== 'welcome' && t.kind !== 'ai') out.push({ ...t, connLabel: s.label, foreign: true }) + } + } + return out + }) + + /** + * @param {import('$lib/stores/connections.js').SavedConnection} conn + * @param {{ focusTab?: string | null }} [opts] Labs: the tab to land on + */ + async function handleSwitchDatabase(conn, opts = {}) { // A deliberate switch is the other half of "PIN to open or reconnect". // Resolves true immediately unless a PIN is set with the connect prompt on. if (!(await requireUnlock('Unlock to connect to a database'))) return @@ -8477,10 +8612,31 @@ let rowSearch = $state('') const previous = connection const multi = multiConnection() if (multi && keepable(previous)) { + if (previous && sessionKey(previous) === sessionKey(conn)) { + // Already here: just the tab. + if (opts.focusTab) void activateTab(opts.focusTab) + return + } keepSession() await liveStop().catch(() => {}) const { invoke } = await import('@tauri-apps/api/core') await invoke('park_connection', { key: sessionKey(previous) }).catch(() => disconnectPostgres().catch(() => {})) + // A database kept open comes back in place: no teardown, no overlay, + // no welcome screen in between (that was the flicker). + const key = sessionKey(conn) + const kept = keepable(conn) ? _sessions.get(key) : undefined + if (kept) { + const resumed = await invoke('resume_connection', { key }).then(Boolean).catch(() => false) + if (resumed) { + setConnRoute(key) + _sessions.delete(key) + noteSession(key) + sessionsTick++ + await resumeSession(conn, kept, opts.focusTab ?? null) + sidebarShowTables() + return + } + } } else { await disconnectPostgres().catch(() => {}) } @@ -8508,7 +8664,16 @@ let rowSearch = $state('') await connectByType(conn) } await onConnected(conn, conn.id) + if (multi && keepable(conn)) { + // Name the new front pool, so calls routed to it (and to the kept + // ones) find the right database. + const key = sessionKey(conn) + noteSession(key) + setConnRoute(key) + void import('@tauri-apps/api/core').then(({ invoke }) => invoke('set_active_conn_key', { key })).catch(() => {}) + } else setConnRoute('') if (multi) await restoreSession(conn) + if (opts.focusTab && tabs.some((t) => t.id === opts.focusTab)) void activateTab(opts.focusTab) // The switch landed, so the sidebar goes back to the tables of the // database you are now in. Every route into a switch - the Databases tab, // the status bar, the command palette, a context menu, another saved @@ -9673,18 +9838,18 @@ let rowSearch = $state('') {#snippet tabStrip()} {#if tabsInTitle} t.kind !== 'ai')} + tabs={barTabs} {activeTabId} - onselect={(id) => activateTab(id)} - onclose={closeTab} - oncloseothers={closeOtherTabs} + onselect={(id) => (tabs.some((t) => t.id === id) ? activateTab(id) : activateForeignTab(id))} + onclose={(id) => (tabs.some((t) => t.id === id) ? closeTab(id) : closeForeignTab(id))} + oncloseothers={(id) => { if (tabs.some((t) => t.id === id)) closeOtherTabs(id) }} oncloseall={closeAllTabs} onclosemany={(ids, anchorId) => void closeManyTabs(ids, anchorId)} - onduplicate={(id) => void duplicateTab(id)} - onresettable={(id) => void resetTableTab(id)} + onduplicate={(id) => { if (tabs.some((t) => t.id === id)) void duplicateTab(id) }} + onresettable={(id) => { if (tabs.some((t) => t.id === id)) void resetTableTab(id) }} onreopenclosed={reopenLastClosedTab} canreopenclosed={closedTabStack.length > 0} - onpintoggle={toggleTabPin} + onpintoggle={(id) => { if (tabs.some((t) => t.id === id)) toggleTabPin(id) }} onnewsql={() => { if (aiMode) exitAiMode(); openNewSqlTab() }} /> {/if} @@ -10034,18 +10199,18 @@ let rowSearch = $state('') (T3 has one row). A second tab brings the strip back. --> {#if tabBarVisible && !tabsInTitle} t.kind !== 'ai')} + tabs={barTabs} {activeTabId} - onselect={(id) => activateTab(id)} - onclose={closeTab} - oncloseothers={closeOtherTabs} + onselect={(id) => (tabs.some((t) => t.id === id) ? activateTab(id) : activateForeignTab(id))} + onclose={(id) => (tabs.some((t) => t.id === id) ? closeTab(id) : closeForeignTab(id))} + oncloseothers={(id) => { if (tabs.some((t) => t.id === id)) closeOtherTabs(id) }} oncloseall={closeAllTabs} onclosemany={(ids, anchorId) => void closeManyTabs(ids, anchorId)} - onduplicate={(id) => void duplicateTab(id)} - onresettable={(id) => void resetTableTab(id)} + onduplicate={(id) => { if (tabs.some((t) => t.id === id)) void duplicateTab(id) }} + onresettable={(id) => { if (tabs.some((t) => t.id === id)) void resetTableTab(id) }} onreopenclosed={reopenLastClosedTab} canreopenclosed={closedTabStack.length > 0} - onpintoggle={toggleTabPin} + onpintoggle={(id) => { if (tabs.some((t) => t.id === id)) toggleTabPin(id) }} onnewsql={() => { if (aiMode) exitAiMode(); openNewSqlTab() }} /> {/if} @@ -10059,14 +10224,14 @@ let rowSearch = $state('') activeTabId={group.activeTabId} onselect={(id) => void focusTabInGroup(group.id, id)} onclose={(id) => void closeTabInGroup(group.id, id)} - oncloseothers={closeOtherTabs} + oncloseothers={(id) => { if (tabs.some((t) => t.id === id)) closeOtherTabs(id) }} oncloseall={closeAllTabs} onclosemany={(ids, anchorId) => void closeManyTabs(ids, anchorId)} - onduplicate={(id) => void duplicateTab(id)} - onresettable={(id) => void resetTableTab(id)} + onduplicate={(id) => { if (tabs.some((t) => t.id === id)) void duplicateTab(id) }} + onresettable={(id) => { if (tabs.some((t) => t.id === id)) void resetTableTab(id) }} onreopenclosed={reopenLastClosedTab} canreopenclosed={closedTabStack.length > 0} - onpintoggle={toggleTabPin} + onpintoggle={(id) => { if (tabs.some((t) => t.id === id)) toggleTabPin(id) }} onnewsql={() => { if (aiMode) exitAiMode(); openNewSqlTab() }} ondragtabstart={(id) => beginTabDrag(id)} ondragtabmove={(x, y) => moveTabDrag(x, y)} diff --git a/src/lib/components/TabBar.svelte b/src/lib/components/TabBar.svelte index 0118487c..275c3175 100644 --- a/src/lib/components/TabBar.svelte +++ b/src/lib/components/TabBar.svelte @@ -216,8 +216,13 @@ )} onclick={() => { if (_suppressTabClick) { _suppressTabClick = false; return } onselect(tab.id) }} > - - {tabDisplayTitle(tab)} + + + {#if tab.connLabel} + {tab.connLabel} + {/if} + {tabDisplayTitle(tab)} {#if tab.pinned}