diff --git a/apps/tauri/src-tauri/src/commands.rs b/apps/tauri/src-tauri/src/commands.rs index 4a8813c2..864ac252 100644 --- a/apps/tauri/src-tauri/src/commands.rs +++ b/apps/tauri/src-tauri/src/commands.rs @@ -123,6 +123,81 @@ pub fn profiles_connect_sqlite( Ok(profile) } +/// Save Postgres profile metadata (no password) and open a live session. +#[tauri::command] +pub fn profiles_connect_postgres( + name: String, + host: String, + port: u16, + database: String, + user: String, + password: Option, + folder_id: Option, + id: Option, + store: State<'_, ProfileStore>, + registry: State<'_, ConnectionRegistry>, +) -> Result { + let display_name = { + let t = name.trim(); + if t.is_empty() { + format!("{user}@{host}/{database}") + } else { + t.to_owned() + } + }; + + let mut profile = match id.filter(|s| !s.trim().is_empty()) { + Some(existing_id) => store + .get(&existing_id) + .map_err(|e| ConnectionError::io(e.to_string()))? + .map(|mut p| { + p.name = display_name.clone(); + p.host = Some(host.clone()); + p.port = Some(i64::from(port)); + p.database_name = Some(database.clone()); + p.username = Some(user.clone()); + p.folder_id = folder_id.clone(); + p.driver = "postgres".into(); + p.path = None; + p + }) + .unwrap_or_else(|| { + let mut p = ConnectionProfile::new_postgres( + display_name.clone(), + host.clone(), + port, + database.clone(), + user.clone(), + ); + p.id = existing_id; + p.folder_id = folder_id.clone(); + p + }), + None => { + let mut p = + ConnectionProfile::new_postgres(display_name, host.clone(), port, database.clone(), user.clone()); + p.folder_id = folder_id; + p + } + }; + profile.touch(); + store + .upsert(&profile) + .map_err(|e| ConnectionError::io(e.to_string()))?; + + if !registry.is_connected(&ConnectionId::from(profile.id.as_str())) { + registry.connect(ConnectionConfig::Postgres { + host, + port, + database, + user, + password, + id: Some(profile.id.clone()), + })?; + } + Ok(profile) +} + #[tauri::command] pub fn db_disconnect( id: ConnectionId, diff --git a/apps/tauri/src-tauri/src/connection/manager.rs b/apps/tauri/src-tauri/src/connection/manager.rs index 796fb89d..648ae9b9 100644 --- a/apps/tauri/src-tauri/src/connection/manager.rs +++ b/apps/tauri/src-tauri/src/connection/manager.rs @@ -231,6 +231,17 @@ impl ConnectionRegistry { sqlite.clone_handle(), ))) } + DriverKind::Postgres => { + let pg = session + .as_any() + .downcast_ref::() + .ok_or(ConnectionError::UnsupportedDriver { + driver: DriverKind::Postgres, + })?; + Ok(Arc::new( + super::postgres_object_tree::PostgresObjectTree::new(pg.clone_handle()), + )) + } other => Err(ConnectionError::UnsupportedDriver { driver: other }), } } diff --git a/apps/tauri/src-tauri/src/connection/mod.rs b/apps/tauri/src-tauri/src/connection/mod.rs index c81170a2..567b3ee7 100644 --- a/apps/tauri/src-tauri/src/connection/mod.rs +++ b/apps/tauri/src-tauri/src/connection/mod.rs @@ -6,6 +6,7 @@ mod introspect; mod manager; mod object_tree; mod postgres; +mod postgres_object_tree; pub(crate) mod postgres_query; mod query; mod runtime; diff --git a/apps/tauri/src-tauri/src/connection/postgres_object_tree.rs b/apps/tauri/src-tauri/src/connection/postgres_object_tree.rs new file mode 100644 index 00000000..1a8b3514 --- /dev/null +++ b/apps/tauri/src-tauri/src/connection/postgres_object_tree.rs @@ -0,0 +1,269 @@ +//! Postgres object tree: schemas → tables/views → columns. + +use super::error::{ConnectionError, ConnectionResult}; +use super::id::DriverKind; +use super::introspect::{ColumnMeta, TableSchema}; +use super::object_tree::{ + column_id, parse_object_id, relation_id, schema_id, ObjectTreeProvider, ParsedObjectId, + SqlObjectKind, SqlObjectNode, +}; +use super::postgres::PostgresSession; +use super::runtime; +use sqlx::Row; + +pub struct PostgresObjectTree { + session: PostgresSession, +} + +impl PostgresObjectTree { + pub fn new(session: PostgresSession) -> Self { + Self { session } + } +} + +impl ObjectTreeProvider for PostgresObjectTree { + fn list_children(&self, parent_id: Option<&str>) -> ConnectionResult> { + match parent_id { + None => self.list_schemas(), + Some(pid) => match parse_object_id(pid)? { + ParsedObjectId::Schema { schema, .. } => self.list_relations(&schema), + ParsedObjectId::Relation { + kind, + schema, + name, + .. + } => self.list_columns_nodes(kind, &schema, &name), + ParsedObjectId::Column { .. } => Ok(vec![]), + }, + } + } + + fn describe(&self, object_id: &str) -> ConnectionResult { + match parse_object_id(object_id)? { + ParsedObjectId::Relation { schema, name, .. } => self.describe_relation(&schema, &name), + _ => Err(ConnectionError::invalid_config( + "describe expects table or view id", + )), + } + } +} + +impl PostgresObjectTree { + fn list_schemas(&self) -> ConnectionResult> { + self.session.with_pool(|pool| { + runtime::block_on(async { + let rows = sqlx::query( + "SELECT nspname + FROM pg_namespace + WHERE nspname NOT IN ('pg_catalog', 'information_schema', 'pg_toast') + AND nspname NOT LIKE 'pg\\_temp%' ESCAPE '\\' + AND nspname NOT LIKE 'pg\\_toast\\_temp%' ESCAPE '\\' + ORDER BY nspname", + ) + .fetch_all(pool) + .await + .map_err(|e| ConnectionError::driver(DriverKind::Postgres, e.to_string()))?; + + Ok(rows + .into_iter() + .map(|r| { + let name: String = r.get(0); + SqlObjectNode::new( + schema_id(DriverKind::Postgres, &name), + name, + SqlObjectKind::Schema, + None, + None, + ) + }) + .collect()) + }) + }) + } + + fn list_relations(&self, schema: &str) -> ConnectionResult> { + let schema_owned = schema.to_owned(); + self.session.with_pool(|pool| { + runtime::block_on(async { + let rows = sqlx::query( + "SELECT c.relname, + CASE c.relkind WHEN 'v' THEN 'view' WHEN 'm' THEN 'view' ELSE 'table' END + FROM pg_class c + JOIN pg_namespace n ON n.oid = c.relnamespace + WHERE n.nspname = $1 + AND c.relkind IN ('r', 'p', 'v', 'm') + AND NOT c.relispartition + ORDER BY c.relname", + ) + .bind(&schema_owned) + .fetch_all(pool) + .await + .map_err(|e| ConnectionError::driver(DriverKind::Postgres, e.to_string()))?; + + let parent = schema_id(DriverKind::Postgres, &schema_owned); + Ok(rows + .into_iter() + .map(|r| { + let name: String = r.get(0); + let kind_s: String = r.get(1); + let kind = if kind_s == "view" { + SqlObjectKind::View + } else { + SqlObjectKind::Table + }; + SqlObjectNode::new( + relation_id(DriverKind::Postgres, kind, &schema_owned, &name), + name, + kind, + Some(schema_owned.clone()), + Some(parent.clone()), + ) + }) + .collect()) + }) + }) + } + + fn list_columns_nodes( + &self, + kind: SqlObjectKind, + schema: &str, + table: &str, + ) -> ConnectionResult> { + let desc = self.describe_relation(schema, table)?; + let parent = relation_id(DriverKind::Postgres, kind, schema, table); + Ok(desc + .columns + .into_iter() + .map(|c| { + SqlObjectNode::new( + column_id(DriverKind::Postgres, schema, table, &c.name), + c.name, + SqlObjectKind::Column, + Some(schema.to_owned()), + Some(parent.clone()), + ) + }) + .collect()) + } + + fn describe_relation(&self, schema: &str, table: &str) -> ConnectionResult { + let schema = schema.to_owned(); + let table = table.to_owned(); + self.session.with_pool(|pool| { + runtime::block_on(async { + let rows = sqlx::query( + "SELECT a.attname, + pg_catalog.format_type(a.atttypid, a.atttypmod), + NOT a.attnotnull, + COALESCE( + (SELECT a2.attnum + FROM pg_index i + JOIN pg_attribute a2 + ON a2.attrelid = i.indrelid AND a2.attnum = ANY (i.indkey) + WHERE i.indrelid = c.oid AND i.indisprimary AND a2.attname = a.attname + LIMIT 1), + 0 + ) AS pk_pos, + pg_get_expr(ad.adbin, ad.adrelid) + FROM pg_attribute a + JOIN pg_class c ON c.oid = a.attrelid + JOIN pg_namespace n ON n.oid = c.relnamespace + LEFT JOIN pg_attrdef ad + ON ad.adrelid = a.attrelid AND ad.adnum = a.attnum + WHERE n.nspname = $1 + AND c.relname = $2 + AND a.attnum > 0 + AND NOT a.attisdropped + ORDER BY a.attnum", + ) + .bind(&schema) + .bind(&table) + .fetch_all(pool) + .await + .map_err(|e| ConnectionError::driver(DriverKind::Postgres, e.to_string()))?; + + if rows.is_empty() { + return Err(ConnectionError::driver( + DriverKind::Postgres, + format!("relation {schema}.{table} not found"), + )); + } + + let mut columns = Vec::with_capacity(rows.len()); + let mut primary_keys = Vec::new(); + for r in rows { + let name: String = r.get(0); + let data_type: String = r.get(1); + let is_nullable: bool = r.get(2); + let pk_pos: i32 = r.get(3); + let default_value: Option = r.get(4); + let is_primary_key = pk_pos > 0; + if is_primary_key { + primary_keys.push(name.clone()); + } + columns.push(ColumnMeta { + name, + data_type, + is_nullable, + is_primary_key, + primary_key_position: if is_primary_key { + Some(pk_pos) + } else { + None + }, + default_value, + }); + } + + Ok(TableSchema { + table_name: table, + schema: Some(schema), + columns, + primary_keys, + }) + }) + }) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::connection::manager::ConnectionSession; + use crate::connection::postgres::{open_postgres, PostgresConnectParams}; + + fn live_session() -> Option { + if std::env::var_os("QUERYA_SKIP_PG").is_some() { + return None; + } + open_postgres(PostgresConnectParams { + host: "127.0.0.1".into(), + port: 5432, + database: "querya".into(), + user: "querya".into(), + password: Some("querya".into()), + id: None, + }) + .ok() + } + + #[test] + fn live_postgres_tree_shop_schema() { + let Some(session) = live_session() else { + return; + }; + let tree = PostgresObjectTree::new(session.clone_handle()); + let schemas = tree.list_children(None).expect("schemas"); + assert!(schemas.iter().any(|s| s.name == "shop")); + let shop = schemas.iter().find(|s| s.name == "shop").unwrap(); + let rels = tree.list_children(Some(&shop.id)).expect("rels"); + assert!(rels.iter().any(|r| r.name == "customers")); + let customers = rels.iter().find(|r| r.name == "customers").unwrap(); + let cols = tree.list_children(Some(&customers.id)).expect("cols"); + assert!(cols.iter().any(|c| c.name == "id")); + let desc = tree.describe(&customers.id).expect("describe"); + assert!(desc.primary_keys.iter().any(|k| k == "id")); + session.disconnect().ok(); + } +} diff --git a/apps/tauri/src-tauri/src/lib.rs b/apps/tauri/src-tauri/src/lib.rs index a8107627..7b645cae 100644 --- a/apps/tauri/src-tauri/src/lib.rs +++ b/apps/tauri/src-tauri/src/lib.rs @@ -12,7 +12,8 @@ pub use profiles::{ConnectionProfile, ProfileStore, ProfileStoreError}; use commands::{ db_connect_postgres, db_connect_sqlite, db_describe_object, db_disconnect, db_execute_query, db_is_connected, db_list_children, db_list_columns, db_list_schemas, db_list_tables, - db_sqlite_overview, profiles_connect_sqlite, profiles_delete, profiles_list, profiles_upsert, + db_sqlite_overview, profiles_connect_postgres, profiles_connect_sqlite, profiles_delete, + profiles_list, profiles_upsert, }; #[tauri::command] @@ -68,6 +69,7 @@ pub fn run() { profiles_upsert, profiles_delete, profiles_connect_sqlite, + profiles_connect_postgres, ]) .run(tauri::generate_context!()) .expect("error while running tauri application"); diff --git a/apps/tauri/src-tauri/src/profiles/store.rs b/apps/tauri/src-tauri/src/profiles/store.rs index 563b3f8c..40f941a7 100644 --- a/apps/tauri/src-tauri/src/profiles/store.rs +++ b/apps/tauri/src-tauri/src/profiles/store.rs @@ -54,6 +54,30 @@ impl ConnectionProfile { } } + pub fn new_postgres( + name: impl Into, + host: impl Into, + port: u16, + database: impl Into, + user: impl Into, + ) -> Self { + let now = now_rfc3339(); + Self { + id: Uuid::new_v4().to_string(), + driver: "postgres".into(), + name: name.into(), + path: None, + host: Some(host.into()), + port: Some(i64::from(port)), + username: Some(user.into()), + database_name: Some(database.into()), + folder_id: None, + sort_order: 0, + created_at: now.clone(), + updated_at: now, + } + } + pub fn touch(&mut self) { self.updated_at = now_rfc3339(); } diff --git a/apps/tauri/src/App.vue b/apps/tauri/src/App.vue index 7ef6dcbe..de216dcb 100644 --- a/apps/tauri/src/App.vue +++ b/apps/tauri/src/App.vue @@ -26,6 +26,7 @@ import WelcomeTourDialog from "./ui/WelcomeTourDialog.vue"; import AboutDialog from "./ui/AboutDialog.vue"; import NewFolderDialog from "./ui/NewFolderDialog.vue"; import NewConnectionDialog, { + type PostgresConnectPayload, type SqliteConnectPayload, } from "./ui/NewConnectionDialog.vue"; @@ -81,6 +82,21 @@ async function onConnectSqliteFromDialog(payload: SqliteConnectPayload) { } } +async function onConnectPostgresFromDialog(payload: PostgresConnectPayload) { + try { + await connections.connectPostgres({ + name: payload.name, + host: payload.host, + port: payload.port, + database: payload.database, + user: payload.user, + password: payload.password, + }); + } catch { + // status already set in store + } +} + function onNewFolder() { newFolderOpen.value = true; } @@ -263,6 +279,7 @@ onUnmounted(() => { diff --git a/apps/tauri/src/api/connection.ts b/apps/tauri/src/api/connection.ts index 02568cb0..2955f5c6 100644 --- a/apps/tauri/src/api/connection.ts +++ b/apps/tauri/src/api/connection.ts @@ -114,6 +114,29 @@ export async function profilesConnectSqlite(opts: { }); } +/** Persist Postgres metadata (no password on disk) + open live session. */ +export async function profilesConnectPostgres(opts: { + name: string; + host: string; + port: number; + database: string; + user: string; + password?: string | null; + folderId?: string | null; + id?: string | null; +}): Promise { + return invoke("profiles_connect_postgres", { + name: opts.name, + host: opts.host, + port: opts.port, + database: opts.database, + user: opts.user, + password: opts.password ?? null, + folderId: opts.folderId ?? null, + id: opts.id ?? null, + }); +} + export async function dbDisconnect(id: string): Promise { await invoke("db_disconnect", { id }); } diff --git a/apps/tauri/src/stores/connections.ts b/apps/tauri/src/stores/connections.ts index f3af8c71..7bd92de3 100644 --- a/apps/tauri/src/stores/connections.ts +++ b/apps/tauri/src/stores/connections.ts @@ -3,6 +3,7 @@ import { reactive, ref } from "vue"; import { dbDisconnect, formatConnectionError, + profilesConnectPostgres, profilesConnectSqlite, profilesDelete, profilesList, @@ -16,43 +17,94 @@ import { useShellStatusStore } from "./shellStatus"; export type LiveConnection = { id: string; - driver: "sqlite"; + driver: "sqlite" | "postgres"; name: string; - path: string; + /** SQLite file path. */ + path?: string; + host?: string; + port?: number; + database?: string; + user?: string; /** Offline UI demo — no Rust session. */ mock?: boolean; /** Optional SERVERS folder id. */ folderId?: string | null; - /** Live rusqlite session open in the registry. */ + /** Live session open in the registry. */ connected?: boolean; }; +/** Session-only passwords — never written to ProfileStore (keyring: #1878). */ +const sessionPasswords = reactive(new Map()); + function fileName(path: string): string { const parts = path.split(/[/\\]/); return parts[parts.length - 1] || path; } +function endpointLabel(conn: LiveConnection): string { + if (conn.mock) return "Demo (offline)"; + if (conn.driver === "sqlite") return conn.path ?? ""; + const host = conn.host ?? "localhost"; + const port = conn.port ?? 5432; + const db = conn.database ?? ""; + return `${host}:${port}/${db}`; +} + function fromProfile(p: ConnectionProfile, connected = false): LiveConnection | null { - if (p.driver !== "sqlite") return null; - const path = p.path?.trim(); - if (!path) return null; - return { - id: p.id, - driver: "sqlite", - name: p.name, - path, - folderId: p.folder_id ?? null, - connected, - }; + if (p.driver === "sqlite") { + const path = p.path?.trim(); + if (!path) return null; + return { + id: p.id, + driver: "sqlite", + name: p.name, + path, + folderId: p.folder_id ?? null, + connected, + }; + } + if (p.driver === "postgres") { + const host = p.host?.trim(); + const database = p.database_name?.trim(); + const user = p.username?.trim(); + if (!host || !database || !user) return null; + return { + id: p.id, + driver: "postgres", + name: p.name, + host, + port: p.port != null ? Number(p.port) : 5432, + database, + user, + folderId: p.folder_id ?? null, + connected, + }; + } + return null; } function toProfile(conn: LiveConnection): ConnectionProfile { const now = String(Math.floor(Date.now() / 1000)); + if (conn.driver === "postgres") { + return { + id: conn.id, + driver: "postgres", + name: conn.name, + host: conn.host ?? null, + port: conn.port ?? 5432, + username: conn.user ?? null, + database_name: conn.database ?? null, + folder_id: conn.folderId ?? null, + sort_order: 0, + created_at: now, + updated_at: now, + }; + } return { id: conn.id, driver: "sqlite", name: conn.name, - path: conn.path, + path: conn.path ?? null, folder_id: conn.folderId ?? null, sort_order: 0, created_at: now, @@ -63,7 +115,6 @@ function toProfile(conn: LiveConnection): ConnectionProfile { /** Saved / live sessions shown in SERVERS (Flutter connections list). */ export const useConnectionsStore = defineStore("connections", () => { const items = ref([]); - /** Incremental index — not rebuilt on every upsert. */ const byId = reactive(new Map()); const hydrated = ref(false); @@ -77,12 +128,12 @@ export const useConnectionsStore = defineStore("connections", () => { function remove(id: string) { byId.delete(id); + sessionPasswords.delete(id); const list = items.value; const i = list.findIndex((c) => c.id === id); if (i >= 0) list.splice(i, 1); } - /** Load saved profiles into SERVERS (not connected until ensureConnected). */ async function hydrate() { if (hydrated.value) return; const status = useShellStatusStore(); @@ -107,7 +158,6 @@ export const useConnectionsStore = defineStore("connections", () => { } } - /** Flutter-style Demo — full UI without opening a real file. */ function launchDemo() { const nav = useShellNavStore(); const status = useShellStatusStore(); @@ -163,7 +213,65 @@ export const useConnectionsStore = defineStore("connections", () => { upsert(conn); nav.setExpanded(conn.id, true); nav.selectConnection(conn.id); - status.setConnection(conn.name, conn.path); + status.setConnection(conn.name, conn.path ?? path); + status.setQueryMetrics({ + busy: false, + message: `Connected · ${conn.name}`, + }); + return conn; + } catch (err) { + const msg = formatConnectionError(err); + status.setQueryMetrics({ busy: false, message: msg }); + throw err; + } + } + + async function connectPostgres(opts: { + name: string; + host: string; + port: number; + database: string; + user: string; + password?: string | null; + folderId?: string | null; + id?: string | null; + }) { + const status = useShellStatusStore(); + const nav = useShellNavStore(); + const name = + opts.name.trim() || + `${opts.user}@${opts.host}/${opts.database}`; + status.setQueryMetrics({ + busy: true, + message: `Connecting ${opts.host}:${opts.port}…`, + }); + try { + const profile = await profilesConnectPostgres({ + name, + host: opts.host, + port: opts.port, + database: opts.database, + user: opts.user, + password: opts.password ?? null, + folderId: opts.folderId ?? null, + id: opts.id ?? null, + }); + if (opts.password) sessionPasswords.set(profile.id, opts.password); + const conn: LiveConnection = { + id: profile.id, + driver: "postgres", + name: profile.name, + host: profile.host ?? opts.host, + port: profile.port != null ? Number(profile.port) : opts.port, + database: profile.database_name ?? opts.database, + user: profile.username ?? opts.user, + folderId: profile.folder_id ?? opts.folderId ?? null, + connected: true, + }; + upsert(conn); + nav.setExpanded(conn.id, true); + nav.selectConnection(conn.id); + status.setConnection(conn.name, endpointLabel(conn)); status.setQueryMetrics({ busy: false, message: `Connected · ${conn.name}`, @@ -176,13 +284,34 @@ export const useConnectionsStore = defineStore("connections", () => { } } - /** Open live session for a saved (or already listed) profile. */ async function ensureConnected(id: string) { const conn = byId.get(id); if (!conn || conn.mock) return conn ?? null; if (conn.connected) return conn; - return connectSqlite(conn.path, { + if (conn.driver === "sqlite") { + return connectSqlite(conn.path ?? "", { + name: conn.name, + folderId: conn.folderId, + id: conn.id, + }); + } + const password = sessionPasswords.get(id) ?? null; + if (!password) { + const status = useShellStatusStore(); + status.setQueryMetrics({ + message: + "Postgres password not in session — reconnect via New Connection (keyring later)", + busy: false, + }); + throw new Error("postgres password required"); + } + return connectPostgres({ name: conn.name, + host: conn.host ?? "localhost", + port: conn.port ?? 5432, + database: conn.database ?? "postgres", + user: conn.user ?? "postgres", + password, folderId: conn.folderId, id: conn.id, }); @@ -202,7 +331,7 @@ export const useConnectionsStore = defineStore("connections", () => { remove(id); } if (nav.selectedConnectionId === id) { - status.setConnection(conn?.name ?? null, conn?.path ?? null); + status.setConnection(conn?.name ?? null, conn ? endpointLabel(conn) : null); status.setQueryMetrics({ message: conn ? `Disconnected · ${conn.name}` : "No connection", busy: false, @@ -211,7 +340,6 @@ export const useConnectionsStore = defineStore("connections", () => { } } - /** Remove from SERVERS + LocalDb (Flutter "Remove connection"). */ async function removeConnection(id: string) { const status = useShellStatusStore(); const nav = useShellNavStore(); @@ -233,7 +361,10 @@ export const useConnectionsStore = defineStore("connections", () => { const next = items.value[0] ?? null; if (next) nav.selectConnection(next.id); else nav.reset(); - status.setConnection(next?.name ?? null, next?.path ?? null); + status.setConnection( + next?.name ?? null, + next ? endpointLabel(next) : null, + ); status.setQueryMetrics({ message: next ? `Connected · ${next.name}` : "No connection", busy: false, @@ -251,11 +382,14 @@ export const useConnectionsStore = defineStore("connections", () => { try { conn = (await ensureConnected(id)) ?? conn; } catch { + // Still select so Overview/SQL are reachable; PG may need re-auth. + nav.selectConnection(id); + status.setConnection(conn.name, endpointLabel(conn)); return; } } nav.selectConnection(id); - status.setConnection(conn.name, conn.mock ? "Demo (offline)" : conn.path); + status.setConnection(conn.name, endpointLabel(conn)); status.setQueryMetrics({ message: conn.mock ? "Demo catalog · UI core (no live DB)" @@ -281,7 +415,6 @@ export const useConnectionsStore = defineStore("connections", () => { } } - /** Detach all connections from a folder (Flutter: folder delete keeps connections). */ function detachFolder(folderId: string) { for (const c of items.value) { if (c.folderId === folderId) { @@ -298,6 +431,7 @@ export const useConnectionsStore = defineStore("connections", () => { hydrate, launchDemo, connectSqlite, + connectPostgres, ensureConnected, disconnect, removeConnection, diff --git a/apps/tauri/src/ui/ConnectionHome.vue b/apps/tauri/src/ui/ConnectionHome.vue index 8f01872a..b32cb4a1 100644 --- a/apps/tauri/src/ui/ConnectionHome.vue +++ b/apps/tauri/src/ui/ConnectionHome.vue @@ -63,6 +63,12 @@ const pagesLabel = computed(() => { async function loadOverview() { const c = conn.value; if (!c) return; + if (c.driver !== "sqlite") { + overview.value = null; + error.value = null; + loading.value = false; + return; + } if (c.mock) { overview.value = { version: "demo", @@ -88,6 +94,21 @@ async function loadOverview() { } } +const isSqlite = computed(() => conn.value?.driver === "sqlite"); +const isPostgres = computed(() => conn.value?.driver === "postgres"); +const driverLabel = computed(() => { + const d = conn.value?.driver; + if (d === "sqlite") return "SQLite"; + if (d === "postgres") return "PostgreSQL"; + return d ?? ""; +}); +const endpointLabel = computed(() => { + const c = conn.value; + if (!c) return ""; + if (c.driver === "sqlite") return c.path ?? ""; + return `${c.host ?? "localhost"}:${c.port ?? 5432}/${c.database ?? ""}`; +}); + watch( selectedConnectionId, () => { @@ -146,14 +167,13 @@ function openRelation(o: { id: string; name: string; kind: string; schema?: stri

