feat(ai): add table mentions

Add table mentions to AI context, Ask/Agent mode selection, and related UI/i18n fixes.
This commit is contained in:
skyler
2026-05-15 16:46:54 +08:00
committed by GitHub
parent 1563173173
commit 0099e1a262
13 changed files with 1150 additions and 49 deletions
+337 -10
View File
@@ -1,5 +1,5 @@
<script setup lang="ts">
import { computed, nextTick, onMounted, ref } from "vue";
import { computed, nextTick, onMounted, onUnmounted, ref } from "vue";
import { uuid } from "@/lib/utils";
import { useI18n } from "vue-i18n";
import { translateBackendError } from "@/i18n/backend-errors";
@@ -17,6 +17,7 @@ import {
MessageSquarePlus,
Replace,
Server,
Table2,
Play,
Square,
Trash2,
@@ -50,12 +51,16 @@ import {
saveAiConversation,
loadAiConversations,
deleteAiConversation,
listSchemas,
listTables,
type AiConversation,
} from "@/lib/api";
import type { AiMessage } from "@/lib/api";
import type { ConnectionConfig, QueryTab } from "@/types/database";
import type { ConnectionConfig, QueryTab, TableInfo } from "@/types/database";
import { useDatabaseOptions } from "@/composables/useDatabaseOptions";
import { resolveDefaultDatabase } from "@/lib/defaultDatabase";
import { isSchemaAware } from "@/lib/databaseCapabilities";
import { formatAiTableMention, parseAiTableMentions, type AiTableMention } from "@/lib/aiTableMentions";
const { t } = useI18n();
const settings = useSettingsStore();
@@ -87,10 +92,29 @@ const messages = ref<ChatMessage[]>([]);
const isGenerating = ref(false);
const scrollRef = ref<InstanceType<typeof ScrollArea> | null>(null);
const activeAction = ref<AiAction>("generate");
const assistantMode = ref<"ask" | "agent">("ask");
const currentSessionId = ref("");
const conversationId = ref("");
const conversations = ref<AiConversation[]>([]);
const showConversationList = ref(false);
const promptTextareaRef = ref<HTMLTextAreaElement | null>(null);
interface AiMentionCandidate {
schema?: string;
name: string;
tableType: string;
}
const mentionOpen = ref(false);
const mentionLoading = ref(false);
const mentionError = ref("");
const mentionStart = ref(0);
const mentionSelectedIndex = ref(0);
const mentionCandidates = ref<AiMentionCandidate[]>([]);
const mentionCache = ref<Record<string, AiMentionCandidate[]>>({});
const selectedMentions = ref<AiTableMention[]>([]);
let mentionTimer: ReturnType<typeof setTimeout> | undefined;
let mentionRequestId = 0;
const actionButtons: { action: AiAction; icon: any; key: string }[] = [
{ action: "generate", icon: Wand2, key: "ai.actions.generate" },
@@ -117,12 +141,17 @@ const chatTitle = computed(() => {
return first ? first.content.slice(0, 30) : t("ai.newChat");
});
const promptMentionChips = computed(() => selectedMentions.value);
const isWaitingForFirstDelta = computed(() => {
const last = messages.value[messages.value.length - 1];
return isGenerating.value && last?.role === "assistant" && !last.content && !last.reasoning;
});
const activePlaceholder = computed(() => t(`ai.placeholders.${activeAction.value}`));
const activePlaceholder = computed(
() => `${t(`ai.placeholders.${activeAction.value}`)} ${t("ai.tableMentionPlaceholderHint")}`,
);
const activeModeHint = computed(() => t(`ai.modeHints.${assistantMode.value}`));
const { databaseOptions: allDbOptions, loadDatabaseOptions } = useDatabaseOptions();
@@ -201,9 +230,208 @@ function scrollToBottom() {
});
}
function mentionCacheKey(connectionId: string, database: string, query: string) {
return `${connectionId}:${database}:${query.toLowerCase()}`;
}
function mentionSchemaOrder(schemas: string[]): string[] {
const currentSchema = props.tab?.tableMeta?.schema;
const preferred = [currentSchema, "public", "dbo", "main"].filter((value): value is string => !!value);
return [...schemas].sort((a, b) => {
const ai = preferred.indexOf(a);
const bi = preferred.indexOf(b);
if (ai >= 0 || bi >= 0) return (ai >= 0 ? ai : 99) - (bi >= 0 ? bi : 99);
return a.localeCompare(b);
});
}
function activeMentionAtCursor(): { start: number; query: string } | null {
const textarea = promptTextareaRef.value;
const cursor = textarea?.selectionStart ?? prompt.value.length;
const beforeCursor = prompt.value.slice(0, cursor);
const match = /(^|[\s([{,;:])@([^\s]*)$/.exec(beforeCursor);
if (!match) return null;
return { start: beforeCursor.length - match[2].length - 1, query: match[2] };
}
function normalizeMentionQuery(query: string): { schemaPrefix: string; tableFilter: string } {
const clean = query.replace(/^["`]+|["`]+$/g, "");
const dot = clean.lastIndexOf(".");
if (dot < 0) return { schemaPrefix: "", tableFilter: clean };
return {
schemaPrefix: clean.slice(0, dot).replace(/^["`]+|["`]+$/g, ""),
tableFilter: clean.slice(dot + 1).replace(/^["`]+|["`]+$/g, ""),
};
}
async function loadMentionCandidates(query: string) {
if (!props.connection || !props.tab?.connectionId || !props.tab.database) return;
const key = mentionCacheKey(props.tab.connectionId, props.tab.database, query);
if (mentionCache.value[key]) {
mentionCandidates.value = mentionCache.value[key];
return;
}
const requestId = ++mentionRequestId;
mentionLoading.value = true;
mentionError.value = "";
const { schemaPrefix, tableFilter } = normalizeMentionQuery(query);
try {
await connectionStore.ensureConnected(props.tab.connectionId);
let candidates: AiMentionCandidate[] = [];
if (isSchemaAware(props.connection.db_type)) {
const schemas = mentionSchemaOrder(await listSchemas(props.tab.connectionId, props.tab.database));
const filteredSchemas = schemaPrefix
? schemas.filter((schema) => schema.toLowerCase().includes(schemaPrefix.toLowerCase()))
: schemas;
const results = await Promise.all(
filteredSchemas.slice(0, 8).map(async (schema) => {
const tables = await listTables(
props.tab!.connectionId,
props.tab!.database,
schema,
tableFilter || undefined,
20,
);
return filterMentionCandidates(
tables.map((table) => mentionCandidateFromTable(table, schema)),
tableFilter,
20,
);
}),
);
candidates = results.flat();
} else {
const schema = props.tab.database || props.connection.database || "main";
const tables = await listTables(props.tab.connectionId, props.tab.database, schema, tableFilter || undefined, 40);
candidates = filterMentionCandidates(
tables.map((table) => mentionCandidateFromTable(table)),
tableFilter,
40,
);
}
if (requestId !== mentionRequestId) return;
mentionCache.value[key] = candidates.slice(0, 40);
mentionCandidates.value = mentionCache.value[key];
mentionSelectedIndex.value = 0;
} catch (e: any) {
if (requestId !== mentionRequestId) return;
mentionError.value = translateBackendError(t, e?.message || String(e));
mentionCandidates.value = [];
} finally {
if (requestId === mentionRequestId) mentionLoading.value = false;
}
}
function mentionCandidateFromTable(table: TableInfo, schema?: string): AiMentionCandidate {
return { schema, name: table.name, tableType: table.table_type };
}
function mentionDisplayName(mention: AiTableMention) {
return [mention.schema, mention.table].filter(Boolean).join(".");
}
function removeMentionChip(mention: AiTableMention) {
selectedMentions.value = selectedMentions.value.filter((item) => item.raw !== mention.raw);
nextTick(() => promptTextareaRef.value?.focus());
}
function addSelectedMention(candidate: AiMentionCandidate) {
const raw = formatAiTableMention(candidate.schema, candidate.name);
const key = `${candidate.schema || ""}.${candidate.name}`.toLowerCase();
if (selectedMentions.value.some((mention) => `${mention.schema || ""}.${mention.table}`.toLowerCase() === key))
return;
selectedMentions.value.push({ raw, schema: candidate.schema, table: candidate.name });
}
function formatMentionTableType(tableType: string) {
const normalized = tableType.toUpperCase().replace(/\s+/g, "_");
if (normalized.includes("VIEW")) return t("ai.tableMentionTypes.view");
if (normalized.includes("SYSTEM")) return t("ai.tableMentionTypes.systemTable");
if (normalized.includes("TEMP")) return t("ai.tableMentionTypes.temporaryTable");
return t("ai.tableMentionTypes.table");
}
function filterMentionCandidates(
candidates: AiMentionCandidate[],
tableFilter: string,
limit: number,
): AiMentionCandidate[] {
const normalizedFilter = tableFilter.toLowerCase();
return candidates
.filter((candidate) => !normalizedFilter || candidate.name.toLowerCase().includes(normalizedFilter))
.slice(0, limit);
}
function refreshMentionState() {
clearTimeout(mentionTimer);
const mention = activeMentionAtCursor();
if (!mention || !props.connection || !props.tab?.database || isGenerating.value) {
mentionOpen.value = false;
return;
}
mentionOpen.value = true;
mentionStart.value = mention.start;
mentionTimer = setTimeout(() => {
loadMentionCandidates(mention.query).catch(() => {});
}, 120);
}
function insertMention(candidate: AiMentionCandidate) {
const textarea = promptTextareaRef.value;
const cursor = textarea?.selectionStart ?? prompt.value.length;
const before = prompt.value.slice(0, mentionStart.value);
const after = prompt.value.slice(cursor);
addSelectedMention(candidate);
prompt.value = `${before}${after}`.replace(/\s{2,}/g, " ");
mentionOpen.value = false;
nextTick(() => {
const nextCursor = before.length;
promptTextareaRef.value?.focus();
promptTextareaRef.value?.setSelectionRange(nextCursor, nextCursor);
});
}
function onPromptKeydown(event: KeyboardEvent) {
if (mentionOpen.value) {
if (event.key === "ArrowDown") {
event.preventDefault();
mentionSelectedIndex.value = Math.min(
mentionSelectedIndex.value + 1,
Math.max(mentionCandidates.value.length - 1, 0),
);
return;
}
if (event.key === "ArrowUp") {
event.preventDefault();
mentionSelectedIndex.value = Math.max(mentionSelectedIndex.value - 1, 0);
return;
}
if ((event.key === "Enter" || event.key === "Tab") && mentionCandidates.value[mentionSelectedIndex.value]) {
event.preventDefault();
insertMention(mentionCandidates.value[mentionSelectedIndex.value]);
return;
}
if (event.key === "Escape") {
event.preventDefault();
mentionOpen.value = false;
return;
}
}
if (event.key === "Enter" && !event.shiftKey && !event.isComposing) {
event.preventDefault();
send();
}
}
async function send() {
const text = prompt.value.trim();
if (!text || isGenerating.value) return;
if ((!text && !selectedMentions.value.length) || isGenerating.value) return;
if (!props.connection || !props.tab) return;
if (!settings.isConfigured()) {
@@ -211,19 +439,25 @@ async function send() {
return;
}
messages.value.push({ role: "user", content: text });
const mentionedTables = [...selectedMentions.value, ...parseAiTableMentions(text)];
const displayText = [selectedMentions.value.map((mention) => mention.raw).join(" "), text].filter(Boolean).join(" ");
messages.value.push({ role: "user", content: displayText });
prompt.value = "";
selectedMentions.value = [];
scrollToBottom();
const requestedAction = activeAction.value;
const shouldAutoExecute = shouldAttemptAiAutoExecute(text, requestedAction);
const shouldAutoExecute = assistantMode.value === "agent" && shouldAttemptAiAutoExecute(displayText, requestedAction);
isGenerating.value = true;
messages.value.push({ role: "assistant", content: "" });
const assistantIdx = messages.value.length - 1;
const sessionId = uuid();
currentSessionId.value = sessionId;
try {
const context = await buildAiContext(props.tab, props.connection);
const context = await buildAiContext(props.tab, props.connection, {
mentionedTables,
});
const history: AiMessage[] = messages.value.slice(0, -2).map((m) => ({
role: m.role,
content: m.content,
@@ -232,7 +466,7 @@ async function send() {
{
config: settings.aiConfig,
action: activeAction.value,
instruction: text,
instruction: displayText,
context,
},
history,
@@ -340,6 +574,10 @@ onMounted(async () => {
conversations.value = await loadAiConversations().catch(() => []);
});
onUnmounted(() => {
clearTimeout(mentionTimer);
});
function triggerAction(action: AiAction, instruction?: string) {
activeAction.value = action;
if (instruction) prompt.value = instruction;
@@ -557,7 +795,7 @@ function formatInlineText(text: string): string {
</ScrollArea>
<div class="p-2">
<div class="rounded-lg border bg-background px-2 pb-2 pt-1">
<div class="relative rounded-lg border bg-background px-2 pb-2 pt-1">
<div v-if="connectionStore.connections.length" class="flex items-center gap-1 mb-1 text-xs text-foreground/80">
<DatabaseIcon v-if="connection" :db-type="connectionIconType(connection)" class="h-3 w-3 shrink-0" />
<Server v-else class="h-3 w-3 shrink-0" />
@@ -605,15 +843,104 @@ function formatInlineText(text: string): string {
</Select>
</template>
</div>
<div
v-if="mentionOpen"
class="absolute bottom-full left-2 right-2 z-20 mb-1 max-h-56 overflow-hidden rounded-md border bg-popover text-popover-foreground shadow-md"
>
<div v-if="mentionLoading" class="flex items-center gap-2 px-2 py-2 text-xs text-muted-foreground">
<Loader2 class="h-3.5 w-3.5 animate-spin" />
<span>{{ t("common.loading") }}</span>
</div>
<div v-else-if="mentionError" class="px-2 py-2 text-xs text-destructive">
{{ mentionError }}
</div>
<div v-else-if="!mentionCandidates.length" class="px-2 py-2 text-xs text-muted-foreground">
{{ t("ai.tableMentionEmpty") }}
</div>
<div v-else class="max-h-56 overflow-auto p-1">
<button
v-for="(candidate, index) in mentionCandidates"
:key="`${candidate.schema || ''}.${candidate.name}`"
type="button"
class="flex w-full min-w-0 items-center gap-2 rounded px-2 py-1.5 text-left text-xs hover:bg-muted"
:class="{ 'bg-muted': index === mentionSelectedIndex }"
@mousedown.prevent="insertMention(candidate)"
@mouseenter="mentionSelectedIndex = index"
>
<Table2 class="h-3.5 w-3.5 shrink-0 text-muted-foreground" />
<span class="min-w-0 flex-1 truncate">
<template v-if="candidate.schema">{{ candidate.schema }}.</template>{{ candidate.name }}
</span>
<span class="shrink-0 text-[10px] text-muted-foreground">{{
formatMentionTableType(candidate.tableType)
}}</span>
</button>
</div>
</div>
<div v-if="promptMentionChips.length" class="mb-1.5 flex flex-wrap gap-1">
<button
v-for="mention in promptMentionChips"
:key="mention.raw"
type="button"
class="group inline-flex max-w-full items-center gap-1 rounded border border-border/80 bg-muted/60 px-1.5 py-0.5 text-[11px] text-foreground/90 hover:bg-muted"
:title="mentionDisplayName(mention)"
@click="removeMentionChip(mention)"
>
<Table2 class="h-3 w-3 shrink-0 text-primary" />
<span class="truncate">{{ mentionDisplayName(mention) }}</span>
<X class="h-3 w-3 shrink-0 text-muted-foreground group-hover:text-foreground" />
</button>
</div>
<textarea
ref="promptTextareaRef"
v-model="prompt"
rows="3"
class="w-full resize-none bg-transparent text-xs outline-none placeholder:text-muted-foreground mb-1"
:placeholder="activePlaceholder"
:disabled="isGenerating"
@keydown.enter.exact="send"
@input="refreshMentionState"
@click="refreshMentionState"
@keyup="refreshMentionState"
@keydown="onPromptKeydown"
/>
<div class="flex items-center gap-1.5">
<DropdownMenu>
<DropdownMenuTrigger as-child>
<button
class="flex items-center gap-1 rounded-full border px-2 py-0.5 text-[11px] text-muted-foreground hover:bg-muted hover:text-foreground"
:title="activeModeHint"
>
<Bot class="h-3 w-3" />
<span>{{ t(`ai.modes.${assistantMode}`) }}</span>
<svg
class="h-3 w-3 opacity-50"
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<path d="m6 9 6 6 6-6" />
</svg>
</button>
</DropdownMenuTrigger>
<DropdownMenuContent align="start" class="w-40">
<DropdownMenuItem class="text-xs gap-1.5" :title="t('ai.modeHints.ask')" @click="assistantMode = 'ask'">
<Check class="h-3 w-3" :class="{ 'opacity-0': assistantMode !== 'ask' }" />
<span>{{ t("ai.modes.ask") }}</span>
</DropdownMenuItem>
<DropdownMenuItem
class="text-xs gap-1.5"
:title="t('ai.modeHints.agent')"
@click="assistantMode = 'agent'"
>
<Check class="h-3 w-3" :class="{ 'opacity-0': assistantMode !== 'agent' }" />
<span>{{ t("ai.modes.agent") }}</span>
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
<DropdownMenu>
<DropdownMenuTrigger as-child>
<button
+257 -21
View File
@@ -4,7 +4,7 @@ const globalDdlOpen = ref(false);
</script>
<script setup lang="ts">
import { computed, nextTick, onUnmounted, watch } from "vue";
import { computed, nextTick, onUnmounted, watch, type Component } from "vue";
import { useI18n } from "vue-i18n";
import {
ArrowUp,
@@ -38,6 +38,10 @@ import {
SquareDashed,
Check,
CopyPlus,
KeyRound,
Link2,
ListTree,
TableProperties,
} from "lucide-vue-next";
import { Button } from "@/components/ui/button";
import {
@@ -60,7 +64,7 @@ import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
import DangerConfirmDialog from "@/components/editor/DangerConfirmDialog.vue";
import type { QueryResult, ColumnInfo, DatabaseType } from "@/types/database";
import type { QueryResult, ColumnInfo, DatabaseType, ForeignKeyInfo, IndexInfo, TriggerInfo } from "@/types/database";
import * as api from "@/lib/api";
import {
buildTableSelectSql,
@@ -1813,7 +1817,10 @@ function onRowContext(rowId: number, rowIndex: number) {
const sqlOneLiner = computed(() => props.sql?.replace(/\s+/g, " ").trim() || "");
const showDdl = globalDdlOpen;
type TableInfoTab = "columns" | "indexes" | "foreignKeys" | "triggers" | "ddl";
const showTableInfo = globalDdlOpen;
const activeTableInfoTab = ref<TableInfoTab>("columns");
const ddlContent = ref("");
const ddlLoading = ref(false);
const ddlWidth = ref(320);
@@ -1821,22 +1828,64 @@ const ddlWrap = ref(true);
const isResizingDdl = ref(false);
let ddlResizeStartX = 0;
let ddlResizeStartWidth = 0;
const indexes = ref<IndexInfo[]>([]);
const indexesLoaded = ref(false);
const indexesLoading = ref(false);
const indexesError = ref("");
const foreignKeys = ref<ForeignKeyInfo[]>([]);
const foreignKeysLoaded = ref(false);
const foreignKeysLoading = ref(false);
const foreignKeysError = ref("");
const triggers = ref<TriggerInfo[]>([]);
const triggersLoaded = ref(false);
const triggersLoading = ref(false);
const triggersError = ref("");
const ddlDrawerStyle = computed(() => ({
width: `${ddlWidth.value}px`,
}));
async function toggleDdl() {
if (showDdl.value) {
showDdl.value = false;
const tableInfoTabs = computed(
() =>
[
{
id: "columns" as const,
label: t("grid.tableInfoColumns"),
icon: ListTree,
count: props.tableMeta?.columns.length,
},
{ id: "indexes" as const, label: t("grid.tableInfoIndexes"), icon: KeyRound, count: indexes.value.length },
{
id: "foreignKeys" as const,
label: t("grid.tableInfoForeignKeys"),
icon: Link2,
count: foreignKeys.value.length,
},
{ id: "triggers" as const, label: t("grid.tableInfoTriggers"), icon: RotateCcw, count: triggers.value.length },
{ id: "ddl" as const, label: "DDL", icon: Code2 },
] satisfies Array<{ id: TableInfoTab; label: string; icon: Component; count?: number }>,
);
async function toggleTableInfo(tab: TableInfoTab = activeTableInfoTab.value) {
if (showTableInfo.value && activeTableInfoTab.value === tab) {
showTableInfo.value = false;
return;
}
await fetchDdl();
showTableInfo.value = true;
await selectTableInfoTab(tab);
}
async function selectTableInfoTab(tab: TableInfoTab) {
activeTableInfoTab.value = tab;
if (tab === "ddl") await fetchDdl();
else if (tab === "indexes") await fetchIndexes();
else if (tab === "foreignKeys") await fetchForeignKeys();
else if (tab === "triggers") await fetchTriggers();
}
async function fetchDdl() {
if (!props.connectionId || !props.tableMeta) return;
showDdl.value = true;
showTableInfo.value = true;
ddlLoading.value = true;
try {
ddlContent.value = await api.getTableDdl(
@@ -1852,8 +1901,82 @@ async function fetchDdl() {
}
}
if (showDdl.value && props.tableMeta && props.connectionId) {
fetchDdl();
async function fetchIndexes() {
if (!props.connectionId || !props.tableMeta || indexesLoaded.value || indexesLoading.value) return;
indexesLoading.value = true;
indexesError.value = "";
try {
indexes.value = await api.listIndexes(
props.connectionId,
props.database || "",
props.tableMeta.schema || props.database || "",
props.tableMeta.tableName,
);
indexesLoaded.value = true;
} catch (e: any) {
indexesError.value = String(e?.message || e);
} finally {
indexesLoading.value = false;
}
}
async function fetchForeignKeys() {
if (!props.connectionId || !props.tableMeta || foreignKeysLoaded.value || foreignKeysLoading.value) return;
foreignKeysLoading.value = true;
foreignKeysError.value = "";
try {
foreignKeys.value = await api.listForeignKeys(
props.connectionId,
props.database || "",
props.tableMeta.schema || props.database || "",
props.tableMeta.tableName,
);
foreignKeysLoaded.value = true;
} catch (e: any) {
foreignKeysError.value = String(e?.message || e);
} finally {
foreignKeysLoading.value = false;
}
}
async function fetchTriggers() {
if (!props.connectionId || !props.tableMeta || triggersLoaded.value || triggersLoading.value) return;
triggersLoading.value = true;
triggersError.value = "";
try {
triggers.value = await api.listTriggers(
props.connectionId,
props.database || "",
props.tableMeta.schema || props.database || "",
props.tableMeta.tableName,
);
triggersLoaded.value = true;
} catch (e: any) {
triggersError.value = String(e?.message || e);
} finally {
triggersLoading.value = false;
}
}
watch(
() => [props.connectionId, props.database, props.tableMeta?.schema, props.tableMeta?.tableName],
() => {
ddlContent.value = "";
indexes.value = [];
indexesLoaded.value = false;
indexesError.value = "";
foreignKeys.value = [];
foreignKeysLoaded.value = false;
foreignKeysError.value = "";
triggers.value = [];
triggersLoaded.value = false;
triggersError.value = "";
if (showTableInfo.value) selectTableInfoTab(activeTableInfoTab.value);
},
);
if (showTableInfo.value && props.tableMeta && props.connectionId) {
selectTableInfoTab(activeTableInfoTab.value);
}
function copyDdl() {
@@ -1949,8 +2072,10 @@ defineExpose({
onToolbarRefresh,
onToolbarCommit,
onToolbarRollback,
showDdl,
toggleDdl,
showDdl: showTableInfo,
toggleDdl: toggleTableInfo,
showTableInfo,
toggleTableInfo,
focusSearch,
});
</script>
@@ -2581,9 +2706,9 @@ defineExpose({
</div>
</div>
</div>
<!-- DDL Drawer -->
<!-- Table Info Drawer -->
<div
v-if="showDdl"
v-if="showTableInfo"
class="relative shrink-0 border-l flex flex-col bg-background min-w-0"
:class="{ 'ddl-drawer-resizing': isResizingDdl }"
:style="ddlDrawerStyle"
@@ -2593,12 +2718,19 @@ defineExpose({
@mousedown.prevent="onDdlResizeStart"
/>
<div class="flex items-center gap-2 px-3 py-1.5 border-b shrink-0 bg-muted/20">
<Code2 class="w-3.5 h-3.5 text-muted-foreground" />
<span class="text-xs font-medium flex-1 min-w-0 truncate">{{ tableMeta?.tableName }} DDL</span>
<Button variant="ghost" size="icon" class="h-5 w-5" @click="copyDdl">
<TableProperties class="w-3.5 h-3.5 text-muted-foreground" />
<span class="text-xs font-medium flex-1 min-w-0 truncate">{{ tableMeta?.tableName }}</span>
<Button
v-if="activeTableInfoTab === 'ddl'"
variant="ghost"
size="icon"
class="h-5 w-5"
@click="copyDdl"
>
<Copy class="w-3 h-3" />
</Button>
<Button
v-if="activeTableInfoTab === 'ddl'"
variant="ghost"
size="icon"
class="h-5 w-5"
@@ -2607,19 +2739,123 @@ defineExpose({
>
<WrapText class="w-3 h-3" />
</Button>
<Button variant="ghost" size="icon" class="h-5 w-5" @click="showDdl = false">
<Button variant="ghost" size="icon" class="h-5 w-5" @click="showTableInfo = false">
<X class="w-3 h-3" />
</Button>
</div>
<div v-if="ddlLoading" class="flex-1 flex items-center justify-center">
<Loader2 class="w-4 h-4 animate-spin text-muted-foreground" />
<div class="grid grid-cols-5 border-b bg-background shrink-0">
<button
v-for="tab in tableInfoTabs"
:key="tab.id"
class="h-9 min-w-0 px-1.5 text-[11px] text-muted-foreground border-b-2 border-transparent hover:bg-muted/50 hover:text-foreground"
:class="{ 'border-primary text-foreground bg-muted/40': activeTableInfoTab === tab.id }"
:title="tab.label"
@click="selectTableInfoTab(tab.id)"
>
<component :is="tab.icon" class="mx-auto h-3.5 w-3.5" />
<span class="block truncate">{{ tab.label }}</span>
</button>
</div>
<div v-if="activeTableInfoTab === 'columns'" class="flex-1 min-h-0 overflow-auto">
<table class="w-full text-xs">
<thead class="sticky top-0 bg-muted/80 backdrop-blur text-muted-foreground">
<tr class="border-b">
<th class="text-left font-medium px-3 py-2">{{ t("grid.columnName") }}</th>
<th class="text-left font-medium px-3 py-2">{{ t("grid.columnType") }}</th>
<th class="text-left font-medium px-3 py-2">{{ t("grid.tableInfoNullable") }}</th>
</tr>
</thead>
<tbody>
<tr v-for="column in tableMeta?.columns" :key="column.name" class="border-b hover:bg-muted/30">
<td class="px-3 py-2 font-medium">
<span class="inline-flex items-center gap-1.5">
<KeyRound v-if="column.is_primary_key" class="h-3 w-3 text-amber-500" />
{{ column.name }}
</span>
<div v-if="column.comment" class="mt-0.5 text-[11px] text-muted-foreground truncate">
{{ column.comment }}
</div>
</td>
<td class="px-3 py-2 font-mono text-[11px] text-muted-foreground">{{ column.data_type }}</td>
<td class="px-3 py-2">{{ column.is_nullable ? "YES" : "NO" }}</td>
</tr>
</tbody>
</table>
</div>
<div v-else-if="activeTableInfoTab === 'indexes'" class="flex-1 min-h-0 overflow-auto">
<div v-if="indexesLoading" class="h-full flex items-center justify-center">
<Loader2 class="w-4 h-4 animate-spin text-muted-foreground" />
</div>
<div v-else-if="indexesError" class="p-3 text-xs text-destructive">{{ indexesError }}</div>
<div v-else-if="indexes.length === 0" class="p-6 text-center text-xs text-muted-foreground">
{{ t("grid.tableInfoEmpty") }}
</div>
<div v-else class="divide-y">
<div v-for="index in indexes" :key="index.name" class="p-3 text-xs">
<div class="font-medium truncate">{{ index.name }}</div>
<div class="mt-1 flex flex-wrap gap-1">
<span v-if="index.is_primary" class="rounded bg-amber-500/10 px-1.5 py-0.5 text-amber-600"
>PK</span
>
<span v-if="index.is_unique" class="rounded bg-emerald-500/10 px-1.5 py-0.5 text-emerald-600"
>UNIQUE</span
>
<span v-if="index.index_type" class="rounded bg-muted px-1.5 py-0.5 text-muted-foreground">{{
index.index_type
}}</span>
</div>
<div class="mt-2 font-mono text-[11px] text-muted-foreground break-all">
{{ index.columns.join(", ") }}
</div>
</div>
</div>
</div>
<div v-else-if="activeTableInfoTab === 'foreignKeys'" class="flex-1 min-h-0 overflow-auto">
<div v-if="foreignKeysLoading" class="h-full flex items-center justify-center">
<Loader2 class="w-4 h-4 animate-spin text-muted-foreground" />
</div>
<div v-else-if="foreignKeysError" class="p-3 text-xs text-destructive">{{ foreignKeysError }}</div>
<div v-else-if="foreignKeys.length === 0" class="p-6 text-center text-xs text-muted-foreground">
{{ t("grid.tableInfoEmpty") }}
</div>
<div v-else class="divide-y">
<div v-for="fk in foreignKeys" :key="`${fk.name}:${fk.column}`" class="p-3 text-xs">
<div class="font-medium truncate">{{ fk.name }}</div>
<div class="mt-1 font-mono text-[11px] text-muted-foreground break-all">
{{ fk.column }} -> {{ fk.ref_table }}.{{ fk.ref_column }}
</div>
</div>
</div>
</div>
<div v-else-if="activeTableInfoTab === 'triggers'" class="flex-1 min-h-0 overflow-auto">
<div v-if="triggersLoading" class="h-full flex items-center justify-center">
<Loader2 class="w-4 h-4 animate-spin text-muted-foreground" />
</div>
<div v-else-if="triggersError" class="p-3 text-xs text-destructive">{{ triggersError }}</div>
<div v-else-if="triggers.length === 0" class="p-6 text-center text-xs text-muted-foreground">
{{ t("grid.tableInfoEmpty") }}
</div>
<div v-else class="divide-y">
<div v-for="trigger in triggers" :key="trigger.name" class="p-3 text-xs">
<div class="font-medium truncate">{{ trigger.name }}</div>
<div class="mt-1 text-[11px] text-muted-foreground">{{ trigger.timing }} {{ trigger.event }}</div>
</div>
</div>
</div>
<pre
v-else
v-else-if="activeTableInfoTab === 'ddl' && !ddlLoading"
class="flex-1 min-w-0 text-xs font-mono p-3 overflow-auto ddl-code leading-5 select-text"
:class="ddlWrap ? 'whitespace-pre-wrap break-words' : 'whitespace-pre'"
v-html="highlightSql(ddlContent)"
></pre>
<div v-else class="flex-1 flex items-center justify-center">
<Loader2 class="w-4 h-4 animate-spin text-muted-foreground" />
</div>
</div>
<!-- Cell Detail Drawer -->
<div
+2 -2
View File
@@ -1,7 +1,7 @@
<script setup lang="ts">
import { computed, ref, defineAsyncComponent } from "vue";
import { useI18n } from "vue-i18n";
import { Loader2, Square, Bot, Table2, GitBranch, BarChart3, Code2 } from "lucide-vue-next";
import { Loader2, Square, Bot, Table2, GitBranch, BarChart3, TableProperties } from "lucide-vue-next";
import { Splitpanes, Pane } from "splitpanes";
import "splitpanes/dist/splitpanes.css";
import { Button } from "@/components/ui/button";
@@ -382,7 +382,7 @@ defineExpose({ focusSearch });
:class="{ 'bg-accent': dataGridRef?.showDdl }"
@click="dataGridRef?.toggleDdl()"
>
<Code2 class="h-3.5 w-3.5" /> DDL
<TableProperties class="h-3.5 w-3.5" /> {{ t("grid.tableInfo") }}
</Button>
</div>
<DataGrid
+26 -6
View File
@@ -12,6 +12,7 @@ import { supportsDataGridTransaction } from "@/lib/tableEditing";
import { useConnectionStore } from "@/stores/connectionStore";
import { useHistoryStore } from "@/stores/historyStore";
import type { ColumnInfo, DatabaseType } from "@/types/database";
import { DBX_NEO4J_ELEMENT_ID_COLUMN, DBX_ROWID_COLUMN } from "@/lib/tableEditing";
type CellValue = string | number | boolean | null;
@@ -371,12 +372,31 @@ export function useDataGridEditor(options: UseDataGridEditorOptions) {
});
}
function clonedRowData(item: RowItem): CellValue[] {
const columnInfoByName = new Map(
(tableMeta.value?.columns ?? []).map((column) => [column.name.toLowerCase(), column]),
);
return item.data.map((val, i) => {
const columnName = result.value.columns[i];
const columnInfo = columnInfoByName.get(columnName.toLowerCase());
return shouldClearClonedColumn(columnName, columnInfo) ? null : val;
});
}
function shouldClearClonedColumn(columnName: string, columnInfo: ColumnInfo | undefined): boolean {
if (databaseType.value === "oracle" && columnName.toUpperCase() === DBX_ROWID_COLUMN) return true;
if (databaseType.value === "neo4j" && columnName === DBX_NEO4J_ELEMENT_ID_COLUMN) return true;
const extra = columnInfo?.extra ?? "";
const columnDefault = columnInfo?.column_default ?? "";
return (
/\b(auto_increment|autoincrement|identity|generated)\b/i.test(extra) || /\bnextval\s*\(/i.test(columnDefault)
);
}
function cloneRow(rowId: number) {
const item = getRowItem(rowId);
if (!item) return;
const primaryKeys = tableMeta.value?.primaryKeys ?? [];
const columns = result.value.columns;
const clonedData = item.data.map((val, i) => (primaryKeys.includes(columns[i]) ? null : val));
const clonedData = clonedRowData(item);
rowStatusFilter.value = rowStatusFilterAfterAddingRow(rowStatusFilter.value);
newRows.value.push(clonedData);
if (useTransaction.value && !transactionActive.value) {
@@ -391,13 +411,11 @@ export function useDataGridEditor(options: UseDataGridEditorOptions) {
}
function cloneRows(rowIds: number[]) {
const primaryKeys = tableMeta.value?.primaryKeys ?? [];
const columns = result.value.columns;
rowStatusFilter.value = rowStatusFilterAfterAddingRow(rowStatusFilter.value);
for (const rowId of rowIds) {
const item = getRowItem(rowId);
if (!item) continue;
const clonedData = item.data.map((val, i) => (primaryKeys.includes(columns[i]) ? null : val));
const clonedData = clonedRowData(item);
newRows.value.push(clonedData);
}
if (useTransaction.value && !transactionActive.value) {
@@ -559,7 +577,9 @@ export function useDataGridEditor(options: UseDataGridEditorOptions) {
const validationError = stmtOptions
? validateDataGridSave({
databaseType: databaseType.value,
tableMeta: tableMeta.value,
columns: stmtOptions.columns,
rows: stmtOptions.rows,
columnInfo: tableMeta.value?.columns,
dirtyRows: stmtOptions.dirtyRows,
newRows: stmtOptions.newRows,
+25 -2
View File
@@ -294,10 +294,10 @@ export default {
discard: "Discard",
dismiss: "Dismiss",
addRow: "Add Row",
cloneRow: "Clone Row",
cloneRow: "Clone as New Row",
deleteRow: "Delete Row",
deleteRows: "Delete {count} Rows",
cloneRows: "Clone {count} Rows",
cloneRows: "Clone {count} as New Rows",
restoreRows: "Restore {count} Rows",
copyRows: "Copy {count} Rows (JSON)",
copyRowsInsert: "Copy {count} Rows as INSERT",
@@ -327,6 +327,13 @@ export default {
transpose: "Transpose Row",
rowsPerPageShort: " rows",
columnDetails: "Column Details",
tableInfo: "Table Info",
tableInfoColumns: "Columns",
tableInfoIndexes: "Indexes",
tableInfoForeignKeys: "Foreign Keys",
tableInfoTriggers: "Triggers",
tableInfoNullable: "Nullable",
tableInfoEmpty: "No metadata",
queryError: "Query Error",
refresh: "Refresh",
commit: "Commit",
@@ -498,6 +505,22 @@ export default {
thinking: "Thinking...",
reasoningProcess: "Thinking process",
stopGenerating: "Stop generating",
tableMentionEmpty: "No matching tables",
tableMentionPlaceholderHint: "Type {'@'} to mention tables for context",
tableMentionTypes: {
table: "Table",
view: "View",
systemTable: "System table",
temporaryTable: "Temporary table",
},
modes: {
ask: "Ask",
agent: "Agent",
},
modeHints: {
ask: "Generate SQL and explanations without auto-running them",
agent: "Auto-run safe queries when possible",
},
fixWithAi: "Fix with AI",
truncated: "Context truncated",
contextSummary: "{database} · {tables} tables",
+2 -2
View File
@@ -295,10 +295,10 @@ export default {
discard: "Descartar",
dismiss: "Cerrar",
addRow: "Agregar fila",
cloneRow: "Clonar fila",
cloneRow: "Clonar como fila nueva",
deleteRow: "Eliminar fila",
deleteRows: "Eliminar {count} filas",
cloneRows: "Clonar {count} filas",
cloneRows: "Clonar {count} como filas nuevas",
restoreRows: "Restaurar {count} filas",
copyRows: "Copiar {count} filas (JSON)",
copyRowsInsert: "Copiar {count} filas como INSERT",
+25 -2
View File
@@ -291,10 +291,10 @@ export default {
discard: "放弃",
dismiss: "关闭",
addRow: "新增行",
cloneRow: "克隆行",
cloneRow: "克隆为新行",
deleteRow: "删除行",
deleteRows: "删除 {count} 行",
cloneRows: "克隆 {count} 行",
cloneRows: "克隆 {count} 行为新行",
restoreRows: "恢复 {count} 行",
copyRows: "复制 {count} 行 (JSON)",
copyRowsInsert: "复制 {count} 行为 INSERT",
@@ -324,6 +324,13 @@ export default {
transpose: "转置查看",
rowsPerPageShort: " 行/页",
columnDetails: "列详情",
tableInfo: "表属性",
tableInfoColumns: "字段",
tableInfoIndexes: "索引",
tableInfoForeignKeys: "外键",
tableInfoTriggers: "触发器",
tableInfoNullable: "可空",
tableInfoEmpty: "暂无元数据",
queryError: "查询出错",
refresh: "刷新",
commit: "提交",
@@ -487,6 +494,22 @@ export default {
thinking: "思考中...",
reasoningProcess: "思考过程",
stopGenerating: "停止生成",
tableMentionEmpty: "没有匹配的表",
tableMentionPlaceholderHint: "输入 {'@'} 可选择表并带入上下文",
tableMentionTypes: {
table: "表",
view: "视图",
systemTable: "系统表",
temporaryTable: "临时表",
},
modes: {
ask: "Ask",
agent: "Agent",
},
modeHints: {
ask: "只生成 SQL 和说明,不自动执行",
agent: "可自动执行安全查询",
},
fixWithAi: "用 AI 修复",
truncated: "上下文已截断",
contextSummary: "{database} · {tables} 张表",
+66 -4
View File
@@ -11,6 +11,8 @@ import type {
} from "@/types/database";
import * as api from "@/lib/api";
import { currentLocale } from "@/i18n";
import { aiTableMentionKey, type AiTableMention } from "@/lib/aiTableMentions";
import { isSchemaAware } from "@/lib/databaseCapabilities";
export type AiAction = "generate" | "explain" | "optimize" | "fix" | "convert" | "sampleData";
@@ -169,6 +171,9 @@ export function buildSystemPrompt(action: AiAction, context: AiContext): string
? "当用户要求分析或查看某个表时,生成 SELECT 查询获取数据,而不是查询元数据。"
: "When the user asks to 'analyze' or 'look at' a table, generate a SELECT query to retrieve data, not a metadata query.",
isZh ? "不要编造 Schema 中不存在的表或列。" : "Never invent tables or columns that are not in the schema context.",
isZh
? "用户输入中的 @schema.table 或 @table 表示用户明确提到的表;这些表已优先放入 Schema 上下文。"
: "User input may contain @schema.table or @table mentions. Treat them as explicit table references; mentioned tables are prioritized in the schema context.",
isZh
? "对于 DROP、DELETE、TRUNCATE、ALTER 或没有 WHERE 的 UPDATE,简要警告并优先提供安全的 SELECT 预览。"
: "For destructive statements (DROP, DELETE, TRUNCATE, ALTER, UPDATE without WHERE), warn briefly and prefer a safer SELECT preview.",
@@ -255,11 +260,12 @@ function formatSchema(context: AiContext): string {
export async function buildAiContext(
tab: QueryTab,
connection: ConnectionConfig,
options: { maxTables?: number; maxColumnsPerTable?: number } = {},
options: { maxTables?: number; maxColumnsPerTable?: number; mentionedTables?: AiTableMention[] } = {},
): Promise<AiContext> {
const maxTables = options.maxTables ?? 50;
const maxColumnsPerTable = options.maxColumnsPerTable ?? 40;
const tables: AiSchemaTable[] = [];
const tableKeys = new Set<string>();
let truncated = false;
if (tab.tableMeta) {
@@ -277,8 +283,20 @@ export async function buildAiContext(
indexes,
foreignKeys,
});
tableKeys.add(aiTableMentionKey(tab.tableMeta.schema, tName));
truncated = tab.tableMeta.columns.length > maxColumnsPerTable;
} else if (!["redis", "mongodb"].includes(connection.db_type)) {
}
for (const mention of options.mentionedTables ?? []) {
const key = aiTableMentionKey(mention.schema, mention.table);
if (tableKeys.has(key)) continue;
const entry = await loadMentionedTableContext(tab, connection, mention, maxColumnsPerTable).catch(() => undefined);
if (!entry) continue;
tableKeys.add(aiTableMentionKey(entry.schema, entry.name));
tables.push(entry);
}
if (!tab.tableMeta && !["redis", "mongodb"].includes(connection.db_type)) {
try {
const schemas = await loadCandidateSchemas(tab, connection);
for (const schema of schemas) {
@@ -295,7 +313,7 @@ export async function buildAiContext(
.listForeignKeys(tab.connectionId, tab.database, schema, table.name)
.catch(() => [] as ForeignKeyInfo[]),
]).then(([columns, indexes, foreignKeys]) => ({
schema: schema === tab.database && connection.db_type !== "postgres" ? undefined : schema,
schema: schema === tab.database && !isSchemaAware(connection.db_type) ? undefined : schema,
name: table.name,
tableType: table.table_type,
columns: columns.slice(0, maxColumnsPerTable),
@@ -309,6 +327,9 @@ export async function buildAiContext(
for (const meta of metaResults) {
if (meta._truncatedCols) truncated = true;
const { _truncatedCols, ...entry } = meta;
const key = aiTableMentionKey(entry.schema, entry.name);
if (tableKeys.has(key)) continue;
tableKeys.add(key);
tables.push(entry);
}
if (tables.length >= maxTables) break;
@@ -330,8 +351,49 @@ export async function buildAiContext(
};
}
async function loadMentionedTableContext(
tab: QueryTab,
connection: ConnectionConfig,
mention: AiTableMention,
maxColumnsPerTable: number,
): Promise<AiSchemaTable | undefined> {
const schema = await resolveMentionedTableSchema(tab, connection, mention);
const [columns, indexes, foreignKeys] = await Promise.all([
api.getColumns(tab.connectionId, tab.database, schema, mention.table),
api.listIndexes(tab.connectionId, tab.database, schema, mention.table).catch(() => [] as IndexInfo[]),
api.listForeignKeys(tab.connectionId, tab.database, schema, mention.table).catch(() => [] as ForeignKeyInfo[]),
]);
return {
schema: schema === tab.database && !isSchemaAware(connection.db_type) ? undefined : schema,
name: mention.table,
tableType: "TABLE",
columns: columns.slice(0, maxColumnsPerTable),
indexes,
foreignKeys,
};
}
async function resolveMentionedTableSchema(
tab: QueryTab,
connection: ConnectionConfig,
mention: AiTableMention,
): Promise<string> {
if (mention.schema) return mention.schema;
if (tab.tableMeta?.tableName.toLowerCase() === mention.table.toLowerCase() && tab.tableMeta.schema) {
return tab.tableMeta.schema;
}
if (isSchemaAware(connection.db_type)) {
const schemas = await loadCandidateSchemas(tab, connection);
for (const schema of schemas) {
const tables = await api.listTables(tab.connectionId, tab.database, schema, mention.table, 10).catch(() => []);
if (tables.some((table) => table.name.toLowerCase() === mention.table.toLowerCase())) return schema;
}
}
return tab.database || connection.database || "main";
}
async function loadCandidateSchemas(tab: QueryTab, connection: ConnectionConfig): Promise<string[]> {
if (connection.db_type === "postgres" || connection.db_type === "sqlserver") {
if (isSchemaAware(connection.db_type)) {
const schemas = await api.listSchemas(tab.connectionId, tab.database);
return prioritizeSchemas(schemas);
}
+103
View File
@@ -0,0 +1,103 @@
export interface AiTableMention {
raw: string;
schema?: string;
table: string;
}
const SIMPLE_IDENTIFIER_RE = /^[\p{L}_][\p{L}\p{N}_$]*$/u;
function isMentionBoundary(char: string | undefined): boolean {
return !char || /\s|[([{,;:]/.test(char);
}
function isUnquotedMentionChar(char: string): boolean {
return /[\p{L}\p{N}_$.-]/u.test(char);
}
function readQuotedSegment(source: string, start: number): { value: string; end: number } | null {
const quote = source[start];
if (quote !== '"' && quote !== "`") return null;
let value = "";
for (let i = start + 1; i < source.length; i++) {
const char = source[i];
if (char === quote) {
if (source[i + 1] === quote) {
value += quote;
i++;
continue;
}
return { value, end: i + 1 };
}
value += char;
}
return null;
}
function readMentionToken(source: string, start: number): { raw: string; parts: string[]; end: number } | null {
let i = start;
const parts: string[] = [];
let raw = "";
while (i < source.length) {
const quoted = readQuotedSegment(source, i);
if (quoted) {
parts.push(quoted.value);
raw += source.slice(i, quoted.end);
i = quoted.end;
} else {
let value = "";
const valueStart = i;
while (i < source.length && isUnquotedMentionChar(source[i]) && source[i] !== ".") {
value += source[i];
i++;
}
if (!value) break;
parts.push(value);
raw += source.slice(valueStart, i);
}
if (source[i] !== ".") break;
raw += ".";
i++;
}
const usableParts = parts.filter(Boolean);
if (!usableParts.length) return null;
return { raw, parts: usableParts, end: i };
}
export function parseAiTableMentions(text: string): AiTableMention[] {
const mentions: AiTableMention[] = [];
const seen = new Set<string>();
for (let i = 0; i < text.length; i++) {
if (text[i] !== "@" || !isMentionBoundary(text[i - 1])) continue;
const token = readMentionToken(text, i + 1);
if (!token) continue;
const table = token.parts[token.parts.length - 1];
const schema = token.parts.length > 1 ? token.parts[token.parts.length - 2] : undefined;
const key = `${schema || ""}.${table}`.toLowerCase();
if (!seen.has(key)) {
seen.add(key);
mentions.push({ raw: `@${token.raw}`, schema, table });
}
i = token.end - 1;
}
return mentions;
}
export function formatAiTableMention(schema: string | undefined, table: string): string {
const parts = [schema, table].filter((part): part is string => !!part);
return `@${parts.map(formatMentionPart).join(".")}`;
}
function formatMentionPart(part: string): string {
if (SIMPLE_IDENTIFIER_RE.test(part)) return part;
return `"${part.replace(/"/g, '""')}"`;
}
export function aiTableMentionKey(schema: string | undefined, table: string): string {
return `${schema || ""}.${table}`.toLowerCase();
}
+61
View File
@@ -29,13 +29,18 @@ export interface DataGridSaveStatementOptions {
export interface DataGridSaveValidationOptions {
databaseType?: DatabaseType;
tableMeta?: DataGridTableMeta;
columns: string[];
rows?: GridCellValue[][];
columnInfo?: DataGridColumnInfo[];
dirtyRows: Array<[number, Array<[number, GridCellValue]>]>;
newRows: GridCellValue[][];
}
export function validateDataGridSave(options: DataGridSaveValidationOptions): string | undefined {
const duplicateKeyError = validateInsertedPrimaryKeys(options);
if (duplicateKeyError) return duplicateKeyError;
const notNullColumns = new Set(
(options.columnInfo ?? [])
.filter(
@@ -69,6 +74,32 @@ export function validateDataGridSave(options: DataGridSaveValidationOptions): st
return undefined;
}
function validateInsertedPrimaryKeys(options: DataGridSaveValidationOptions): string | undefined {
const primaryKeys = options.tableMeta?.primaryKeys ?? [];
if (primaryKeys.length === 0 || options.newRows.length === 0) return undefined;
const primaryKeyIndexes = primaryKeys.map((primaryKey) => findColumnIndex(options.columns, primaryKey));
if (primaryKeyIndexes.some((index) => index === -1)) return undefined;
const existingKeys = new Set<string>();
for (const row of options.rows ?? []) {
const key = primaryKeyValueKey(primaryKeyIndexes, row);
if (key) existingKeys.add(key);
}
const newKeys = new Set<string>();
for (const row of options.newRows) {
const key = primaryKeyValueKey(primaryKeyIndexes, row);
if (!key) continue;
if (existingKeys.has(key) || newKeys.has(key)) {
return duplicatePrimaryKeyError(primaryKeys, primaryKeyIndexes, row, existingKeys.has(key));
}
newKeys.add(key);
}
return undefined;
}
export function buildDataGridSaveStatements(options: DataGridSaveStatementOptions): string[] {
if (options.databaseType === "neo4j") return buildNeo4jDataGridSaveStatements(options);
@@ -252,6 +283,36 @@ function isNullWriteToNotNullColumn(
return value === null && notNullColumns.has(normalizeColumnName(column));
}
function findColumnIndex(columns: string[], target: string): number {
const normalizedTarget = normalizeColumnName(target);
return columns.findIndex((column) => normalizeColumnName(column) === normalizedTarget);
}
function primaryKeyValueKey(primaryKeyIndexes: number[], row: GridCellValue[]): string | undefined {
const values = primaryKeyIndexes.map((index) => row[index]);
if (values.some((value) => value === null || value === undefined)) return undefined;
return JSON.stringify(values);
}
function duplicatePrimaryKeyError(
primaryKeys: string[],
primaryKeyIndexes: number[],
row: GridCellValue[],
matchesExistingRow: boolean,
): string {
const keySummary = primaryKeys
.map((primaryKey, index) => `${primaryKey} = ${formatKeyValueForMessage(row[primaryKeyIndexes[index]])}`)
.join(", ");
const source = matchesExistingRow ? "the existing primary key" : "another new row's primary key";
return `New row duplicates ${source} (${keySummary}). Change the key before saving.`;
}
function formatKeyValueForMessage(value: GridCellValue): string {
if (value === null || value === undefined) return "NULL";
if (typeof value === "string") return `"${value.replace(/"/g, '\\"')}"`;
return String(value);
}
function normalizeColumnName(name: string): string {
return name.toUpperCase();
}
+28
View File
@@ -0,0 +1,28 @@
import { strict as assert } from "node:assert";
import test from "node:test";
import { formatAiTableMention, parseAiTableMentions } from "../src/lib/aiTableMentions.ts";
test("parses simple and schema-qualified AI table mentions", () => {
assert.deepEqual(parseAiTableMentions("show @users and join @public.orders"), [
{ raw: "@users", schema: undefined, table: "users" },
{ raw: "@public.orders", schema: "public", table: "orders" },
]);
});
test("parses quoted AI table mentions with spaces and dots", () => {
assert.deepEqual(parseAiTableMentions('compare @"sales schema"."order.items" with @"audit log"'), [
{ raw: '@"sales schema"."order.items"', schema: "sales schema", table: "order.items" },
{ raw: '@"audit log"', schema: undefined, table: "audit log" },
]);
});
test("deduplicates AI table mentions case-insensitively", () => {
assert.deepEqual(parseAiTableMentions("check @public.Users then @PUBLIC.users"), [
{ raw: "@public.Users", schema: "public", table: "Users" },
]);
});
test("formats AI table mentions with quotes only when needed", () => {
assert.equal(formatAiTableMention("public", "users"), "@public.users");
assert.equal(formatAiTableMention("sales schema", "order items"), '@"sales schema"."order items"');
});
+162
View File
@@ -0,0 +1,162 @@
import { strict as assert } from "node:assert";
import test from "node:test";
import { computed, nextTick, ref } from "vue";
import { createPinia, setActivePinia } from "pinia";
import { useDataGridEditor } from "../src/composables/useDataGridEditor.ts";
import type { ColumnInfo } from "../src/types/database.ts";
type CellValue = string | number | boolean | null;
function installBrowserTestGlobals() {
globalThis.document = { querySelector: () => null } as unknown as Document;
globalThis.localStorage = {
getItem: () => null,
setItem: () => {},
removeItem: () => {},
clear: () => {},
key: () => null,
length: 0,
};
}
function column(name: string, isPrimaryKey = false, extra: string | null = null): ColumnInfo {
return {
name,
data_type: "VARCHAR",
is_nullable: true,
column_default: null,
is_primary_key: isPrimaryKey,
extra,
};
}
test("cloning a row copies non-generated primary key values without executing save", async () => {
setActivePinia(createPinia());
installBrowserTestGlobals();
const result = computed(() => ({
columns: ["code", "year", "score"],
rows: [["AFW", 1995, 35271.907090628745] as CellValue[]],
}));
const rowStatusFilter = ref<"all" | "changed" | "edited" | "new" | "deleted">("all");
let saveCalls = 0;
let editor: ReturnType<typeof useDataGridEditor>;
editor = useDataGridEditor({
result,
editable: computed(() => true),
databaseType: computed(() => "postgres"),
connectionId: computed(() => undefined),
database: computed(() => undefined),
tableMeta: computed(() => ({
tableName: "metrics",
columns: [column("code", true), column("year", true), column("score")],
primaryKeys: ["code", "year"],
})),
onExecuteSql: computed(() => undefined),
customSave: computed(() => async () => {
saveCalls += 1;
}),
sql: computed(() => undefined),
searchText: ref(""),
whereFilterInput: ref(""),
orderByInput: ref(""),
rowStatusFilter,
pageSize: ref(100),
currentPage: ref(1),
getRowItem: (rowId) => {
if (rowId === 0) {
return {
id: 0,
sourceIndex: 0,
data: result.value.rows[0],
isNew: false,
isDeleted: false,
isDirtyCol: [false, false, false],
status: "clean",
};
}
if (rowId < 0) {
const newIndex = -rowId - 1;
const row = editor.newRows.value[newIndex];
if (!row) return undefined;
return {
id: rowId,
newIndex,
data: row,
isNew: true,
isDeleted: false,
isDirtyCol: [false, false, false],
status: "new",
};
}
return undefined;
},
emit: () => {},
});
editor.cloneRow(0);
await nextTick();
assert.equal(saveCalls, 0);
assert.deepEqual(editor.newRows.value, [["AFW", 1995, 35271.907090628745]]);
assert.equal(editor.transactionActive.value, true);
assert.deepEqual(editor.editingCell.value, { rowId: -1, col: 0 });
await editor.saveChanges();
assert.equal(saveCalls, 1);
assert.deepEqual(editor.newRows.value, []);
});
test("cloning a row clears auto-generated key columns", async () => {
setActivePinia(createPinia());
installBrowserTestGlobals();
const result = computed(() => ({
columns: ["id", "name"],
rows: [[1, "Ada"] as CellValue[]],
}));
const rowStatusFilter = ref<"all" | "changed" | "edited" | "new" | "deleted">("all");
let editor: ReturnType<typeof useDataGridEditor>;
editor = useDataGridEditor({
result,
editable: computed(() => true),
databaseType: computed(() => "mysql"),
connectionId: computed(() => undefined),
database: computed(() => undefined),
tableMeta: computed(() => ({
tableName: "people",
columns: [column("id", true, "auto_increment"), column("name")],
primaryKeys: ["id"],
})),
onExecuteSql: computed(() => undefined),
customSave: computed(() => undefined),
sql: computed(() => undefined),
searchText: ref(""),
whereFilterInput: ref(""),
orderByInput: ref(""),
rowStatusFilter,
pageSize: ref(100),
currentPage: ref(1),
getRowItem: (rowId) => {
if (rowId !== 0) return undefined;
return {
id: 0,
sourceIndex: 0,
data: result.value.rows[0],
isNew: false,
isDeleted: false,
isDirtyCol: [false, false],
status: "clean",
};
},
emit: () => {},
});
editor.cloneRow(0);
await nextTick();
assert.deepEqual(editor.newRows.value, [[null, "Ada"]]);
});
+56
View File
@@ -232,7 +232,12 @@ test("rejects NULL writes to non-null table columns", () => {
test("allows NULL for MySQL auto increment columns when inserting rows", () => {
const error = validateDataGridSave({
databaseType: "mysql",
tableMeta: {
tableName: "people",
primaryKeys: ["id"],
},
columns: ["id", "name"],
rows: [],
columnInfo: [
{ name: "id", is_nullable: false, column_default: null, is_primary_key: true, extra: "auto_increment" },
{ name: "name", is_nullable: false, column_default: null, is_primary_key: false, extra: null },
@@ -243,3 +248,54 @@ test("allows NULL for MySQL auto increment columns when inserting rows", () => {
assert.equal(error, undefined);
});
test("rejects inserted rows that duplicate existing primary key values", () => {
const error = validateDataGridSave({
databaseType: "postgres",
tableMeta: {
tableName: "education_data",
primaryKeys: ["country_code", "year"],
},
columns: ["country_code", "year", "value"],
rows: [["ALB", 2021, 0.812]],
columnInfo: [
{ name: "country_code", is_nullable: false, column_default: null, is_primary_key: true, extra: null },
{ name: "year", is_nullable: false, column_default: null, is_primary_key: true, extra: null },
{ name: "value", is_nullable: true, column_default: null, is_primary_key: false, extra: null },
],
dirtyRows: [],
newRows: [["ALB", 2021, 0.812]],
});
assert.equal(
error,
'New row duplicates the existing primary key (country_code = "ALB", year = 2021). Change the key before saving.',
);
});
test("rejects inserted rows that duplicate another new row primary key", () => {
const error = validateDataGridSave({
databaseType: "postgres",
tableMeta: {
tableName: "education_data",
primaryKeys: ["country_code", "year"],
},
columns: ["country_code", "year", "value"],
rows: [],
columnInfo: [
{ name: "country_code", is_nullable: false, column_default: null, is_primary_key: true, extra: null },
{ name: "year", is_nullable: false, column_default: null, is_primary_key: true, extra: null },
{ name: "value", is_nullable: true, column_default: null, is_primary_key: false, extra: null },
],
dirtyRows: [],
newRows: [
["ALB", 2021, 0.812],
["ALB", 2021, 0.913],
],
});
assert.equal(
error,
'New row duplicates another new row\'s primary key (country_code = "ALB", year = 2021). Change the key before saving.',
);
});