Skip to content

armgit / dbx

Public Imported from GitHub
0

25 MB lightweight cross-platform database client for 100+ databases, including MySQL, PostgreSQL, SQLite, Redis, MongoDB, DuckDB, SQL Server, and Dameng. Built-in AI, MCP Server, CLI, desktop and Docker. | 轻量级跨平台数据库管理工具,支持 MySQL、PostgreSQL、SQLite、Redis、MongoDB、达梦等 100+ 数据库,提供桌面端、Docker、CLI、内置 AI 助手和 MCP。

11.2 KB
Raw Blame
<script setup lang="ts">
import { computed, nextTick, ref, watch } from "vue";
import { Braces, Copy } from "@lucide/vue";
import { useI18n } from "vue-i18n";
import { Button } from "@/components/ui/button";
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Popover, PopoverAnchor, PopoverContent } from "@/components/ui/popover";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import TruncatedTextTooltip from "@/components/ui/TruncatedTextTooltip.vue";
import { loadSqlParameterHistory, rememberSqlParameterValues } from "@/lib/sql/sqlParameterHistory";
import { substituteSqlParameters, type SqlParameterDescriptor, type SqlParameterInput, type SqlParameterSyntax, type SqlParameterValueKind } from "@/lib/sql/sqlParameters";
import { useDialogEditorFocusRestore } from "@/composables/useDialogEditorFocusRestore";
import { useSqlHighlighter } from "@/composables/useSqlHighlighter";
import { useToast } from "@/composables/useToast";
import { copyToClipboard } from "@/lib/common/clipboard";
import type { DatabaseType } from "@/types/database";

const { t } = useI18n();
const { highlight } = useSqlHighlighter();
const { toast } = useToast();

const open = defineModel<boolean>("open", { default: false });

const props = defineProps<{
  sql: string;
  parameters: SqlParameterDescriptor[];
  databaseType?: DatabaseType;
  enabledSyntaxes?: SqlParameterSyntax[];
}>();

const emit = defineEmits<{
  execute: [sql: string];
}>();

const values = ref<Record<string, SqlParameterInput>>({});
const histories = ref<Record<string, SqlParameterInput[]>>({});
const activeHistoryName = ref("");
let closeHistoryTimer: ReturnType<typeof setTimeout> | undefined;

const { onCloseAutoFocus: onSqlParameterDialogCloseAutoFocus } = useDialogEditorFocusRestore(open);

const parameterKinds: SqlParameterValueKind[] = ["string", "number", "boolean", "null", "raw"];

const syntaxLabels: Record<SqlParameterSyntax, string> = {
  positional: "?",
  named: ":name",
  shell: "${name}",
  "bracketed-shell": "[${name}]",
  mybatis: "#{name}",
  sqlserver: "@name",
  substitution: "&name",
};

function syntaxLabel(parameter: SqlParameterDescriptor): string {
  return parameter.collection ? "<foreach>" : syntaxLabels[parameter.syntax];
}

const resolvedSql = computed(() => substituteSqlParameters(props.sql, values.value, { databaseType: props.databaseType, enabledSyntaxes: props.enabledSyntaxes }));
const highlightedSql = computed(() => highlight(resolvedSql.value));

watch(
  () => [open.value, props.parameters] as const,
  ([isOpen]) => {
    if (!isOpen) return;
    const next: Record<string, SqlParameterInput> = {};
    const nextHistories: Record<string, SqlParameterInput[]> = {};
    for (const parameter of props.parameters) {
      const history = loadSqlParameterHistory(parameter.key);
      nextHistories[parameter.key] = history;
      next[parameter.key] = values.value[parameter.key] ?? history[0] ?? { kind: "string", value: "" };
    }
    values.value = next;
    histories.value = nextHistories;
  },
  { immediate: true },
);

function updateKind(name: string, kind: SqlParameterValueKind) {
  const current = values.value[name] ?? { value: "" };
  const value = kind === "null" ? "NULL" : current.kind === "null" ? "" : current.value;
  values.value[name] = { ...current, kind, value };
}

