diff --git a/apps/tauri/src-tauri/src/connection/query.rs b/apps/tauri/src-tauri/src/connection/query.rs index 45453cd6..0d1cc9f4 100644 --- a/apps/tauri/src-tauri/src/connection/query.rs +++ b/apps/tauri/src-tauri/src/connection/query.rs @@ -3,7 +3,7 @@ use serde::Serialize; /// Events pushed over a Tauri [`tauri::ipc::Channel`] during `db_execute_query`. -#[derive(Debug, Clone, Serialize)] +#[derive(Debug, Serialize)] #[serde(tag = "type", rename_all = "snake_case")] pub enum QueryEvent { Columns { diff --git a/apps/tauri/src-tauri/src/connection/sqlite_query.rs b/apps/tauri/src-tauri/src/connection/sqlite_query.rs index 9fd396a6..39c72504 100644 --- a/apps/tauri/src-tauri/src/connection/sqlite_query.rs +++ b/apps/tauri/src-tauri/src/connection/sqlite_query.rs @@ -91,6 +91,8 @@ fn stream_rows( offset, })?; offset += n; + // `take` leaves capacity 0 — re-reserve so the next batch does not grow from empty. + batch.reserve(batch_size); } } @@ -125,10 +127,12 @@ fn value_ref_to_json(v: ValueRef<'_>) -> serde_json::Value { serde_json::Value::String(f.to_string()) } } - ValueRef::Text(bytes) => { - let s = String::from_utf8_lossy(bytes); - serde_json::Value::String(s.into_owned()) - } + ValueRef::Text(bytes) => match std::str::from_utf8(bytes) { + Ok(s) => serde_json::Value::String(s.to_owned()), + Err(_) => { + serde_json::Value::String(String::from_utf8_lossy(bytes).into_owned()) + } + }, ValueRef::Blob(bytes) => { let mut hex = String::with_capacity(2 + bytes.len() * 2); hex.push_str("X'"); diff --git a/apps/tauri/src/api/queryAccumulate.test.ts b/apps/tauri/src/api/queryAccumulate.test.ts index 5d3bf625..da9a65b9 100644 --- a/apps/tauri/src/api/queryAccumulate.test.ts +++ b/apps/tauri/src/api/queryAccumulate.test.ts @@ -3,22 +3,23 @@ import { applyQueryEvent, emptyAccumulatedQuery } from "./queryAccumulate"; describe("applyQueryEvent (SQLite slice smoke)", () => { it("accumulates columns then batched rows then done", () => { - let state = emptyAccumulatedQuery(); - state = applyQueryEvent(state, { + const state = emptyAccumulatedQuery(); + const rowsBuf = state.rows; + applyQueryEvent(state, { type: "columns", names: ["id", "email"], }); - state = applyQueryEvent(state, { + applyQueryEvent(state, { type: "rows", rows: [[1, "a@ex.com"]], offset: 0, }); - state = applyQueryEvent(state, { + applyQueryEvent(state, { type: "rows", rows: [[2, "b@ex.com"]], offset: 1, }); - state = applyQueryEvent(state, { + applyQueryEvent(state, { type: "done", row_count: 2, truncated: false, @@ -27,6 +28,7 @@ describe("applyQueryEvent (SQLite slice smoke)", () => { expect(state.columns).toEqual(["id", "email"]); expect(state.rows).toHaveLength(2); + expect(state.rows).toBe(rowsBuf); // in-place append, no realloc of buffer expect(state.rowCount).toBe(2); expect(state.truncated).toBe(false); expect(state.elapsedMs).toBe(3); diff --git a/apps/tauri/src/api/queryAccumulate.ts b/apps/tauri/src/api/queryAccumulate.ts index e0499f72..1b559792 100644 --- a/apps/tauri/src/api/queryAccumulate.ts +++ b/apps/tauri/src/api/queryAccumulate.ts @@ -22,36 +22,42 @@ export function emptyAccumulatedQuery(): AccumulatedQuery { }; } -/** Pure reducer used by the queryResult store and smoke tests. */ +/** + * Mutating reducer — appends row batches in place (no full-array concat). + * Callers must treat `state.rows` as the durable buffer across events. + */ export function applyQueryEvent( state: AccumulatedQuery, ev: QueryEvent, ): AccumulatedQuery { switch (ev.type) { case "columns": - return { - ...state, - columns: ev.names, - rows: [], - error: null, - }; - case "rows": - return { - ...state, - rows: state.rows.concat(ev.rows), - }; + state.columns = ev.names; + state.rows.length = 0; + state.rowCount = 0; + state.truncated = false; + state.elapsedMs = null; + state.affectedRows = null; + state.error = null; + return state; + case "rows": { + // Append batch only — do not copy prior rows (was O(n²) via concat). + const rows = state.rows; + const batch = ev.rows; + for (let i = 0; i < batch.length; i++) rows.push(batch[i]!); + return state; + } case "done": - return { - ...state, - rowCount: ev.row_count, - truncated: ev.truncated, - elapsedMs: ev.elapsed_ms, - affectedRows: - ev.affected_rows === undefined || ev.affected_rows === null - ? null - : ev.affected_rows, - }; + state.rowCount = ev.row_count; + state.truncated = ev.truncated; + state.elapsedMs = ev.elapsed_ms; + state.affectedRows = + ev.affected_rows === undefined || ev.affected_rows === null + ? null + : ev.affected_rows; + return state; case "error": - return { ...state, error: ev.message }; + state.error = ev.message; + return state; } } diff --git a/apps/tauri/src/stores/connections.ts b/apps/tauri/src/stores/connections.ts index f2257c8e..3a3b0bcf 100644 --- a/apps/tauri/src/stores/connections.ts +++ b/apps/tauri/src/stores/connections.ts @@ -1,5 +1,5 @@ import { defineStore } from "pinia"; -import { computed, ref } from "vue"; +import { reactive, ref } from "vue"; import { dbConnectSqlite, dbDisconnect, @@ -29,16 +29,22 @@ function fileName(path: string): string { /** Saved / live sessions shown in SERVERS (Flutter connections list). */ export const useConnectionsStore = defineStore("connections", () => { const items = ref([]); - - const byId = computed(() => { - const map = new Map(); - for (const c of items.value) map.set(c.id, c); - return map; - }); + /** Incremental index — not rebuilt on every upsert. */ + const byId = reactive(new Map()); function upsert(conn: LiveConnection) { - const rest = items.value.filter((c) => c.id !== conn.id); - items.value = [...rest, conn]; + const list = items.value; + const i = list.findIndex((c) => c.id === conn.id); + if (i >= 0) list[i] = conn; + else list.push(conn); + byId.set(conn.id, conn); + } + + function remove(id: string) { + byId.delete(id); + const list = items.value; + const i = list.findIndex((c) => c.id === id); + if (i >= 0) list.splice(i, 1); } /** Flutter-style Demo — full UI without opening a real file. */ @@ -105,11 +111,11 @@ export const useConnectionsStore = defineStore("connections", () => { async function disconnect(id: string) { const status = useShellStatusStore(); const nav = useShellNavStore(); - const conn = byId.value.get(id); + const conn = byId.get(id); try { if (conn && !conn.mock) await dbDisconnect(id); } finally { - items.value = items.value.filter((c) => c.id !== id); + remove(id); if (nav.selectedConnectionId === id) { const next = items.value[0] ?? null; if (next) nav.selectConnection(next.id); @@ -124,7 +130,7 @@ export const useConnectionsStore = defineStore("connections", () => { } function select(id: string) { - const conn = byId.value.get(id); + const conn = byId.get(id); if (!conn) return; const nav = useShellNavStore(); const status = useShellStatusStore(); @@ -139,7 +145,7 @@ export const useConnectionsStore = defineStore("connections", () => { } function moveToFolder(connectionId: string, folderId: string | null) { - const conn = items.value.find((c) => c.id === connectionId); + const conn = byId.get(connectionId); if (!conn) return; conn.folderId = folderId; } diff --git a/apps/tauri/src/stores/folders.ts b/apps/tauri/src/stores/folders.ts index a74d8bff..3033a2d4 100644 --- a/apps/tauri/src/stores/folders.ts +++ b/apps/tauri/src/stores/folders.ts @@ -35,15 +35,15 @@ function newId(): string { export const useFoldersStore = defineStore("folders", () => { const folders = reactive(load()); + // Persist id/name only — expand toggles must not rewrite localStorage. watch( - folders, + () => folders.map((f) => `${f.id}\0${f.name}`).join("\n"), () => { const payload: Stored = { folders: folders.map(({ id, name }) => ({ id, name })), }; localStorage.setItem(STORAGE_KEY, JSON.stringify(payload)); }, - { deep: true }, ); const byId = computed(() => { diff --git a/apps/tauri/src/stores/objectTree.ts b/apps/tauri/src/stores/objectTree.ts index 09d97d6e..14597601 100644 --- a/apps/tauri/src/stores/objectTree.ts +++ b/apps/tauri/src/stores/objectTree.ts @@ -209,13 +209,28 @@ export const useObjectTreeStore = defineStore("objectTree", () => { ); watch( - () => nav.expandedConnectionIds.slice(), + () => nav.expandedConnectionIds, (ids) => { for (const id of ids) void ensureLoaded(id); }, { immediate: true }, ); + /** Memoized filter per connection — avoids recloning the tree every panel paint. */ + const filteredRootsByConnection = computed(() => { + const out: Record = {}; + for (const id of Object.keys(byConnection)) { + const st = byConnection[id]!; + const q = st.filter.trim().toLowerCase(); + out[id] = q ? filterTree(st.roots, q) : st.roots; + } + return out; + }); + + function filteredRootsFor(connId: string): TreeUiNode[] { + return filteredRootsByConnection.value[connId] ?? stateOf(connId).roots; + } + return { byConnection, connectionId, @@ -224,6 +239,8 @@ export const useObjectTreeStore = defineStore("objectTree", () => { loading, error, filter, + filteredRootsByConnection, + filteredRootsFor, stateOf, ensureLoaded, loadFor, diff --git a/apps/tauri/src/stores/queryResult.ts b/apps/tauri/src/stores/queryResult.ts index d754a014..aae63a02 100644 --- a/apps/tauri/src/stores/queryResult.ts +++ b/apps/tauri/src/stores/queryResult.ts @@ -1,10 +1,9 @@ import { defineStore } from "pinia"; -import { ref } from "vue"; +import { ref, shallowRef } from "vue"; import { dbExecuteQuery, type QueryEvent } from "../api/query"; import { applyQueryEvent, emptyAccumulatedQuery, - type AccumulatedQuery, } from "../api/queryAccumulate"; import { formatConnectionError } from "../api/connection"; import { useConnectionsStore } from "./connections"; @@ -13,8 +12,13 @@ import { useShellStatusStore } from "./shellStatus"; /** Last streamed / browsed result — Glide grid binds here. */ export const useQueryResultStore = defineStore("queryResult", () => { - const columns = ref([]); - const rows = ref([]); + let acc = emptyAccumulatedQuery(); + + const columns = shallowRef(acc.columns); + /** Durable row buffer — mutated in place across batches. */ + const rows = shallowRef(acc.rows); + /** Bumps on any result change so grids can shallow-watch without deep scan. */ + const revision = ref(0); const running = ref(false); const truncated = ref(false); const rowCount = ref(0); @@ -22,26 +26,45 @@ export const useQueryResultStore = defineStore("queryResult", () => { const affectedRows = ref(null); const error = ref(null); - let acc = emptyAccumulatedQuery(); + function bump() { + revision.value += 1; + } - function syncFrom(next: AccumulatedQuery) { - columns.value = next.columns; - rows.value = next.rows; - truncated.value = next.truncated; - rowCount.value = next.rowCount; - elapsedMs.value = next.elapsedMs; - affectedRows.value = next.affectedRows; - error.value = next.error; + function bindBuffers() { + columns.value = acc.columns; + rows.value = acc.rows; + } + + function syncScalars() { + truncated.value = acc.truncated; + rowCount.value = acc.rowCount || acc.rows.length; + elapsedMs.value = acc.elapsedMs; + affectedRows.value = acc.affectedRows; + error.value = acc.error; } function reset() { acc = emptyAccumulatedQuery(); - syncFrom(acc); + bindBuffers(); + syncScalars(); + bump(); } function feedEvent(ev: QueryEvent) { - acc = applyQueryEvent(acc, ev); - syncFrom(acc); + applyQueryEvent(acc, ev); + if (ev.type === "columns") { + bindBuffers(); + } else if (rows.value !== acc.rows) { + rows.value = acc.rows; + } + if (ev.type === "rows") { + // Interim count while streaming; `done` sets authoritative row_count. + rowCount.value = acc.rows.length; + } else { + syncScalars(); + } + if (ev.type === "error") error.value = acc.error; + bump(); } function setSnapshot(opts: { @@ -49,14 +72,14 @@ export const useQueryResultStore = defineStore("queryResult", () => { rows: unknown[][]; message?: string; }) { - acc = { - ...emptyAccumulatedQuery(), - columns: opts.columns, - rows: opts.rows, - rowCount: opts.rows.length, - elapsedMs: 0, - }; - syncFrom(acc); + acc = emptyAccumulatedQuery(); + acc.columns = opts.columns; + acc.rows = opts.rows; + acc.rowCount = opts.rows.length; + acc.elapsedMs = 0; + bindBuffers(); + syncScalars(); + bump(); if (opts.message) { useShellStatusStore().setQueryMetrics({ message: opts.message, @@ -128,6 +151,7 @@ export const useQueryResultStore = defineStore("queryResult", () => { return { columns, rows, + revision, running, truncated, rowCount, diff --git a/apps/tauri/src/stores/shellNav.ts b/apps/tauri/src/stores/shellNav.ts index 8182586c..ea7a8f1c 100644 --- a/apps/tauri/src/stores/shellNav.ts +++ b/apps/tauri/src/stores/shellNav.ts @@ -1,5 +1,5 @@ import { defineStore } from "pinia"; -import { computed, ref } from "vue"; +import { computed, reactive, ref } from "vue"; /** Flutter MainScreen workspace selection — chrome routing, not DB. */ export type WorkspaceSurface = "empty" | "connectionHome" | "tableObject"; @@ -21,8 +21,8 @@ export const useShellNavStore = defineStore("shellNav", () => { const selectedObject = ref(null); const homeTab = ref("overview"); const objectTab = ref("data"); - /** Expanded connection ids in the SERVERS tree (Flutter expand = show objects). */ - const expandedConnectionIds = ref([]); + /** Expanded SERVERS rows — Record avoids Set→array realloc on every toggle. */ + const expanded = reactive>({}); const surface = computed(() => { if (selectedObject.value) return "tableObject"; @@ -30,6 +30,13 @@ export const useShellNavStore = defineStore("shellNav", () => { return "empty"; }); + /** Snapshot of expanded ids for watchers (stable when membership unchanged). */ + const expandedConnectionIds = computed(() => Object.keys(expanded)); + + function isExpanded(id: string): boolean { + return expanded[id] === true; + } + function selectConnection(id: string | null) { selectedConnectionId.value = id; selectedObject.value = null; @@ -48,17 +55,13 @@ export const useShellNavStore = defineStore("shellNav", () => { } function toggleExpanded(id: string) { - const set = new Set(expandedConnectionIds.value); - if (set.has(id)) set.delete(id); - else set.add(id); - expandedConnectionIds.value = [...set]; + if (expanded[id]) delete expanded[id]; + else expanded[id] = true; } - function setExpanded(id: string, expanded: boolean) { - const set = new Set(expandedConnectionIds.value); - if (expanded) set.add(id); - else set.delete(id); - expandedConnectionIds.value = [...set]; + function setExpanded(id: string, on: boolean) { + if (on) expanded[id] = true; + else delete expanded[id]; } function reset() { @@ -66,7 +69,7 @@ export const useShellNavStore = defineStore("shellNav", () => { selectedObject.value = null; homeTab.value = "overview"; objectTab.value = "data"; - expandedConnectionIds.value = []; + for (const k of Object.keys(expanded)) delete expanded[k]; } return { @@ -74,7 +77,9 @@ export const useShellNavStore = defineStore("shellNav", () => { selectedObject, homeTab, objectTab, + expanded, expandedConnectionIds, + isExpanded, surface, selectConnection, selectObject, diff --git a/apps/tauri/src/stores/workspace.ts b/apps/tauri/src/stores/workspace.ts index a19ae998..1f33c92a 100644 --- a/apps/tauri/src/stores/workspace.ts +++ b/apps/tauri/src/stores/workspace.ts @@ -36,7 +36,7 @@ export const useWorkspaceStore = defineStore("workspace", () => { function ensureSql(id: string, seed = DEFAULT_SQL) { if (!(id in sqlBuffers.value)) { - sqlBuffers.value = { ...sqlBuffers.value, [id]: seed }; + sqlBuffers.value[id] = seed; } } @@ -45,7 +45,8 @@ export const useWorkspaceStore = defineStore("workspace", () => { } function setSql(id: string, sql: string) { - sqlBuffers.value = { ...sqlBuffers.value, [id]: sql }; + // In-place — avoid `{ ...buffers }` identity churn on every keystroke. + sqlBuffers.value[id] = sql; } function addTab(partial?: Partial>) { @@ -63,8 +64,7 @@ export const useWorkspaceStore = defineStore("workspace", () => { function closeTab(id: string) { const idx = tabs.value.findIndex((t) => t.id === id); if (idx < 0) return; - const { [id]: _removed, ...rest } = sqlBuffers.value; - sqlBuffers.value = rest; + delete sqlBuffers.value[id]; if (tabs.value.length === 1) { const welcome = { id: nextId(), title: "Welcome", kind: "welcome" as const }; tabs.value = [welcome]; diff --git a/apps/tauri/src/ui/ConnectionsPanel.vue b/apps/tauri/src/ui/ConnectionsPanel.vue index 16ebdd41..7d1a6655 100644 --- a/apps/tauri/src/ui/ConnectionsPanel.vue +++ b/apps/tauri/src/ui/ConnectionsPanel.vue @@ -8,11 +8,7 @@ import { } from "../stores/connections"; import { useFoldersStore } from "../stores/folders"; import { useShellNavStore } from "../stores/shellNav"; -import { - filterTree, - useObjectTreeStore, - type TreeUiNode, -} from "../stores/objectTree"; +import { useObjectTreeStore, type TreeUiNode } from "../stores/objectTree"; import { useQueryaMotion } from "../motion"; import SplitHandle from "./SplitHandle.vue"; import QueryaContextMenu, { type CtxItem } from "./QueryaContextMenu.vue"; @@ -30,8 +26,7 @@ const nav = useShellNavStore(); const tree = useObjectTreeStore(); const { items } = storeToRefs(connections); const { folders } = storeToRefs(foldersStore); -const { selectedConnectionId, expandedConnectionIds, selectedObject } = - storeToRefs(nav); +const { selectedConnectionId, selectedObject } = storeToRefs(nav); const motion = useQueryaMotion(); const filter = ref(""); const dragging = ref(false); @@ -205,8 +200,7 @@ function treeState(connId: string) { } function filteredRootsFor(connId: string) { - const st = tree.stateOf(connId); - return filterTree(st.roots, st.filter.trim().toLowerCase()); + return tree.filteredRootsFor(connId); } function driverGlyph(c: LiveConnection): string { @@ -284,7 +278,7 @@ onUnmounted(() => { class="conn" :class="{ active: c.id === selectedConnectionId && !selectedObject, - expanded: expandedConnectionIds.includes(c.id), + expanded: nav.isExpanded(c.id), }" >
{
@@ -384,7 +378,7 @@ onUnmounted(() => { class="conn" :class="{ active: c.id === selectedConnectionId && !selectedObject, - expanded: expandedConnectionIds.includes(c.id), + expanded: nav.isExpanded(c.id), }" >
{
diff --git a/apps/tauri/src/ui/ResultGrid.vue b/apps/tauri/src/ui/ResultGrid.vue index f30d82e9..7c0cf2fb 100644 --- a/apps/tauri/src/ui/ResultGrid.vue +++ b/apps/tauri/src/ui/ResultGrid.vue @@ -13,7 +13,7 @@ import { import "@glideapps/glide-data-grid/dist/index.css"; const query = useQueryResultStore(); -const { columns, rows } = storeToRefs(query); +const { columns, rows, revision, rowCount } = storeToRefs(query); const host = ref(null); const size = ref({ width: 640, height: 320 }); @@ -57,7 +57,8 @@ onMounted(() => { refreshTheme(); }); -watch([columns, rows], () => render(), { deep: true }); +// Shallow: revision/rowCount bump on append — no deep walk of unknown[][]. +watch([columns, revision, rowCount], () => render()); onBeforeUnmount(() => { unsubTheme?.();