diff --git a/apps/tauri/src-tauri/src/commands.rs b/apps/tauri/src-tauri/src/commands.rs index 3e9b4a1d..c4847246 100644 --- a/apps/tauri/src-tauri/src/commands.rs +++ b/apps/tauri/src-tauri/src/commands.rs @@ -1,6 +1,6 @@ use crate::connection::{ ConnectionConfig, ConnectionError, ConnectionId, ConnectionManager, ConnectionRegistry, - SchemaObject, TableSchema, + SchemaObject, SchemaObjectKind, SqlObjectKind, SqlObjectNode, TableSchema, }; use tauri::ipc::Channel; use tauri::State; @@ -26,22 +26,69 @@ pub fn db_is_connected(id: ConnectionId, registry: State<'_, ConnectionRegistry> registry.is_connected(&id) } +/// Universal object tree: `parent_id = null` → schemas; schema → relations; table/view → columns. +#[tauri::command] +pub fn db_list_children( + id: ConnectionId, + parent_id: Option, + registry: State<'_, ConnectionRegistry>, +) -> Result, ConnectionError> { + registry.list_children(&id, parent_id.as_deref()) +} + +/// Describe a table/view by stable object id (`sqlite:table:main:users`). +#[tauri::command] +pub fn db_describe_object( + id: ConnectionId, + object_id: String, + registry: State<'_, ConnectionRegistry>, +) -> Result { + registry.describe_object(&id, &object_id) +} + +/// Shim: schema names via object tree roots. #[tauri::command] pub fn db_list_schemas( id: ConnectionId, registry: State<'_, ConnectionRegistry>, ) -> Result, ConnectionError> { - registry.with_sqlite(&id, |s| s.list_schemas()) + Ok(registry + .list_children(&id, None)? + .into_iter() + .map(|n| n.name) + .collect()) } +/// Shim: flat tables/views under `main` (legacy callers). #[tauri::command] pub fn db_list_tables( id: ConnectionId, registry: State<'_, ConnectionRegistry>, ) -> Result, ConnectionError> { - registry.with_sqlite(&id, |s| s.list_tables()) + let main = registry + .list_children(&id, None)? + .into_iter() + .find(|n| n.name == "main") + .ok_or_else(|| ConnectionError::invalid_config("sqlite schema main missing"))?; + Ok(registry + .list_children(&id, Some(&main.id))? + .into_iter() + .filter_map(|n| { + let kind = match n.kind { + SqlObjectKind::Table => SchemaObjectKind::Table, + SqlObjectKind::View => SchemaObjectKind::View, + _ => return None, + }; + Some(SchemaObject { + name: n.name, + kind, + schema: n.schema, + }) + }) + .collect()) } +/// Shim: columns by table/view name (legacy callers). #[tauri::command] pub fn db_list_columns( id: ConnectionId, diff --git a/apps/tauri/src-tauri/src/connection/manager.rs b/apps/tauri/src-tauri/src/connection/manager.rs index 663f0596..d082fc24 100644 --- a/apps/tauri/src-tauri/src/connection/manager.rs +++ b/apps/tauri/src-tauri/src/connection/manager.rs @@ -144,6 +144,44 @@ impl ConnectionRegistry { ) -> ConnectionResult<()> { self.with_sqlite(id, |s| s.execute_streaming(sql, limit, emit)) } + + /// Driver-agnostic object tree for a live connection (SQLite first). + pub fn object_tree( + &self, + id: &ConnectionId, + ) -> ConnectionResult> { + let session = self.session_arc(id)?; + match session.driver() { + DriverKind::Sqlite => { + let sqlite = session + .as_any() + .downcast_ref::() + .ok_or(ConnectionError::UnsupportedDriver { + driver: DriverKind::Sqlite, + })?; + Ok(Arc::new(super::sqlite_object_tree::SqliteObjectTree::new( + sqlite.clone_handle(), + ))) + } + other => Err(ConnectionError::UnsupportedDriver { driver: other }), + } + } + + pub fn list_children( + &self, + id: &ConnectionId, + parent_id: Option<&str>, + ) -> ConnectionResult> { + self.object_tree(id)?.list_children(parent_id) + } + + pub fn describe_object( + &self, + id: &ConnectionId, + object_id: &str, + ) -> ConnectionResult { + self.object_tree(id)?.describe(object_id) + } } impl ConnectionManager for ConnectionRegistry { diff --git a/apps/tauri/src-tauri/src/connection/mod.rs b/apps/tauri/src-tauri/src/connection/mod.rs index a345cd87..2cd49f37 100644 --- a/apps/tauri/src-tauri/src/connection/mod.rs +++ b/apps/tauri/src-tauri/src/connection/mod.rs @@ -4,14 +4,17 @@ mod error; mod id; mod introspect; mod manager; +mod object_tree; mod query; mod smoke_slice; mod sqlite; mod sqlite_introspect; +mod sqlite_object_tree; pub(crate) mod sqlite_query; pub use error::ConnectionError; pub use id::{ConnectionId, DriverKind}; pub use introspect::{ColumnMeta, SchemaObject, SchemaObjectKind, TableSchema}; pub use manager::{ConnectionConfig, ConnectionManager, ConnectionRegistry}; +pub use object_tree::{ObjectTreeProvider, SqlObjectKind, SqlObjectNode}; pub use query::QueryEvent; diff --git a/apps/tauri/src-tauri/src/connection/object_tree.rs b/apps/tauri/src-tauri/src/connection/object_tree.rs new file mode 100644 index 00000000..4f1b768d --- /dev/null +++ b/apps/tauri/src-tauri/src/connection/object_tree.rs @@ -0,0 +1,256 @@ +//! Driver-agnostic SQL object tree (schemas → tables/views → columns). + +use super::error::{ConnectionError, ConnectionResult}; +use super::id::DriverKind; +use super::introspect::TableSchema; +use serde::{Deserialize, Serialize}; + +/// Catalog node kinds. Extra variants reserved for later driver epics. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum SqlObjectKind { + Schema, + Table, + View, + Column, + Index, + Trigger, + Function, + Procedure, +} + +impl SqlObjectKind { + pub fn as_str(self) -> &'static str { + match self { + Self::Schema => "schema", + Self::Table => "table", + Self::View => "view", + Self::Column => "column", + Self::Index => "index", + Self::Trigger => "trigger", + Self::Function => "function", + Self::Procedure => "procedure", + } + } + + fn parse(s: &str) -> Option { + match s { + "schema" => Some(Self::Schema), + "table" => Some(Self::Table), + "view" => Some(Self::View), + "column" => Some(Self::Column), + "index" => Some(Self::Index), + "trigger" => Some(Self::Trigger), + "function" => Some(Self::Function), + "procedure" => Some(Self::Procedure), + _ => None, + } + } + + pub fn is_expandable(self) -> bool { + matches!( + self, + Self::Schema | Self::Table | Self::View | Self::Index | Self::Function | Self::Procedure + ) + } + + pub fn is_relation(self) -> bool { + matches!(self, Self::Table | Self::View) + } +} + +/// Stable tree node shared across IPC and UI. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub struct SqlObjectNode { + /// Durable id, e.g. `sqlite:table:main:users`. + pub id: String, + pub name: String, + pub kind: SqlObjectKind, + #[serde(skip_serializing_if = "Option::is_none")] + pub schema: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub parent_id: Option, + pub expandable: bool, +} + +impl SqlObjectNode { + pub fn new( + id: String, + name: String, + kind: SqlObjectKind, + schema: Option, + parent_id: Option, + ) -> Self { + Self { + id, + name, + kind, + schema, + parent_id, + expandable: kind.is_expandable(), + } + } +} + +/// Per-connection object tree. Drivers implement; registry returns Arc. +pub trait ObjectTreeProvider: Send + Sync { + fn list_children(&self, parent_id: Option<&str>) -> ConnectionResult>; + fn describe(&self, object_id: &str) -> ConnectionResult; +} + +/// Encode a path segment so `:` / `%` in names do not break ids. +pub fn enc_segment(s: &str) -> String { + s.replace('%', "%25").replace(':', "%3A") +} + +pub fn dec_segment(s: &str) -> String { + let mut out = String::with_capacity(s.len()); + let bytes = s.as_bytes(); + let mut i = 0; + while i < bytes.len() { + if bytes[i] == b'%' && i + 2 < bytes.len() { + let hex = &s[i + 1..i + 3]; + if let Ok(v) = u8::from_str_radix(hex, 16) { + out.push(v as char); + i += 3; + continue; + } + } + out.push(bytes[i] as char); + i += 1; + } + out +} + +pub fn schema_id(driver: DriverKind, schema: &str) -> String { + format!("{}:schema:{}", driver.as_str(), enc_segment(schema)) +} + +pub fn relation_id(driver: DriverKind, kind: SqlObjectKind, schema: &str, name: &str) -> String { + debug_assert!(kind.is_relation()); + format!( + "{}:{}:{}:{}", + driver.as_str(), + kind.as_str(), + enc_segment(schema), + enc_segment(name) + ) +} + +pub fn column_id(driver: DriverKind, schema: &str, table: &str, column: &str) -> String { + format!( + "{}:column:{}:{}:{}", + driver.as_str(), + enc_segment(schema), + enc_segment(table), + enc_segment(column) + ) +} + +/// Parsed object id. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum ParsedObjectId { + Schema { + driver: DriverKind, + schema: String, + }, + Relation { + driver: DriverKind, + kind: SqlObjectKind, + schema: String, + name: String, + }, + Column { + driver: DriverKind, + schema: String, + table: String, + column: String, + }, +} + +fn bad_id(msg: impl Into) -> ConnectionError { + ConnectionError::invalid_config(msg) +} + +pub fn parse_object_id(id: &str) -> ConnectionResult { + let parts: Vec<&str> = id.split(':').collect(); + if parts.len() < 3 { + return Err(bad_id(format!("invalid object id: {id}"))); + } + let driver = match parts[0] { + "sqlite" => DriverKind::Sqlite, + "postgres" => DriverKind::Postgres, + "mysql" => DriverKind::Mysql, + other => return Err(bad_id(format!("unknown driver in object id: {other}"))), + }; + let kind = SqlObjectKind::parse(parts[1]) + .ok_or_else(|| bad_id(format!("unknown object kind in id: {id}")))?; + + match kind { + SqlObjectKind::Schema if parts.len() == 3 => Ok(ParsedObjectId::Schema { + driver, + schema: dec_segment(parts[2]), + }), + SqlObjectKind::Table | SqlObjectKind::View if parts.len() == 4 => { + Ok(ParsedObjectId::Relation { + driver, + kind, + schema: dec_segment(parts[2]), + name: dec_segment(parts[3]), + }) + } + SqlObjectKind::Column if parts.len() == 5 => Ok(ParsedObjectId::Column { + driver, + schema: dec_segment(parts[2]), + table: dec_segment(parts[3]), + column: dec_segment(parts[4]), + }), + SqlObjectKind::Schema => Err(bad_id(format!("invalid schema id: {id}"))), + SqlObjectKind::Table | SqlObjectKind::View => { + Err(bad_id(format!("invalid relation id: {id}"))) + } + SqlObjectKind::Column => Err(bad_id(format!("invalid column id: {id}"))), + other => Err(bad_id(format!( + "object kind {:?} not supported in ids yet", + other + ))), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn round_trip_ids_with_colon_in_name() { + let id = relation_id(DriverKind::Sqlite, SqlObjectKind::Table, "main", "a:b"); + assert_eq!(id, "sqlite:table:main:a%3Ab"); + match parse_object_id(&id).unwrap() { + ParsedObjectId::Relation { name, schema, .. } => { + assert_eq!(schema, "main"); + assert_eq!(name, "a:b"); + } + other => panic!("unexpected {other:?}"), + } + } + + #[test] + fn column_id_round_trip() { + let id = column_id(DriverKind::Sqlite, "main", "users", "id"); + assert_eq!(id, "sqlite:column:main:users:id"); + match parse_object_id(&id).unwrap() { + ParsedObjectId::Column { + schema, + table, + column, + .. + } => { + assert_eq!(schema, "main"); + assert_eq!(table, "users"); + assert_eq!(column, "id"); + } + other => panic!("unexpected {other:?}"), + } + } +} diff --git a/apps/tauri/src-tauri/src/connection/sqlite.rs b/apps/tauri/src-tauri/src/connection/sqlite.rs index 7c87f8bc..6d84b43b 100644 --- a/apps/tauri/src-tauri/src/connection/sqlite.rs +++ b/apps/tauri/src-tauri/src/connection/sqlite.rs @@ -21,6 +21,15 @@ impl SqliteSession { &self.path } + /// Clone the session handle (shared connection Arc) for providers outside the registry lock. + pub fn clone_handle(&self) -> Self { + Self { + id: self.id.clone(), + path: self.path.clone(), + conn: Arc::clone(&self.conn), + } + } + pub fn with_connection( &self, f: impl FnOnce(&Connection) -> ConnectionResult, diff --git a/apps/tauri/src-tauri/src/connection/sqlite_object_tree.rs b/apps/tauri/src-tauri/src/connection/sqlite_object_tree.rs new file mode 100644 index 00000000..4f5ef907 --- /dev/null +++ b/apps/tauri/src-tauri/src/connection/sqlite_object_tree.rs @@ -0,0 +1,178 @@ +//! SQLite [`ObjectTreeProvider`] — schemas → tables/views → columns. + +use super::error::{ConnectionError, ConnectionResult}; +use super::id::DriverKind; +use super::introspect::{SchemaObjectKind, TableSchema}; +use super::object_tree::{ + column_id, parse_object_id, relation_id, schema_id, ObjectTreeProvider, ParsedObjectId, + SqlObjectKind, SqlObjectNode, +}; +use super::sqlite::SqliteSession; + +const DRIVER: DriverKind = DriverKind::Sqlite; + +/// Object tree backed by a cloned [`SqliteSession`] handle (registry lock already released). +pub struct SqliteObjectTree { + session: SqliteSession, +} + +impl SqliteObjectTree { + pub fn new(session: SqliteSession) -> Self { + Self { session } + } +} + +impl ObjectTreeProvider for SqliteObjectTree { + fn list_children(&self, parent_id: Option<&str>) -> ConnectionResult> { + match parent_id { + None => self.list_schemas(), + Some(id) => match parse_object_id(id)? { + ParsedObjectId::Schema { schema, .. } => self.list_relations(&schema, id), + ParsedObjectId::Relation { schema, name, .. } => { + self.list_columns(&schema, &name, id) + } + ParsedObjectId::Column { .. } => Ok(vec![]), + }, + } + } + + fn describe(&self, object_id: &str) -> ConnectionResult { + match parse_object_id(object_id)? { + ParsedObjectId::Relation { name, .. } => self.session.list_columns(&name), + ParsedObjectId::Schema { .. } | ParsedObjectId::Column { .. } => Err( + ConnectionError::invalid_config("describe requires a table or view id"), + ), + } + } +} + +impl SqliteObjectTree { + fn list_schemas(&self) -> ConnectionResult> { + Ok(self + .session + .list_schemas()? + .into_iter() + .map(|name| { + SqlObjectNode::new( + schema_id(DRIVER, &name), + name.clone(), + SqlObjectKind::Schema, + Some(name), + None, + ) + }) + .collect()) + } + + fn list_relations( + &self, + schema: &str, + parent_id: &str, + ) -> ConnectionResult> { + // SQLite only exposes `main` for now; attached DBs later. + if schema != "main" { + return Ok(vec![]); + } + Ok(self + .session + .list_tables()? + .into_iter() + .map(|o| { + let kind = match o.kind { + SchemaObjectKind::View => SqlObjectKind::View, + SchemaObjectKind::Table => SqlObjectKind::Table, + }; + let schema_name = o.schema.unwrap_or_else(|| "main".into()); + SqlObjectNode::new( + relation_id(DRIVER, kind, &schema_name, &o.name), + o.name, + kind, + Some(schema_name), + Some(parent_id.to_owned()), + ) + }) + .collect()) + } + + fn list_columns( + &self, + schema: &str, + table: &str, + parent_id: &str, + ) -> ConnectionResult> { + Ok(self + .session + .list_columns(table)? + .columns + .into_iter() + .map(|c| { + SqlObjectNode::new( + column_id(DRIVER, schema, table, &c.name), + c.name, + SqlObjectKind::Column, + Some(schema.to_owned()), + Some(parent_id.to_owned()), + ) + }) + .collect()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::connection::manager::{ConnectionConfig, ConnectionManager, ConnectionRegistry}; + use rusqlite::Connection; + use std::time::{SystemTime, UNIX_EPOCH}; + + fn temp_db() -> std::path::PathBuf { + let nanos = SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap() + .as_nanos(); + std::env::temp_dir().join(format!("querya_obj_tree_{nanos}.db")) + } + + #[test] + fn sqlite_tree_schema_table_column() { + let path = temp_db(); + { + let conn = Connection::open(&path).unwrap(); + conn.execute_batch( + "CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT); + CREATE VIEW v_users AS SELECT id FROM users;", + ) + .unwrap(); + } + let reg = ConnectionRegistry::with_builtin_drivers(); + let id = reg + .connect(ConnectionConfig::Sqlite { + path: path.to_string_lossy().into(), + }) + .unwrap(); + + let schemas = reg.list_children(&id, None).unwrap(); + assert_eq!(schemas.len(), 1); + assert_eq!(schemas[0].kind, SqlObjectKind::Schema); + assert_eq!(schemas[0].id, "sqlite:schema:main"); + + let relations = reg.list_children(&id, Some(&schemas[0].id)).unwrap(); + assert_eq!(relations.len(), 2); + assert!(relations.iter().any(|n| n.id == "sqlite:table:main:users")); + assert!(relations.iter().any(|n| n.id == "sqlite:view:main:v_users")); + + let users = relations + .iter() + .find(|n| n.name == "users") + .expect("users"); + let cols = reg.list_children(&id, Some(&users.id)).unwrap(); + assert_eq!(cols.len(), 2); + assert_eq!(cols[0].id, "sqlite:column:main:users:id"); + + let schema = reg.describe_object(&id, &users.id).unwrap(); + assert_eq!(schema.primary_keys, vec!["id".to_string()]); + + reg.disconnect(&id).unwrap(); + let _ = std::fs::remove_file(&path); + } +} diff --git a/apps/tauri/src-tauri/src/lib.rs b/apps/tauri/src-tauri/src/lib.rs index 5f785d32..381317d9 100644 --- a/apps/tauri/src-tauri/src/lib.rs +++ b/apps/tauri/src-tauri/src/lib.rs @@ -3,12 +3,13 @@ mod connection; pub use connection::{ ColumnMeta, ConnectionConfig, ConnectionError, ConnectionId, ConnectionManager, - ConnectionRegistry, DriverKind, QueryEvent, SchemaObject, SchemaObjectKind, TableSchema, + ConnectionRegistry, DriverKind, ObjectTreeProvider, QueryEvent, SchemaObject, SchemaObjectKind, + SqlObjectKind, SqlObjectNode, TableSchema, }; use commands::{ - db_connect_sqlite, db_disconnect, db_execute_query, db_is_connected, db_list_columns, - db_list_schemas, db_list_tables, + 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, }; #[tauri::command] @@ -47,6 +48,8 @@ pub fn run() { db_list_schemas, db_list_tables, db_list_columns, + db_list_children, + db_describe_object, db_execute_query, ]) .run(tauri::generate_context!()) diff --git a/apps/tauri/src/api/connection.ts b/apps/tauri/src/api/connection.ts index 35f71156..3e829800 100644 --- a/apps/tauri/src/api/connection.ts +++ b/apps/tauri/src/api/connection.ts @@ -8,6 +8,26 @@ export type SchemaObject = { schema?: string | null; }; +export type SqlObjectKind = + | "schema" + | "table" + | "view" + | "column" + | "index" + | "trigger" + | "function" + | "procedure"; + +/** Stable tree node from `db_list_children`. */ +export type SqlObjectNode = { + id: string; + name: string; + kind: SqlObjectKind; + schema?: string | null; + parent_id?: string | null; + expandable: boolean; +}; + export type ColumnMeta = { name: string; data_type: string; @@ -36,6 +56,23 @@ export async function dbIsConnected(id: string): Promise { return invoke("db_is_connected", { id }); } +export async function dbListChildren( + id: string, + parentId?: string | null, +): Promise { + return invoke("db_list_children", { + id, + parentId: parentId ?? null, + }); +} + +export async function dbDescribeObject( + id: string, + objectId: string, +): Promise { + return invoke("db_describe_object", { id, objectId }); +} + export async function dbListSchemas(id: string): Promise { return invoke("db_list_schemas", { id }); } diff --git a/apps/tauri/src/mock/demoCatalog.ts b/apps/tauri/src/mock/demoCatalog.ts index a2508032..63f78be9 100644 --- a/apps/tauri/src/mock/demoCatalog.ts +++ b/apps/tauri/src/mock/demoCatalog.ts @@ -1,5 +1,7 @@ /** Offline demo catalog for UI-core review (no live DB). */ +import type { SqlObjectNode } from "../api/connection"; + export type DemoColumn = { name: string; data_type: string; @@ -99,3 +101,45 @@ export const DEMO_CONNECTION: DemoConnection = { export function findDemoObject(name: string): DemoObject | undefined { return DEMO_CONNECTION.objects.find((o) => o.name === name); } + +const MAIN_SCHEMA_ID = "sqlite:schema:main"; + +/** Root schemas for the demo object tree (same shape as live IPC). */ +export function demoRootNodes(): SqlObjectNode[] { + return [ + { + id: MAIN_SCHEMA_ID, + name: "main", + kind: "schema", + schema: "main", + parent_id: null, + expandable: true, + }, + ]; +} + +export function demoListChildren(parentId: string | null): SqlObjectNode[] { + if (parentId == null) return demoRootNodes(); + if (parentId === MAIN_SCHEMA_ID) { + return DEMO_CONNECTION.objects.map((o) => ({ + id: `sqlite:${o.kind}:main:${o.name}`, + name: o.name, + kind: o.kind, + schema: "main", + parent_id: parentId, + expandable: true, + })); + } + const relation = DEMO_CONNECTION.objects.find( + (o) => parentId === `sqlite:${o.kind}:main:${o.name}`, + ); + if (!relation) return []; + return relation.columns.map((c) => ({ + id: `sqlite:column:main:${relation.name}:${c.name}`, + name: c.name, + kind: "column" as const, + schema: "main", + parent_id: parentId, + expandable: false, + })); +} diff --git a/apps/tauri/src/stores/objectTree.ts b/apps/tauri/src/stores/objectTree.ts index fb4f4a77..52f18581 100644 --- a/apps/tauri/src/stores/objectTree.ts +++ b/apps/tauri/src/stores/objectTree.ts @@ -1,71 +1,95 @@ import { defineStore } from "pinia"; -import { ref, watch } from "vue"; +import { computed, ref, watch } from "vue"; import { - dbListColumns, - dbListTables, + dbListChildren, formatConnectionError, - type ColumnMeta, - type SchemaObject, + type SqlObjectNode, } from "../api/connection"; -import { DEMO_CONNECTION } from "../mock/demoCatalog"; +import { demoListChildren } from "../mock/demoCatalog"; import { useConnectionsStore } from "./connections"; import { useShellNavStore } from "./shellNav"; -export type TreeTableNode = SchemaObject & { +export type TreeUiNode = SqlObjectNode & { expanded: boolean; - loadingColumns: boolean; - columns: ColumnMeta[] | null; + loading: boolean; + children: TreeUiNode[] | null; error: string | null; }; +function toUi(nodes: SqlObjectNode[]): TreeUiNode[] { + return nodes.map((n) => ({ + ...n, + expanded: false, + loading: false, + children: n.expandable ? null : [], + error: null, + })); +} + +function findNode(nodes: TreeUiNode[], id: string): TreeUiNode | null { + for (const n of nodes) { + if (n.id === id) return n; + if (n.children) { + const hit = findNode(n.children, id); + if (hit) return hit; + } + } + return null; +} + +/** Keep nodes that match `q` or have a matching descendant. */ +export function filterTree(nodes: TreeUiNode[], q: string): TreeUiNode[] { + if (!q) return nodes; + const out: TreeUiNode[] = []; + for (const n of nodes) { + const nameHit = n.name.toLowerCase().includes(q); + const kids = n.children ? filterTree(n.children, q) : null; + const kidHit = (kids?.length ?? 0) > 0; + if (nameHit || kidHit) { + out.push({ + ...n, + expanded: nameHit || kidHit || n.expanded, + children: kids ?? n.children, + }); + } + } + return out; +} + export const useObjectTreeStore = defineStore("objectTree", () => { const connectionId = ref(null); - const objects = ref([]); + const roots = ref([]); const loading = ref(false); const error = ref(null); const filter = ref(""); - function fromDemo(): TreeTableNode[] { - return DEMO_CONNECTION.objects.map((o) => ({ - name: o.name, - kind: o.kind, - schema: "main", - expanded: false, - loadingColumns: false, - columns: o.columns.map((c) => ({ - name: c.name, - data_type: c.data_type, - is_nullable: c.is_nullable, - is_primary_key: c.is_primary_key, - })), - error: null, - })); + function isMock(id: string): boolean { + return Boolean(useConnectionsStore().byId.get(id)?.mock); + } + + async function fetchChildren( + connId: string, + parentId: string | null, + ): Promise { + if (isMock(connId)) return demoListChildren(parentId); + return dbListChildren(connId, parentId); } async function loadFor(id: string | null) { connectionId.value = id; - objects.value = []; + roots.value = []; error.value = null; filter.value = ""; if (!id) return; - const connections = useConnectionsStore(); - const conn = connections.byId.get(id); - if (conn?.mock) { - objects.value = fromDemo(); - return; - } - loading.value = true; try { - const list = await dbListTables(id); - objects.value = list.map((o) => ({ - ...o, - expanded: false, - loadingColumns: false, - columns: null, - error: null, - })); + roots.value = toUi(await fetchChildren(id, null)); + // SQLite / Demo: single `main` schema — expand so tables show immediately. + const [only] = roots.value; + if (roots.value.length === 1 && only?.expandable) { + await expandNode(id, only); + } } catch (err) { error.value = formatConnectionError(err); } finally { @@ -73,33 +97,44 @@ export const useObjectTreeStore = defineStore("objectTree", () => { } } - async function toggleColumns(name: string) { - const id = connectionId.value; - const node = objects.value.find((o) => o.name === name); - if (!id || !node) return; - - if (node.expanded) { - node.expanded = false; - return; - } + async function expandNode(connId: string, node: TreeUiNode) { node.expanded = true; - if (node.columns) return; - - const connections = useConnectionsStore(); - if (connections.byId.get(id)?.mock) return; - - node.loadingColumns = true; + if (node.children) return; + node.loading = true; node.error = null; try { - const schema = await dbListColumns(id, name); - node.columns = schema.columns; + node.children = toUi(await fetchChildren(connId, node.id)); } catch (err) { node.error = formatConnectionError(err); + node.children = []; } finally { - node.loadingColumns = false; + node.loading = false; } } + async function toggleExpand(nodeId: string) { + const id = connectionId.value; + const node = findNode(roots.value, nodeId); + if (!id || !node || !node.expandable) return; + + if (node.expanded) { + node.expanded = false; + return; + } + await expandNode(id, node); + } + + /** Flat tables/views under loaded schema children (for ConnectionHome quick list). */ + const relations = computed(() => { + const out: TreeUiNode[] = []; + for (const root of roots.value) { + for (const child of root.children ?? []) { + if (child.kind === "table" || child.kind === "view") out.push(child); + } + } + return out; + }); + function refresh() { return loadFor(connectionId.value); } @@ -115,12 +150,13 @@ export const useObjectTreeStore = defineStore("objectTree", () => { return { connectionId, - objects, + roots, + relations, loading, error, filter, loadFor, - toggleColumns, + toggleExpand, refresh, }; }); diff --git a/apps/tauri/src/stores/shellNav.ts b/apps/tauri/src/stores/shellNav.ts index 86b43294..8182586c 100644 --- a/apps/tauri/src/stores/shellNav.ts +++ b/apps/tauri/src/stores/shellNav.ts @@ -11,6 +11,9 @@ export type SelectedObject = { connectionId: string; name: string; kind: "table" | "view"; + /** Stable object id when known (`sqlite:table:main:users`). */ + objectId?: string; + schema?: string | null; }; export const useShellNavStore = defineStore("shellNav", () => { diff --git a/apps/tauri/src/ui/ConnectionHome.vue b/apps/tauri/src/ui/ConnectionHome.vue index 3b51618b..511995c6 100644 --- a/apps/tauri/src/ui/ConnectionHome.vue +++ b/apps/tauri/src/ui/ConnectionHome.vue @@ -18,9 +18,11 @@ const conn = computed(() => ); const tables = computed(() => - tree.objects.filter((o) => o.kind === "table"), + tree.relations.filter((o) => o.kind === "table"), +); +const views = computed(() => + tree.relations.filter((o) => o.kind === "view"), ); -const views = computed(() => tree.objects.filter((o) => o.kind === "view"));