function setAllParametersToRaw() {
  const next = { ...values.value };
  for (const parameter of props.parameters) {
    const current = next[parameter.key] ?? { kind: "string", value: "" };
    next[parameter.key] = { ...current, kind: "raw" };
  }
  values.value = next;
}

function clearParameterValues() {
  const next = { ...values.value };
  for (const parameter of props.parameters) {
    const current = next[parameter.key] ?? { kind: "string", value: "" };
    next[parameter.key] = { ...current, value: "" };
  }
  activeHistoryName.value = "";
  values.value = next;
}

function ignoreParameters() {
  open.value = false;
  emit("execute", props.sql);
}

function updateValue(name: string, value: string) {
  const matchedHistory = histories.value[name]?.find((entry) => entry.value === value);
  values.value[name] = { ...(values.value[name] ?? { kind: "string" }), ...(matchedHistory ? { kind: matchedHistory.kind } : {}), value };
}

function filteredSqlParameterHistory(name: string): SqlParameterInput[] {
  const history = histories.value[name] ?? [];
  const query = values.value[name]?.value?.trim().toLowerCase() ?? "";
  if (!query) return history;
  return history.filter((entry) => entry.value.toLowerCase().includes(query));
}

function focusParameterInput(name: string, event: FocusEvent) {
  if (closeHistoryTimer) clearTimeout(closeHistoryTimer);
  activeHistoryName.value = name;
  const input = event.target as HTMLInputElement;
  void nextTick(() => input.focus());
}

function closeParameterHistory(name: string) {
  closeHistoryTimer = setTimeout(() => {
    if (activeHistoryName.value === name) activeHistoryName.value = "";
  }, 120);
}

function selectHistoryEntry(name: string, entry: SqlParameterInput) {
  if (closeHistoryTimer) clearTimeout(closeHistoryTimer);
  values.value[name] = { ...entry };
  activeHistoryName.value = "";
}

function execute() {
  histories.value = { ...histories.value, ...rememberSqlParameterValues(values.value) };
  open.value = false;
  emit("execute", resolvedSql.value);
}

async function copyResolvedSql() {
  try {
    await copyToClipboard(resolvedSql.value);
    toast(t("grid.copied"));
  } catch (e: any) {
    toast(t("grid.copyFailed", { message: e?.message || String(e) }), 5000);
  }
}
</script>

