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
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,7 @@
"pinia": "^3.0.4",
"pinia-plugin-persistedstate": "^4.7.1",
"pretty-bytes": "^7.1.0",
"sql-formatter": "^9.0.0",
"vue": "^3.5.35",
"vue-router": "5.0.7",
"xterm-theme": "^1.1.0",
Expand Down
11 changes: 11 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

31 changes: 30 additions & 1 deletion ui/chen/api/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import type { ChenActionItem, ChenAuthResponse, ChenProfile, ChenTreeNode } from "~/chen/types";
import type { ChenActionItem, ChenAuthResponse, ChenProfile, ChenSqlHints, ChenTreeNode } from "~/chen/types";

const buildHeaders = (token?: string, init?: HeadersInit) => ({
...getWebApiHeaders(),
Expand Down Expand Up @@ -68,6 +68,35 @@ export async function uploadChenSqlFile(
return { path: result.path };
}

export async function fetchChenSqlHints(
chenToken: string,
nodeKey: string,
context: string,
fetchImpl: typeof fetch = fetch
): Promise<ChenSqlHints> {
const response = await fetchImpl(chenPath("/api/resources/hints"), {
method: "POST",
credentials: "include",
headers: {
...buildHeaders(chenToken, getWebApiMutationHeaders()),
"Content-Type": "application/json"
},
body: JSON.stringify({ nodeKey, context })
});
const result = await readJson<unknown>(response);
if (!result || typeof result !== "object" || Array.isArray(result)) {
throw new Error("Chen returned malformed SQL hints");
}

return Object.fromEntries(
Object.entries(result)
.filter((entry): entry is [string, string[]] => (
Array.isArray(entry[1]) && entry[1].every((column) => typeof column === "string")
))
.map(([table, columns]) => [table, [...columns]])
);
}

export function sanitizeChenExportFileName(value: string, fallback = "chen-export") {
const withoutControls = Array.from(value)
.filter((character) => {
Expand Down
57 changes: 55 additions & 2 deletions ui/chen/components/QueryConsolePanel.vue
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import ChenSqlEditor from "~/chen/components/SqlEditor.client.vue";
import SqlSnippetSaveDialog from "~/chen/components/SqlSnippetSaveDialog.vue";
import SqlSnippetSelectDialog from "~/chen/components/SqlSnippetSelectDialog.vue";
import { useChenSqlSnippets } from "~/chen/composables/useChenSqlSnippets";
import { formatChenSql } from "~/chen/utils/sqlFormat";

const props = defineProps<{
tab: ChenQueryConsoleTab
Expand All @@ -17,6 +18,7 @@ const props = defineProps<{
const emit = defineEmits<{
run: [tab: ChenQueryConsoleTab, selectedSql: string]
cancel: [tab: ChenQueryConsoleTab]
changeContext: [tab: ChenQueryConsoleTab, context: string]
uploadSql: [tab: ChenQueryConsoleTab, file: File]
dataViewAction: [tab: ChenQueryConsoleTab, result: ChenQueryResultTab, action: ChenDataViewAction, data?: ChenDataViewActionData]
dismissMessage: [tab: ChenQueryConsoleTab]
Expand All @@ -25,7 +27,10 @@ const emit = defineEmits<{
closeResult: [tab: ChenQueryConsoleTab, title: string]
}>();

const sqlEditor = ref<{ selectedText: () => string } | null>(null);
const sqlEditor = ref<{
replaceDocument: (value: string) => void
selectedText: () => string
} | null>(null);
const sqlUploadInput = ref<HTMLInputElement | null>(null);
const hasSelection = ref(false);
const messageOpen = ref(false);
Expand All @@ -36,6 +41,13 @@ let messageCloseTimer: ReturnType<typeof setTimeout> | null = null;
const toast = useToast();
const sqlSnippets = useChenSqlSnippets(() => props.dbType);
const queryBusy = computed(() => Boolean(props.tab.state.loading || props.tab.state.inQuery));
const contextBusy = computed(() => Boolean(queryBusy.value || props.tab.state.editorLoading));
const contextItems = computed(() => (props.tab.state.contexts || []).map((context) => ({
label: context,
icon: context === props.tab.state.currentContext ? "i-lucide-check" : undefined,
disabled: contextBusy.value || context === props.tab.state.currentContext,
onSelect: () => emit("changeContext", props.tab, context)
})));

const messageColor = computed(() => {
if (props.tab.message?.type === "error") return "error";
Expand All @@ -52,6 +64,22 @@ function runSelectedQuery() {
emit("run", props.tab, sqlEditor.value?.selectedText() || "");
}

function formatStatement() {
if (contextBusy.value) return;
const original = props.tab.statement;
try {
const formatted = formatChenSql(original, props.dbType);
if (formatted === original) return;
sqlEditor.value?.replaceDocument(formatted);
} catch (cause) {
toast.add({
title: "SQL format failed",
description: requestErrorMessage(cause),
color: "error"
});
}
}

function requestErrorMessage(cause: unknown) {
return cause instanceof Error ? cause.message : String(cause);
}
Expand Down Expand Up @@ -185,6 +213,15 @@ onBeforeUnmount(clearMessageTimer);
:disabled="!tab.state.canCancel"
@click="emit('cancel', tab)"
/>
<UButton
size="sm"
color="neutral"
variant="soft"
:disabled="contextBusy"
@click="formatStatement"
>
Format
</UButton>
<UButton
icon="i-lucide-folder-open"
size="sm"
Expand Down Expand Up @@ -223,14 +260,30 @@ onBeforeUnmount(clearMessageTimer);
>
Upload SQL
</UButton>
<UDropdownMenu :items="contextItems">
<UButton
class="ml-auto"
icon="i-lucide-database"
trailing-icon="i-lucide-chevron-down"
size="sm"
color="neutral"
variant="soft"
:disabled="contextBusy || contextItems.length === 0"
>
{{ tab.state.currentContext || "Context" }}
</UButton>
</UDropdownMenu>
</div>
<div class="relative flex min-h-0 flex-1">
<ChenSqlEditor
ref="sqlEditor"
v-model="statementValue"
class="min-h-0 flex-1"
:read-only="Boolean(tab.state.loading)"
:db-type="dbType"
:hints="tab.sqlHints"
:read-only="Boolean(tab.state.loading || tab.state.editorLoading)"
@selection-change="hasSelection = $event"
@format="formatStatement"
@open-snippets="openSnippetDialog"
@run="runSelectedQuery"
@save-snippet="openSaveSnippetDialog"
Expand Down
27 changes: 26 additions & 1 deletion ui/chen/components/SqlEditor.client.vue
Original file line number Diff line number Diff line change
@@ -1,21 +1,28 @@
<script setup lang="ts">
import type { Extension } from "@codemirror/state";
import type { ChenSqlHints } from "~/chen/types";
import { sql } from "@codemirror/lang-sql";
import { Compartment, EditorState, Prec } from "@codemirror/state";
import { EditorView, keymap } from "@codemirror/view";
import { basicSetup } from "codemirror";
import { chenSqlConfig, replaceChenSqlDocument } from "~/chen/utils/sqlEditor";
import { createCodeMirrorSyntaxTheme, createCodeMirrorTheme } from "~/shared/theme/adapters/codemirror";

const props = withDefaults(defineProps<{
modelValue: string
dbType?: string
hints?: ChenSqlHints
readOnly?: boolean
}>(), {
dbType: "",
hints: () => ({}),
readOnly: false
});

const emit = defineEmits<{
"update:modelValue": [value: string]
selectionChange: [hasSelection: boolean]
format: []
openSnippets: []
run: []
saveSnippet: []
Expand All @@ -26,16 +33,24 @@ const colorMode = useColorMode();
const container = ref<HTMLElement | null>(null);
const themeSlot = new Compartment();
const editableSlot = new Compartment();
const sqlLanguageSlot = new Compartment();
let editor: EditorView | null = null;
let applyingExternalValue = false;

const editorExtensions: Extension[] = [
basicSetup,
sql(),
sqlLanguageSlot.of(sql(chenSqlConfig(props.dbType, props.hints))),
createCodeMirrorSyntaxTheme(),
EditorView.lineWrapping,
EditorState.tabSize.of(2),
Prec.highest(keymap.of([
{
key: "Mod-l",
run: () => {
emit("format");
return true;
}
},
{
key: "Ctrl-r",
run: () => {
Expand Down Expand Up @@ -86,6 +101,11 @@ function focus() {
editor?.focus();
}

function replaceDocument(value: string) {
if (!editor) return;
replaceChenSqlDocument(editor, value);
}

onMounted(() => {
if (!container.value) return;
editor = new EditorView({
Expand All @@ -112,6 +132,10 @@ watch(() => props.readOnly, (value) => {
editor?.dispatch({ effects: editableSlot.reconfigure(EditorView.editable.of(!value)) });
});

watch(() => [props.dbType, props.hints] as const, ([dbType, hints]) => {
editor?.dispatch({ effects: sqlLanguageSlot.reconfigure(sql(chenSqlConfig(dbType, hints))) });
});

watch(() => colorMode.value, () => {
editor?.dispatch({ effects: themeSlot.reconfigure(createCodeMirrorTheme()) });
});
Expand All @@ -120,6 +144,7 @@ onBeforeUnmount(() => editor?.destroy());

defineExpose({
focus,
replaceDocument,
selectedText
});
</script>
Expand Down
19 changes: 19 additions & 0 deletions ui/chen/composables/useChenQueryConsole.ts
Original file line number Diff line number Diff line change
Expand Up @@ -159,6 +159,24 @@ export function useChenQueryConsole(
});
}

function changeQueryContext(tab: ChenQueryConsoleTab, context: string) {
if (
tab.state.loading
|| tab.state.inQuery
|| tab.state.editorLoading
|| !context.trim()
|| context === tab.state.currentContext
|| !tab.state.contexts?.includes(context)
) {
return;
}

sendConsoleAction(tab, "query_console_action", {
action: "change_current_context",
data: context
});
}

function runConsoleTab(tab: ChenPromptConsoleTab) {
const sql = tab.pendingSql.trim();
if (!sql) return;
Expand All @@ -181,6 +199,7 @@ export function useChenQueryConsole(
return {
appendLog,
cancelQueryLikeTab,
changeQueryContext,
closeQueryResult,
dismissQueryMessage,
handleQueryConsolePacket,
Expand Down
26 changes: 26 additions & 0 deletions ui/chen/composables/useChenSqlHints.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import type { ChenQueryConsoleTab, ChenSqlHints } from "~/chen/types";

export function useChenSqlHints(
fetchHints: (tab: ChenQueryConsoleTab, context: string) => Promise<ChenSqlHints>,
onError: (cause: unknown) => void = () => {}
) {
async function load(tab: ChenQueryConsoleTab, context: string) {
const generation = ++tab.hintsRequestGeneration;
tab.hintsLoading = true;
try {
const hints = await fetchHints(tab, context);
if (generation === tab.hintsRequestGeneration && context === tab.state.currentContext) {
tab.sqlHints = hints;
tab.hintsContext = context;
}
} catch (cause) {
if (generation === tab.hintsRequestGeneration && context === tab.state.currentContext) {
onError(cause);
}
} finally {
if (generation === tab.hintsRequestGeneration) tab.hintsLoading = false;
}
}

return { load };
}
4 changes: 4 additions & 0 deletions ui/chen/composables/useChenWorkspaceTabs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,10 @@ export function useChenWorkspaceTabs() {
nodeKey,
statement: "",
uploadingSql: false,
sqlHints: {},
hintsContext: "",
hintsLoading: false,
hintsRequestGeneration: 0,
state: {},
logs: [],
message: null,
Expand Down
7 changes: 7 additions & 0 deletions ui/chen/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -74,9 +74,12 @@ export interface ChenDataViewDataset {
data: Array<Record<string, any>>
}

export type ChenSqlHints = Record<string, string[]>;

export interface ChenConsoleState {
loading?: boolean
inQuery?: boolean
editorLoading?: boolean
canCancel?: boolean
currentContext?: string
contexts?: string[]
Expand Down Expand Up @@ -114,6 +117,10 @@ export interface ChenQueryConsoleTab extends ChenTabDefinition {
kind: "query"
statement: string
uploadingSql: boolean
sqlHints: ChenSqlHints
hintsContext: string
hintsLoading: boolean
hintsRequestGeneration: number
state: ChenConsoleState
logs: string[]
message: ChenConsoleMessage | null
Expand Down
Loading
Loading