mirror of
https://github.com/l0ng-ai/openidea.git
synced 2026-11-22 09:39:27 -10:00
Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c7c9826a0a | ||
|
|
d9fa1169b6 |
No files matched your search
@@ -71,6 +71,8 @@ pub struct Settings {
|
||||
pub scopes: Vec<NamedScope>,
|
||||
/// Appearance & Behavior › File Colors.
|
||||
pub file_colors: FileColorSettings,
|
||||
/// Database › Query Execution.
|
||||
pub database: DatabaseSettings,
|
||||
/// Plugin settings (`[contributes.settings]`): plugin id → its values by key.
|
||||
#[specta(type = BTreeMap<String, BTreeMap<String, specta_typescript::Unknown>>)]
|
||||
pub plugins: BTreeMap<String, serde_json::Map<String, serde_json::Value>>,
|
||||
@@ -508,6 +510,7 @@ impl Default for Settings {
|
||||
agent_security: AgentSecuritySettings::default(),
|
||||
scopes: Vec::new(),
|
||||
file_colors: FileColorSettings::default(),
|
||||
database: DatabaseSettings::default(),
|
||||
plugins: BTreeMap::new(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -241,6 +241,15 @@ impl Default for LogLevelColors {
|
||||
}
|
||||
}
|
||||
|
||||
/// Database › Query Execution.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct DatabaseSettings {
|
||||
/// A console's result sets show under the statements that produced them, in the editor,
|
||||
/// instead of in the Services view's result tabs.
|
||||
pub in_editor_results: bool,
|
||||
}
|
||||
|
||||
/// Build, Execution, Deployment › Console.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
|
||||
@@ -3862,6 +3862,15 @@ export type DataSource_Serialize = {
|
||||
pluginSourceId?: string | null,
|
||||
};
|
||||
|
||||
/** Database › Query Execution. */
|
||||
export type DatabaseSettings = {
|
||||
/**
|
||||
* A console's result sets show under the statements that produced them, in the editor,
|
||||
* instead of in the Services view's result tabs.
|
||||
*/
|
||||
inEditorResults?: boolean,
|
||||
};
|
||||
|
||||
/** System Settings › Date Formats (Git log, Local History, blame). */
|
||||
export type DateFormatSettings = {
|
||||
/** Use `pattern` / `use24_hour` instead of the system locale's format. */
|
||||
@@ -9938,6 +9947,8 @@ export type Settings_Deserialize = {
|
||||
scopes?: NamedScope[],
|
||||
/** Appearance & Behavior › File Colors. */
|
||||
fileColors?: FileColorSettings,
|
||||
/** Database › Query Execution. */
|
||||
database?: DatabaseSettings,
|
||||
/** Plugin settings (`[contributes.settings]`): plugin id → its values by key. */
|
||||
plugins?: { [key in string]: { [key in string]: unknown } },
|
||||
};
|
||||
@@ -10008,6 +10019,8 @@ export type Settings_Serialize = {
|
||||
scopes: NamedScope[],
|
||||
/** Appearance & Behavior › File Colors. */
|
||||
fileColors: FileColorSettings,
|
||||
/** Database › Query Execution. */
|
||||
database: DatabaseSettings,
|
||||
/** Plugin settings (`[contributes.settings]`): plugin id → its values by key. */
|
||||
plugins: { [key in string]: { [key in string]: unknown } },
|
||||
};
|
||||
|
||||
@@ -1407,3 +1407,33 @@
|
||||
color: inherit;
|
||||
cursor: default;
|
||||
}
|
||||
|
||||
/* In-Editor Results: a result set under its statement in the console. */
|
||||
:global(.cm-openidea-db-inline) {
|
||||
padding: var(--space-1) 0 var(--space-2);
|
||||
cursor: default;
|
||||
}
|
||||
.inlineResult {
|
||||
position: relative;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
max-width: 100%;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius-control);
|
||||
overflow: hidden;
|
||||
background: var(--bg-editor);
|
||||
font-family: var(--font-ui);
|
||||
font-size: var(--fs-ui);
|
||||
line-height: normal;
|
||||
white-space: normal;
|
||||
}
|
||||
.inlineResult > :first-child {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
}
|
||||
.inlineResize {
|
||||
position: absolute;
|
||||
inset: auto 0 0;
|
||||
height: 5px;
|
||||
cursor: row-resize;
|
||||
}
|
||||
@@ -254,7 +254,8 @@ function setSubmittingResult(result: DbQueryResult, on: boolean) {
|
||||
notifyResults();
|
||||
}
|
||||
|
||||
function Result({ tab }: { tab: ResultTab }) {
|
||||
/** A result set's toolbar, grid and pager; `onClose` makes it an in-editor result (closed in place, not pinned). */
|
||||
export function Result({ tab, onClose }: { tab: ResultTab; onClose?: () => void }) {
|
||||
const [view, setView] = useState<"table" | "chart">("table");
|
||||
const [panel, setPanel] = useState<DataPanel | null>(null);
|
||||
const [searchOpen, setSearchOpen] = useState(false);
|
||||
@@ -516,7 +517,7 @@ function Result({ tab }: { tab: ResultTab }) {
|
||||
disabled={busy}
|
||||
onClick={() => void rerunResult(tab.id)}
|
||||
/>
|
||||
<PinButton tab={tab} />
|
||||
{!onClose && <PinButton tab={tab} />}
|
||||
{view === "table" && (
|
||||
<IconButton
|
||||
icon="search"
|
||||
@@ -568,6 +569,7 @@ function Result({ tab }: { tab: ResultTab }) {
|
||||
onClick={(e) => showExport({ x: e.clientX, y: e.clientY })}
|
||||
/>
|
||||
{view === "table" && <PanelToggle panel={panel} onChange={setPanel} />}
|
||||
{onClose && <IconButton icon="close" title="Close" onClick={onClose} />}
|
||||
</Toolbar>
|
||||
{view === "chart" ? (
|
||||
<div className={styles.fill}>
|
||||
|
||||
@@ -39,13 +39,14 @@ import {
|
||||
type Panel,
|
||||
type Tooltip,
|
||||
} from "@codemirror/view";
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
import { useEffect, useMemo, useRef, useState, type PointerEvent } from "react";
|
||||
import { createRoot } from "react-dom/client";
|
||||
import type { EditorDocContext } from "@/editor/api";
|
||||
import { iconNode } from "@/ui/iconNode";
|
||||
import { call, commands, type DbDriver, type DbSessionContext, type DbStatementOutcome } from "@/platform/ipc";
|
||||
import { shortcutLabel } from "@/platform/keymap";
|
||||
import { IconButton, Select } from "@/ui";
|
||||
import { IconButton, Select, lazyComponent } from "@/ui";
|
||||
import { useProject } from "@/platform/project";
|
||||
import { activeSchema, schemaSwitchable, sourceLabel, splitTarget, targetOf } from "./model";
|
||||
import { loadSavedCatalog, offerIntrospection } from "./introspection";
|
||||
import { analyze, templateContexts, valuesSlot } from "./sql/analyze";
|
||||
@@ -61,6 +62,9 @@ import { snowflakeLanguage } from "./sql/snowflakeHighlight";
|
||||
import {
|
||||
bindConsole,
|
||||
cancelConsole,
|
||||
closeInlineResults,
|
||||
inEditorResults,
|
||||
setInEditorResults,
|
||||
consoleSchema,
|
||||
consoleSource,
|
||||
executeConsole,
|
||||
@@ -84,6 +88,7 @@ import {
|
||||
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";
|
||||
@@ -252,6 +257,213 @@ export async function explainInView(view: EditorView, path: string) {
|
||||
|
||||
const consolePath = Facet.define<string, string>({ combine: (v) => v[0] ?? "" });
|
||||
|
||||
/** 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<number, { from: number; to: number }>();
|
||||
const heights = new Map<number, number>();
|
||||
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<InlineAnchor[]>();
|
||||
/** An in-editor result was resized: its widget is redrawn so the editor measures it again. */
|
||||
const resized = StateEffect.define<null>();
|
||||
|
||||
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<readonly InlineAnchor[]>({
|
||||
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<HTMLDivElement>) => {
|
||||
e.preventDefault();
|
||||
e.currentTarget.setPointerCapture(e.pointerId);
|
||||
drag.current = { y: e.clientY, height };
|
||||
};
|
||||
const onPointerMove = (e: PointerEvent<HTMLDivElement>) => {
|
||||
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 (
|
||||
<div className={styles.inlineResult} style={{ height }}>
|
||||
<InlineGrid tab={tab} onClose={() => closeInlineResults([id])} />
|
||||
<div
|
||||
className={styles.inlineResize}
|
||||
role="separator"
|
||||
aria-orientation="horizontal"
|
||||
aria-label={tx("Resize")}
|
||||
onPointerDown={onPointerDown}
|
||||
onPointerMove={onPointerMove}
|
||||
onPointerUp={() => (drag.current = null)}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const inlineRoots = new WeakMap<HTMLElement, ReturnType<typeof createRoot>>();
|
||||
|
||||
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(<InlineResult id={this.id} view={view} />);
|
||||
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);
|
||||
@@ -261,6 +473,7 @@ function ConsoleBar({ path, view }: { path: string; view: EditorView }) {
|
||||
const manual = useDatabase((s) => !!bound && s.manualCommit.has(bound));
|
||||
const pending = useDatabase((s) => !!bound && s.pendingTx.has(bound));
|
||||
const databases = useDatabase((s) => s.databases);
|
||||
const inEditor = useProject((s) => inEditorResults(s.settings));
|
||||
const boundId = bound ? splitTarget(bound).id : null;
|
||||
const supportsTransactions = sourceById(boundId)?.driver !== "clickhouse";
|
||||
const sqlServer = sourceById(boundId)?.driver === "sqlServer";
|
||||
@@ -348,6 +561,12 @@ function ConsoleBar({ path, view }: { path: string; view: EditorView }) {
|
||||
/>
|
||||
<span className={styles.toolbarSeparator} />
|
||||
<IconButton icon="history" title="Browse Query History" disabled={!bound} onClick={() => openHistory(path)} />
|
||||
<IconButton
|
||||
icon="db-in-editor-results"
|
||||
title="In-Editor Results"
|
||||
aria-pressed={inEditor}
|
||||
onClick={() => void setInEditorResults(!inEditor)}
|
||||
/>
|
||||
<span className={styles.toolbarSeparator} />
|
||||
<Select
|
||||
aria-label="Row limit"
|
||||
@@ -779,6 +998,8 @@ export function consoleExtension(ctx: EditorDocContext): Extension {
|
||||
consolePath.of(ctx.path),
|
||||
runField,
|
||||
runGutter,
|
||||
inlineField,
|
||||
syncInline,
|
||||
showPanel.of(consolePanel(ctx.path)),
|
||||
EditorState.languageData.of(() => [
|
||||
{ openideaCompletion: completionSource(ctx.path), [TEMPLATE_CONTEXT_KEY]: templateContextsAt(ctx.path) },
|
||||
|
||||
@@ -0,0 +1,136 @@
|
||||
import { act } from "@testing-library/react";
|
||||
import { EditorState } from "@codemirror/state";
|
||||
import { EditorView } from "@codemirror/view";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { useProject } from "@/platform/project";
|
||||
import { consoleExtension } from "./console";
|
||||
import { SQL_LANGUAGE } from "./sqlLanguage";
|
||||
import { executeConsole, rerunResult, useDatabase } from "./store";
|
||||
|
||||
const backend = vi.hoisted(() => ({ execute: vi.fn(), statements: vi.fn() }));
|
||||
|
||||
vi.mock("@/platform/ipc", async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import("@/platform/ipc")>();
|
||||
return {
|
||||
...actual,
|
||||
commands: { ...actual.commands, dbExecute: backend.execute, dbStatements: backend.statements },
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock("@tanstack/react-virtual", () => ({
|
||||
useVirtualizer: ({ count }: { count: number }) => ({
|
||||
getTotalSize: () => count * 24,
|
||||
getVirtualItems: () => Array.from({ length: count }, (_, index) => ({ index, start: index * 24, key: index })),
|
||||
scrollToIndex: () => {},
|
||||
}),
|
||||
}));
|
||||
|
||||
const PATH = "/p/console.sql";
|
||||
const initial = useDatabase.getState();
|
||||
let runs = 0;
|
||||
|
||||
beforeEach(() => {
|
||||
runs = 0;
|
||||
useProject.setState({
|
||||
project: { name: "p", root: "/p", trusted: true } as never,
|
||||
settings: { database: { inEditorResults: true } } as never,
|
||||
});
|
||||
useDatabase.setState({
|
||||
...initial,
|
||||
loaded: true,
|
||||
sources: [{ id: "pg", name: "Local", driver: "postgres", readOnly: false }],
|
||||
completion: { pg: { defaultSchema: "public", tables: [], foreignKeys: [] } },
|
||||
consoles: { [PATH]: "pg" },
|
||||
results: [],
|
||||
inline: [],
|
||||
});
|
||||
backend.statements.mockImplementation((_id: unknown, text: string, from: number, to: number) => {
|
||||
let at = 0;
|
||||
const all = text.split(";").flatMap((part) => {
|
||||
const start = at + part.length - part.trimStart().length;
|
||||
at += part.length + 1;
|
||||
const st = part.trim();
|
||||
return st ? [{ from: start, to: start + st.length, text: st }] : [];
|
||||
});
|
||||
const picked = from === to ? all.filter((s) => s.from <= from && from <= s.to + 1) : all;
|
||||
return Promise.resolve({ status: "ok", data: picked });
|
||||
});
|
||||
backend.execute.mockImplementation((_r: unknown, _id: unknown, statements: Array<{ text: string }>) => {
|
||||
runs++;
|
||||
return Promise.resolve({
|
||||
status: "ok",
|
||||
data: statements.map((st) => ({
|
||||
statement: st,
|
||||
result: {
|
||||
statement: st.text,
|
||||
columns: [{ name: "v", typeName: "text" }],
|
||||
rows: [[`${st.text} #${runs}`]],
|
||||
affected: null,
|
||||
hasMore: false,
|
||||
elapsedMs: 1,
|
||||
executionMs: 1,
|
||||
},
|
||||
error: null,
|
||||
})),
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
document.body.innerHTML = "";
|
||||
});
|
||||
|
||||
describe("In-Editor Results", () => {
|
||||
it("keeps a run's result sets out of the result tabs, and re-runs them in place", async () => {
|
||||
await executeConsole(PATH, "SELECT 1; SELECT 2", 0, 18);
|
||||
const st = useDatabase.getState();
|
||||
expect(st.results).toEqual([]);
|
||||
expect(st.inline.map((r) => r.outcome.statement.text)).toEqual(["SELECT 1", "SELECT 2"]);
|
||||
const id = st.inline[0]!.id;
|
||||
await rerunResult(id);
|
||||
expect(useDatabase.getState().inline[0]!.outcome.result!.rows).toEqual([["SELECT 1 #2"]]);
|
||||
expect(useDatabase.getState().inline[0]!.id).toBe(id);
|
||||
});
|
||||
|
||||
it("goes to the result tabs while the setting is off", async () => {
|
||||
useProject.setState({ settings: {} as never });
|
||||
await executeConsole(PATH, "SELECT 1", 0, 0);
|
||||
expect(useDatabase.getState().inline).toEqual([]);
|
||||
expect(useDatabase.getState().results).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("shows each result under its statement, replaces it on a re-run and drops it with the statement", async () => {
|
||||
const parent = document.createElement("div");
|
||||
document.body.append(parent);
|
||||
const doc = "SELECT 1;\nSELECT 2;\n";
|
||||
const view = new EditorView({
|
||||
parent,
|
||||
state: EditorState.create({
|
||||
doc,
|
||||
extensions: consoleExtension({ language: SQL_LANGUAGE, path: PATH } as never),
|
||||
}),
|
||||
});
|
||||
const widgets = () => [...view.dom.querySelectorAll(".cm-openidea-db-inline")];
|
||||
const ids = () => useDatabase.getState().inline.map((r) => r.id);
|
||||
|
||||
await act(async () => void (await executeConsole(PATH, view.state.doc.toString(), 0, doc.length)));
|
||||
await act(async () => {});
|
||||
expect(widgets()).toHaveLength(2);
|
||||
const [first, second] = ids();
|
||||
|
||||
// Running the first statement again replaces only its own result.
|
||||
await act(async () => void (await executeConsole(PATH, view.state.doc.toString(), 0, 0)));
|
||||
await act(async () => {});
|
||||
expect(ids()).toHaveLength(2);
|
||||
expect(ids()).toContain(second);
|
||||
expect(ids()).not.toContain(first);
|
||||
expect(widgets()).toHaveLength(2);
|
||||
|
||||
// Deleting the second statement closes its result.
|
||||
await act(async () => view.dispatch({ changes: { from: 10, to: 19 } }));
|
||||
await act(async () => {});
|
||||
expect(ids()).not.toContain(second);
|
||||
expect(widgets()).toHaveLength(1);
|
||||
view.destroy();
|
||||
});
|
||||
});
|
||||
@@ -39,6 +39,8 @@ import {
|
||||
RESULTS_VIEW,
|
||||
consoleSource,
|
||||
consoleTints,
|
||||
inEditorResults,
|
||||
setInEditorResults,
|
||||
loadSources,
|
||||
connect,
|
||||
loadSchemas,
|
||||
@@ -135,6 +137,7 @@ export function activate(): () => void {
|
||||
objects: {},
|
||||
completion: {},
|
||||
results: [],
|
||||
inline: [],
|
||||
output: [],
|
||||
activeResult: null,
|
||||
selectedSource: null,
|
||||
@@ -262,6 +265,16 @@ export function activate(): () => void {
|
||||
await (await import("./console")).executeInView(e.view, e.ctx.path);
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "db.toggleInEditorResults",
|
||||
title: "In-Editor Results",
|
||||
description: "Show query results in the editor, under the statements that produced them",
|
||||
category: "Tools",
|
||||
icon: "db-in-editor-results",
|
||||
keywords: ["inline", "results", "console", "grid"],
|
||||
toggled: () => inEditorResults(),
|
||||
run: () => setInEditorResults(!inEditorResults()),
|
||||
},
|
||||
{
|
||||
id: "db.executeScript",
|
||||
title: "Execute SQL Script",
|
||||
|
||||
@@ -87,6 +87,18 @@ export interface ResultTab {
|
||||
total?: number | null;
|
||||
/** Kept when the console runs again (Pin Tab); results otherwise replace the console's last ones. */
|
||||
pinned?: boolean;
|
||||
/** Shown in the editor under its statement (In-Editor Results), not as a result tab. */
|
||||
inline?: boolean;
|
||||
}
|
||||
|
||||
/** Database › In-Editor Results: result sets show under their statements instead of in result tabs. */
|
||||
export function inEditorResults(settings: unknown = useProject.getState().settings): boolean {
|
||||
return (settings as { database?: { inEditorResults?: unknown } } | null)?.database?.inEditorResults === true;
|
||||
}
|
||||
|
||||
export async function setInEditorResults(on: boolean): Promise<void> {
|
||||
const settings = await call(commands.settingsSet("global", "database.inEditorResults", JSON.stringify(on)));
|
||||
useProject.setState({ settings });
|
||||
}
|
||||
|
||||
/** One line of the consoles' Output log (IDEA's Database Console output). */
|
||||
@@ -167,6 +179,8 @@ interface DatabaseState {
|
||||
separateProceduresAndFunctions: boolean;
|
||||
completion: Record<string, DbCompletion>;
|
||||
results: ResultTab[];
|
||||
/** Results shown in the editor under their statements (In-Editor Results), oldest first. */
|
||||
inline: ResultTab[];
|
||||
/** Result tab id, or `OUTPUT_TAB`. */
|
||||
activeResult: number | null;
|
||||
output: OutputLine[];
|
||||
@@ -234,6 +248,7 @@ export const useDatabase = create<DatabaseState>(() => ({
|
||||
separateProceduresAndFunctions: readSeparateProceduresAndFunctions(),
|
||||
completion: {},
|
||||
results: [],
|
||||
inline: [],
|
||||
activeResult: null,
|
||||
output: [],
|
||||
running: {},
|
||||
@@ -1141,6 +1156,10 @@ export async function executeConsole(
|
||||
const title = index === 1 ? tx`Result ${n}` : tx`Result ${n}-${index}`;
|
||||
return { id: nextTab++, title, path, sourceId: id, schema, outcome, page: 0, pageSize };
|
||||
});
|
||||
if (inEditorResults()) {
|
||||
useDatabase.setState((s) => ({ inline: [...s.inline, ...tabs.map((t) => ({ ...t, inline: true }))] }));
|
||||
return outcomes;
|
||||
}
|
||||
const failed = outcomes.some((o) => o.error);
|
||||
useDatabase.setState((s) => ({
|
||||
results: replaceResults(s.results, path, tabs),
|
||||
@@ -1282,7 +1301,7 @@ export async function openObjectDdl(id: string, schema: string, kind: DbObjectKi
|
||||
|
||||
/** Re-runs the statement of result tab `tabId`, replacing its rows (a plan tab explains it again). */
|
||||
export async function rerunResult(tabId: number): Promise<void> {
|
||||
const tab = useDatabase.getState().results.find((r) => r.id === tabId);
|
||||
const tab = findResult(tabId);
|
||||
if (!tab || tab.busy) return;
|
||||
if (tab.plan) {
|
||||
patchResult(tabId, { busy: true });
|
||||
@@ -1305,8 +1324,16 @@ export function pageable(tab: ResultTab): boolean {
|
||||
return !tab.plan && isReadOnlyQuery(tab.outcome.statement.text, sourceById(tab.sourceId)?.driver ?? "sqlite");
|
||||
}
|
||||
|
||||
/** Result tab `tabId`, in the Services view or in an editor. */
|
||||
export function findResult(tabId: number): ResultTab | undefined {
|
||||
const st = useDatabase.getState();
|
||||
return st.results.find((r) => r.id === tabId) ?? st.inline.find((r) => r.id === tabId);
|
||||
}
|
||||
|
||||
function patchResult(tabId: number, p: Partial<ResultTab>) {
|
||||
useDatabase.setState((s) => ({ results: s.results.map((r) => (r.id === tabId ? { ...r, ...p } : r)) }));
|
||||
const patch = (list: ResultTab[]) =>
|
||||
list.some((r) => r.id === tabId) ? list.map((r) => (r.id === tabId ? { ...r, ...p } : r)) : list;
|
||||
useDatabase.setState((s) => ({ results: patch(s.results), inline: patch(s.inline) }));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -1315,7 +1342,7 @@ function patchResult(tabId: number, p: Partial<ResultTab>) {
|
||||
* `rerun` also forgets the counted total.
|
||||
*/
|
||||
export async function loadResultPage(tabId: number, page: number, pageSize: number, rerun = false): Promise<void> {
|
||||
const tab = useDatabase.getState().results.find((r) => r.id === tabId);
|
||||
const tab = findResult(tabId);
|
||||
if (!tab || tab.busy || tab.plan) return;
|
||||
if (page > 0 && !pageable(tab)) return;
|
||||
patchResult(tabId, { busy: true });
|
||||
@@ -1363,7 +1390,7 @@ export function countable(tab: ResultTab): boolean {
|
||||
|
||||
/** Counts the rows of result tab `tabId`'s whole query (the pager's "of 501+"). */
|
||||
export async function countResult(tabId: number): Promise<number | null> {
|
||||
const tab = useDatabase.getState().results.find((r) => r.id === tabId);
|
||||
const tab = findResult(tabId);
|
||||
if (!tab || tab.busy || !countable(tab)) return null;
|
||||
const text = countQuery(tab.outcome.statement.text)!;
|
||||
patchResult(tabId, { busy: true });
|
||||
@@ -1468,6 +1495,12 @@ export function closeResult(id: number) {
|
||||
});
|
||||
}
|
||||
|
||||
/** Closes in-editor results `ids`. */
|
||||
export function closeInlineResults(ids: readonly number[]) {
|
||||
if (!ids.length) return;
|
||||
useDatabase.setState((s) => ({ inline: s.inline.filter((r) => !ids.includes(r.id)) }));
|
||||
}
|
||||
|
||||
export function pinResult(id: number, pinned: boolean) {
|
||||
patchResult(id, { pinned });
|
||||
}
|
||||
@@ -63,6 +63,8 @@ export interface ValidSettings extends WorkflowSettings {
|
||||
plugins: Record<string, Record<string, unknown>>;
|
||||
scopes: NamedScope[];
|
||||
fileColors: FileColorSettings;
|
||||
/** Database › Query Execution. */
|
||||
database: { inEditorResults: boolean };
|
||||
general: {
|
||||
reopenLastProject: boolean;
|
||||
confirmExit: boolean;
|
||||
@@ -165,6 +167,7 @@ export const DEFAULT_SETTINGS: ValidSettings = {
|
||||
plugins: {},
|
||||
scopes: [],
|
||||
fileColors: DEFAULT_FILE_COLORS,
|
||||
database: { inEditorResults: false },
|
||||
general: {
|
||||
reopenLastProject: true,
|
||||
confirmExit: true,
|
||||
@@ -340,6 +343,7 @@ export function validateSettings(raw: Settings | unknown): ValidSettings {
|
||||
plugins: Object.fromEntries(Object.entries(obj(root.plugins)).map(([id, values]) => [id, obj(values)])),
|
||||
scopes: validateScopes(root.scopes),
|
||||
fileColors: validateFileColors(root.fileColors),
|
||||
database: { inEditorResults: bool(obj(root.database).inEditorResults, d.database.inEditorResults) },
|
||||
general: {
|
||||
...validateGeneralExtras(g),
|
||||
reopenLastProject: bool(g.reopenLastProject, d.general.reopenLastProject),
|
||||
|
||||
@@ -1969,5 +1969,7 @@
|
||||
"file:src//*.ts && !file:*.test.ts — paths are relative to the project; // is any folders, * any characters. file[module]:pattern limits a pattern to a module.": "file:src//*.ts && !file:*.test.ts — paths are relative to the project; // is any folders, * any characters. file[module]:pattern limits a pattern to a module.",
|
||||
"Clear File Color": "Clear File Color",
|
||||
"Edit File Colors…": "Edit File Colors…",
|
||||
"Enable system notifications": "Enable system notifications"
|
||||
"Enable system notifications": "Enable system notifications",
|
||||
"In-Editor Results": "In-Editor Results",
|
||||
"Show query results in the editor, under the statements that produced them": "Show query results in the editor, under the statements that produced them"
|
||||
}
|
||||
@@ -8361,5 +8361,7 @@
|
||||
"file:src//*.ts && !file:*.test.ts — paths are relative to the project; // is any folders, * any characters. file[module]:pattern limits a pattern to a module.": "file:src//*.ts && !file:*.test.ts —— 路径相对于项目;// 表示任意层文件夹,* 表示任意字符。file[module]:pattern 将模式限定在某个模块内。",
|
||||
"Clear File Color": "清除文件颜色",
|
||||
"Edit File Colors…": "编辑文件颜色…",
|
||||
"Enable system notifications": "启用系统通知"
|
||||
"Enable system notifications": "启用系统通知",
|
||||
"In-Editor Results": "编辑器内结果",
|
||||
"Show query results in the editor, under the statements that produced them": "在编辑器中、产生结果的语句下方显示查询结果"
|
||||
}
|
||||
@@ -383,6 +383,7 @@ const ICONS = {
|
||||
"db-sequence": "openidea/database/sequence",
|
||||
"db-plan": "openidea/database/plan",
|
||||
"db-chart": "openidea/database/chart",
|
||||
"db-in-editor-results": "openidea/database/inEditorResults",
|
||||
"db-sort": "openidea/database/sort",
|
||||
"db-folder": "openidea/database/folder",
|
||||
"db-add": "openidea/database/addDropdown",
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
<!-- OpenIDEA: in-editor results (text lines over a result grid) -->
|
||||
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<path d="M2.5 2.5H10.5M2.5 5H7.5" stroke="#6C707E" stroke-linecap="round"/><rect x="2.5" y="7.5" width="11" height="6" rx="1" stroke="#6C707E"/><path d="M2.5 10.5H13.5M6.5 7.5V13.5" stroke="#6C707E"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 373 B |
Reference in new issue
Block a user