{{ conn.name }}

- {{ - conn.driver === "sqlite" ? "SQLite" : conn.driver - }} + {{ driverLabel }} demo
-

{{ conn.path }}

+

{{ endpointLabel }}

-

Loading database overview…

+ + +

+ Loading database overview… +

{{ error }}

-
+
diff --git a/apps/tauri/src/ui/ConnectionsPanel.vue b/apps/tauri/src/ui/ConnectionsPanel.vue index fd2ce39a..4b25b60f 100644 --- a/apps/tauri/src/ui/ConnectionsPanel.vue +++ b/apps/tauri/src/ui/ConnectionsPanel.vue @@ -46,10 +46,13 @@ const ctx = ref<{ open: boolean; x: number; y: number; target: CtxTarget }>({ const filteredConnections = computed(() => { const q = filter.value.trim().toLowerCase(); if (!q) return items.value; - return items.value.filter( - (c) => - c.name.toLowerCase().includes(q) || c.path.toLowerCase().includes(q), - ); + return items.value.filter((c) => { + if (c.name.toLowerCase().includes(q)) return true; + if (c.path?.toLowerCase().includes(q)) return true; + if (c.host?.toLowerCase().includes(q)) return true; + if (c.database?.toLowerCase().includes(q)) return true; + return false; + }); }); const rootConnections = computed(() => @@ -87,6 +90,9 @@ const ctxItems = computed(() => { })), ]; return [ + nav.isExpanded(t.connectionId) + ? { id: "collapse", label: "Collapse" } + : { id: "expand", label: "Expand" }, { id: "disconnect", label: "Disconnect" }, { id: "remove", label: "Remove connection" }, { @@ -140,8 +146,9 @@ function onConnClick(id: string) { function onConnExpand(id: string, e: MouseEvent) { e.stopPropagation(); + const willExpand = !nav.isExpanded(id); nav.toggleExpanded(id); - void tree.ensureLoaded(id); + if (willExpand) void tree.ensureLoaded(id); } function onFolderExpand(id: string, e: MouseEvent) { @@ -186,8 +193,14 @@ function onCtxSelect(id: string) { else if (id === "remove-folder" && t.type === "folder") { connections.detachFolder(t.folderId); foldersStore.remove(t.folderId); + } else if (id === "expand" && t.type === "connection") { + nav.setExpanded(t.connectionId, true); + void tree.ensureLoaded(t.connectionId); + } else if (id === "collapse" && t.type === "connection") { + nav.setExpanded(t.connectionId, false); } else if (id === "disconnect" && t.type === "connection") { void connections.disconnect(t.connectionId); + nav.setExpanded(t.connectionId, false); tree.drop(t.connectionId); } else if (id === "remove" && t.type === "connection") { void connections.removeConnection(t.connectionId); @@ -209,6 +222,7 @@ function filteredRootsFor(connId: string) { function driverGlyph(c: LiveConnection): string { if (c.mock) return "◈"; + if (c.driver === "postgres") return "◇"; return "▤"; } @@ -295,7 +309,11 @@ onUnmounted(() => { type="button" class="chev" :aria-expanded="nav.isExpanded(c.id)" - :aria-label="`Expand ${c.name}`" + :aria-label=" + nav.isExpanded(c.id) + ? `Collapse ${c.name}` + : `Expand ${c.name}` + " @click="onConnExpand(c.id, $event)" > {{ nav.isExpanded(c.id) ? "▾" : "▸" }} @@ -304,6 +322,7 @@ onUnmounted(() => { type="button" class="conn-main" @click="onConnClick(c.id)" + @dblclick="onConnExpand(c.id, $event)" > -
{ type="button" class="chev" :aria-expanded="nav.isExpanded(c.id)" - :aria-label="`Expand ${c.name}`" + :aria-label=" + nav.isExpanded(c.id) + ? `Collapse ${c.name}` + : `Expand ${c.name}` + " @click="onConnExpand(c.id, $event)" > {{ nav.isExpanded(c.id) ? "▾" : "▸" }} @@ -404,6 +416,7 @@ onUnmounted(() => { type="button" class="conn-main" @click="onConnClick(c.id)" + @dblclick="onConnExpand(c.id, $event)" > -
{ font-family: var(--q-font-mono); } -.conn-x, .refresh { appearance: none; border: 0; @@ -678,7 +679,6 @@ onUnmounted(() => { cursor: pointer; } -.conn-x:hover, .refresh:hover { background: var(--q-accent); color: var(--q-foreground); diff --git a/apps/tauri/src/ui/NewConnectionDialog.vue b/apps/tauri/src/ui/NewConnectionDialog.vue index 9531d957..40cb2c7c 100644 --- a/apps/tauri/src/ui/NewConnectionDialog.vue +++ b/apps/tauri/src/ui/NewConnectionDialog.vue @@ -18,6 +18,16 @@ export type SqliteConnectPayload = { path: string; }; +export type PostgresConnectPayload = { + driver: "postgresql"; + name: string; + host: string; + port: number; + database: string; + user: string; + password: string; +}; + type Category = "all" | "sql" | "nosql"; type DriverChoice = { @@ -71,13 +81,14 @@ const CATEGORY_ITEMS: { id: Category; label: string }[] = [ const open = defineModel("open", { required: true }); const emit = defineEmits<{ connectSqlite: [payload: SqliteConnectPayload]; + connectPostgres: [payload: PostgresConnectPayload]; }>(); function dismiss() { open.value = false; } -type Step = "pick" | "sqlite" | "stub"; +type Step = "pick" | "sqlite" | "postgres" | "stub"; const step = ref("pick"); const category = ref("all"); @@ -89,6 +100,11 @@ const nameEl = ref(null); const name = ref(""); const path = ref(""); const readOnly = ref(false); +const host = ref("localhost"); +const port = ref("5432"); +const database = ref("querya"); +const user = ref("querya"); +const password = ref("querya"); const error = ref(null); const stubDriver = ref(null); @@ -115,6 +131,19 @@ const canSaveSqlite = computed( () => name.value.trim().length > 0 && path.value.trim().length > 0, ); +const canSavePostgres = computed(() => { + const p = Number(port.value); + return ( + name.value.trim().length > 0 && + host.value.trim().length > 0 && + database.value.trim().length > 0 && + user.value.trim().length > 0 && + Number.isFinite(p) && + p > 0 && + p <= 65535 + ); +}); + function reset() { step.value = "pick"; category.value = "all"; @@ -123,6 +152,11 @@ function reset() { name.value = ""; path.value = ""; readOnly.value = false; + host.value = "localhost"; + port.value = "5432"; + database.value = "querya"; + user.value = "querya"; + password.value = "querya"; error.value = null; stubDriver.value = null; } @@ -164,6 +198,12 @@ function goNext() { void nextTick(() => nameEl.value?.focus()); return; } + if (choice.id === "postgresql") { + step.value = "postgres"; + if (!name.value.trim()) name.value = "querya"; + void nextTick(() => nameEl.value?.focus()); + return; + } stubDriver.value = choice; step.value = "stub"; } @@ -214,6 +254,33 @@ function submitSqlite() { emit("connectSqlite", { driver: "sqlite", name: n, path: p }); } +function submitPostgres() { + error.value = null; + const n = name.value.trim(); + const h = host.value.trim(); + const db = database.value.trim(); + const u = user.value.trim(); + const p = Number(port.value); + if (!n) { + error.value = "Connection name is required."; + return; + } + if (!h || !db || !u || !Number.isFinite(p) || p <= 0) { + error.value = "Host, port, database, and user are required."; + return; + } + dismiss(); + emit("connectPostgres", { + driver: "postgresql", + name: n, + host: h, + port: p, + database: db, + user: u, + password: password.value, + }); +} + function onKey(e: KeyboardEvent) { if (!open.value) return; if (e.key === "Escape") { @@ -224,6 +291,8 @@ function onKey(e: KeyboardEvent) { e.preventDefault(); if (step.value === "pick" && canNext.value) goNext(); else if (step.value === "sqlite" && canSaveSqlite.value) submitSqlite(); + else if (step.value === "postgres" && canSavePostgres.value) + submitPostgres(); } } @@ -426,7 +495,81 @@ onUnmounted(() => window.removeEventListener("keydown", onKey, true));
- + + + +
`"${s.replace(/"/g, '""')}"`; + const sql = + c.driver === "postgres" && obj.schema + ? `SELECT * FROM ${ident(obj.schema)}.${ident(obj.name)} LIMIT 200` + : `SELECT * FROM ${ident(obj.name)} LIMIT 200`; await dbExecuteQuery(c.id, sql, (ev) => query.feedEvent(ev)); status.setQueryMetrics({ message: `${query.rowCount} rows · ${query.columns.length} cols`,