<template>
  <Dialog v-model:open="open">
    <DialogContent class="max-h-[86vh] border border-border !bg-background-solid text-foreground shadow-2xl !backdrop-blur-none sm:max-w-[720px]" @close-auto-focus="onSqlParameterDialogCloseAutoFocus">
      <DialogHeader>
        <DialogTitle class="flex items-center gap-2">
          <Braces class="h-5 w-5 text-primary" />
          {{ t("sqlParameters.title") }}
        </DialogTitle>
      </DialogHeader>

      <div class="grid max-h-[calc(86vh-8rem)] gap-4 overflow-y-auto pr-1">
        <div class="flex flex-wrap items-center gap-2">
          <p class="min-w-0 flex-1 text-sm text-muted-foreground">{{ t("sqlParameters.description") }}</p>
          <Button type="button" size="sm" variant="outline" class="shrink-0" data-testid="sql-parameters-clear-values" @click="clearParameterValues">
            {{ t("sqlParameters.clearValues") }}
          </Button>
          <Button type="button" size="sm" variant="outline" class="ml-auto shrink-0" data-testid="sql-parameters-use-raw-all" @click="setAllParametersToRaw">
            {{ t("sqlParameters.useRawForAll") }}
          </Button>
        </div>

        <div class="relative z-20 max-h-[302px] overflow-auto rounded-md border bg-background">
          <div class="min-w-[680px]">
            <div class="sticky top-0 z-10 grid grid-cols-[minmax(140px,1fr)_104px_132px_minmax(180px,1.5fr)] border-b bg-muted px-3 py-2 text-xs font-medium text-muted-foreground">
              <div>{{ t("sqlParameters.name") }}</div>
              <div>{{ t("sqlParameters.syntax") }}</div>
              <div>{{ t("sqlParameters.type") }}</div>
              <div>{{ t("sqlParameters.value") }}</div>
            </div>
            <div v-for="parameter in parameters" :key="parameter.key" class="grid grid-cols-[minmax(140px,1fr)_104px_132px_minmax(180px,1.5fr)] items-center gap-2 border-b px-3 py-2 text-sm last:border-b-0">
              <div class="min-w-0 truncate font-mono text-xs">{{ parameter.name }}</div>
              <div class="min-w-0 truncate font-mono text-[11px] text-muted-foreground">{{ syntaxLabel(parameter) }}</div>
              <Select :model-value="values[parameter.key]?.kind || 'string'" @update:model-value="(value) => updateKind(parameter.key, value as SqlParameterValueKind)">
                <SelectTrigger class="h-8 bg-background text-xs">
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem v-for="kind in parameterKinds" :key="kind" :value="kind">
                    {{ t(`sqlParameters.kind.${kind}`) }}
                  </SelectItem>
                </SelectContent>
              </Select>
              <div class="relative min-w-0">
                <Popover :open="activeHistoryName === parameter.key && filteredSqlParameterHistory(parameter.key).length > 0">
                  <PopoverAnchor as-child>
                    <Input
                      :model-value="values[parameter.key]?.value || ''"
                      class="h-8 bg-background font-mono text-xs"
                      :disabled="values[parameter.key]?.kind === 'null'"
                      autocomplete="off"
                      data-lpignore="true"
                      data-form-type="other"
                      :placeholder="parameter.collection ? t('sqlParameters.collectionValuePlaceholder') : t('sqlParameters.valuePlaceholder')"
                      @focus="focusParameterInput(parameter.key, $event)"
                      @blur="closeParameterHistory(parameter.key)"
                      @update:model-value="(value) => updateValue(parameter.key, String(value))"
                    />
                  </PopoverAnchor>
                  <PopoverContent align="start" side="bottom" class="z-[80] w-[var(--reka-popover-trigger-width)] max-h-40 gap-0 overflow-auto p-1" @open-auto-focus.prevent>
                    <button
                      v-for="entry in filteredSqlParameterHistory(parameter.key)"
                      :key="`${entry.kind}:${entry.value}`"
                      type="button"
                      class="flex w-full min-w-0 items-center justify-between gap-2 rounded px-2 py-1 text-left text-xs hover:bg-accent hover:text-accent-foreground"
                      @mousedown.prevent="selectHistoryEntry(parameter.key, entry)"
                    >
                      <TruncatedTextTooltip :text="entry.value" class="min-w-0 flex-1 font-mono" side="top" :delay="150" />
                      <span class="shrink-0 text-[10px] uppercase text-muted-foreground">{{ t(`sqlParameters.kind.${entry.kind}`) }}</span>
                    </button>
                  </PopoverContent>
                </Popover>
              </div>
            </div>
          </div>
        </div>

        <div class="relative z-10 grid gap-2">
          <div class="text-xs font-medium text-muted-foreground">{{ t("sqlParameters.preview") }}</div>
          <pre class="max-h-48 min-w-0 overflow-auto rounded-md bg-muted px-3 py-3 text-xs font-mono whitespace-pre" v-html="highlightedSql" />
        </div>
      </div>

      <DialogFooter>
        <Button type="button" variant="outline" data-testid="sql-parameters-ignore" @click="ignoreParameters">
          {{ t("sqlParameters.ignore") }}
        </Button>
        <Button variant="outline" @click="open = false">{{ t("dangerDialog.cancel") }}</Button>
        <Button variant="outline" @click="copyResolvedSql">
          <Copy class="mr-1.5 h-4 w-4" />
          {{ t("grid.copy") }}
        </Button>
        <Button @click="execute">{{ t("sqlParameters.execute") }}</Button>
      </DialogFooter>
    </DialogContent>
  </Dialog>
</template>