/** * Query console integration for SQL editors: a toolbar panel binding the file * to a data source (execute / stop / row limit), run feedback on the text * (gutter check / error, timing, error banner) and context-aware completion * from the introspected schema. */ import { hasNextSnippetField, hasPrevSnippetField, insertCompletionText, nextSnippetField, pickedCompletion, snippet, startCompletion, type Completion, type CompletionContext, type CompletionResult, type CompletionSource, } from "@codemirror/autocomplete"; import { Compartment, EditorSelection, EditorState, Facet, Prec, RangeSet, type Range, StateEffect, StateField, type Extension, } from "@codemirror/state"; import { Decoration, EditorView, GutterMarker, RectangleMarker, ViewPlugin, WidgetType, gutter, layer, showPanel, showTooltip, type Panel, type Tooltip, } from "@codemirror/view"; import { useEffect, useMemo, useRef, useState, type PointerEvent } from "react"; import { createRoot } from "react-dom/client"; import type { EditorDocContext } from "@/editor/api"; import { iconNode, spinnerNode } from "@/ui/iconNode"; import { call, commands, type DbDriver, type DbSessionContext, type DbStatementOutcome, type SqlStatement, } from "@/platform/ipc"; import { shortcutLabel } from "@/platform/keymap"; import { Icon, IconButton, Select, Toolbar, lazyComponent } from "@/ui"; import { useProject } from "@/platform/project"; import { activeSchema, parseSchemaTreeValue, schemaSwitchable, schemaTreeRows, schemaTreeValue, sourceIcon, sourceLabel, splitTarget, targetOf, } from "./model"; import { loadSavedCatalog, offerIntrospection } from "./introspection"; import { analyze, templateContexts, valuesSlot } from "./sql/analyze"; import { shouldAutoCompleteSql, sqlCandidates, type CandidateKind, type SqlCandidate, type SqlCatalog, } from "./sql/complete"; import { WHOLE_FILE, sqlSupport, type SqlText } from "./sqlSupport"; import { snowflakeLanguage } from "./sql/snowflakeHighlight"; import { allowsPassiveConsoleMetadata, bindConsole, cancelConsole, closeInlineResults, inEditorResults, setInEditorResults, consoleSchema, consoleSource, executeConsole, explainConsole, finishTransaction, openHistory, loadCompletion, runSql, listsDatabases, loadDatabases, loadSchemas, loadSources, loadTables, tablesKey, setConsoleSchema, setManualCommit, sourceById, useDatabase, } from "./store"; import styles from "./Database.module.css"; import { tx } from "@/platform/i18n"; import { databaseRequest, projectRequest } from "./requests"; import type { ResultTab } from "./store"; /** `templates` feature's language-data key for finer template contexts. */ const TEMPLATE_CONTEXT_KEY = "openideaTemplateContexts"; import { formatElapsed } from "./resultView"; import { SQL_LANGUAGE } from "./sqlLanguage"; import { jdbcDialect } from "./vendors"; export { SQL_LANGUAGE }; const ROW_LIMITS = ["100", "500", "1000", "5000", "50000"]; /** Statement outcomes of the last run, kept on the text (IDEA's gutter check / error and timing). */ interface RunMark { from: number; to: number; /** After the statement's `;` when it has one. */ timingAt: number; error: string | null; ms: number | null; } interface Executing { /** Tells this run from a later one on the same console. */ token: number; active: { index: number; startedAt: number } | null; spans: readonly { from: number; to: number }[]; } function activeSpan(ex: Executing | null) { const span = ex?.active ? ex.spans[ex.active.index] : undefined; return span && span.from < span.to ? span : undefined; } interface RunState { marks: readonly RunMark[]; /** Message of the bottom error banner (`null`: hidden). */ banner: string | null; executing: Executing | null; } const setRun = StateEffect.define(); const runField = StateField.define({ create: () => ({ marks: [], banner: null, executing: null }), update(value, tr) { for (const e of tr.effects) if (e.is(setRun)) return e.value; if (!tr.docChanged) return value; // The request runs the text it was sent; edits only move where that shows. const ex = value.executing; const executing = ex && { ...ex, spans: ex.spans.map((r) => ({ from: tr.changes.mapPos(r.from, 1), to: tr.changes.mapPos(r.to, -1) })), }; // Editing a statement drops its mark. const marks: RunMark[] = []; for (const m of value.marks) { let touched = false; tr.changes.iterChangedRanges((a, b) => { if (a <= m.to && b >= m.from) touched = true; }); if (!touched) marks.push({ ...m, from: tr.changes.mapPos(m.from), to: tr.changes.mapPos(m.to), timingAt: tr.changes.mapPos(m.timingAt), }); } return { ...value, marks, executing }; }, provide: (f) => [ EditorView.decorations.compute([f], (state) => { const st = state.field(f); const ranges = []; const active = st.executing?.active; const span = activeSpan(st.executing); if (active && span) { const end = state.sliceDoc(span.to, span.to + 1) === ";" ? span.to + 1 : span.to; const at = Math.min(end, state.doc.lineAt(span.from).to); ranges.push(Decoration.mark({ class: "cm-openidea-db-executing" }).range(span.from, span.to)); ranges.push(Decoration.widget({ widget: new ElapsedWidget(active.startedAt), side: 1 }).range(at)); } for (const m of st.marks) { if (m.error) ranges.push( Decoration.mark({ class: "cm-openidea-db-error", attributes: { title: m.error } }).range(m.from, m.to), ); if (m.ms !== null) ranges.push(Decoration.widget({ widget: new TimingWidget(m.ms), side: 1 }).range(m.timingAt)); } return Decoration.set(ranges, true); }), showPanel.from(f, (st) => (st.banner ? errorBanner(st.banner) : null)), ], }); class TimingWidget extends WidgetType { constructor(readonly ms: number) { super(); } eq(other: TimingWidget) { return other.ms === this.ms; } toDOM() { const span = document.createElement("span"); span.className = "cm-openidea-db-timing"; span.textContent = formatElapsed(this.ms); return span; } } /** The running time of the request, ticking until it ends. */ class ElapsedWidget extends WidgetType { private timer: ReturnType | undefined; constructor(readonly startedAt: number) { super(); } eq(other: ElapsedWidget) { return other.startedAt === this.startedAt; } toDOM() { const span = document.createElement("span"); span.className = "cm-openidea-db-timing cm-openidea-db-elapsed"; const tick = () => { const elapsed = formatElapsed(Date.now() - this.startedAt); span.textContent = tx`Executing… ${elapsed}`; }; tick(); this.timer = setInterval(tick, 100); return span; } destroy() { clearInterval(this.timer); } } class ExecutingMarker extends GutterMarker { eq(other: GutterMarker) { return other instanceof ExecutingMarker; } toDOM() { const el = spinnerNode(12, "cm-openidea-db-run-executing"); el.title = tx("Executing"); return el; } } class RunMarker extends GutterMarker { constructor(readonly error: string | null) { super(); } eq(other: RunMarker) { return other.error === this.error; } toDOM() { const el = iconNode( this.error ? "error" : "check", 14, this.error ? "cm-openidea-db-run-error" : "cm-openidea-db-run-ok", ); el.title = this.error ?? "Executed"; return el; } } const runGutter = gutter({ class: "cm-openidea-db-gutter", markers: (view) => { const st = view.state.field(runField); const doc = view.state.doc; const active = activeSpan(st.executing); const line = active ? doc.lineAt(active.from).from : undefined; const ranges: Range[] = st.marks .filter((m) => m.from <= doc.length) .map((m) => new RunMarker(m.error).range(doc.lineAt(m.from).from)); if (line !== undefined) ranges.push(new ExecutingMarker().range(line)); return RangeSet.of(ranges, true); }, }); function errorBanner(message: string) { return (view: EditorView): Panel => { const dom = document.createElement("div"); dom.className = "cm-openidea-db-banner"; dom.setAttribute("role", "alert"); const text = document.createElement("span"); text.className = "cm-openidea-db-banner-text"; text.textContent = message; text.title = message; const close = document.createElement("button"); close.type = "button"; close.className = "cm-openidea-db-banner-close"; close.setAttribute("aria-label", "Close"); close.appendChild(iconNode("close", 14)); close.onclick = () => view.dispatch({ effects: setRun.of({ ...view.state.field(runField), banner: null }) }); dom.append(text, close); return { dom, top: false }; }; } let nextExecution = 0; /** Runs `from`–`to` of `view`, following each statement as it executes. */ async function executeRange(view: EditorView, path: string, from: number, to: number) { const token = ++nextExecution; const sent = view.state.doc; const start = (statements: readonly SqlStatement[]) => { const st = view.state.field(runField, false); // The offsets are into the text sent; an edit since (while asking for parameters) leaves them unplaced. if (!st || view.state.doc !== sent) return; const spans = statements.map((st) => ({ from: st.from, to: st.to })); const first = spans[0]!; const last = spans[spans.length - 1]!; const marks = st.marks.filter((mark) => mark.to <= first.from || mark.from >= last.to); view.dispatch({ effects: setRun.of({ marks, banner: null, executing: { token, spans, active: null } }) }); }; try { await executeConsole(path, sent.toString(), from, to, start, (events) => { const st = view.state.field(runField, false); const ex = st?.executing; if (!st || ex?.token !== token) return; const last = events[events.length - 1]!; const active = last.type === "started" ? { index: last.index, startedAt: Date.now() } : null; const marks = [...st.marks]; let banner = st.banner; const placed = new Map(); for (const event of events) { if (event.type === "started") continue; const span = ex.spans[event.index]; if (!span || span.from >= span.to) continue; const { from, to } = span; const { error, result } = event.outcome; marks.push({ from, to, timingAt: view.state.sliceDoc(to, to + 1) === ";" ? to + 1 : to, error, ms: result?.elapsedMs ?? null, }); if (error) banner = `[${sourceById(consoleSource(path))?.name ?? ""}] ${error}`; placed.set(event.index, { ...event.outcome, statement: { ...event.outcome.statement, ...span } }); } view.dispatch({ effects: setRun.of({ marks, banner, executing: { ...ex, active } }) }); return placed; }); } finally { const st = view.state.field(runField, false); if (st?.executing?.token === token) view.dispatch({ effects: setRun.of({ ...st, executing: null }) }); } } /** Runs the statement at the caret (or the selected ones) of `view`. */ export async function executeInView(view: EditorView, path: string) { const sel = view.state.selection.main; await executeRange(view, path, sel.from, sel.to); } /** Runs every statement of `view`, in order (stops at the first that fails). */ export async function executeScriptInView(view: EditorView, path: string) { await executeRange(view, path, 0, view.state.doc.length); } /** Explain Plan of the statement at the caret (or the first selected one) of `view`. */ export async function explainInView(view: EditorView, path: string) { const sel = view.state.selection.main; await explainConsole(path, view.state.doc.toString(), sel.from, sel.to); } const consolePath = Facet.define({ combine: (v) => v[0] ?? "" }); const setPreview = StateEffect.define(); /** * The range the console's next Execute would submit, bordered on the text (DataGrip's current * statement border): the caret's statement, or the selection's — the statements `db_statements` * splits that range into, the very call the run itself makes. */ const previewField = StateField.define({ create: () => [], update(value, tr) { for (const e of tr.effects) if (e.is(setPreview)) return e.value; if (!tr.docChanged) return value; // The preview is of the text it was computed for; edits only move where that is. const next: { from: number; to: number }[] = []; for (const r of value) { const from = tr.changes.mapPos(r.from, 1); const to = tr.changes.mapPos(r.to, -1); if (from < to) next.push({ from, to }); } return next; }, }); /** The bordered ranges: a run in progress keeps its submitted range, whatever the caret does. */ export function previewRanges(state: EditorState): readonly { from: number; to: number }[] { const ex = state.field(runField, false)?.executing; const ranges = ex?.spans.length ? [{ from: ex.spans[0]!.from, to: ex.spans[ex.spans.length - 1]!.to }] : (state.field(previewField, false) ?? []); return ranges.filter((r) => r.from < r.to); } const PREVIEW_CLASS = "cm-openidea-db-preview"; /** * One box around each statement's text: the union of its lines' text (indentation and trailing * blanks left out), as tall as the statement even where it runs out of view. */ function previewBoxes(view: EditorView): RectangleMarker[] { const { doc } = view.state; const boxes: RectangleMarker[] = []; for (const r of previewRanges(view.state)) { let left = Infinity; let right = -Infinity; let offset: number | null = null; for (const visible of view.visibleRanges) { const from = Math.max(r.from, visible.from); const to = Math.min(r.to, visible.to); if (from >= to) continue; for (let pos = from; pos <= to;) { const line = doc.lineAt(pos); const text = line.text; let start = Math.max(from, line.from) - line.from; let end = Math.min(to, line.to) - line.from; while (start < end && /\s/.test(text[start]!)) start++; while (end > start && /\s/.test(text[end - 1]!)) end--; if (start < end) for (const m of RectangleMarker.forRange( view, PREVIEW_CLASS, EditorSelection.range(line.from + start, line.from + end), )) { left = Math.min(left, m.left); right = Math.max(right, m.left + (m.width ?? 0)); offset ??= m.top - view.lineBlockAt(line.from).top; } pos = line.to + 1; } } if (offset == null || right <= left) continue; const top = view.lineBlockAt(r.from).top + offset; const bottom = view.lineBlockAt(r.to).bottom + offset; boxes.push(new RectangleMarker(PREVIEW_CLASS, left - 2, top, right - left + 4, bottom - top)); } return boxes; } const previewLayer = layer({ above: false, markers: previewBoxes, update: (u) => u.docChanged || u.viewportChanged || u.geometryChanged || u.startState.field(previewField, false) !== u.state.field(previewField, false) || u.startState.field(runField, false)?.executing !== u.state.field(runField, false)?.executing, }); /** How long typing pauses before the preview is split again (until then it follows the edit). */ const PREVIEW_TYPING_DELAY_MS = 150; /** Re-splits the caret's (or the selection's) range for the preview, as `executeConsole` does. */ const previewSync = ViewPlugin.define((view) => { const path = view.state.facet(consolePath); let run = 0; let timer: ReturnType | undefined; const preview = () => { clearTimeout(timer); timer = undefined; const id = consoleSource(path); if (!id) return; const sent = view.state.doc; const sel = view.state.selection.main; const token = ++run; void call(commands.dbStatements(id, sent.toString(), sel.from, sel.to)) .then((statements) => { // A newer move, an edit or a run started since: what came back no longer applies. if (token !== run || view.state.doc !== sent || view.state.field(runField, false)?.executing) return; view.dispatch({ effects: setPreview.of(statements.map((st) => ({ from: st.from, to: st.to }))) }); }) .catch(() => {}); }; preview(); return { update(u) { const executing = (s: EditorState) => !!s.field(runField, false)?.executing; if (executing(u.startState) && !executing(u.state)) preview(); // While a run is in progress its submitted range stays; the caret is not followed. else if (executing(u.state)) return; // Typing sends the whole text each time: wait for a pause, the mapped preview meanwhile. else if (u.docChanged) { clearTimeout(timer); timer = setTimeout(preview, PREVIEW_TYPING_DELAY_MS); } else if (u.selectionSet) preview(); }, destroy() { clearTimeout(timer); run++; }, }; }); /** An in-editor result and the statement it shows under (mapped through edits). */ interface InlineAnchor { id: number; from: number; to: number; } /** * Where each in-editor result's statement is now and how tall the result is, by result id: * a console's view can be rebuilt (closed and reopened), and its results go back where they were. */ const anchors = new Map(); const heights = new Map(); const MAX_FIT_HEIGHT = 320; const MIN_HEIGHT = 96; /** Toolbar, notice, header row, the rows and room for the floating pager, up to `MAX_FIT_HEIGHT`. */ function fitHeight(tab: ResultTab | undefined): number { const rows = tab?.outcome.result?.rows.length ?? 0; return Math.max(MIN_HEIGHT, Math.min(MAX_FIT_HEIGHT, 40 + 24 + 24 + Math.max(rows, 1) * 24 + 56)); } const setInline = StateEffect.define(); /** An in-editor result was resized: its widget is redrawn so the editor measures it again. */ const resized = StateEffect.define(); function anchorOf(tab: ResultTab): InlineAnchor { return { id: tab.id, ...(anchors.get(tab.id) ?? { from: tab.outcome.statement.from, to: tab.outcome.statement.to }) }; } const inlineField = StateField.define({ create: (state) => { const path = state.facet(consolePath); return useDatabase .getState() .inline.filter((t) => t.path === path) .map(anchorOf) .filter((a) => a.to <= state.doc.length); }, update(value, tr) { for (const e of tr.effects) { if (e.is(setInline)) value = e.value; else if (e.is(resized)) value = [...value]; } if (!tr.docChanged) return value; const next: InlineAnchor[] = []; for (const a of value) { const from = tr.changes.mapPos(a.from, 1); const to = tr.changes.mapPos(a.to, -1); // The statement was deleted: so is its result (the store drops it in `syncInline`). if (to <= from) continue; anchors.set(a.id, { from, to }); next.push({ id: a.id, from, to }); } return next; }, // Under the statement's last line. provide: (f) => EditorView.decorations.compute([f], (state) => Decoration.set( state .field(f) .map((a) => Decoration.widget({ widget: new InlineResultWidget(a.id, heightOf(a.id)), block: true, side: 1 }).range( state.doc.lineAt(a.to).to, ), ), true, ), ), }); /** * Keeps the view's in-editor results in step with the store: a run's new results show under * their statements (replacing what those statements showed before), closed ones go away. */ const syncInline = ViewPlugin.define((view) => { const path = view.state.facet(consolePath); let destroyed = false; const sync = () => { if (destroyed) return; const current = view.state.field(inlineField); const tabs = useDatabase.getState().inline.filter((t) => t.path === path); const ids = new Set(tabs.map((t) => t.id)); const known = new Set(current.map((a) => a.id)); const len = view.state.doc.length; const added = tabs .filter((t) => !known.has(t.id)) .map(anchorOf) .filter((a) => a.to <= len); const overlaps = (a: InlineAnchor) => added.some((b) => b.from < a.to && a.from < b.to); const replaced = current.filter((a) => ids.has(a.id) && overlaps(a)).map((a) => a.id); const kept = current.filter((a) => ids.has(a.id) && !replaced.includes(a.id)); for (const a of current) if (!ids.has(a.id)) { anchors.delete(a.id); heights.delete(a.id); } if (!added.length && kept.length === current.length) return; for (const a of added) anchors.set(a.id, { from: a.from, to: a.to }); view.dispatch({ effects: setInline.of([...kept, ...added].sort((a, b) => a.to - b.to || a.id - b.id)) }); if (replaced.length) closeInlineResults(replaced); }; let shown = view.state.field(inlineField); const stop = useDatabase.subscribe((s, prev) => { if (s.inline !== prev.inline) queueMicrotask(sync); }); queueMicrotask(sync); return { // Results whose statements were deleted go too. update(u) { const next = u.state.field(inlineField); if (next === shown) return; const gone = shown.filter((a) => !next.some((b) => b.id === a.id)).map((a) => a.id); shown = next; if (gone.length && u.docChanged) queueMicrotask(() => closeInlineResults(gone)); }, destroy: () => { destroyed = true; stop(); }, }; }); function heightOf(id: number): number { return heights.get(id) ?? fitHeight(useDatabase.getState().inline.find((r) => r.id === id)); } const InlineGrid = lazyComponent(() => import("./ResultsView").then((m) => m.Result)); function InlineResult({ id, view }: { id: number; view: EditorView }) { const tab = useDatabase((s) => s.inline.find((r) => r.id === id)); const [height, setHeight] = useState(() => heightOf(id)); const drag = useRef<{ y: number; height: number } | null>(null); const measured = useRef(height); useEffect(() => { if (measured.current === height) return; measured.current = height; view.dispatch({ effects: resized.of(null) }); }, [height, view]); if (!tab) return null; const onPointerDown = (e: PointerEvent) => { e.preventDefault(); e.currentTarget.setPointerCapture(e.pointerId); drag.current = { y: e.clientY, height }; }; const onPointerMove = (e: PointerEvent) => { if (!drag.current) return; const next = Math.max(MIN_HEIGHT, Math.round(drag.current.height + e.clientY - drag.current.y)); heights.set(id, next); setHeight(next); }; return (
closeInlineResults([id])} />
(drag.current = null)} />
); } const inlineRoots = new WeakMap>(); class InlineResultWidget extends WidgetType { constructor( readonly id: number, readonly height: number, ) { super(); } eq(other: InlineResultWidget) { return other.id === this.id && other.height === this.height; } /** A resized result keeps its DOM (and grid state); only the editor's measurement changes. */ updateDOM(dom: HTMLElement) { return dom.dataset.result === String(this.id); } get estimatedHeight() { return this.height + 12; } toDOM(view: EditorView) { const dom = document.createElement("div"); dom.className = "cm-openidea-db-inline"; dom.contentEditable = "false"; dom.dataset.result = String(this.id); const root = createRoot(dom); inlineRoots.set(dom, root); root.render(); return dom; } destroy(dom: HTMLElement) { const root = inlineRoots.get(dom); inlineRoots.delete(dom); queueMicrotask(() => root?.unmount()); } ignoreEvent() { return true; } } function ConsoleBar({ path, view }: { path: string; view: EditorView }) { const sources = useDatabase((s) => s.sources); const loaded = useDatabase((s) => s.loaded); const bound = useDatabase(() => consoleSource(path)); const running = useDatabase((s) => !!s.running[path]); const maxRows = useDatabase((s) => s.maxRows); const manual = useDatabase((s) => !!bound && s.manualCommit.has(bound)); const pending = useDatabase((s) => !!bound && s.pendingTx.has(bound)); const inEditor = useProject((s) => inEditorResults(s.settings)); // SQL resolution scopes in the settings can move the console to another data source. useProject((s) => s.settings); const boundId = bound ? splitTarget(bound).id : null; const driver = sources.find((s) => s.id === boundId)?.driver; const jdbc = driver === "jdbc"; const supportsTransactions = driver !== "clickhouse" && !jdbc; const switchable = schemaSwitchable(driver); // The console's active schema: its pick, else the connection's default (`completion.defaultSchema`). const pickedSchema = useDatabase((s) => s.consoleSchemas[path]); const defaultSchema = useDatabase((s) => (bound ? s.completion[bound]?.defaultSchema : undefined)); const schemaList = useDatabase((s) => (bound ? s.schemas[bound] : undefined)); const preloadMetadata = useDatabase((s) => !!bound && allowsPassiveConsoleMetadata(bound, s.pausedConsoleMetadata)); const schema = activeSchema(pickedSchema, defaultSchema); useEffect(() => { if ( preloadMetadata && boundId && allowsPassiveConsoleMetadata(boundId) && listsDatabases(sourceById(boundId)) && !useDatabase.getState().databases[boundId] ) void loadDatabases(boundId); }, [boundId, preloadMetadata]); // Loads the list again after a refresh drops it. const schemasMissing = !schemaList; useEffect(() => { if (preloadMetadata && bound && allowsPassiveConsoleMetadata(bound) && switchable && schemasMissing) void loadSchemas(bound); }, [bound, preloadMetadata, switchable, schemasMissing]); const schemaOptions = useMemo(() => { if (!switchable) return []; const names = schemaList?.status === "ok" ? schemaList.value : []; const out = names.map((n) => ({ value: n, label: n, verbatim: true, icon: "db-schema" })); // The connection's default is offered even before its schema list loads. if (defaultSchema && !names.includes(defaultSchema)) out.unshift({ value: defaultSchema, label: defaultSchema, verbatim: true, icon: "db-schema" }); return out; }, [switchable, schemaList, defaultSchema]); // IDEA's order: pick the data source, then a database and a schema in it. const sourceOptions = useMemo( () => sources.map((s) => ({ value: s.id ?? "", label: s.name ?? "", verbatim: true, detail: sourceLabel(s).slice((s.name ?? "").length + 1), icon: sourceIcon(s), })), [sources], ); useEffect(() => { if (!loaded) void loadSources(); }, [loaded]); useEffect(() => { if (preloadMetadata && bound && allowsPassiveConsoleMetadata(bound)) void loadCompletion(bound); }, [bound, preloadMetadata]); return ( void executeInView(view, path)} /> void executeScriptInView(view, path)} /> openHistory(path)} /> {!jdbc && ( void explainInView(view, path)} /> )} void setInEditorResults(!inEditor)} /> {supportsTransactions && ( ({ value: v, label: tx`${Number(v).toLocaleString("en")} rows` }))} onChange={(v) => useDatabase.setState({ maxRows: Number(v) })} /> {bound && driver === "snowflake" && } { if (bound && !useDatabase.getState().schemas[bound]) void loadSchemas(bound); }} onChange={(v) => setConsoleSchema(path, v)} disabled={!bound} /> ) )} {driver === "sqlite" && ( {schema || "main"} )} ); } /** * The `database.schema` switcher of a data source that shows several databases (IDEA's): a tree of * its databases, expanding to their schemas. Choosing a schema in another database moves the console there. */ function DatabaseSchemaSwitcher({ path, bound, sourceId, schema, }: { path: string; bound: string; sourceId: string; schema: string; }) { const listed = useDatabase((s) => s.databases[sourceId]); const schemas = useDatabase((s) => s.schemas); const read = useDatabase((s) => s.catalogs[sourceId]?.databases); const paused = useDatabase((s) => s.pausedConsoleMetadata); const current = listed?.status === "ok" ? listed.value.current : null; const database = splitTarget(bound).database ?? current; // The console's database starts expanded, again whenever the console moves to another one. const [opened, setOpened] = useState<{ at: string | null; open: ReadonlySet } | null>(null); const expanded = useMemo( () => (opened && opened.at === database ? opened.open : new Set(database ? [database] : [])), [opened, database], ); const targetFor = (name: string) => (name === database ? bound : targetOf(sourceId, name, current)); // Schemas of expanded databases that are not read yet, or were dropped by a refresh. const missing = [...expanded] .filter((name) => !read?.[name]) .map(targetFor) .filter((target) => !schemas[target] && allowsPassiveConsoleMetadata(target, paused)) .join("\n"); useEffect(() => { for (const target of missing ? missing.split("\n") : []) { if (allowsPassiveConsoleMetadata(target) && !useDatabase.getState().schemas[target]) void loadSchemas(target); } }, [missing]); const rows = useMemo(() => { const names = listed?.status === "ok" ? [...listed.value.names] : []; // The console's database is offered even before the list loads. if (database && !names.includes(database)) names.unshift(database); return schemaTreeRows(names, expanded, (name) => { const target = name === database ? bound : targetOf(sourceId, name, current); const list = schemas[target]; if (list?.status === "ok") return list.value; if (read?.[name]) return read[name].map((s) => s.name); return list?.status === "error" ? { error: list.message } : undefined; }); }, [listed, database, expanded, schemas, read, bound, sourceId, current]); const value = database && schema ? schemaTreeValue(database, schema) : null; return ( 10} onChange={(v) => void use("WAREHOUSE", v)} disabled={!idle} />