Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion apps/tauri/src-tauri/src/connection/query.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
12 changes: 8 additions & 4 deletions apps/tauri/src-tauri/src/connection/sqlite_query.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
}

Expand Down Expand Up @@ -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'");
Expand Down
12 changes: 7 additions & 5 deletions apps/tauri/src/api/queryAccumulate.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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);
Expand Down
52 changes: 29 additions & 23 deletions apps/tauri/src/api/queryAccumulate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
}
32 changes: 19 additions & 13 deletions apps/tauri/src/stores/connections.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { defineStore } from "pinia";
import { computed, ref } from "vue";
import { reactive, ref } from "vue";
import {
dbConnectSqlite,
dbDisconnect,
Expand Down Expand Up @@ -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<LiveConnection[]>([]);

const byId = computed(() => {
const map = new Map<string, LiveConnection>();
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<string, LiveConnection>());

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. */
Expand Down Expand Up @@ -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);
Expand All @@ -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();
Expand All @@ -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;
}
Expand Down
4 changes: 2 additions & 2 deletions apps/tauri/src/stores/folders.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,15 +35,15 @@ function newId(): string {
export const useFoldersStore = defineStore("folders", () => {
const folders = reactive<ConnectionFolder[]>(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(() => {
Expand Down
19 changes: 18 additions & 1 deletion apps/tauri/src/stores/objectTree.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, TreeUiNode[]> = {};
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,
Expand All @@ -224,6 +239,8 @@ export const useObjectTreeStore = defineStore("objectTree", () => {
loading,
error,
filter,
filteredRootsByConnection,
filteredRootsFor,
stateOf,
ensureLoaded,
loadFor,
Expand Down
72 changes: 48 additions & 24 deletions apps/tauri/src/stores/queryResult.ts
Original file line number Diff line number Diff line change
@@ -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";
Expand All @@ -13,50 +12,74 @@ import { useShellStatusStore } from "./shellStatus";

/** Last streamed / browsed result — Glide grid binds here. */
export const useQueryResultStore = defineStore("queryResult", () => {
const columns = ref<string[]>([]);
const rows = ref<unknown[][]>([]);
let acc = emptyAccumulatedQuery();

const columns = shallowRef<string[]>(acc.columns);
/** Durable row buffer — mutated in place across batches. */
const rows = shallowRef<unknown[][]>(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);
const elapsedMs = ref<number | null>(null);
const affectedRows = ref<number | null>(null);
const error = ref<string | null>(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: {
columns: string[];
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,
Expand Down Expand Up @@ -128,6 +151,7 @@ export const useQueryResultStore = defineStore("queryResult", () => {
return {
columns,
rows,
revision,
running,
truncated,
rowCount,
Expand Down
Loading
Loading